text
stringlengths
8
4.13M
pub mod get; pub mod toml_to_struct;
//! Peripheral access API for STM32G4 microcontrollers //! (generated using [svd2rust](https://github.com/rust-embedded/svd2rust) //! 0.30.0) //! //! You can find an overview of the API here: //! [svd2rust/#peripheral-api](https://docs.rs/svd2rust/0.30.0/svd2rust/#peripheral-api) //! //! For more details see the README here: //! [stm32-rs](https://github.com/stm32-rs/stm32-rs) //! //! This crate supports all STM32G4 devices; for the complete list please //! see: //! [stm32g4](https://crates.io/crates/stm32g4) //! //! Due to doc build limitations, not all devices may be shown on docs.rs; //! a representative few have been selected instead. For a complete list of //! available registers and fields see: [stm32-rs Device Coverage](https://stm32-rs.github.io/stm32-rs/) #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![no_std] mod generic; pub use self::generic::*; #[cfg(feature = "stm32g431")] pub mod stm32g431; #[cfg(feature = "stm32g441")] pub mod stm32g441; #[cfg(feature = "stm32g471")] pub mod stm32g471; #[cfg(feature = "stm32g473")] pub mod stm32g473; #[cfg(feature = "stm32g474")] pub mod stm32g474; #[cfg(feature = "stm32g483")] pub mod stm32g483; #[cfg(feature = "stm32g484")] pub mod stm32g484; #[cfg(feature = "stm32g491")] pub mod stm32g491; #[cfg(feature = "stm32g4a1")] pub mod stm32g4a1;
#[doc = "Register `TIR` reader"] pub type R = crate::R<TIR_SPEC>; #[doc = "Register `TIR` writer"] pub type W = crate::W<TIR_SPEC>; #[doc = "Field `TXRQ` reader - TXRQ"] pub type TXRQ_R = crate::BitReader; #[doc = "Field `TXRQ` writer - TXRQ"] pub type TXRQ_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTR` reader - RTR"] pub type RTR_R = crate::BitReader; #[doc = "Field `RTR` writer - RTR"] pub type RTR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `IDE` reader - IDE"] pub type IDE_R = crate::BitReader; #[doc = "Field `IDE` writer - IDE"] pub type IDE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EXID` reader - EXID"] pub type EXID_R = crate::FieldReader<u32>; #[doc = "Field `EXID` writer - EXID"] pub type EXID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 18, O, u32>; #[doc = "Field `STID` reader - STID"] pub type STID_R = crate::FieldReader<u16>; #[doc = "Field `STID` writer - STID"] pub type STID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 11, O, u16>; impl R { #[doc = "Bit 0 - TXRQ"] #[inline(always)] pub fn txrq(&self) -> TXRQ_R { TXRQ_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - RTR"] #[inline(always)] pub fn rtr(&self) -> RTR_R { RTR_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - IDE"] #[inline(always)] pub fn ide(&self) -> IDE_R { IDE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 3:20 - EXID"] #[inline(always)] pub fn exid(&self) -> EXID_R { EXID_R::new((self.bits >> 3) & 0x0003_ffff) } #[doc = "Bits 21:31 - STID"] #[inline(always)] pub fn stid(&self) -> STID_R { STID_R::new(((self.bits >> 21) & 0x07ff) as u16) } } impl W { #[doc = "Bit 0 - TXRQ"] #[inline(always)] #[must_use] pub fn txrq(&mut self) -> TXRQ_W<TIR_SPEC, 0> { TXRQ_W::new(self) } #[doc = "Bit 1 - RTR"] #[inline(always)] #[must_use] pub fn rtr(&mut self) -> RTR_W<TIR_SPEC, 1> { RTR_W::new(self) } #[doc = "Bit 2 - IDE"] #[inline(always)] #[must_use] pub fn ide(&mut self) -> IDE_W<TIR_SPEC, 2> { IDE_W::new(self) } #[doc = "Bits 3:20 - EXID"] #[inline(always)] #[must_use] pub fn exid(&mut self) -> EXID_W<TIR_SPEC, 3> { EXID_W::new(self) } #[doc = "Bits 21:31 - STID"] #[inline(always)] #[must_use] pub fn stid(&mut self) -> STID_W<TIR_SPEC, 21> { STID_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "TX mailbox identifier register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tir::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tir::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TIR_SPEC; impl crate::RegisterSpec for TIR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`tir::R`](R) reader structure"] impl crate::Readable for TIR_SPEC {} #[doc = "`write(|w| ..)` method takes [`tir::W`](W) writer structure"] impl crate::Writable for TIR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TIR to value 0"] impl crate::Resettable for TIR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::*; use crate::helpers::solver::create_default_refinement_ctx; use crate::models::examples::create_example_problem; use crate::utils::compare_floats; use std::cmp::Ordering; fn compare_statistic(refinement_ctx: &RefinementContext, expected: (usize, f64, f64)) { assert_eq!(refinement_ctx.statistics.generation, expected.0); assert_eq!(compare_floats(refinement_ctx.statistics.improvement_all_ratio, expected.1), Ordering::Equal); assert_eq!(compare_floats(refinement_ctx.statistics.improvement_1000_ratio, expected.2), Ordering::Equal); } #[test] fn can_update_statistic() { let mut refinement_ctx = create_default_refinement_ctx(create_example_problem()); let mut telemetry = Telemetry::new(TelemetryMode::None); telemetry.start(); telemetry.on_initial(0, 1, Timer::start(), 0.); telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), true); compare_statistic(&refinement_ctx, (0, 1., 1.)); telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), false); compare_statistic(&refinement_ctx, (1, 0.5, 0.5)); telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), false); telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), false); compare_statistic(&refinement_ctx, (3, 0.25, 0.25)); (0..996).for_each(|_| { telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), false); }); compare_statistic(&refinement_ctx, (999, 0.001, 0.001)); telemetry.on_generation(&mut refinement_ctx, 0., Timer::start(), true); compare_statistic(&refinement_ctx, (1000, 2. / 1001., 0.001)); }
use crate::config::dfinity::{Config, Profile}; use crate::lib::canister_info::CanisterInfo; use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::models::canister::CanisterPool; use crate::lib::provider::get_network_context; use ic_types::principal::Principal as CanisterId; use std::path::PathBuf; use std::sync::Arc; mod assets; mod custom; mod motoko; #[derive(Debug)] pub enum WasmBuildOutput { // Wasm(Vec<u8>), File(PathBuf), } #[derive(Debug)] pub enum IdlBuildOutput { // IDLProg(IDLProg), File(PathBuf), } /// The output of a build. pub struct BuildOutput { pub canister_id: CanisterId, pub wasm: WasmBuildOutput, pub idl: IdlBuildOutput, } /// A stateless canister builder. This is meant to not keep any state and be passed everything. pub trait CanisterBuilder { /// Returns true if this builder supports building the canister. fn supports(&self, info: &CanisterInfo) -> bool; /// Returns the dependencies of this canister, if any. This should not be a transitive /// list. fn get_dependencies( &self, _pool: &CanisterPool, _info: &CanisterInfo, ) -> DfxResult<Vec<CanisterId>> { Ok(Vec::new()) } fn prebuild( &self, _pool: &CanisterPool, _info: &CanisterInfo, _config: &BuildConfig, ) -> DfxResult { Ok(()) } /// Build a canister. The canister contains all information related to a single canister, /// while the config contains information related to this particular build. fn build( &self, pool: &CanisterPool, info: &CanisterInfo, config: &BuildConfig, ) -> DfxResult<BuildOutput>; fn postbuild( &self, _pool: &CanisterPool, _info: &CanisterInfo, _config: &BuildConfig, ) -> DfxResult { Ok(()) } } #[derive(Clone)] pub struct BuildConfig { profile: Profile, pub build_mode_check: bool, pub network_name: String, /// The root of all IDL files. pub idl_root: PathBuf, /// The root for all build files. pub build_root: PathBuf, } impl BuildConfig { pub fn from_config(config: &Config) -> DfxResult<Self> { let config_intf = config.get_config(); let network_name = get_network_context()?; let build_root = config.get_temp_path().join(&network_name); let build_root = build_root.join("canisters"); Ok(BuildConfig { network_name, profile: config_intf.profile.unwrap_or(Profile::Debug), build_mode_check: false, build_root: build_root.clone(), idl_root: build_root.join("idl/"), }) } pub fn with_build_mode_check(self, build_mode_check: bool) -> Self { Self { build_mode_check, ..self } } } pub struct BuilderPool { builders: Vec<Arc<dyn CanisterBuilder>>, } impl BuilderPool { pub fn new(env: &dyn Environment) -> DfxResult<Self> { let mut builders: Vec<Arc<dyn CanisterBuilder>> = Vec::new(); builders.push(Arc::new(assets::AssetsBuilder::new(env)?)); builders.push(Arc::new(custom::CustomBuilder::new(env)?)); builders.push(Arc::new(motoko::MotokoBuilder::new(env)?)); Ok(Self { builders }) } pub fn get(&self, info: &CanisterInfo) -> Option<Arc<dyn CanisterBuilder>> { self.builders .iter() .find(|builder| builder.supports(&info)) .map(|x| Arc::clone(x)) } }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. //! Contains an implementation of FRI verifier and associated components. use crate::{folding::fold_positions, utils::map_positions_to_indexes, FriOptions, VerifierError}; use core::{convert::TryInto, marker::PhantomData, mem}; use crypto::{ElementHasher, RandomCoin}; use math::{fft, log2, polynom, FieldElement, StarkField}; use utils::collections::Vec; mod channel; pub use channel::{DefaultVerifierChannel, VerifierChannel}; // FRI VERIFIER // ================================================================================================ /// Implements the verifier component of the FRI protocol. /// /// Given a small number of evaluations of some function *f* over domain *D* and a FRI proof, a /// FRI verifier determines whether *f* is a polynomial of some bounded degree *d*, such that *d* /// < |*D*| / 2. /// /// The verifier is parametrized by the following types: /// /// * `B` specifies the base field of the STARK protocol. /// * `E` specifies the filed in which the FRI protocol is executed. This can be the same as the /// base field `B`, but it can also be an extension of the base field in cases when the base /// field is too small to provide desired security level for the FRI protocol. /// * `C` specifies the type used to simulate prover-verifier interaction. This type is used /// as an abstraction for a [FriProof](crate::FriProof). Meaning, the verifier does not consume /// a FRI proof directly, but reads it via [VerifierChannel] interface. /// * `H` specifies the Hash function used by the prover to commit to polynomial evaluations. /// /// Proof verification is performed in two phases: commit phase and query phase. /// /// # Commit phase /// During the commit phase, which is executed when the verifier is instantiated via /// [new()](FriVerifier::new()) function, the verifier receives a list of FRI layer commitments /// from the prover (via [VerifierChannel]). After each received commitment, the verifier /// draws a random value α from the entire field, and sends it to the prover. In the /// non-interactive version of the protocol, α values are derived pseudo-randomly from FRI /// layer commitments. /// /// # Query phase /// During the query phase, which is executed via [verify()](FriVerifier::verify()) function, /// the verifier sends a set of positions in the domain *D* to the prover, and the prover responds /// with polynomial evaluations at these positions (together with corresponding Merkle paths) /// across all FRI layers. The verifier then checks that: /// * The Merkle paths are valid against the layer commitments the verifier received during /// the commit phase. /// * The evaluations are consistent across FRI layers (i.e., the degree-respecting projection /// was applied correctly). /// * The degree of the polynomial implied by evaluations at the last FRI layer (the remainder) /// is smaller than the degree resulting from reducing degree *d* by `folding_factor` at each /// FRI layer. pub struct FriVerifier<B, E, C, H> where B: StarkField, E: FieldElement<BaseField = B>, C: VerifierChannel<E, Hasher = H>, H: ElementHasher<BaseField = B>, { max_poly_degree: usize, domain_size: usize, domain_generator: B, layer_commitments: Vec<H::Digest>, layer_alphas: Vec<E>, options: FriOptions, num_partitions: usize, _channel: PhantomData<C>, } impl<B, E, C, H> FriVerifier<B, E, C, H> where B: StarkField, E: FieldElement<BaseField = B>, C: VerifierChannel<E, Hasher = H>, H: ElementHasher<BaseField = B>, { /// Returns a new instance of FRI verifier created from the specified parameters. /// /// The `max_poly_degree` parameter specifies the highest polynomial degree accepted by the /// returned verifier. In combination with `blowup_factor` from the `options` parameter, /// `max_poly_degree` also defines the domain over which the tested polynomial is evaluated. /// /// Creating a FRI verifier executes the commit phase of the FRI protocol from the verifier's /// perspective. Specifically, the verifier reads FRI layer commitments from the `channel`, /// and for each commitment, updates the `public_coin` with this commitment and then draws /// a random value α from the coin. /// /// The verifier stores layer commitments and corresponding α values in its internal state, /// and, thus, an instance of FRI verifier can be used to verify only a single proof. /// /// # Errors /// Returns an error if: /// * `max_poly_degree` is inconsistent with the number of FRI layers read from the channel /// and `folding_factor` specified in the `options` parameter. /// * An error was encountered while drawing a random α value from the coin. pub fn new( channel: &mut C, public_coin: &mut RandomCoin<B, H>, options: FriOptions, max_poly_degree: usize, ) -> Result<Self, VerifierError> { // infer evaluation domain info let domain_size = max_poly_degree.next_power_of_two() * options.blowup_factor(); let domain_generator = B::get_root_of_unity(log2(domain_size)); let num_partitions = channel.read_fri_num_partitions(); // read layer commitments from the channel and use them to build a list of alphas let layer_commitments = channel.read_fri_layer_commitments(); let mut layer_alphas = Vec::with_capacity(layer_commitments.len()); let mut max_degree_plus_1 = max_poly_degree + 1; for (depth, commitment) in layer_commitments.iter().enumerate() { public_coin.reseed(*commitment); let alpha = public_coin.draw().map_err(VerifierError::PublicCoinError)?; layer_alphas.push(alpha); // make sure the degree can be reduced by the folding factor at all layers // but the remainder layer if depth != layer_commitments.len() - 1 && max_degree_plus_1 % options.folding_factor() != 0 { return Err(VerifierError::DegreeTruncation( max_degree_plus_1 - 1, options.folding_factor(), depth, )); } max_degree_plus_1 /= options.folding_factor(); } Ok(FriVerifier { max_poly_degree, domain_size, domain_generator, layer_commitments, layer_alphas, options, num_partitions, _channel: PhantomData, }) } // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- /// Returns maximum degree of a polynomial accepted by this verifier. pub fn max_poly_degree(&self) -> usize { self.max_poly_degree } /// Returns size of the domain over which a polynomial commitment checked by this verifier /// has been evaluated. /// /// The domain size can be computed by rounding `max_poly_degree` to the next power of two /// and multiplying the result by the `blowup_factor` from the protocol options. pub fn domain_size(&self) -> usize { self.domain_size } /// Returns number of partitions used during FRI proof generation. /// /// For non-distributed proof generation, number of partitions is usually set to 1. pub fn num_partitions(&self) -> usize { self.num_partitions } /// Returns protocol configuration options for this verifier. pub fn options(&self) -> &FriOptions { &self.options } // VERIFICATION PROCEDURE // -------------------------------------------------------------------------------------------- /// Executes the query phase of the FRI protocol. /// /// Returns `Ok(())` if values in the `evaluations` slice represent evaluations of a polynomial /// with degree <= `max_poly_degree` at x coordinates specified by the `positions` slice. /// /// Thus, `positions` parameter represents the positions in the evaluation domain at which the /// verifier queries the prover at the first FRI layer. Similarly, the `evaluations` parameter /// specifies the evaluations of the polynomial at the first FRI layer returned by the prover /// for these positions. /// /// Evaluations of layer polynomials for all subsequent FRI layers the verifier reads from the /// specified `channel`. /// /// # Errors /// Returns an error if: /// * The length of `evaluations` is not equal to the length of `positions`. /// * An unsupported folding factor was specified by the `options` for this verifier. /// * Decommitments to polynomial evaluations don't match the commitment value at any of the /// FRI layers. /// * The verifier detects an error in how the degree-respecting projection was applied /// at any of the FRI layers. /// * The degree of the remainder at the last FRI layer is greater than the degree implied by /// `max_poly_degree` reduced by the folding factor at each FRI layer. pub fn verify( &self, channel: &mut C, evaluations: &[E], positions: &[usize], ) -> Result<(), VerifierError> { if evaluations.len() != positions.len() { return Err(VerifierError::NumPositionEvaluationMismatch( positions.len(), evaluations.len(), )); } // static dispatch for folding factor parameter let folding_factor = self.options.folding_factor(); match folding_factor { 4 => self.verify_generic::<4>(channel, evaluations, positions), 8 => self.verify_generic::<8>(channel, evaluations, positions), 16 => self.verify_generic::<16>(channel, evaluations, positions), _ => Err(VerifierError::UnsupportedFoldingFactor(folding_factor)), } } /// This is the actual implementation of the verification procedure described above, but it /// also takes folding factor as a generic parameter N. fn verify_generic<const N: usize>( &self, channel: &mut C, evaluations: &[E], positions: &[usize], ) -> Result<(), VerifierError> { // pre-compute roots of unity used in computing x coordinates in the folded domain let folding_roots = (0..N) .map(|i| { self.domain_generator .exp(((self.domain_size / N * i) as u64).into()) }) .collect::<Vec<_>>(); // 1 ----- verify the recursive components of the FRI proof ----------------------------------- let mut domain_generator = self.domain_generator; let mut domain_size = self.domain_size; let mut max_degree_plus_1 = self.max_poly_degree + 1; let mut positions = positions.to_vec(); let mut evaluations = evaluations.to_vec(); for depth in 0..self.options.num_fri_layers(self.domain_size) { // determine which evaluations were queried in the folded layer let mut folded_positions = fold_positions(&positions, domain_size, self.options.folding_factor()); // determine where these evaluations are in the commitment Merkle tree let position_indexes = map_positions_to_indexes( &folded_positions, domain_size, self.options.folding_factor(), self.num_partitions, ); // read query values from the specified indexes in the Merkle tree let layer_commitment = self.layer_commitments[depth]; // TODO: add layer depth to the potential error message let layer_values = channel.read_layer_queries(&position_indexes, &layer_commitment)?; let query_values = get_query_values::<E, N>(&layer_values, &positions, &folded_positions, domain_size); if evaluations != query_values { return Err(VerifierError::InvalidLayerFolding(depth)); } // build a set of x coordinates for each row polynomial #[rustfmt::skip] let xs = folded_positions.iter().map(|&i| { let xe = domain_generator.exp((i as u64).into()) * self.options.domain_offset(); folding_roots.iter() .map(|&r| E::from(xe * r)) .collect::<Vec<_>>().try_into().unwrap() }) .collect::<Vec<_>>(); // interpolate x and y values into row polynomials let row_polys = polynom::interpolate_batch(&xs, &layer_values); // calculate the pseudo-random value used for linear combination in layer folding let alpha = self.layer_alphas[depth]; // check that when the polynomials are evaluated at alpha, the result is equal to // the corresponding column value evaluations = row_polys.iter().map(|p| polynom::eval(p, alpha)).collect(); // make sure next degree reduction does not result in degree truncation if max_degree_plus_1 % N != 0 { return Err(VerifierError::DegreeTruncation( max_degree_plus_1 - 1, N, depth, )); } // update variables for the next iteration of the loop domain_generator = domain_generator.exp((N as u32).into()); max_degree_plus_1 /= N; domain_size /= N; mem::swap(&mut positions, &mut folded_positions); } // 2 ----- verify the remainder of the FRI proof ---------------------------------------------- // read the remainder from the channel and make sure it matches with the columns // of the previous layer let remainder_commitment = self.layer_commitments.last().unwrap(); let remainder = channel.read_remainder::<N>(remainder_commitment)?; for (&position, evaluation) in positions.iter().zip(evaluations) { if remainder[position] != evaluation { return Err(VerifierError::InvalidRemainderFolding); } } // make sure the remainder values satisfy the degree verify_remainder(remainder, max_degree_plus_1 - 1) } } // REMAINDER DEGREE VERIFICATION // ================================================================================================ /// Returns Ok(true) if values in the `remainder` slice represent evaluations of a polynomial /// with degree <= `max_degree` against a domain of the same size as `remainder`. fn verify_remainder<B: StarkField, E: FieldElement<BaseField = B>>( mut remainder: Vec<E>, max_degree: usize, ) -> Result<(), VerifierError> { if max_degree >= remainder.len() - 1 { return Err(VerifierError::RemainderDegreeNotValid); } // interpolate remainder polynomial from its evaluations; we don't shift the domain here // because the degree of the polynomial will not change as long as we interpolate over a // coset of the original domain. let inv_twiddles = fft::get_inv_twiddles(remainder.len()); fft::interpolate_poly(&mut remainder, &inv_twiddles); let poly = remainder; // make sure the degree is valid if max_degree < polynom::degree_of(&poly) { Err(VerifierError::RemainderDegreeMismatch(max_degree)) } else { Ok(()) } } // HELPER FUNCTIONS // ================================================================================================ fn get_query_values<E: FieldElement, const N: usize>( values: &[[E; N]], positions: &[usize], folded_positions: &[usize], domain_size: usize, ) -> Vec<E> { let row_length = domain_size / N; let mut result = Vec::new(); for position in positions { let idx = folded_positions .iter() .position(|&v| v == position % row_length) .unwrap(); let value = values[idx][position / row_length]; result.push(value); } result }
use owned_ttf_parser::{AsFaceRef, OwnedFace}; const FONT: &[u8] = include_bytes!("../fonts/font.ttf"); #[test] fn move_and_use() { let owned_data = FONT.to_vec(); let pin_face = OwnedFace::from_vec(owned_data, 0).unwrap(); let ascent = pin_face.as_face_ref().ascender(); // force a move let moved = Box::new(pin_face); assert_eq!(moved.as_face_ref().ascender(), ascent); }
use crate::dasm::InstructionData; use crate::spec::cpu::{Error, CPU}; use crate::spec::mmu::MMU; use crate::spec::mnemonic::Mnemonic; use crate::spec::opcode::Instruction; use crate::spec::opcodes::unexpected_op; use crate::spec::register::TRegister; impl CPU { pub(crate) fn evaluate_control( &mut self, instruction_data: &InstructionData, _opcode_data: &[u8; 2], mmu: &mut MMU, ) -> Result<u8, Error> { match instruction_data.instruction { Instruction::CCF => { let mut flags = self.registers.flag_register(); flags.c = (flags.c == 0) as u8; flags.h = 0; flags.n = 0; self.registers.f.set_value(flags.into()); Ok(1) } Instruction::SCF => { let mut flags = self.registers.flag_register(); flags.c = 1; flags.h = 0; flags.n = 0; self.registers.f.set_value(flags.into()); Ok(1) } Instruction::NOP => Ok(1), Instruction::HALT => { self.halt = true; Ok(1) } Instruction::STOP => { unimplemented!() } Instruction::DI => { mmu.write_interrupt_enable_reg(false); Ok(1) } Instruction::EI => { mmu.write_interrupt_enable_reg(true); Ok(1) } _ => Err(unexpected_op(&instruction_data.mnemonic, &Mnemonic::PUSH)), } } }
use hacspec_lib::prelude::*; // XXX: Careful in here. The `test` functions use `Numeric` functions and hence // will end up being the same as what they test. Rewrite when merging! #[test] fn test_cswap() { let x = 123u8; let y = 234u8; let (xs, ys) = cswap(x, y, 0); assert_eq!(xs, x); assert_eq!(ys, y); let (xs, ys) = cswap_bit(x, y, 0); assert_eq!(xs, x); assert_eq!(ys, y); let (xs, ys) = cswap(x, y, u8::max_val()); assert_eq!(xs, y); assert_eq!(ys, x); let (xs, ys) = cswap_bit(x, y, 1); assert_eq!(xs, y); assert_eq!(ys, x); } #[test] fn test_csub() { fn test<T: Integer + Copy>(x: T, y: T) { let d = csub(x, y, T::default()); assert!(d.equal(x)); let d = csub(x, y, T::max_val()); assert!(d.equal(x.wrap_sub(y))); } test(13u8, 234u8); test(827629u64, 16u64); } #[test] fn test_cadd() { fn test<T: Integer + Copy>(x: T, y: T) { let d = cadd(x, y, T::default()); assert!(d.equal(x)); let d = cadd(x, y, T::max_val()); assert!(d.equal(x.wrap_add(y))); } test(13u8, 234u8); test(827629u64, 16u64); } #[test] fn test_cmul() { fn test<T: Integer + Copy>(x: T, y: T) { let d = cmul(x, y, T::default()); assert!(d.equal(x)); let d = cmul(x, y, T::max_val()); assert!(d.equal(x.wrap_mul(y))); } test(13u8, 234u8); test(827629u64, 16u64); } #[test] fn test_div() { fn test<T: Integer + Copy>(x: T, y: T) { let (q, r) = ct_div(x, y); assert!(q.equal(x.divide(y))); assert!(r.equal(x.modulo(y))); } fn test_8(x: u8, y: u8) { test(x, y); test(U8(x), U8(y)); } test_8(13, 234); fn test_16(x: u16, y: u16) { test(x, y); test(U16(x), U16(y)); } test_16(13, 234); fn test_32(x: u32, y: u32) { test(x, y); test(U32(x), U32(y)); } test_32(827629, 12); fn test_64(x: u64, y: u64) { test(x, y); test(U64(x), U64(y)); } test_64(827629, 12); test_64(16, 827629); } #[test] fn test_zn_inv() { let n = 65537; // assert_eq!(u128::inv(23647, n), 52791); assert_eq!(u128::inv(37543865, n), 37686); // let n = 106103; // assert_eq!(u128::inv(8752725684352, n), 52673); // assert_eq!(u128::inv(123, n), 99202); // let n = 106103i128; // assert_eq!(i128::inv(-123, n), 6901); } #[test] fn test_poly_div() { // x³ + 3 let a: Seq<i128> = Seq::from_native_slice(&[3, 3]); // x + 1 let b: Seq<i128> = Seq::from_native_slice(&[1, 1]); // 3x +3 / x + 1 (mod 4) = 3 let mut quotient = div_poly(&a, &b, 4); // q = 3 and r = 0 let r: Seq<i128> = Seq::from_native_slice(&[0, 0]); let q: Seq<i128> = Seq::from_native_slice(&[3, 0]); assert_eq!(degree_poly(&quotient.clone().unwrap().0), 0); assert_eq!(quotient.clone().unwrap().0[0], q[0]); assert_eq!(degree_poly(&quotient.clone().unwrap().1), 0); assert_eq!(quotient.clone().unwrap().1[0], r[0]); //x¹² + x let a_2: Seq<i128> = Seq::from_native_slice(&[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); //x - 1 let b_2: Seq<i128> = Seq::from_native_slice(&[-1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // (x¹² + x )/ (x-1) mod 4 = x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 2 quotient = div_poly(&a_2, &b_2, 4); // q = x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 2 assert_eq!(degree_poly(&quotient.clone().unwrap().0), 11); for i in 1..12 { assert_eq!(quotient.clone().unwrap().0[i], 1i128); } assert_eq!(quotient.clone().unwrap().0[0], 2i128); // r = 2 assert_eq!(degree_poly(&quotient.clone().unwrap().1), 0); assert_eq!(quotient.unwrap().1[0], 2i128); } #[test] fn test_mul_poly() { //-2x + 1 let a: Seq<i128> = Seq::from_native_slice(&[1, -2, 0, 0, 0, 0]); // 2x³ + x -1 let b: Seq<i128> = Seq::from_native_slice(&[-1, 1, 0, 2, 0, 0]); //(-2x + 1)(2x³ + x -1) = -4 x^4 + 2 x^3 - 2 x^2 + 3 x - 1 let product = mul_poly(&a, &b, 5); //-4 x^4 + 2 x^3 - 2 x^2 + 3 x - 1 let p: Seq<i128> = Seq::from_native_slice(&[-1, 3, -2, 2, -4, 0]); for i in 0..6 { assert_eq!(product[i], p[i]); } } #[test] fn test_mul_poly_with_unequal_sized_poly() { //x¹² + x let a: Seq<i128> = Seq::from_native_slice(&[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); //x - 1 let b: Seq<i128> = Seq::from_native_slice(&[-1, 1]); mul_poly(&a, &b, 3); } #[test] fn test_poly_eea() { let h: Seq<i128> = Seq::from_native_slice(&[1, 0, 1, 0]); // x^3 + 2x + 1 let irr: Seq<i128> = Seq::from_native_slice(&[1, 2, 0, 1]); let h_pre_inv = extended_euclid(&h, &irr, 3); let h_inv = match h_pre_inv { Ok(v) => v, Err(_) => panic!("test, failed!"), }; //2x^2 -2x + 2 let expected: Seq<i128> = Seq::from_native_slice(&[2, 1, 2]); assert_eq!(h_inv.len(), expected.len()); for i in 0..h_inv.len() { assert_eq!(h_inv[i], expected[i]); } let scalar = mul_poly_irr(&h, &h_inv, &irr, 3); let one: Seq<i128> = Seq::from_native_slice(&[1, 0, 0, 0]); assert_eq!(scalar.len(), one.len()); for i in 0..scalar.len() { assert_eq!(one[i], scalar[i]); } }
use std::net::{IpAddr, UdpSocket}; use std::time::{Duration, Instant}; use std::fs; use ipconfig; fn main() -> std::io::Result<()> { let system_ip_addresses = get_system_ip_adresses(); let mut found_dhcp_server_ips: Vec<IpAddr> = Vec::new(); for ip_address in &system_ip_addresses { send_dhcp_broadcast(&ip_address.to_string()); for found_ip in listen_for_dhcp_broadcasts() { found_dhcp_server_ips.push(found_ip); } } let mut rogue_dhcp_ips: Vec<String> = Vec::new(); for found_dhcp_server_ip in found_dhcp_server_ips { let mut is_good = false; for system_ip_address in &system_ip_addresses { if &found_dhcp_server_ip == system_ip_address { is_good = true; } } if is_good == false { rogue_dhcp_ips.push(found_dhcp_server_ip.to_string()); } } if rogue_dhcp_ips.len() > 0 { println!("Found rogue DHCP servers: {:?}", rogue_dhcp_ips); } Ok(()) } fn listen_for_dhcp_broadcasts() -> Vec<IpAddr>{ let now = Instant::now(); let five_seconds = Duration::new(5,0); let socket = UdpSocket::bind("0.0.0.0:68").unwrap(); socket.set_read_timeout(Some(five_seconds)).expect("Setting read timeout failed for some reason"); let mut buf = [0; 10000]; let mut received_ips: Vec<IpAddr> = Vec::new(); // let mut ip_addr_string_vec: Vec<String> = Vec::new(); while now.elapsed() < five_seconds { let f = socket.recv_from(&mut buf); let f = match f { Ok((amt, src)) => Some((amt, src)), Err(_) => None, }; if f == None { continue } let m = f.as_ref().unwrap(); received_ips.push(m.1.ip()); } return received_ips } fn send_dhcp_broadcast(_given_ip: &String){ let dhcp_file = fs::read("broadcast.bin").expect("broadcast file read failed"); let socket = UdpSocket::bind(format!("{}:34254", &_given_ip)).unwrap(); socket.set_broadcast(true).expect("Setting broadcast failed"); socket.send_to(&dhcp_file, "255.255.255.255:67").expect("Couldn't send data"); } fn get_system_ip_adresses() -> Vec<IpAddr>{ let adapters = ipconfig::get_adapters(); let mut ip_addr_string_vec: Vec<IpAddr> = Vec::new(); for adapter in adapters { for m in adapter { for ip in m.ip_addresses() { if ip.is_ipv4() == true { ip_addr_string_vec.push(*ip); } } } } ip_addr_string_vec }
// This file is part of Darwinia. // // Copyright (C) 2018-2021 Darwinia Network // SPDX-License-Identifier: GPL-3.0 // // Darwinia is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Darwinia is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Darwinia. If not, see <https://www.gnu.org/licenses/>. // --- paritytech --- use sc_service::{ChainType, GenericChainSpec, Properties}; use sc_telemetry::TelemetryEndpoints; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::UncheckedInto, sr25519}; // --- darwinia-network --- use super::*; use darwinia_parachain_runtime::*; /// Specialized `ChainSpec` for the `Darwinia Parachain` parachain runtime. pub type ChainSpec = GenericChainSpec<GenesisConfig, Extensions>; pub const PARA_ID: u32 = 2003; const TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; /// Generate the session keys from individual elements. /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). fn session_keys(keys: AuraId) -> SessionKeys { SessionKeys { aura: keys } } fn properties() -> Properties { let mut properties = Properties::new(); properties.insert("ss58Format".into(), 18.into()); properties.insert("tokenDecimals".into(), 9.into()); properties.insert("tokenSymbol".into(), "RING".into()); properties } pub fn config() -> Result<ChainSpec, String> { ChainSpec::from_json_bytes(&include_bytes!("../../res/darwinia-parachain.json")[..]) } pub fn genesis_config() -> ChainSpec { fn genesis() -> GenesisConfig { let root: AccountId = array_bytes::hex_into_unchecked( "0x129d025b24257aabdefac93d00419f06a38e3a5e2314dd6866b16e8f205ce074", ); let invulnerables = [ // Darwinia Dev "0x7e8672b2c2ad0904ba6137de480eaa3b9476042f3f2ae08da033c4ccf2272d5a", "0xbe7e6c55feca7ffbfd961c93acdf1bc68bea91d758fb8da92f65c66bbf12ea74", // Way "0xea0f4185dd32c1278d7bbd3cdd2fbaec3ca29921a88c04c175401a0668d88e66", "0x56695000227fee2b4e2b15e892527250e47d4671e17f6e604cd67fb7213bbc19", // Xavier "0xb4f7f03bebc56ebe96bc52ea5ed3159d45a0ce3a8d7f082983c33ef133274747", "0x28b4a5e67767ec4aba8e8d99ac58481ec74e48185507f1552b1f8ba00994cf59", ] .iter() .map(|hex| { ( array_bytes::hex_into_unchecked(hex), array_bytes::hex2array_unchecked(hex).unchecked_into(), ) }) .collect::<Vec<_>>(); GenesisConfig { system: SystemConfig { code: wasm_binary_unwrap().into(), changes_trie_config: Default::default(), }, balances: BalancesConfig { balances: vec![ // Root (root.clone(), 100_000 * COIN), // Darwinia Dev ( array_bytes::hex_into_unchecked( "0x0a66532a23c418cca12183fee5f6afece770a0bb8725f459d7d1b1b598f91c49", ), 100_000 * COIN, ), ], }, parachain_info: ParachainInfoConfig { parachain_id: PARA_ID.into(), }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: 0, ..Default::default() }, session: SessionConfig { keys: invulnerables .iter() .cloned() .map(|(acc, aura)| { ( acc.clone(), // account id acc.clone(), // validator id session_keys(aura), // session keys ) }) .collect(), }, // no need to pass anything to aura, in fact it will panic if we do. Session will take care // of this. aura: Default::default(), aura_ext: Default::default(), sudo: SudoConfig { key: root }, parachain_system: Default::default(), } } return ChainSpec::from_genesis( "Darwinia Parachain", "Darwinia Parachain", ChainType::Live, genesis, vec![], Some( TelemetryEndpoints::new(vec![(TELEMETRY_URL.to_string(), 0)]) .expect("Darwinia Parachain telemetry url is valid; qed"), ), None, Some(properties()), Extensions { relay_chain: "polkadot".into(), para_id: PARA_ID, }, ); } pub fn development_config() -> ChainSpec { fn genesis() -> GenesisConfig { let root = get_account_id_from_seed::<sr25519::Public>("Alice"); let invulnerables = vec![( get_account_id_from_seed::<sr25519::Public>("Alice"), get_collator_keys_from_seed("Alice"), )]; GenesisConfig { system: SystemConfig { code: wasm_binary_unwrap().into(), changes_trie_config: Default::default(), }, balances: BalancesConfig { balances: invulnerables .iter() .cloned() .map(|(acc, _)| (acc, 100_000 * COIN)) .collect(), }, parachain_info: ParachainInfoConfig { parachain_id: PARA_ID.into(), }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: 0, ..Default::default() }, session: SessionConfig { keys: invulnerables .iter() .cloned() .map(|(acc, aura)| { ( acc.clone(), // account id acc.clone(), // validator id session_keys(aura), // session keys ) }) .collect(), }, // no need to pass anything to aura, in fact it will panic if we do. Session will take care // of this. aura: Default::default(), aura_ext: Default::default(), sudo: SudoConfig { key: root }, parachain_system: Default::default(), } } return ChainSpec::from_genesis( "Darwinia Parachain Dev", "Darwinia Parachain Dev", ChainType::Development, genesis, vec![], None, None, Some(properties()), Extensions { relay_chain: "rococo-local".into(), para_id: PARA_ID, }, ); }
use glow::HasContext as _; use glutin::{ event::{ModifiersState, WindowEvent}, event_loop::ControlFlow, window::{Window, WindowId}, PossiblyCurrent, WindowedContext, }; pub trait PyriteWindow { fn process_window_event(&mut self, event: WindowEvent) { match event { WindowEvent::ModifiersChanged(modifiers) => *self.modifiers_mut() = modifiers, WindowEvent::Resized(size) => self.context().resize(size), _ => (), } self.on_window_event(event) } fn on_window_event(&mut self, _event: WindowEvent) {} fn gl_render(&mut self, _flow: &mut ControlFlow) { if !self.try_swap_context() { return; } let size = self.window().inner_size(); unsafe { self.gl() .viewport(0, 0, size.width as i32, size.height as i32) }; self.render(); self.present(); } fn render(&mut self); /// Returns true if the window should rerender. fn update(&mut self) -> bool { true } fn modifiers_mut(&mut self) -> &mut ModifiersState; fn try_swap_context(&mut self) -> bool { if self.context().is_current() { return true; } let mut success = true; if let Some(mut context) = self.context_mut_opt().take() { context = match unsafe { context.make_current() } { Ok(new_context) => new_context, Err((new_context, err)) => { success = false; log::error!("error while switching context: {err:?}"); new_context } }; *self.context_mut_opt() = Some(context); } success } fn context_mut_opt(&mut self) -> &mut Option<WindowedContext<PossiblyCurrent>>; fn context_opt(&self) -> &Option<WindowedContext<PossiblyCurrent>>; fn context(&self) -> &WindowedContext<PossiblyCurrent> { self.context_opt().as_ref().unwrap() } fn gl(&self) -> &glow::Context; fn present(&mut self) { if let Err(err) = self.context_opt().as_ref().unwrap().swap_buffers() { log::error!("error occurred while swapping context buffers: {err:?}"); } } fn window(&self) -> &Window { self.context().window() } fn window_id(&self) -> WindowId { self.window().id() } fn request_redraw(&self) { self.window().request_redraw() } }
use drogue_client::{ error::{ClientError, ErrorInformation}, openid::{OpenIdTokenProvider, TokenInjector}, Context, }; use drogue_cloud_service_api::auth::device::authn::{ AuthenticationRequest, AuthenticationResponse, }; use reqwest::{Client, Response, StatusCode}; use url::Url; /// An authentication client backed by reqwest. #[derive(Clone, Debug)] pub struct ReqwestAuthenticatorClient { client: Client, auth_service_url: Url, token_provider: Option<OpenIdTokenProvider>, } impl ReqwestAuthenticatorClient { /// Create a new client instance. pub fn new(client: Client, url: Url, token_provider: Option<OpenIdTokenProvider>) -> Self { Self { client, auth_service_url: url, token_provider, } } pub async fn authenticate( &self, request: AuthenticationRequest, context: Context, ) -> Result<AuthenticationResponse, ClientError<reqwest::Error>> { let req = self .client .post(self.auth_service_url.clone()) .inject_token(&self.token_provider, context) .await?; let response: Response = req.json(&request).send().await.map_err(|err| { log::warn!("Error while authenticating {:?}: {}", request, err); Box::new(err) })?; match response.status() { StatusCode::OK => match response.json::<AuthenticationResponse>().await { Ok(result) => { log::debug!("Outcome for {:?} is {:?}", request, result); Ok(result) } Err(err) => { log::debug!("Authentication failed for {:?}. Result: {:?}", request, err); Err(ClientError::Request(format!( "Failed to decode service response: {}", err ))) } }, code => match response.json::<ErrorInformation>().await { Ok(result) => { log::debug!("Service reported error ({}): {}", code, result); Err(ClientError::Service(result)) } Err(err) => { log::debug!( "Authentication failed ({}) for {:?}. Result couldn't be decoded: {:?}", code, request, err ); Err(ClientError::Request(format!( "Failed to decode service error response: {}", err ))) } }, } } }
pub mod encryption; pub mod storage; pub mod constants;
use std::convert::{TryFrom, TryInto}; use std::fmt::{Display, Formatter}; use std::ops::{Add, Index, IndexMut, Mul, Neg}; use itertools::Itertools; use std::str::FromStr; /// A point in 2-space. Supports addition, scalar multiplication, manhattan_dist. #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct Point { pub x: isize, pub y: isize, } impl Point { pub fn manhattan_dist(&self, rhs: &Self) -> isize { let mut d0 = self.x - rhs.x; if d0 < Default::default() { d0 = -d0; } let mut d1 = self.y - rhs.y; if d1 < Default::default() { d1 = -d1; } d0 + d1 } pub fn rotate_deg(&self, deg: isize) -> Self { match deg { 0 | 360 => self.clone(), 90 | -270 => Self { x: -self.y, y: self.x, }, 180 | -180 => Self { x: -self.x, y: -self.y, }, 270 | -90 => Self { x: self.y, y: -self.x, }, _ => panic!("Bad rotation"), } } } impl Add for Point { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self { x: self.x + rhs.x, y: self.y + rhs.y, } } } impl Mul<isize> for Point { type Output = Self; fn mul(self, rhs: isize) -> Self::Output { Point { x: self.x * rhs, y: self.y * rhs, } } } impl Neg for Point { type Output = Self; fn neg(self) -> Self::Output { Point { x: -self.x, y: -self.y, } } } impl<T> From<&(T, T)> for Point where T: TryInto<isize>, (T, T): Clone, { fn from(p: &(T, T)) -> Self { Point::from(p.clone()) } } impl<T> From<(T, T)> for Point where T: TryInto<isize>, { fn from(p: (T, T)) -> Self { if let Ok(x) = p.0.try_into() { if let Ok(y) = p.1.try_into() { return Point { x, y }; } } panic!("Could not convert to Point") } } #[derive(Clone, Eq, PartialEq, Hash)] pub struct DenseStore<Glyph> { data: Vec<Glyph>, width: usize, } impl<Glyph: Clone> DenseStore<Glyph> { pub fn new(grid: &Vec<Vec<Glyph>>) -> Self { if grid.is_empty() { DenseStore { data: Vec::new(), width: 0, } } else { DenseStore { data: grid.iter().flatten().cloned().collect(), width: grid[0].len(), } } } pub fn get(&self, p: Point) -> Option<&Glyph> { let Point { x, y } = p; let width = self.width as isize; if let Ok(i) = usize::try_from(x + y * width) { return self.data.get(i); } None } pub fn get_mut(&mut self, p: Point) -> Option<&mut Glyph> { let Point { x, y } = p; let width = self.width as isize; if let Ok(i) = usize::try_from(x + y * width) { return self.data.get_mut(i); } None } pub fn tiles<'a>(&'a self) -> impl Iterator<Item = (&'a Glyph, Point)> + 'a { let width = self.width; self.data.iter().enumerate().map(move |(i, g)| { let y = (i / width) as isize; let x = (i % width) as isize; let p = (x, y).into(); (g, p) }) } pub fn tiles_mut(&mut self) -> impl Iterator<Item = (&mut Glyph, Point)> + '_ { let width = self.width; self.data.iter_mut().enumerate().map(move |(i, g)| { let y = (i / width) as isize; let x = (i % width) as isize; let p = (x, y).into(); (g, p) }) } pub fn width(&self) -> usize { self.width } pub fn height(&self) -> usize { self.data.len() / self.width } } impl<Glyph: Clone> Index<Point> for DenseStore<Glyph> { type Output = Glyph; fn index(&self, index: Point) -> &Self::Output { self.get(index).expect("No such point") } } impl<Glyph: Clone> IndexMut<Point> for DenseStore<Glyph> { fn index_mut(&mut self, index: Point) -> &mut Self::Output { self.get_mut(index).expect("No such point") } } impl<Glyph> Display for DenseStore<Glyph> where Glyph: Clone, Glyph: Into<char>, { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let s = self .data .windows(self.width) .map(|row| { row.iter() .map(|g| <Glyph as Into<char>>::into(g.clone())) .collect::<String>() }) .join("\n"); write!(f, "{}", s) } } impl<Glyph> FromStr for DenseStore<Glyph> where Glyph: Clone, char: Into<Glyph>, { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { let data = parse_grid(s); Ok(DenseStore::new(&data)) } } pub trait Grid { type Glyph; fn coord_transform(&self, p: Point) -> Point; fn data(&self) -> &Vec<Vec<Self::Glyph>>; fn data_mut(&mut self) -> &mut Vec<Vec<Self::Glyph>>; fn at(&self, p: Point) -> Option<&Self::Glyph> { let Point { x, y } = self.coord_transform(p); if let Ok(row) = usize::try_from(y) { if let Ok(col) = usize::try_from(x) { self.data() .get(row) .and_then(|row: &Vec<Self::Glyph>| row.get(col)) } else { None } } else { None } } fn at_mut(&mut self, p: Point) -> Option<&mut Self::Glyph> { let Point { x, y } = self.coord_transform(p); if let Ok(row) = usize::try_from(y) { if let Ok(col) = usize::try_from(x) { return Some(&mut self.data_mut()[row][col]); } } None } } pub fn parse_grid<Glyph>(glyph_str: &str) -> Vec<Vec<Glyph>> where char: Into<Glyph>, { glyph_str .lines() .map(|l| l.chars().map(|c| c.into()).collect()) .collect() } /// Dense Grid #[derive(Clone, Eq, PartialEq)] pub struct DenseGrid<Glyph> { data: Vec<Vec<Glyph>>, offset: Point, } impl<Glyph> DenseGrid<Glyph> where char: Into<Glyph>, Glyph: Clone, { pub fn new(src: &str) -> Self { DenseGrid { data: parse_grid(src), offset: Default::default(), } } pub fn with_offset(mut self, origin: Point) -> Self { self.offset = -origin; self } pub fn enumerate_tiles(&self) -> impl Iterator<Item = (Glyph, Point)> + '_ { self.data.iter().enumerate().flat_map(|(y, src_row)| { src_row.iter().enumerate().map(move |(x, g)| { let p = (x, y).into(); (g.clone(), p) }) }) } pub fn transform<F: FnMut(&Glyph, Point) -> Glyph>(&self, mut tile_mapper: F) -> Self { let data = self .data .iter() .enumerate() .map(|(y, src_row)| { let mut row = Vec::with_capacity(self.data[y as usize].len()); row.extend(src_row.iter().enumerate().map(|(x, g)| { let p = (x, y).into(); tile_mapper(g, p) })); row }) .collect(); Self { data, offset: self.offset, } } } impl<Glyph> Grid for DenseGrid<Glyph> { type Glyph = Glyph; fn coord_transform(&self, p: Point) -> Point { p + self.offset } fn data(&self) -> &Vec<Vec<Glyph>> { &self.data } fn data_mut(&mut self) -> &mut Vec<Vec<Glyph>> { &mut self.data } } impl<Glyph> Display for DenseGrid<Glyph> where Glyph: Clone, Glyph: Into<char>, { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let s = self .data .iter() .map(|row| { row.iter() .map(|g| <Glyph as Into<char>>::into(g.clone())) .collect::<String>() }) .join("\n"); write!(f, "{}", s) } } #[cfg(test)] mod tests { use crate::{parse_grid, Point}; #[test] fn add_test() { assert_eq!( Point { x: 2, y: 2 } + Point { x: 3, y: 4 }, Point { x: 5, y: 6 } ); } #[test] fn mul_test() { assert_eq!(Point { x: 3, y: 4 } * 5, Point { x: 15, y: 20 }); } #[test] fn into_test() { let p1: Point = (2, 2).into(); let p2: Point = (3, 4).into(); assert_eq!(p1 + p2, (5, 6).into()); } #[test] fn manhattan_dist_test() { let p0: Point = (0, 0).into(); let p1: Point = (1, 4).into(); assert_eq!(p0.manhattan_dist(&p1), 5); assert_eq!(p1.manhattan_dist(&p0), 5); } #[test] fn rotate_test() { let p: Point = (1, 0).into(); let p90 = p.rotate_deg(90); let p180 = p.rotate_deg(180); let p270 = p.rotate_deg(270); assert_eq!(p90, (0, 1).into()); assert_eq!(p180, (-1, 0).into()); assert_eq!(p270, (0, -1).into()); assert_eq!(p, p90.rotate_deg(-90)); assert_eq!(p, p180.rotate_deg(-180)); assert_eq!(p, p270.rotate_deg(-270)); } #[test] fn parse_grid_test() { #[derive(Debug, Eq, PartialEq)] enum Tiles { Space, Tree, } impl From<char> for Tiles { fn from(ch: char) -> Self { match ch { '#' => Tiles::Tree, '.' => Tiles::Space, _ => panic!("Invalid character"), } } } let in_str = "..#\n.#."; let data = parse_grid::<Tiles>(in_str); assert_eq!(data[0][2], Tiles::Tree); assert_eq!(data[1][1], Tiles::Tree); assert_eq!(data[0][0], Tiles::Space); } }
extern crate gl; extern crate glutin; extern crate chrono; extern crate byteorder; mod support; use cpal; use glutin::Context; use gl::types::*; use std::mem; use std::ptr; use std::str; use std::os::raw::c_void; use std::ffi::CString; use std::ffi::CStr; use std::sync::atomic::AtomicBool; use std::path::{Path, PathBuf}; use std::fs::File; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::env; use std::io::prelude::*; use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt}; use winit::{ElementState, VirtualKeyCode}; use chrono::prelude::*; use std::env::args; use std::process::exit; const SCREEN_WIDTH: f64 = 800.0; const SCREEN_HEIGHT: f64 = 600.0; enum RecordingEvent { Start(PathBuf), Stop(), Data(Vec<f32>), } fn main() { match args().skip(1).next() { Some(path) => play(path), _ => record() } } fn record() { let base_path = { let mut base = env::current_dir().unwrap(); base.push("recordings"); base.push(Local::now().format("%Y-%m-%d-%H:%M:%S").to_string()); base }; std::fs::create_dir_all(base_path.clone()); let local = Local::now(); // initialize the audio stuffs let event_loop = cpal::EventLoop::new(); // Default devices. let input_device = cpal::default_input_device().expect("Failed to get default input device"); let output_device = cpal::default_output_device().expect("Failed to get default output device"); println!("Using default input device: \"{}\"", input_device.name()); println!("Using default output device: \"{}\"", output_device.name()); // We'll try and use the same format between streams to keep it simple let mut format = input_device.default_output_format().expect("Failed to get default format"); format.data_type = cpal::SampleFormat::F32; // Build streams. println!("Attempting to build both streams with `{:?}`.", format); let input_stream_id = event_loop.build_input_stream(&input_device, &format).unwrap(); let output_stream_id = event_loop.build_output_stream(&output_device, &format).unwrap(); println!("Successfully built streams."); let recording = Arc::new(AtomicBool::new(false)); // The channel to send recording data. let (tx, rx) = std::sync::mpsc::sync_channel(1024); std::thread::spawn(move || { let mut file = None; loop { match rx.recv().unwrap() { RecordingEvent::Start(path) => { println!("Starting recording on path {:?}", path); file = Some(File::create(path).unwrap()); } RecordingEvent::Stop() => { file = None } RecordingEvent::Data(data) => { match file { Some(ref mut f) => { data.into_iter().for_each(|d| { f.write_f32::<BigEndian>(d); }); } None => { println!("Received data when not recording"); } } } } } }); event_loop.play_stream(input_stream_id.clone()); // event_loop.play_stream(output_stream_id.clone()); // Run the event loop on a separate thread. { let recording = recording.clone(); std::thread::spawn(move || { let mut was_recording = false; let mut count = 0; event_loop.run(move |id, data| { match data { cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::F32(buffer) } => { assert_eq!(id, input_stream_id); if recording.load(Relaxed) { if !was_recording { let mut path = base_path.to_path_buf(); path.push(format!("{:06}", count)); tx.send(RecordingEvent::Start(path)); was_recording = true; count += 1; } tx.send(RecordingEvent::Data(buffer.to_vec())); // send data } else { if was_recording { was_recording = false; tx.send(RecordingEvent::Stop()); } }; } cpal::StreamData::Output { buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer) } => { } _ => panic!("we're expecting f32 data"), } }); }); } // initialize the gl window and event loop let mut el = glutin::EventsLoop::new(); let wb = glutin::WindowBuilder::new().with_title("A fantastic window!"); let windowed_context = glutin::ContextBuilder::new() .build_windowed(wb, &el) .unwrap(); let windowed_context = unsafe { windowed_context.make_current().unwrap() }; println!( "Pixel format of the window's GL context: {:?}", windowed_context.get_pixel_format() ); let gl = support::load(&windowed_context.context()); let mut running = true; while running { el.poll_events(|event| { match event { glutin::Event::DeviceEvent { event, .. } => match event { glutin::DeviceEvent::Key(input) => { match input.virtual_keycode { Some(VirtualKeyCode::R) => { if input.state == ElementState::Pressed { recording.store(true, Relaxed); } else { recording.store(false, Relaxed); } } Some(VirtualKeyCode::Escape) => { if input.state == ElementState::Released { running = false; } } _ => () } } _ => () }, glutin::Event::WindowEvent { event, .. } => match event { glutin::WindowEvent::CloseRequested => running = false, glutin::WindowEvent::Resized(logical_size) => { let dpi_factor = windowed_context.window().get_hidpi_factor(); windowed_context .resize(logical_size.to_physical(dpi_factor)); } _ => (), }, _ => (), } }); let color = if recording.load(Relaxed) { [1.0, 0.0, 0.0, 1.0] } else { [0.2, 0.2, 0.8, 1.0] }; gl.draw_frame(color); windowed_context.swap_buffers().unwrap(); } } fn play(path: String) { println!("playing path {:?}", path); // initialize the audio stuffs let event_loop = cpal::EventLoop::new(); let input_device = cpal::default_input_device().expect("Failed to get default input device"); let output_device = cpal::default_output_device().expect("Failed to get default output device"); println!("Using default input device: \"{}\"", input_device.name()); println!("Using default output device: \"{}\"", output_device.name()); // We'll try and use the same format between streams to keep it simple let mut format = input_device.default_output_format().expect("Failed to get default format"); format.data_type = cpal::SampleFormat::F32; // Build streams. println!("Attempting to build both streams with `{:?}`.", format); let input_stream_id = event_loop.build_input_stream(&input_device, &format).unwrap(); let output_stream_id = event_loop.build_output_stream(&output_device, &format).unwrap(); println!("Successfully built streams."); event_loop.play_stream(output_stream_id.clone()); let mut file = File::open(path).unwrap(); let mut finished = false; event_loop.run(move |id, data| { if finished { exit(0); } match data { cpal::StreamData::Output { buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer) } => { assert_eq!(id, output_stream_id); for sample in buffer.iter_mut() { *sample = match file.read_f32::<BigEndian>() { Ok(s) => s, Err(err) => { finished = true; 0.0 } }; } } _ => () // panic!("we're expecting f32 data"), } }); }
// -*- mode:rust;mode:rust-playground -*- // snippet of code @ 2017-04-25 15:04:46 // === Rust Playground === // Execute the snippet with Ctl-Return // Remove the snippet completely with its dir and all files M-x `rust-playground-rm` enum Message { Move { x: i32, y: i32}, Write(String), } fn main() { let v = vec!["Hello".to_string(), "World".to_string()]; let vl: Vec<Message> = v.into_iter().map(Message::Write).collect(); println!("{:?}", vl[0]); }
use std::collections::HashSet; use std::fs; use std::io::Error as IoError; use std::path::PathBuf; use walkdir::{WalkDir, IntoIter as WalkerIter}; #[derive(Debug)] pub struct FileScanner<I> { dir_iter: I, exclude: HashSet<PathBuf>, current_walker: Option<WalkerIter>, } impl<I> FileScanner<I> where I: Iterator<Item = PathBuf>, { pub fn new<J, E>(dir_iter: J, exclude_iter: E) -> Result<FileScanner<I>, IoError> where J: IntoIterator<IntoIter = I, Item = PathBuf>, E: IntoIterator<Item = PathBuf>, { let mut exclude = HashSet::new(); // Enter canonical paths into exclude set. for exclude_path in exclude_iter { // Errors and returns if we see a bad path. // Perhaps we should just log it? exclude.insert(fs::canonicalize(exclude_path)?); } Ok(FileScanner { dir_iter: dir_iter.into_iter(), exclude: exclude, current_walker: None, }) } } impl<I> Iterator for FileScanner<I> where I: Iterator<Item = PathBuf>, { type Item = Result<PathBuf, IoError>; fn next(&mut self) -> Option<Self::Item> { // If we have a walker, continue iterating on it. if let Some(ref mut walker) = self.current_walker { match walker.next() { Some(Ok(entry)) => { // If we have a proper entry, canonicalize and check if it's excluded. let canonical = match fs::canonicalize(entry.path()) { Ok(path) => path, // If the path can't be canonicalized, pass up the error. Err(e) => return Some(Err(e)), }; if self.exclude.contains(&canonical) { // If it's excluded, skip it and recurse. walker.skip_current_dir(); self.next() } else { // If it's not excluded, return it. Some(Ok(canonical)) } } Some(Err(e)) => { // If we got an error, pass it up. Some(Err(e.into())) } None => { // If the walker is exhausted, clear it and recurse. self.current_walker = None; self.next() } } } else { // If we don't have a walker, go grab the next directory to search. if let Some(directory) = self.dir_iter.next() { // Make a new walker and recurse. self.current_walker = Some(WalkDir::new(directory).into_iter()); self.next() } else { // No more directories means we're done. Return None. None } } } }
// Copyright (c) 2015, <daggerbot@gmail.com> // All rights reserved. use ::display::Xid; /** Cursor identifier type. */ pub type Cursor = Xid;
#[doc = "Register `IER` reader"] pub type R = crate::R<IER_SPEC>; #[doc = "Register `IER` writer"] pub type W = crate::W<IER_SPEC>; #[doc = "Field `ADRDYIE` reader - ADC ready interrupt enable This bit is set and cleared by software to enable/disable the ADC Ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type ADRDYIE_R = crate::BitReader; #[doc = "Field `ADRDYIE` writer - ADC ready interrupt enable This bit is set and cleared by software to enable/disable the ADC Ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type ADRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EOSMPIE` reader - End of sampling flag interrupt enable This bit is set and cleared by software to enable/disable the end of the sampling phase interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOSMPIE_R = crate::BitReader; #[doc = "Field `EOSMPIE` writer - End of sampling flag interrupt enable This bit is set and cleared by software to enable/disable the end of the sampling phase interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOSMPIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EOCIE` reader - End of conversion interrupt enable This bit is set and cleared by software to enable/disable the end of conversion interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOCIE_R = crate::BitReader; #[doc = "Field `EOCIE` writer - End of conversion interrupt enable This bit is set and cleared by software to enable/disable the end of conversion interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EOSIE` reader - End of conversion sequence interrupt enable This bit is set and cleared by software to enable/disable the end of sequence of conversions interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOSIE_R = crate::BitReader; #[doc = "Field `EOSIE` writer - End of conversion sequence interrupt enable This bit is set and cleared by software to enable/disable the end of sequence of conversions interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOSIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `OVRIE` reader - Overrun interrupt enable This bit is set and cleared by software to enable/disable the overrun interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type OVRIE_R = crate::BitReader; #[doc = "Field `OVRIE` writer - Overrun interrupt enable This bit is set and cleared by software to enable/disable the overrun interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type OVRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AWD1IE` reader - Analog watchdog 1 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD1IE_R = crate::BitReader; #[doc = "Field `AWD1IE` writer - Analog watchdog 1 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AWD2IE` reader - Analog watchdog 2 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD2IE_R = crate::BitReader; #[doc = "Field `AWD2IE` writer - Analog watchdog 2 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AWD3IE` reader - Analog watchdog 3 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD3IE_R = crate::BitReader; #[doc = "Field `AWD3IE` writer - Analog watchdog 3 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type AWD3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EOCALIE` reader - End of calibration interrupt enable This bit is set and cleared by software to enable/disable the end of calibration interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOCALIE_R = crate::BitReader; #[doc = "Field `EOCALIE` writer - End of calibration interrupt enable This bit is set and cleared by software to enable/disable the end of calibration interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type EOCALIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CCRDYIE` reader - Channel Configuration Ready Interrupt enable This bit is set and cleared by software to enable/disable the channel configuration ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type CCRDYIE_R = crate::BitReader; #[doc = "Field `CCRDYIE` writer - Channel Configuration Ready Interrupt enable This bit is set and cleared by software to enable/disable the channel configuration ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] pub type CCRDYIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - ADC ready interrupt enable This bit is set and cleared by software to enable/disable the ADC Ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn adrdyie(&self) -> ADRDYIE_R { ADRDYIE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - End of sampling flag interrupt enable This bit is set and cleared by software to enable/disable the end of the sampling phase interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn eosmpie(&self) -> EOSMPIE_R { EOSMPIE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - End of conversion interrupt enable This bit is set and cleared by software to enable/disable the end of conversion interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn eocie(&self) -> EOCIE_R { EOCIE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - End of conversion sequence interrupt enable This bit is set and cleared by software to enable/disable the end of sequence of conversions interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn eosie(&self) -> EOSIE_R { EOSIE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Overrun interrupt enable This bit is set and cleared by software to enable/disable the overrun interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn ovrie(&self) -> OVRIE_R { OVRIE_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 7 - Analog watchdog 1 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn awd1ie(&self) -> AWD1IE_R { AWD1IE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Analog watchdog 2 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn awd2ie(&self) -> AWD2IE_R { AWD2IE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Analog watchdog 3 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn awd3ie(&self) -> AWD3IE_R { AWD3IE_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 11 - End of calibration interrupt enable This bit is set and cleared by software to enable/disable the end of calibration interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn eocalie(&self) -> EOCALIE_R { EOCALIE_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 13 - Channel Configuration Ready Interrupt enable This bit is set and cleared by software to enable/disable the channel configuration ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] pub fn ccrdyie(&self) -> CCRDYIE_R { CCRDYIE_R::new(((self.bits >> 13) & 1) != 0) } } impl W { #[doc = "Bit 0 - ADC ready interrupt enable This bit is set and cleared by software to enable/disable the ADC Ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn adrdyie(&mut self) -> ADRDYIE_W<IER_SPEC, 0> { ADRDYIE_W::new(self) } #[doc = "Bit 1 - End of sampling flag interrupt enable This bit is set and cleared by software to enable/disable the end of the sampling phase interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn eosmpie(&mut self) -> EOSMPIE_W<IER_SPEC, 1> { EOSMPIE_W::new(self) } #[doc = "Bit 2 - End of conversion interrupt enable This bit is set and cleared by software to enable/disable the end of conversion interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn eocie(&mut self) -> EOCIE_W<IER_SPEC, 2> { EOCIE_W::new(self) } #[doc = "Bit 3 - End of conversion sequence interrupt enable This bit is set and cleared by software to enable/disable the end of sequence of conversions interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn eosie(&mut self) -> EOSIE_W<IER_SPEC, 3> { EOSIE_W::new(self) } #[doc = "Bit 4 - Overrun interrupt enable This bit is set and cleared by software to enable/disable the overrun interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn ovrie(&mut self) -> OVRIE_W<IER_SPEC, 4> { OVRIE_W::new(self) } #[doc = "Bit 7 - Analog watchdog 1 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn awd1ie(&mut self) -> AWD1IE_W<IER_SPEC, 7> { AWD1IE_W::new(self) } #[doc = "Bit 8 - Analog watchdog 2 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn awd2ie(&mut self) -> AWD2IE_W<IER_SPEC, 8> { AWD2IE_W::new(self) } #[doc = "Bit 9 - Analog watchdog 3 interrupt enable This bit is set and cleared by software to enable/disable the analog watchdog interrupt. Note: The Software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn awd3ie(&mut self) -> AWD3IE_W<IER_SPEC, 9> { AWD3IE_W::new(self) } #[doc = "Bit 11 - End of calibration interrupt enable This bit is set and cleared by software to enable/disable the end of calibration interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn eocalie(&mut self) -> EOCALIE_W<IER_SPEC, 11> { EOCALIE_W::new(self) } #[doc = "Bit 13 - Channel Configuration Ready Interrupt enable This bit is set and cleared by software to enable/disable the channel configuration ready interrupt. Note: The software is allowed to write this bit only when ADSTART bit is cleared to 0 (this ensures that no conversion is ongoing)."] #[inline(always)] #[must_use] pub fn ccrdyie(&mut self) -> CCRDYIE_W<IER_SPEC, 13> { CCRDYIE_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "ADC interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IER_SPEC; impl crate::RegisterSpec for IER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ier::R`](R) reader structure"] impl crate::Readable for IER_SPEC {} #[doc = "`write(|w| ..)` method takes [`ier::W`](W) writer structure"] impl crate::Writable for IER_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets IER to value 0"] impl crate::Resettable for IER_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::path::PathBuf; use std::process; use std::thread; use std::time::Duration; use druid::widget::{Flex, Label}; use druid::{ AppDelegate, AppLauncher, Command, Data, DelegateCtx, Env, Lens, Selector, Target, Widget, WidgetExt, WindowDesc, }; const TICK: Selector<String> = Selector::new("tick"); #[cfg(debug_assertions)] pub fn resource_path(end: PathBuf) -> PathBuf { // Relative path for debug builds end } #[cfg(not(debug_assertions))] pub fn resource_path(end: PathBuf) -> PathBuf { // Path relative_path to current executable for release builds match std::env::current_exe() { Ok(mut p) => { p.pop(); p.join(end) } Err(_) => panic!("Can't locate current directory"), } } #[derive(Data, Lens, Clone)] pub struct State { time: String, } struct Delegate; impl AppDelegate<State> for Delegate { fn command( &mut self, _ctx: &mut DelegateCtx, _target: Target, cmd: &Command, data: &mut State, _env: &Env, ) -> bool { if let Some(time) = cmd.get(TICK) { data.time = time.clone(); false } else { false } } } fn main() { let main_window = WindowDesc::new(ui_builder); let data = State { time: "".to_string(), }; let launcher = AppLauncher::with_window(main_window); let sink = launcher.get_external_handle(); let delegate = Delegate {}; thread::spawn(move || { loop { // Executable path based on OS #[cfg(target_os = "macos")] let relative_path = "resources/macos/clock"; #[cfg(target_os = "linux")] let relative_path = "resources/linux/clock"; #[cfg(target_os = "windows")] let relative_path = "resources/windows/clock.exe"; // Get current unix time by calling "clock" executable let absolute_path = resource_path(PathBuf::from(&relative_path)) .canonicalize() .expect("couldn't build canonical path"); let output = process::Command::new(absolute_path) .output() .expect("couldn't spawn clock command"); let unix_time = String::from_utf8(output.stdout).expect("couldn't parse datetime"); // Send result to GUI thread sink.submit_command(TICK, unix_time, None) .expect("Failed to submit command"); // Sleep one second thread::sleep(Duration::from_secs(1)); } }); launcher .delegate(delegate) .use_simple_logger() .launch(data) .expect("failed to launch"); } fn ui_builder() -> impl Widget<State> { let label = Label::dynamic(|data: &State, _env| format!("Time: {}", data.time.clone())) .padding(5.0) .center(); Flex::column().with_child(label) }
#![a = {enum b {
#[doc = "Register `PWR_WKUPFR` reader"] pub type R = crate::R<PWR_WKUPFR_SPEC>; #[doc = "Field `WKUPF1` reader - WKUPF1"] pub type WKUPF1_R = crate::BitReader; #[doc = "Field `WKUPF2` reader - WKUPF2"] pub type WKUPF2_R = crate::BitReader; #[doc = "Field `WKUPF3` reader - WKUPF3"] pub type WKUPF3_R = crate::BitReader; #[doc = "Field `WKUPF4` reader - WKUPF4"] pub type WKUPF4_R = crate::BitReader; #[doc = "Field `WKUPF5` reader - WKUPF5"] pub type WKUPF5_R = crate::BitReader; #[doc = "Field `WKUPF6` reader - WKUPF6"] pub type WKUPF6_R = crate::BitReader; impl R { #[doc = "Bit 0 - WKUPF1"] #[inline(always)] pub fn wkupf1(&self) -> WKUPF1_R { WKUPF1_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - WKUPF2"] #[inline(always)] pub fn wkupf2(&self) -> WKUPF2_R { WKUPF2_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - WKUPF3"] #[inline(always)] pub fn wkupf3(&self) -> WKUPF3_R { WKUPF3_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - WKUPF4"] #[inline(always)] pub fn wkupf4(&self) -> WKUPF4_R { WKUPF4_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - WKUPF5"] #[inline(always)] pub fn wkupf5(&self) -> WKUPF5_R { WKUPF5_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - WKUPF6"] #[inline(always)] pub fn wkupf6(&self) -> WKUPF6_R { WKUPF6_R::new(((self.bits >> 5) & 1) != 0) } } #[doc = "Not reset by wakeup from Standby mode but by any Application reset (NRST, IWDG, ...)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pwr_wkupfr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PWR_WKUPFR_SPEC; impl crate::RegisterSpec for PWR_WKUPFR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pwr_wkupfr::R`](R) reader structure"] impl crate::Readable for PWR_WKUPFR_SPEC {} #[doc = "`reset()` method sets PWR_WKUPFR to value 0"] impl crate::Resettable for PWR_WKUPFR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `WHMONR` reader"] pub type R = crate::R<WHMONR_SPEC>; #[doc = "Field `WHITMON` reader - cache write-hit monitor counter"] pub type WHITMON_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - cache write-hit monitor counter"] #[inline(always)] pub fn whitmon(&self) -> WHITMON_R { WHITMON_R::new(self.bits) } } #[doc = "DCACHE write-hit monitor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`whmonr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct WHMONR_SPEC; impl crate::RegisterSpec for WHMONR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`whmonr::R`](R) reader structure"] impl crate::Readable for WHMONR_SPEC {} #[doc = "`reset()` method sets WHMONR to value 0"] impl crate::Resettable for WHMONR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#![feature( auto_traits, iter_intersperse, negative_impls, stmt_expr_attributes, trait_alias )] #![allow(incomplete_features)] #![cfg_attr(debug_assertions, allow(dead_code, unused_imports, unused_variables))] mod assembunny; mod astar; mod mat2; mod parsers; mod prelude; #[macro_use] mod test_helpers; mod vec2; mod vec3; use anyhow::anyhow; use aoc_proc_macro::generate_module_list; use prelude::IterEx; use std::fmt::{self, Display}; use std::io::Write; use std::sync::{mpsc, Arc, Mutex}; use std::thread; generate_module_list!(DAY_LIST; day01[pt1, pt2]: parse, day02[pt1, pt2]: parse, day03[pt1, pt2]: parse, day04[pt1, pt2]: parse, day05[pt1, pt2], day06[pt1, pt2]: parse, day07[pt1, pt2]: parse, day08[pts]: parse, day09[pt1, pt2], day10[pts]: parse, day11[pt1, pt2]: parse, day12[pt1, pt2]: parse, day13[pt1, pt2]: parse, day14[pt1, pt2], day15[pt1, pt2]: parse, day16[pt1, pt2]: parse, day17[pt1, pt2]: parse, day18[pt1, pt2]: parse, day19[pt1, pt2]: parse, day20[pt1, pt2]: parse, day21[pt1, pt2]: parse, day22[pt1, pt2]: parse, day23[pt1, pt2]: parse, day24[pts]: parse, day25[pt]: parse, ); #[derive(Clone, Copy, PartialEq, Eq)] enum TaskState { Pending, Running, Done, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct RepeatChar(char, usize); impl Display for RepeatChar { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; for _ in 0..self.1 { f.write_char(self.0)?; } Ok(()) } } // Used on main thread struct TaskTracker { module_name: &'static str, part_name: &'static str, state: TaskState, output: Option<Result<String, anyhow::Error>>, } // Used on worker thread struct TaskWork { input: String, function: fn(&str) -> Result<String, anyhow::Error>, } // Sent from worker thread to main thread enum TaskUpdate { WorkStarted(usize), WorkDone(usize, Result<String, anyhow::Error>), } fn pop_work(work_queue: &Mutex<Vec<Option<TaskWork>>>) -> Option<(usize, TaskWork)> { let mut work_queue = work_queue.lock().unwrap(); loop { let len = work_queue.len(); match work_queue.pop()? { Some(work) => return Some((len - 1, work)), None => continue, } } } fn init_progress<W: Write>(out: &mut W) -> crossterm::Result<()> { use crossterm::{ queue, style::{Print, PrintStyledContent, Stylize}, }; queue!( out, PrintStyledContent("\nAdvent".red().bold()), Print(" "), PrintStyledContent("of".white()), Print(" "), PrintStyledContent("Code".green().bold()), Print(" "), PrintStyledContent("2016".blue()), Print("\n\n") )?; out.flush()?; Ok(()) } fn update_progress<W: Write>(out: &mut W, tasks: &Vec<TaskTracker>) -> crossterm::Result<()> { use arrayvec::ArrayVec; use crossterm::{ cursor::MoveUp, queue, style::{style, Print, PrintStyledContent, StyledContent, Stylize}, terminal::{Clear, ClearType}, }; let total = tasks.len(); let completed = tasks .iter() .filter(|task| task.state == TaskState::Done) .count(); queue!( out, MoveUp(1), Clear(ClearType::CurrentLine), Print('['), PrintStyledContent(style(RepeatChar('=', completed)).white()), PrintStyledContent(style('>').white()), Print(RepeatChar(' ', total - completed)), Print("] ") )?; for sections in tasks .iter() .filter(|task| task.state == TaskState::Running) .map(|task| { let mut sections = ArrayVec::<StyledContent<&'static str>, 3>::new(); sections.push(task.module_name.green()); sections.push(style(" ")); sections.push(task.part_name.blue().bold()); sections }) .intersperse({ let mut section = ArrayVec::new(); section.push(", ".grey()); section }) .limit(10, || { let mut section = ArrayVec::new(); section.push("...".grey()); section }) { for section in sections { queue!(out, PrintStyledContent(section))?; } } queue!(out, Print('\n'))?; out.flush()?; Ok(()) } fn output_results<W: Write>(out: &mut W, tasks: &Vec<TaskTracker>) -> crossterm::Result<()> { use crossterm::{ cursor::MoveUp, queue, style::{style, Print, PrintStyledContent, Stylize}, terminal::{Clear, ClearType}, }; debug_assert!(tasks .iter() .all(|task| task.state == TaskState::Done && task.output.is_some())); queue!(out, MoveUp(1), Clear(ClearType::CurrentLine), Print("\n"))?; for task in tasks { let output = task.output.as_ref().unwrap().as_ref(); let is_simple = output.is_ok() && !output.unwrap().contains("\n"); queue!( out, PrintStyledContent(task.module_name.blue().bold()), Print(' '), PrintStyledContent(task.part_name.green().bold()) )?; if is_simple { queue!( out, Print(' '), PrintStyledContent(style(output.unwrap()).white()), Print('\n') )?; continue; } match output { Ok(value) => { queue!(out, Print('\n'), PrintStyledContent(style(value).white()))?; } Err(err) => { queue!( out, PrintStyledContent(" error\n".red().bold()), PrintStyledContent(style(err).red()) )?; } } queue!(out, Print('\n'))?; } out.flush()?; Ok(()) } fn main() { let default_panic_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { let stderr = std::io::stderr(); let mut stderr = stderr.lock(); default_panic_hook(panic_info); let _ = stderr.write(b"\n"); let _ = stderr.flush(); })); let exclusive_day = std::env::args().skip(1).next(); let (mut task_trackers, task_work): (Vec<_>, Vec<_>) = DAY_LIST .iter() .cloned() .filter(|&(module_name, _)| { if let Some(exclusive_day) = &exclusive_day { module_name.contains(exclusive_day) } else { true } }) .flat_map(|(module_name, parts)| { let input = std::fs::read_to_string(format!("./data/{}.txt", module_name)); parts .iter() .cloned() .map(move |(part_name, function)| match &input { Ok(input) => ( TaskTracker { module_name, part_name, state: TaskState::Pending, output: None, }, Some(TaskWork { input: input.clone(), function, }), ), Err(err) => ( TaskTracker { module_name, part_name, state: TaskState::Done, output: Some(Err(anyhow!( "cannot read input file ./data/{}.txt ({})", module_name, err ))), }, None, ), }) }) .unzip(); if task_trackers.len() == 0 { println!("No tasks to run"); return; } let (result_sender, result_receiver) = mpsc::channel::<TaskUpdate>(); let work_count = task_work.iter().filter(|work| work.is_some()).count(); let work_queue = Arc::new(Mutex::new(task_work)); let worker_threads = (0..(num_cpus::get() - 1).max(1).min(work_count)) .map(|thread_idx| { let work_queue = work_queue.clone(); let result_sender = result_sender.clone(); thread::Builder::new() .name(format!("worker thread {}", thread_idx)) .spawn(move || { while let Some((task_index, work)) = pop_work(&work_queue) { result_sender .send(TaskUpdate::WorkStarted(task_index)) .unwrap(); let result = std::panic::catch_unwind(move || (work.function)(&work.input)) .unwrap_or_else(|_| Err(anyhow!("task panicked"))); result_sender .send(TaskUpdate::WorkDone(task_index, result)) .unwrap(); } }) .unwrap() }) .collect::<Vec<_>>(); let stdout = std::io::stdout(); init_progress(&mut stdout.lock()).unwrap(); let mut work_left = work_count; while work_left > 0 { match result_receiver.recv().unwrap() { TaskUpdate::WorkStarted(idx) => { task_trackers[idx].state = TaskState::Running; } TaskUpdate::WorkDone(idx, result) => { let task = &mut task_trackers[idx]; task.state = TaskState::Done; task.output = Some(result); work_left -= 1; } } update_progress(&mut stdout.lock(), &task_trackers).unwrap(); } output_results(&mut stdout.lock(), &task_trackers).unwrap(); for worker_thread in worker_threads { worker_thread.join().unwrap(); } }
/* Copyright 2019-2023 Didier Plaindoux Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::meta::syntax::ASTParsec; use crate::meta::token::Token::{AllAtom, Atom}; use crate::meta::token::{First, Token}; impl First<char> for ASTParsec { fn first(&self) -> Vec<Token<char>> { match self { ASTParsec::PIdent(_) => vec![AllAtom], ASTParsec::PChar(c) => vec![Atom(c.clone())], ASTParsec::PString(s) => s.chars().next().map(|c| vec![Atom(c)]).unwrap_or(vec![]), ASTParsec::PBind(_, p) => p.first(), ASTParsec::PCode(_) => vec![AllAtom], ASTParsec::PMap(p, _) => p.first(), ASTParsec::PSequence(p, q) => { let p = p.first(); if p.len() > 0 { return p; } q.first() } ASTParsec::PChoice(p, q) => { let mut p = p.first(); p.append(&mut q.first()); p } ASTParsec::PNot(_) => vec![], ASTParsec::PTry(p) => p.first(), ASTParsec::PCheck(p) => p.first(), ASTParsec::POptional(p) => p.first(), // TODO ASTParsec::PRepeat(true, p) => p.first(), // TODO ASTParsec::PRepeat(false, p) => p.first(), ASTParsec::PLookahead(p) => p.first(), } } }
#[macro_use] extern crate log; use sled; use structopt::StructOpt; mod controller; mod input; use input::bot; use input::web_api::server; use input::web_api::server::{PasswordDatabase, State}; mod errors; #[derive(StructOpt)] #[structopt(name = "homeautomation")] struct Opt { /// port to bind to and listen for traffic #[structopt(short = "p", long = "port", default_value = "443")] port: u16, /// port to which telegram bot traffic should be send #[structopt(short = "e", long = "external-port", default_value = "443")] external_port: u16, /// telegram bot token #[structopt(short = "t", long = "token")] token: String, /// domain to which telegram bot traffic should be send #[structopt(short = "d", long = "domain")] domain: String, #[structopt(short = "a", long = "admin-password")] password: String, #[structopt(short = "i", long = "allowed-telegram-ids")] valid_ids: Vec<i64>, /// secret url part on which sensor data is recieved #[structopt(short = "h", long = "ha-key")] ha_key: String, } #[actix_rt::main] async fn main() { let opt = Opt::from_args(); errors::setup_logging(2).unwrap(); let db = sled::Config::default() //651ms .path("database") .flush_every_ms(None) //do not flush to disk unless explicitly asked .cache_capacity(1024 * 1024 * 32) //32 mb cache .open() .unwrap(); let mut passw_db = PasswordDatabase::from_db(&db).unwrap(); passw_db.add_admin(&opt.password).unwrap(); let (controller_tx, controller_rx) = crossbeam_channel::unbounded(); let (joblist, _waker_thread) = input::jobs::Jobs::setup(controller_tx.clone(), db.clone()).unwrap(); let wakeup = input::jobs::WakeUp::setup(db.clone(), joblist.clone()).unwrap(); let (youtube_dl, _downloader_thread) = input::YoutubeDownloader::init(opt.token.clone(), db.clone()) .await .unwrap(); let (mpd_status, _mpd_watcher_thread, _updater_tx) = input::MpdStatus::start_updating().unwrap(); let _controller_thread = controller::start(controller_rx, mpd_status.clone(), wakeup.clone()).unwrap(); let state = State::new( passw_db, controller_tx.clone(), joblist, wakeup, youtube_dl, opt.token.clone(), opt.valid_ids.clone(), ); //start the webserver let _web_handle = server::start_webserver( state, opt.port, opt.domain.clone(), opt.ha_key.clone(), ); bot::set_webhook( &opt.domain, &opt.token, opt.external_port, ) .await .unwrap(); loop { std::thread::park(); } }
mod config; use config::{PREFIX, TOKEN}; use serde_json::value::Value; use serenity::async_trait; use serenity::client::{Client, Context, EventHandler}; use serenity::model::channel::Message; use std::collections::HashMap; use std::fs::File; fn search_game(game: String) -> Option<i64> { let file = File::open("games.json").unwrap(); let json: Value = serde_json::from_reader(file).unwrap(); for app in json["response"]["apps"].as_array().unwrap() { if app["name"].as_str().unwrap() == game { return Some(app["appid"].as_i64().unwrap()); } } None } struct Handler; #[async_trait] impl EventHandler for Handler { async fn message(&self, ctx: Context, msg: Message) { if msg.content.starts_with(PREFIX) { let content = &*msg.content.replace(PREFIX, ""); let mut cmd = content.split(" ").collect::<Vec<&str>>(); match cmd[0] { "bara" => { msg.reply(ctx, "https://www.youtube.com/watch?v=APJZeNY6dKo") .await; } "help" => { msg.reply(ctx, "Commands:\n•bara \n•nekopara \n•price\n•TellHim") .await; } "TellHim" => { msg.reply(ctx, "Who asked Freddie").await; } "EyeBurner" => { msg.reply(ctx, "https://ibb.co/3Frj6m4").await; } "players" => { cmd.remove(0); let game = cmd.join(" "); msg.reply(ctx,format!("there are {} degenerates playing {}\n https://tenor.com/view/capibara-gif-22235175",reqwest::get(format!("https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?appid={}",search_game(game.clone()).unwrap())) .await.unwrap() .json::<Value>() .await.unwrap()["response"]["player_count"].as_i64().unwrap(),game)).await; } //pog "price" => { cmd.remove(0); let game = cmd.join(" "); let id = search_game(game).unwrap(); msg.reply( ctx, format!( "It costs {}", reqwest::get(format!( "http://store.steampowered.com/api/appdetails?appids={}", id )) .await .unwrap() .json::<Value>() .await .unwrap()[id.to_string()]["data"]["price_overview"]["final_formatted"] .as_str() .unwrap() ), ) .await; } _ => {} } } } } #[tokio::main] async fn main() { let mut client = Client::builder(TOKEN) .event_handler(Handler) .await .expect("Error creating client"); client.start().await; }
pub fn thing() { println!("I am a thing!"); }
#[doc = "Port output data register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [out](out) module"] pub type OUT = crate::Reg<u32, _OUT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OUT; #[doc = "`read()` method returns [out::R](out::R) reader structure"] impl crate::Readable for OUT {} #[doc = "`write(|w| ..)` method takes [out::W](out::W) writer structure"] impl crate::Writable for OUT {} #[doc = "Port output data register"] pub mod out; #[doc = "Port output data set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [out_clr](out_clr) module"] pub type OUT_CLR = crate::Reg<u32, _OUT_CLR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OUT_CLR; #[doc = "`read()` method returns [out_clr::R](out_clr::R) reader structure"] impl crate::Readable for OUT_CLR {} #[doc = "`write(|w| ..)` method takes [out_clr::W](out_clr::W) writer structure"] impl crate::Writable for OUT_CLR {} #[doc = "Port output data set register"] pub mod out_clr; #[doc = "Port output data clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [out_set](out_set) module"] pub type OUT_SET = crate::Reg<u32, _OUT_SET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OUT_SET; #[doc = "`read()` method returns [out_set::R](out_set::R) reader structure"] impl crate::Readable for OUT_SET {} #[doc = "`write(|w| ..)` method takes [out_set::W](out_set::W) writer structure"] impl crate::Writable for OUT_SET {} #[doc = "Port output data clear register"] pub mod out_set; #[doc = "Port output data invert register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [out_inv](out_inv) module"] pub type OUT_INV = crate::Reg<u32, _OUT_INV>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OUT_INV; #[doc = "`read()` method returns [out_inv::R](out_inv::R) reader structure"] impl crate::Readable for OUT_INV {} #[doc = "`write(|w| ..)` method takes [out_inv::W](out_inv::W) writer structure"] impl crate::Writable for OUT_INV {} #[doc = "Port output data invert register"] pub mod out_inv; #[doc = "Port input state register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [in_](in_) module"] pub type IN = crate::Reg<u32, _IN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IN; #[doc = "`read()` method returns [in_::R](in_::R) reader structure"] impl crate::Readable for IN {} #[doc = "Port input state register"] pub mod in_; #[doc = "Port interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"] pub type INTR = crate::Reg<u32, _INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR; #[doc = "`read()` method returns [intr::R](intr::R) reader structure"] impl crate::Readable for INTR {} #[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"] impl crate::Writable for INTR {} #[doc = "Port interrupt status register"] pub mod intr; #[doc = "Port interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"] pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASK; #[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"] impl crate::Readable for INTR_MASK {} #[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"] impl crate::Writable for INTR_MASK {} #[doc = "Port interrupt mask register"] pub mod intr_mask; #[doc = "Port interrupt masked status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"] pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASKED; #[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"] impl crate::Readable for INTR_MASKED {} #[doc = "Port interrupt masked status register"] pub mod intr_masked; #[doc = "Port interrupt set register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"] pub type INTR_SET = crate::Reg<u32, _INTR_SET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_SET; #[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"] impl crate::Readable for INTR_SET {} #[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"] impl crate::Writable for INTR_SET {} #[doc = "Port interrupt set register"] pub mod intr_set; #[doc = "Port interrupt configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_cfg](intr_cfg) module"] pub type INTR_CFG = crate::Reg<u32, _INTR_CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_CFG; #[doc = "`read()` method returns [intr_cfg::R](intr_cfg::R) reader structure"] impl crate::Readable for INTR_CFG {} #[doc = "`write(|w| ..)` method takes [intr_cfg::W](intr_cfg::W) writer structure"] impl crate::Writable for INTR_CFG {} #[doc = "Port interrupt configuration register"] pub mod intr_cfg; #[doc = "Port configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub type CFG = crate::Reg<u32, _CFG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFG; #[doc = "`read()` method returns [cfg::R](cfg::R) reader structure"] impl crate::Readable for CFG {} #[doc = "`write(|w| ..)` method takes [cfg::W](cfg::W) writer structure"] impl crate::Writable for CFG {} #[doc = "Port configuration register"] pub mod cfg; #[doc = "Port input buffer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cfg_in](cfg_in) module"] pub type CFG_IN = crate::Reg<u32, _CFG_IN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFG_IN; #[doc = "`read()` method returns [cfg_in::R](cfg_in::R) reader structure"] impl crate::Readable for CFG_IN {} #[doc = "`write(|w| ..)` method takes [cfg_in::W](cfg_in::W) writer structure"] impl crate::Writable for CFG_IN {} #[doc = "Port input buffer configuration register"] pub mod cfg_in; #[doc = "Port output buffer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cfg_out](cfg_out) module"] pub type CFG_OUT = crate::Reg<u32, _CFG_OUT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFG_OUT; #[doc = "`read()` method returns [cfg_out::R](cfg_out::R) reader structure"] impl crate::Readable for CFG_OUT {} #[doc = "`write(|w| ..)` method takes [cfg_out::W](cfg_out::W) writer structure"] impl crate::Writable for CFG_OUT {} #[doc = "Port output buffer configuration register"] pub mod cfg_out; #[doc = "Port SIO configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cfg_sio](cfg_sio) module"] pub type CFG_SIO = crate::Reg<u32, _CFG_SIO>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFG_SIO; #[doc = "`read()` method returns [cfg_sio::R](cfg_sio::R) reader structure"] impl crate::Readable for CFG_SIO {} #[doc = "`write(|w| ..)` method takes [cfg_sio::W](cfg_sio::W) writer structure"] impl crate::Writable for CFG_SIO {} #[doc = "Port SIO configuration register"] pub mod cfg_sio; #[doc = "Port GPIO5V input buffer configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cfg_in_gpio5v](cfg_in_gpio5v) module"] pub type CFG_IN_GPIO5V = crate::Reg<u32, _CFG_IN_GPIO5V>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CFG_IN_GPIO5V; #[doc = "`read()` method returns [cfg_in_gpio5v::R](cfg_in_gpio5v::R) reader structure"] impl crate::Readable for CFG_IN_GPIO5V {} #[doc = "`write(|w| ..)` method takes [cfg_in_gpio5v::W](cfg_in_gpio5v::W) writer structure"] impl crate::Writable for CFG_IN_GPIO5V {} #[doc = "Port GPIO5V input buffer configuration register"] pub mod cfg_in_gpio5v;
use { bytes::{Buf, Bytes}, futures::prelude::*, http::header::{Entry, HeaderMap}, reqwest::IntoUrl, std::{mem, net::SocketAddr}, tsukuyomi::{ app::REMOTE_ADDR, chain, extractor::{self, ExtractorExt}, // future::TryFuture, output::{IntoResponse, ResponseBody}, Error, Extractor, }, }; #[derive(Debug)] pub struct Client { client: reqwest::r#async::Client, headers: HeaderMap, remote_addr: Option<SocketAddr>, } impl Client { pub fn send_forwarded_request( self, url: impl IntoUrl, ) -> impl Future<Error = Error, Item = ProxyResponse> { let Self { client, mut headers, remote_addr, } = self; headers.remove("host"); match headers .entry("x-forwarded-for") .expect("should be a valid header name") { Entry::Occupied(mut entry) => { let addrs = match remote_addr { Some(remote_addr) => { format!("{}, {}", entry.get().to_str().unwrap(), remote_addr) .parse() .unwrap() } None => entry.get().clone(), }; entry.insert(addrs); } Entry::Vacant(entry) => { if let Some(remote_addr) = remote_addr { entry.insert(remote_addr.to_string().parse().unwrap()); } } } client .get(url) .headers(headers) .send() .map(|resp| ProxyResponse { resp }) .map_err(tsukuyomi::error::internal_server_error) } } pub struct ProxyResponse { resp: reqwest::r#async::Response, } impl ProxyResponse { pub fn receive_all(mut self) -> impl Future<Error = Error, Item = impl IntoResponse> { let mut response = http::Response::new(()); *response.status_mut() = self.resp.status(); mem::swap(response.headers_mut(), self.resp.headers_mut()); let content_length = response .headers() .get("content-length") .and_then(|h| h.to_str().ok()) .and_then(|s| s.parse::<usize>().ok()) .unwrap_or(0); self.resp .into_body() .fold(Vec::with_capacity(content_length), |mut acc, chunk| { acc.extend_from_slice(&*chunk); Ok::<_, reqwest::Error>(acc) }) .map(move |chunks| response.map(|_| chunks)) .map_err(tsukuyomi::error::internal_server_error) } } impl IntoResponse for ProxyResponse { fn into_response(mut self) -> tsukuyomi::output::Response { let mut response = http::Response::new(()); *response.status_mut() = self.resp.status(); mem::swap(response.headers_mut(), self.resp.headers_mut()); let body_stream = ResponseBody::wrap_stream( self.resp .into_body() .map(|chunk| chunk.collect::<Bytes>().into()), ); response.map(|_| body_stream) } } pub fn proxy_client( client: reqwest::r#async::Client, ) -> impl Extractor< Output = (Client,), // Error = tsukuyomi::Error, Extract = impl TryFuture<Ok = (Client,), Error = tsukuyomi::Error> + Send + 'static, > { chain![ extractor::local::clone(&REMOTE_ADDR).optional(), extractor::header::headers(), extractor::value(client), ] .map(|remote_addr, headers, client| Client { client, headers, remote_addr, }) }
use super::line_segment::*; use std::cmp::Ordering; #[derive(Debug, Eq)] pub enum Event { UpperPoint(LineSegment), // Top point on a LineSegment CrossPoint(Point, LineSegment, LineSegment), // Intersection between two LineSegments LowerPoint(LineSegment), // Bottom point on a LineSegment } impl Event { // Value used that orders events in the order the sweep-line reaches them. fn cmp_value(&self) -> i32 { match self { Event::UpperPoint(line) => line.top_endpoint()[Y], Event::LowerPoint(line) => line.bot_endpoint()[Y], Event::CrossPoint(p, _, _) => p[Y], } } } impl Ord for Event { fn cmp(&self, other: &Event) -> Ordering { let self_top = self.cmp_value(); let other_top = other.cmp_value(); if self_top < other_top { Ordering::Less } else if self_top > other_top { Ordering::Greater } else { Ordering::Equal } } } impl PartialEq for Event { fn eq(&self, other: &Event) -> bool { self.cmp(other) == Ordering::Equal } } impl PartialOrd for Event { fn partial_cmp(&self, other: &Event) -> Option<Ordering> { Some(self.cmp(other)) } }
use crate::{Net, Spec, DEFAULT_TX_PROPOSAL_WINDOW}; use ckb_types::{ core::{capacity_bytes, Capacity, TransactionView}, packed::CellOutputBuilder, prelude::*, }; use log::info; pub struct DifferentTxsWithSameInput; impl Spec for DifferentTxsWithSameInput { crate::name!("different_txs_with_same_input"); fn run(&self, net: &mut Net) { let node0 = &net.nodes[0]; node0.generate_blocks((DEFAULT_TX_PROPOSAL_WINDOW.1 + 2) as usize); let tx_hash_0 = node0.generate_transaction(); info!("Generate 2 txs with same input"); let tx1 = node0.new_transaction(tx_hash_0.clone()); let tx2_temp = node0.new_transaction(tx_hash_0); // Set tx2 fee to a higher value, tx1 capacity is 100, set tx2 capacity to 80 for +20 fee. let output = CellOutputBuilder::default() .capacity(capacity_bytes!(80).pack()) .build(); let tx2 = tx2_temp .as_advanced_builder() .set_outputs(vec![output]) .build(); node0 .rpc_client() .send_transaction(tx1.clone().data().into()); node0 .rpc_client() .send_transaction(tx2.clone().data().into()); node0.generate_block(); node0.generate_block(); info!("RBF (Replace-By-Fees) is not implemented, but transaction fee sorting is ready"); info!("tx2 should be included in the next + 2 block, and tx1 should be ignored"); node0.generate_block(); let tip_block = node0.get_tip_block(); let commit_txs_hash: Vec<_> = tip_block .transactions() .iter() .map(TransactionView::hash) .collect(); assert!(commit_txs_hash.contains(&tx2.hash())); assert!(!commit_txs_hash.contains(&tx1.hash())); } }
use std::cmp; use std::collections::HashSet; use parser::{ BaseType, EnumerationType, File, FileHash, Function, StructType, Type, TypeDef, TypeKind, TypeOffset, UnionType, Unit, UnspecifiedType, Variable, }; use crate::Options; pub(crate) fn filter_units<'input, 'file>( file: &'file File<'input>, options: &Options, ) -> Vec<&'file Unit<'input>> { file.units() .iter() .filter(|a| filter_unit(a, options)) .collect() } pub(crate) fn enumerate_and_filter_units<'input, 'file>( file: &'file File<'input>, options: &Options, ) -> Vec<(usize, &'file Unit<'input>)> { file.units() .iter() .enumerate() .filter(|a| filter_unit(a.1, options)) .collect() } /// Return true if this unit matches the filter options. fn filter_unit(unit: &Unit, options: &Options) -> bool { if let Some(filter) = options.filter_unit.as_ref() { let (prefix, suffix) = options.prefix_map(unit.name().unwrap_or("")); let iter = prefix.bytes().chain(suffix.bytes()); iter.cmp(filter.bytes()) == cmp::Ordering::Equal } else { true } } /// The offsets of types that should be printed inline. fn inline_types(unit: &Unit, hash: &FileHash) -> HashSet<TypeOffset> { let mut inline_types = HashSet::new(); for ty in unit.types() { // Assume all anonymous types are inline. We don't actually check // that they will be inline, but in future we could (eg for TypeDefs). // TODO: is this a valid assumption? if ty.is_anon() && ty.offset().is_some() { inline_types.insert(ty.offset()); } // Find all inline members. for t in ty.members() { if t.is_inline(hash) && t.type_offset().is_some() { inline_types.insert(t.type_offset()); } } } inline_types } /// Filter and the list of types using the options. /// Perform additional filtering when diffing. pub(crate) fn filter_types<'input, 'unit>( unit: &'unit Unit<'input>, hash: &FileHash, options: &Options, diff: bool, ) -> Vec<&'unit Type<'input>> { let inline_types = inline_types(unit, hash); unit.types() .iter() .filter(|a| filter_type(a, options, diff, &inline_types)) .collect() } pub(crate) fn enumerate_and_filter_types<'input, 'unit>( unit: &'unit Unit<'input>, hash: &FileHash, options: &Options, diff: bool, ) -> Vec<(usize, &'unit Type<'input>)> { let inline_types = inline_types(unit, hash); unit.types() .iter() .enumerate() .filter(|a| filter_type(a.1, options, diff, &inline_types)) .collect() } pub(crate) fn filter_functions<'input, 'unit>( unit: &'unit Unit<'input>, options: &Options, ) -> Vec<&'unit Function<'input>> { unit.functions() .iter() .filter(|a| filter_function(a, options)) .collect() } pub(crate) fn enumerate_and_filter_functions<'input, 'unit>( unit: &'unit Unit<'input>, options: &Options, ) -> Vec<(usize, &'unit Function<'input>)> { unit.functions() .iter() .enumerate() .filter(|a| filter_function(a.1, options)) .collect() } pub(crate) fn filter_variables<'input, 'unit>( unit: &'unit Unit<'input>, options: &Options, ) -> Vec<&'unit Variable<'input>> { unit.variables() .iter() .filter(|a| filter_variable(a, options)) .collect() } pub(crate) fn enumerate_and_filter_variables<'input, 'unit>( unit: &'unit Unit<'input>, options: &Options, ) -> Vec<(usize, &'unit Variable<'input>)> { unit.variables() .iter() .enumerate() .filter(|a| filter_variable(a.1, options)) .collect() } fn filter_function(f: &Function, options: &Options) -> bool { if !f.is_inline() && (f.address().is_none() || f.size().is_none()) { // This is either a declaration or a dead function that was removed // from the code, but wasn't removed from the debuginfo. // TODO: make this configurable? return false; } options.filter_name(f.name()) && options.filter_namespace(f.namespace()) && options.filter_function_inline(f.is_inline()) } fn filter_variable(v: &Variable, options: &Options) -> bool { if !v.is_declaration() && v.address().is_none() { // TODO: make this configurable? return false; } options.filter_name(v.name()) && options.filter_namespace(v.namespace()) } fn filter_type( ty: &Type, options: &Options, diff: bool, inline_types: &HashSet<TypeOffset>, ) -> bool { // Filter by user options. if !match *ty.kind() { TypeKind::Base(ref val) => filter_base(val, options), TypeKind::Def(ref val) => filter_type_def(val, options), TypeKind::Struct(ref val) => filter_struct(val, options), TypeKind::Union(ref val) => filter_union(val, options), TypeKind::Enumeration(ref val) => filter_enumeration(val, options), TypeKind::Unspecified(ref val) => filter_unspecified(val, options), TypeKind::Void | TypeKind::Array(..) | TypeKind::Function(..) | TypeKind::PointerToMember(..) | TypeKind::Modifier(..) | TypeKind::Subrange(..) => options.filter_name.is_none(), } { return false; } match *ty.kind() { TypeKind::Struct(ref val) => { // Hack for rust closures // TODO: is there better way of identifying these, or a // a way to match pairs for diffing? if diff && val.name() == Some("closure") { return false; } } TypeKind::Base(..) | TypeKind::Def(..) | TypeKind::Union(..) | TypeKind::Enumeration(..) => {} TypeKind::Void | TypeKind::Array(..) | TypeKind::Function(..) | TypeKind::Unspecified(..) | TypeKind::PointerToMember(..) | TypeKind::Modifier(..) | TypeKind::Subrange(..) => return false, } // Filter out inline types. ty.offset().is_some() && !inline_types.contains(&ty.offset()) } fn filter_base(ty: &BaseType, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(None) } fn filter_type_def(ty: &TypeDef, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(ty.namespace()) } fn filter_struct(ty: &StructType, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(ty.namespace()) } fn filter_union(ty: &UnionType, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(ty.namespace()) } fn filter_enumeration(ty: &EnumerationType, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(ty.namespace()) } fn filter_unspecified(ty: &UnspecifiedType, options: &Options) -> bool { options.filter_name(ty.name()) && options.filter_namespace(ty.namespace()) }
#[test] fn test_we_can_get_item_from_array() { // Create an array assert!("5" == foo[2]); } #[test] fn test_we_add_a_new_item_to_an_array() { let mut foo = ~[]; // Add new items to the array/vector assert!(foo.len() == 4); } #[test] fn test_we_can_pop_items_from_list() { let mut foo = ~["a", "b", "c"]; // Pop items from the list assert!(foo.len() == 2); assert!(~["a", "b"] == foo); } #[test] fn test_that_we_can_slice_arrays() { let foo = ["a", "b", "c"]; // Slice the array so you get 1 array item back assert!(["c"] == bar); } #[test] fn should_find_the_largest_number_in_an_array(){ let mut max = 0; let vec = [1, 5, 6, 8, 2, 3, 4]; // Use a map to find the largest number assert!(8 == max); }
#[doc = "Register `MDIOS_DOUTR9` reader"] pub type R = crate::R<MDIOS_DOUTR9_SPEC>; #[doc = "Field `DOUT` reader - DOUT"] pub type DOUT_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:15 - DOUT"] #[inline(always)] pub fn dout(&self) -> DOUT_R { DOUT_R::new((self.bits & 0xffff) as u16) } } #[doc = "MDIOS output data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`mdios_doutr9::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MDIOS_DOUTR9_SPEC; impl crate::RegisterSpec for MDIOS_DOUTR9_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`mdios_doutr9::R`](R) reader structure"] impl crate::Readable for MDIOS_DOUTR9_SPEC {} #[doc = "`reset()` method sets MDIOS_DOUTR9 to value 0"] impl crate::Resettable for MDIOS_DOUTR9_SPEC { const RESET_VALUE: Self::Ux = 0; }
table! { files (id) { id -> Text, filename -> Text, last_modified -> BigInt, } }
use crate::rtb_type_strict; rtb_type_strict! { PlayabckCessationMode, OnVideoCompletion=1; OnLeavingViewport=2; OnLeavingViewportContinuesAsFloatingOrSliderUnit=3 }
pub mod dr { pub mod dr { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40023000u32 as *const u32) & 0xFFFFFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40023000u32 as *const u32); reg &= 0x0u32; reg |= val & 0xFFFFFFFF; core::ptr::write_volatile(0x40023000u32 as *mut u32, reg); } } } } pub mod idr { pub mod idr { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40023004u32 as *const u32) & 0xFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40023004u32 as *const u32); reg &= 0xFFFFFF00u32; reg |= val & 0xFF; core::ptr::write_volatile(0x40023004u32 as *mut u32, reg); } } } } pub mod cr { pub mod reset { pub fn set(val: u32) { unsafe { let reg = val & 0x1; core::ptr::write_volatile(0x40023008u32 as *mut u32, reg); } } } }
use anyhow::Result; use proger_core::protocol::{ model::StepPageModel, request::{DeleteStepPage, CreateStepPage, UpdateStepPage}, }; use rand::{distributions::Alphanumeric, Rng}; use sha3::{Digest, Sha3_256}; use thiserror::Error; use tokio::runtime::Runtime; const PASSWORD_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789)(*&^%$#@!~"; const PASSWORD_LEN: usize = 30; /// The create session message #[derive(Debug)] pub enum StorageCmd { CreateStepPage(CreateStepPage), ReadStepPage(String), UpdateStepPage(String, UpdateStepPage), DeleteStepPage(String, DeleteStepPage), } #[derive(Error, Debug)] pub enum StorageError { #[error("Wrong password when trying to update page")] WrongPassword, #[error("The link `{0}` does not exists")] LinkNotExists(String), #[error("The page descriptor schema doesn't match")] CorruptedItem, } /// Trait to allow different database backend pub trait StorageDriver: 'static + Unpin { fn connect(&self) -> Result<()>; fn execute(&self, rt: &mut Runtime, cmd: StorageCmd) -> Result<StepPageModel>; } pub fn generate_link() -> String { let link: String = rand::thread_rng() .sample_iter(&Alphanumeric) .take(60) .collect(); link } pub fn generate_secret() -> String { let mut rng = rand::thread_rng(); let secret: String = (0..PASSWORD_LEN) .map(|_| { let idx = rng.gen_range(0, PASSWORD_CHARSET.len()); PASSWORD_CHARSET[idx] as char }) .collect(); secret } pub fn hash_secret(secret: &str) -> String { let mut hasher = Sha3_256::new(); hasher.input(secret.as_bytes()); let mut hash = "".to_string(); for byte in hasher.result() { hash.push_str(&format!("{:x}", byte)); } hash } #[cfg(test)] mod tests { use super::*; #[test] fn link() { let link1 = generate_link(); let link2 = generate_link(); println!("link1: {}", link1); println!("link2: {}", link2); assert_ne!(link1, link2); } #[test] fn secret() { let secret1 = generate_secret(); let secret2 = generate_secret(); println!("secret1: {}", secret1); println!("secret2: {}", secret2); assert_ne!(secret1, secret2); } #[test] fn hash() { let secret = generate_secret(); let hash1 = hash_secret(&secret); let hash2 = hash_secret(&secret); println!("hash1: {}", hash1); println!("hash2: {}", hash2); assert_eq!(hash1, hash2); } }
use std::collections::BTreeMap; fn letter_frequency(input: &str) -> BTreeMap<char, i32> { let mut dic = BTreeMap::new(); let s: Vec<char> = input.to_string().to_lowercase().chars().collect(); for elem in s { if (elem >= 'A' as char && elem <= 'Z' as char) || (elem >= 'a' as char && elem <= 'z' as char) { *dic.entry(elem).or_insert(0) += 1; } } dic } #[test] fn test0() { let answer: BTreeMap<char, i32> = [('a', 1)] .iter().cloned().collect(); assert_eq!(letter_frequency("a"), answer); } #[test] fn test1() { let answer: BTreeMap<char, i32> = [('a', 1)] .iter().cloned().collect(); assert_eq!(letter_frequency("A"), answer); } #[test] fn test2() { let answer: BTreeMap<char, i32> = [('a', 3)] .iter().cloned().collect(); assert_eq!(letter_frequency("aaa"), answer); } #[test] fn test3() { let answer: BTreeMap<char, i32> = [('a', 3)] .iter().cloned().collect(); assert_eq!(letter_frequency("AAA"), answer); } #[test] fn test4() { let answer: BTreeMap<char, i32> = [('a', 6)] .iter().cloned().collect(); assert_eq!(letter_frequency("AaAaAa"), answer); } #[test] fn test5() { let answer: BTreeMap<char, i32> = [('a', 1), ('b', 1), ('c', 1)] .iter().cloned().collect(); assert_eq!(letter_frequency("abc"), answer); } #[test] fn test6() { let answer: BTreeMap<char, i32> = [('a', 1), ('b', 1), ('c', 1)] .iter().cloned().collect(); assert_eq!(letter_frequency("aBc"), answer); } #[test] fn test7() { let answer: BTreeMap<char, i32> = [('a', 2), ('b', 2), ('c', 2)] .iter().cloned().collect(); assert_eq!(letter_frequency("AaBbCc"), answer); } #[test] fn test8() { let answer: BTreeMap<char, i32> = [('a', 2), ('b', 2), ('c', 2)] .iter().cloned().collect(); assert_eq!(letter_frequency("Aa Bb Cc"), answer); } #[test] fn test9() { let answer: BTreeMap<char, i32> = [('a', 2), ('b', 2), ('c', 2), ('x', 9)] .iter().cloned().collect(); assert_eq!(letter_frequency("xAxax xBxbx xCxcx"), answer); } fn main() { }
use std::fs::File; use std::io; use std::io::Read; use std::collections::HashMap; use std::hash::Hasher; use std::collections::hash_map::DefaultHasher; use rusttype::{Font, Scale, Point, Rect, HMetrics}; use derive_more::{Error, From}; use crate::draw::{Vertex, load_data_to_gpu, ObjDef}; use crate::draw::{UIDrawInfo, ui_draw}; use glium::{Display, Frame, texture::{SrgbTexture2d, RawImage2d, TextureCreationError}}; use crate::assets::find_asset; pub enum TextAlign { Left, Center, Right } struct FontChar { texture: Option<SrgbTexture2d>, bbox: Option<Rect<i32>>, h_metrics: HMetrics } pub struct FontText { chars: Vec<(char, Option<ObjDef>)>, last_font_hash: u64, align: TextAlign, text: String, pub ui_draw_info: UIDrawInfo } #[derive(Default)] pub struct LoadedFont { hash: u64, chars: HashMap<char, FontChar>, pub font_size: f32 } #[derive(Debug, derive_more::Display, Error, From)] pub enum FontError { IOError(io::Error), LoadError, TextureUploadError(TextureCreationError), CharNotAvailable } impl LoadedFont { pub fn load(display: &Display, filename: &str, app_id: &str, font_size: f32) -> Result<Self, FontError> { let mut f = File::open(find_asset(filename, app_id))?; let mut f_contents = Vec::new(); f.read_to_end(&mut f_contents)?; let font = Font::try_from_vec(f_contents).ok_or(FontError::LoadError)?; let scale = Scale::uniform(font_size); let mut hasher = DefaultHasher::new(); hasher.write(filename.as_bytes()); hasher.write_u32(font_size.to_bits()); let mut result = Self { hash: hasher.finish(), font_size: font_size, ..Default::default() }; for ch in b' '..=b'~' { let glyph = font.glyph(ch as char).scaled(scale); let h_metrics = glyph.h_metrics(); let positioned = glyph.positioned(Point { x: 0., y: 0. }); let mut char_result = FontChar { texture: None, bbox: None, h_metrics: h_metrics }; if let Some(positioned_box) = positioned.pixel_bounding_box() { let glyph_size = (positioned_box.width() as usize, positioned_box.height() as usize); let mut glyph_data = vec![0u8; glyph_size.1 * glyph_size.0 * 4]; positioned.draw(|x, y, v| { let val = (v * 255.) as u8; let index = ((y * (glyph_size.0 as u32) + x) * 4) as usize; glyph_data[index] = 255; glyph_data[index + 1] = 255; glyph_data[index + 2] = 255; glyph_data[index + 3] = val; }); let txt = SrgbTexture2d::new(display, RawImage2d::from_raw_rgba_reversed(&glyph_data, (glyph_size.0 as u32, glyph_size.1 as u32)))?; char_result.texture = Some(txt); char_result.bbox = Some(positioned_box); } result.chars.insert(ch as char, char_result); } Ok(result) } } impl FontText { pub fn new(text: String, size: f32, pos: (f32, f32), align: TextAlign) -> Self { let text_len = text.len(); Self { text: text, align: align, last_font_hash: 0, chars: Vec::with_capacity(text_len), ui_draw_info: UIDrawInfo::new(pos, (size, size)) } } pub fn measure_width(&mut self, font: &LoadedFont) -> Result<f32, FontError> { let mut width = 0.0f32; for c in self.text.chars() { let ch = font.chars.get(&c).ok_or(FontError::CharNotAvailable)?; width += ch.h_metrics.advance_width / font.font_size; } Ok(width) } fn starting_position(&mut self, font: &LoadedFont) -> Result<f32, FontError> { let width = self.measure_width(font)?; let x_offset: f32 = match self.align { TextAlign::Left => 0., TextAlign::Right => width, TextAlign::Center => width / 2. }; Ok(-x_offset) } fn prepare_chars(&mut self, display: &Display, font: &LoadedFont) -> Result<(), FontError> { let mut pos = (self.starting_position(font)?, 0.0); for c in self.text.chars() { let mut char_result: Option<ObjDef> = None; let ch = font.chars.get(&c).ok_or(FontError::CharNotAvailable)?; pos.0 += ch.h_metrics.left_side_bearing / font.font_size; if let Some(bbox) = ch.bbox { let ch_size = (bbox.width() as f32, bbox.height() as f32); let real_size = (ch_size.0 / font.font_size, ch_size.1 / font.font_size); pos.1 -= (bbox.max.y as f32) / font.font_size; let vertices = [ Vertex { position: [pos.0, pos.1, 0.], normal: [0., 0., -1.], texcoords: [0., 0.] }, Vertex { position: [pos.0 + real_size.0, pos.1, 0.], normal: [0., 0., -1.], texcoords: [1., 0.] }, Vertex { position: [pos.0 + real_size.0, pos.1 + real_size.1, 0.], normal: [0., 0., -1.], texcoords: [1., 1.] }, Vertex { position: [pos.0, pos.1 + real_size.1, 0.], normal: [0., 0., -1.], texcoords: [0., 1.] } ]; let indices = [0, 1, 2, 0, 2, 3]; char_result = Some(load_data_to_gpu(display, &vertices, &indices)); pos.1 += (bbox.max.y as f32) / font.font_size; } self.chars.push((c, char_result)); pos.0 += (ch.h_metrics.advance_width - ch.h_metrics.left_side_bearing) / font.font_size; } Ok(()) } pub fn draw(&mut self, target: &mut Frame, display: &Display, program: &glium::Program, font: &LoadedFont) -> Result<(), FontError> { if self.last_font_hash != font.hash { self.chars.clear(); self.prepare_chars(display, font)?; self.last_font_hash = font.hash; } self.ui_draw_info.generate_matrix(target); for (c, obj_def) in &self.chars { let ch = font.chars.get(&c).ok_or(FontError::CharNotAvailable)?; if let Some(obj_def) = obj_def { ui_draw(target, &obj_def, &self.ui_draw_info, program, ch.texture.as_ref().unwrap()); } } Ok(()) } }
pub const WORDLIST: &'static [&'static str] = &[ "aalglad", "aalscholver", "aambeeld", "aangeef", "aanlandig", "aanvaard", "aanwakker", "aapmens", "aarten", "abdicatie", "abnormaal", "abrikoos", "accu", "acuut", "adjudant", "admiraal", "advies", "afbidding", "afdracht", "affaire", "affiche", "afgang", "afkick", "afknap", "aflees", "afmijner", "afname", "afpreekt", "afrader", "afspeel", "aftocht", "aftrek", "afzijdig", "ahornboom", "aktetas", "akzo", "alchemist", "alcohol", "aldaar", "alexander", "alfabet", "alfredo", "alice", "alikruik", "allrisk", "altsax", "alufolie", "alziend", "amai", "ambacht", "ambieer", "amina", "amnestie", "amok", "ampul", "amuzikaal", "angela", "aniek", "antje", "antwerpen", "anya", "aorta", "apache", "apekool", "appelaar", "arganolie", "argeloos", "armoede", "arrenslee", "artritis", "arubaan", "asbak", "ascii", "asgrauw", "asjes", "asml", "aspunt", "asurn", "asveld", "aterling", "atomair", "atrium", "atsma", "atypisch", "auping", "aura", "avifauna", "axiaal", "azoriaan", "azteek", "azuur", "bachelor", "badderen", "badhotel", "badmantel", "badsteden", "balie", "ballans", "balvers", "bamibal", "banneling", "barracuda", "basaal", "batelaan", "batje", "beambte", "bedlamp", "bedwelmd", "befaamd", "begierd", "begraaf", "behield", "beijaard", "bejaagd", "bekaaid", "beks", "bektas", "belaad", "belboei", "belderbos", "beloerd", "beluchten", "bemiddeld", "benadeeld", "benijd", "berechten", "beroemd", "besef", "besseling", "best", "betichten", "bevind", "bevochten", "bevraagd", "bewust", "bidplaats", "biefstuk", "biemans", "biezen", "bijbaan", "bijeenkom", "bijfiguur", "bijkaart", "bijlage", "bijpaard", "bijtgaar", "bijweg", "bimmel", "binck", "bint", "biobak", "biotisch", "biseks", "bistro", "bitter", "bitumen", "bizar", "blad", "bleken", "blender", "bleu", "blief", "blijven", "blozen", "bock", "boef", "boei", "boks", "bolder", "bolus", "bolvormig", "bomaanval", "bombarde", "bomma", "bomtapijt", "bookmaker", "boos", "borg", "bosbes", "boshuizen", "bosloop", "botanicus", "bougie", "bovag", "boxspring", "braad", "brasem", "brevet", "brigade", "brinckman", "bruid", "budget", "buffel", "buks", "bulgaar", "buma", "butaan", "butler", "buuf", "cactus", "cafeetje", "camcorder", "cannabis", "canyon", "capoeira", "capsule", "carkit", "casanova", "catalaan", "ceintuur", "celdeling", "celplasma", "cement", "censeren", "ceramisch", "cerberus", "cerebraal", "cesium", "cirkel", "citeer", "civiel", "claxon", "clenbuterol", "clicheren", "clijsen", "coalitie", "coassistentschap", "coaxiaal", "codetaal", "cofinanciering", "cognac", "coltrui", "comfort", "commandant", "condensaat", "confectie", "conifeer", "convector", "copier", "corfu", "correct", "coup", "couvert", "creatie", "credit", "crematie", "cricket", "croupier", "cruciaal", "cruijff", "cuisine", "culemborg", "culinair", "curve", "cyrano", "dactylus", "dading", "dagblind", "dagje", "daglicht", "dagprijs", "dagranden", "dakdekker", "dakpark", "dakterras", "dalgrond", "dambord", "damkat", "damlengte", "damman", "danenberg", "debbie", "decibel", "defect", "deformeer", "degelijk", "degradant", "dejonghe", "dekken", "deppen", "derek", "derf", "derhalve", "detineren", "devalueer", "diaken", "dicht", "dictaat", "dief", "digitaal", "dijbreuk", "dijkmans", "dimbaar", "dinsdag", "diode", "dirigeer", "disbalans", "dobermann", "doenbaar", "doerak", "dogma", "dokhaven", "dokwerker", "doling", "dolphijn", "dolven", "dombo", "dooraderd", "dopeling", "doping", "draderig", "drama", "drenkbak", "dreumes", "drol", "drug", "duaal", "dublin", "duplicaat", "durven", "dusdanig", "dutchbat", "dutje", "dutten", "duur", "duwwerk", "dwaal", "dweil", "dwing", "dyslexie", "ecostroom", "ecotaks", "educatie", "eeckhout", "eede", "eemland", "eencellig", "eeneiig", "eenruiter", "eenwinter", "eerenberg", "eerrover", "eersel", "eetmaal", "efteling", "egaal", "egtberts", "eickhoff", "eidooier", "eiland", "eind", "eisden", "ekster", "elburg", "elevatie", "elfkoppig", "elfrink", "elftal", "elimineer", "elleboog", "elma", "elodie", "elsa", "embleem", "embolie", "emoe", "emonds", "emplooi", "enduro", "enfin", "engageer", "entourage", "entstof", "epileer", "episch", "eppo", "erasmus", "erboven", "erebaan", "erelijst", "ereronden", "ereteken", "erfhuis", "erfwet", "erger", "erica", "ermitage", "erna", "ernie", "erts", "ertussen", "eruitzien", "ervaar", "erven", "erwt", "esbeek", "escort", "esdoorn", "essing", "etage", "eter", "ethanol", "ethicus", "etholoog", "eufonisch", "eurocent", "evacuatie", "exact", "examen", "executant", "exen", "exit", "exogeen", "exotherm", "expeditie", "expletief", "expres", "extase", "extinctie", "faal", "faam", "fabel", "facultair", "fakir", "fakkel", "faliekant", "fallisch", "famke", "fanclub", "fase", "fatsoen", "fauna", "federaal", "feedback", "feest", "feilbaar", "feitelijk", "felblauw", "figurante", "fiod", "fitheid", "fixeer", "flap", "fleece", "fleur", "flexibel", "flits", "flos", "flow", "fluweel", "foezelen", "fokkelman", "fokpaard", "fokvee", "folder", "follikel", "folmer", "folteraar", "fooi", "foolen", "forfait", "forint", "formule", "fornuis", "fosfaat", "foxtrot", "foyer", "fragiel", "frater", "freak", "freddie", "fregat", "freon", "frijnen", "fructose", "frunniken", "fuiven", "funshop", "furieus", "fysica", "gadget", "galder", "galei", "galg", "galvlieg", "galzuur", "ganesh", "gaswet", "gaza", "gazelle", "geaaid", "gebiecht", "gebufferd", "gedijd", "geef", "geflanst", "gefreesd", "gegaan", "gegijzeld", "gegniffel", "gegraaid", "gehikt", "gehobbeld", "gehucht", "geiser", "geiten", "gekaakt", "gekheid", "gekijf", "gekmakend", "gekocht", "gekskap", "gekte", "gelubberd", "gemiddeld", "geordend", "gepoederd", "gepuft", "gerda", "gerijpt", "geseald", "geshockt", "gesierd", "geslaagd", "gesnaaid", "getracht", "getwijfel", "geuit", "gevecht", "gevlagd", "gewicht", "gezaagd", "gezocht", "ghanees", "giebelen", "giechel", "giepmans", "gips", "giraal", "gistachtig", "gitaar", "glaasje", "gletsjer", "gleuf", "glibberen", "glijbaan", "gloren", "gluipen", "gluren", "gluur", "gnoe", "goddelijk", "godgans", "godschalk", "godzalig", "goeierd", "gogme", "goklustig", "gokwereld", "gonggrijp", "gonje", "goor", "grabbel", "graf", "graveer", "grif", "grolleman", "grom", "groosman", "grubben", "gruijs", "grut", "guacamole", "guido", "guppy", "haazen", "hachelijk", "haex", "haiku", "hakhout", "hakken", "hanegem", "hans", "hanteer", "harrie", "hazebroek", "hedonist", "heil", "heineken", "hekhuis", "hekman", "helbig", "helga", "helwegen", "hengelaar", "herkansen", "hermafrodiet", "hertaald", "hiaat", "hikspoors", "hitachi", "hitparade", "hobo", "hoeve", "holocaust", "hond", "honnepon", "hoogacht", "hotelbed", "hufter", "hugo", "huilbier", "hulk", "humus", "huwbaar", "huwelijk", "hype", "iconisch", "idema", "ideogram", "idolaat", "ietje", "ijker", "ijkheid", "ijklijn", "ijkmaat", "ijkwezen", "ijmuiden", "ijsbox", "ijsdag", "ijselijk", "ijskoud", "ilse", "immuun", "impliceer", "impuls", "inbijten", "inbuigen", "indijken", "induceer", "indy", "infecteer", "inhaak", "inkijk", "inluiden", "inmijnen", "inoefenen", "inpolder", "inrijden", "inslaan", "invitatie", "inwaaien", "ionisch", "isaac", "isolatie", "isotherm", "isra", "italiaan", "ivoor", "jacobs", "jakob", "jammen", "jampot", "jarig", "jehova", "jenever", "jezus", "joana", "jobdienst", "josua", "joule", "juich", "jurk", "juut", "kaas", "kabelaar", "kabinet", "kagenaar", "kajuit", "kalebas", "kalm", "kanjer", "kapucijn", "karregat", "kart", "katvanger", "katwijk", "kegelaar", "keiachtig", "keizer", "kenletter", "kerdijk", "keus", "kevlar", "kezen", "kickback", "kieviet", "kijken", "kikvors", "kilheid", "kilobit", "kilsdonk", "kipschnitzel", "kissebis", "klad", "klagelijk", "klak", "klapbaar", "klaver", "klene", "klets", "klijnhout", "klit", "klok", "klonen", "klotefilm", "kluif", "klumper", "klus", "knabbel", "knagen", "knaven", "kneedbaar", "knmi", "knul", "knus", "kokhals", "komiek", "komkommer", "kompaan", "komrij", "komvormig", "koning", "kopbal", "kopklep", "kopnagel", "koppejan", "koptekst", "kopwand", "koraal", "kosmisch", "kostbaar", "kram", "kraneveld", "kras", "kreling", "krengen", "kribbe", "krik", "kruid", "krulbol", "kuijper", "kuipbank", "kuit", "kuiven", "kutsmoes", "kuub", "kwak", "kwatong", "kwetsbaar", "kwezelaar", "kwijnen", "kwik", "kwinkslag", "kwitantie", "lading", "lakbeits", "lakken", "laklaag", "lakmoes", "lakwijk", "lamheid", "lamp", "lamsbout", "lapmiddel", "larve", "laser", "latijn", "latuw", "lawaai", "laxeerpil", "lebberen", "ledeboer", "leefbaar", "leeman", "lefdoekje", "lefhebber", "legboor", "legsel", "leguaan", "leiplaat", "lekdicht", "lekrijden", "leksteen", "lenen", "leraar", "lesbienne", "leugenaar", "leut", "lexicaal", "lezing", "lieten", "liggeld", "lijdzaam", "lijk", "lijmstang", "lijnschip", "likdoorn", "likken", "liksteen", "limburg", "link", "linoleum", "lipbloem", "lipman", "lispelen", "lissabon", "litanie", "liturgie", "lochem", "loempia", "loesje", "logheid", "lonen", "lonneke", "loom", "loos", "losbaar", "loslaten", "losplaats", "loting", "lotnummer", "lots", "louie", "lourdes", "louter", "lowbudget", "luijten", "luikenaar", "luilak", "luipaard", "luizenbos", "lulkoek", "lumen", "lunzen", "lurven", "lutjeboer", "luttel", "lutz", "luuk", "luwte", "luyendijk", "lyceum", "lynx", "maakbaar", "magdalena", "malheid", "manchet", "manfred", "manhaftig", "mank", "mantel", "marion", "marxist", "masmeijer", "massaal", "matsen", "matverf", "matze", "maude", "mayonaise", "mechanica", "meifeest", "melodie", "meppelink", "midvoor", "midweeks", "midzomer", "miezel", "mijnraad", "minus", "mirck", "mirte", "mispakken", "misraden", "miswassen", "mitella", "moker", "molecule", "mombakkes", "moonen", "mopperaar", "moraal", "morgana", "mormel", "mosselaar", "motregen", "mouw", "mufheid", "mutueel", "muzelman", "naaidoos", "naald", "nadeel", "nadruk", "nagy", "nahon", "naima", "nairobi", "napalm", "napels", "napijn", "napoleon", "narigheid", "narratief", "naseizoen", "nasibal", "navigatie", "nawijn", "negatief", "nekletsel", "nekwervel", "neolatijn", "neonataal", "neptunus", "nerd", "nest", "neuzelaar", "nihiliste", "nijenhuis", "nijging", "nijhoff", "nijl", "nijptang", "nippel", "nokkenas", "noordam", "noren", "normaal", "nottelman", "notulant", "nout", "nuance", "nuchter", "nudorp", "nulde", "nullijn", "nulmeting", "nunspeet", "nylon", "obelisk", "object", "oblie", "obsceen", "occlusie", "oceaan", "ochtend", "ockhuizen", "oerdom", "oergezond", "oerlaag", "oester", "okhuijsen", "olifant", "olijfboer", "omaans", "ombudsman", "omdat", "omdijken", "omdoen", "omgebouwd", "omkeer", "omkomen", "ommegaand", "ommuren", "omroep", "omruil", "omslaan", "omsmeden", "omvaar", "onaardig", "onedel", "onenig", "onheilig", "onrecht", "onroerend", "ontcijfer", "onthaal", "ontvallen", "ontzadeld", "onzacht", "onzin", "onzuiver", "oogappel", "ooibos", "ooievaar", "ooit", "oorarts", "oorhanger", "oorijzer", "oorklep", "oorschelp", "oorworm", "oorzaak", "opdagen", "opdien", "opdweilen", "opel", "opgebaard", "opinie", "opjutten", "opkijken", "opklaar", "opkuisen", "opkwam", "opnaaien", "opossum", "opsieren", "opsmeer", "optreden", "opvijzel", "opvlammen", "opwind", "oraal", "orchidee", "orkest", "ossuarium", "ostendorf", "oublie", "oudachtig", "oudbakken", "oudnoors", "oudshoorn", "oudtante", "oven", "over", "oxidant", "pablo", "pacht", "paktafel", "pakzadel", "paljas", "panharing", "papfles", "paprika", "parochie", "paus", "pauze", "paviljoen", "peek", "pegel", "peigeren", "pekela", "pendant", "penibel", "pepmiddel", "peptalk", "periferie", "perron", "pessarium", "peter", "petfles", "petgat", "peuk", "pfeifer", "picknick", "pief", "pieneman", "pijlkruid", "pijnacker", "pijpelink", "pikdonker", "pikeer", "pilaar", "pionier", "pipet", "piscine", "pissebed", "pitchen", "pixel", "plamuren", "plan", "plausibel", "plegen", "plempen", "pleonasme", "plezant", "podoloog", "pofmouw", "pokdalig", "ponywagen", "popachtig", "popidool", "porren", "positie", "potten", "pralen", "prezen", "prijzen", "privaat", "proef", "prooi", "prozawerk", "pruik", "prul", "publiceer", "puck", "puilen", "pukkelig", "pulveren", "pupil", "puppy", "purmerend", "pustjens", "putemmer", "puzzelaar", "queenie", "quiche", "raam", "raar", "raat", "raes", "ralf", "rally", "ramona", "ramselaar", "ranonkel", "rapen", "rapunzel", "rarekiek", "rarigheid", "rattenhol", "ravage", "reactie", "recreant", "redacteur", "redster", "reewild", "regie", "reijnders", "rein", "replica", "revanche", "rigide", "rijbaan", "rijdansen", "rijgen", "rijkdom", "rijles", "rijnwijn", "rijpma", "rijstafel", "rijtaak", "rijzwepen", "rioleer", "ripdeal", "riphagen", "riskant", "rits", "rivaal", "robbedoes", "robot", "rockact", "rodijk", "rogier", "rohypnol", "rollaag", "rolpaal", "roltafel", "roof", "roon", "roppen", "rosbief", "rosharig", "rosielle", "rotan", "rotleven", "rotten", "rotvaart", "royaal", "royeer", "rubato", "ruby", "ruche", "rudge", "ruggetje", "rugnummer", "rugpijn", "rugtitel", "rugzak", "ruilbaar", "ruis", "ruit", "rukwind", "rulijs", "rumoeren", "rumsdorp", "rumtaart", "runnen", "russchen", "ruwkruid", "saboteer", "saksisch", "salade", "salpeter", "sambabal", "samsam", "satelliet", "satineer", "saus", "scampi", "scarabee", "scenario", "schobben", "schubben", "scout", "secessie", "secondair", "seculair", "sediment", "seeland", "settelen", "setwinst", "sheriff", "shiatsu", "siciliaan", "sidderaal", "sigma", "sijben", "silvana", "simkaart", "sinds", "situatie", "sjaak", "sjardijn", "sjezen", "sjor", "skinhead", "skylab", "slamixen", "sleijpen", "slijkerig", "slordig", "slowaak", "sluieren", "smadelijk", "smiecht", "smoel", "smos", "smukken", "snackcar", "snavel", "sneaker", "sneu", "snijdbaar", "snit", "snorder", "soapbox", "soetekouw", "soigneren", "sojaboon", "solo", "solvabel", "somber", "sommatie", "soort", "soppen", "sopraan", "soundbar", "spanen", "spawater", "spijgat", "spinaal", "spionage", "spiraal", "spleet", "splijt", "spoed", "sporen", "spul", "spuug", "spuw", "stalen", "standaard", "star", "stefan", "stencil", "stijf", "stil", "stip", "stopdas", "stoten", "stoven", "straat", "strobbe", "strubbel", "stucadoor", "stuif", "stukadoor", "subhoofd", "subregent", "sudoku", "sukade", "sulfaat", "surinaams", "suus", "syfilis", "symboliek", "sympathie", "synagoge", "synchroon", "synergie", "systeem", "taanderij", "tabak", "tachtig", "tackelen", "taiwanees", "talman", "tamheid", "tangaslip", "taps", "tarkan", "tarwe", "tasman", "tatjana", "taxameter", "teil", "teisman", "telbaar", "telco", "telganger", "telstar", "tenant", "tepel", "terzet", "testament", "ticket", "tiesinga", "tijdelijk", "tika", "tiksel", "tilleman", "timbaal", "tinsteen", "tiplijn", "tippelaar", "tjirpen", "toezeggen", "tolbaas", "tolgeld", "tolhek", "tolo", "tolpoort", "toltarief", "tolvrij", "tomaat", "tondeuse", "toog", "tooi", "toonbaar", "toos", "topclub", "toppen", "toptalent", "topvrouw", "toque", "torment", "tornado", "tosti", "totdat", "toucheer", "toulouse", "tournedos", "tout", "trabant", "tragedie", "trailer", "traject", "traktaat", "trauma", "tray", "trechter", "tred", "tref", "treur", "troebel", "tros", "trucage", "truffel", "tsaar", "tucht", "tuenter", "tuitelig", "tukje", "tuktuk", "tulp", "tuma", "tureluurs", "twijfel", "twitteren", "tyfoon", "typograaf", "ugandees", "uiachtig", "uier", "uisnipper", "ultiem", "unitair", "uranium", "urbaan", "urendag", "ursula", "uurcirkel", "uurglas", "uzelf", "vaat", "vakantie", "vakleraar", "valbijl", "valpartij", "valreep", "valuatie", "vanmiddag", "vanonder", "varaan", "varken", "vaten", "veenbes", "veeteler", "velgrem", "vellekoop", "velvet", "veneberg", "venlo", "vent", "venusberg", "venw", "veredeld", "verf", "verhaaf", "vermaak", "vernaaid", "verraad", "vers", "veruit", "verzaagd", "vetachtig", "vetlok", "vetmesten", "veto", "vetrek", "vetstaart", "vetten", "veurink", "viaduct", "vibrafoon", "vicariaat", "vieux", "vieveen", "vijfvoud", "villa", "vilt", "vimmetje", "vindbaar", "vips", "virtueel", "visdieven", "visee", "visie", "vlaag", "vleugel", "vmbo", "vocht", "voesenek", "voicemail", "voip", "volg", "vork", "vorselaar", "voyeur", "vracht", "vrekkig", "vreten", "vrije", "vrozen", "vrucht", "vucht", "vugt", "vulkaan", "vulmiddel", "vulva", "vuren", "waas", "wacht", "wadvogel", "wafel", "waffel", "walhalla", "walnoot", "walraven", "wals", "walvis", "wandaad", "wanen", "wanmolen", "want", "warklomp", "warm", "wasachtig", "wasteil", "watt", "webhandel", "weblog", "webpagina", "webzine", "wedereis", "wedstrijd", "weeda", "weert", "wegmaaien", "wegscheer", "wekelijks", "wekken", "wekroep", "wektoon", "weldaad", "welwater", "wendbaar", "wenkbrauw", "wens", "wentelaar", "wervel", "wesseling", "wetboek", "wetmatig", "whirlpool", "wijbrands", "wijdbeens", "wijk", "wijnbes", "wijting", "wild", "wimpelen", "wingebied", "winplaats", "winter", "winzucht", "wipstaart", "wisgerhof", "withaar", "witmaker", "wokkel", "wolf", "wonenden", "woning", "worden", "worp", "wortel", "wrat", "wrijf", "wringen", "yoghurt", "ypsilon", "zaaijer", "zaak", "zacharias", "zakelijk", "zakkam", "zakwater", "zalf", "zalig", "zaniken", "zebracode", "zeeblauw", "zeef", "zeegaand", "zeeuw", "zege", "zegje", "zeil", "zesbaans", "zesenhalf", "zeskantig", "zesmaal", "zetbaas", "zetpil", "zeulen", "ziezo", "zigzag", "zijaltaar", "zijbeuk", "zijlijn", "zijmuur", "zijn", "zijwaarts", "zijzelf", "zilt", "zimmerman", "zinledig", "zinnelijk", "zionist", "zitdag", "zitruimte", "zitzak", "zoal", "zodoende", "zoekbots", "zoem", "zoiets", "zojuist", "zondaar", "zotskap", "zottebol", "zucht", "zuivel", "zulk", "zult", "zuster", "zuur", "zweedijk", "zwendel", "zwepen", "zwiep", "zwijmel", "zworen", ];
pub mod inline_hook; pub mod utils; pub use libil2cpp;
pub mod instance; pub use instance::{ Instance };
//! A JSON schema validation library. //! TODO //! [ ] Null schema //! [ ] schema references per JSON pointer syntax //! [ ] enums #![deny(missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![warn(missing_docs)] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![recursion_limit = "128"] extern crate chrono; #[macro_use] extern crate error_chain; extern crate regex; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate url; extern crate quote; /// Error and result types pub mod errors; /// Basic types pub mod schema; /// Implementation of the array schema pub mod array; /// Implementation of the object schema pub mod object; /// Implementation of the number schema pub mod number; /// Implementation of the string schema pub mod string; /// Implementation of the boolean schema pub mod boolean; /// Implementation of the integer schmea pub mod integer; /// Implementation of references pub mod reference; mod util; pub use schema::{Schema, SchemaBase}; pub use array::ArraySchemaBuilder; pub use object::ObjectSchemaBuilder;
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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. // Regression test pub fn retry<F: Fn()>(f: F) { for _i in 0.. { f(); } } fn main() { for y in 0..4 { let func = || (); func(); } }
/* 借用 * * 借用的实现原理是调用原型变量的`引用`对象, * * 继而在函数中创建一个临时的引用; * * 函数退出之后,临时创建的引用也就不复存在了。 */ fn main() { borrow_common(); borrow_box(); borrow_and_change(); borrow_ref_and_change(); } // 此处借用了一个i32类型变量 fn borrow_i32(n: &i32) { println!("Borrowing int({})", n); } fn destory_box(n: Box<i32>) { println!("Destroying int({})", n); } fn destory_i32(n: i32) { println!("Destroying int({})", n); } fn borrow_common() { // 初始化普通变量 变量保存在栈内 let x = 6_i32; // 借用了 box 的内容,但没有取得所有权,所以 box 的内容之后可以再次借用。 // 译注:请注意函数自身就是一个作用域,因此下面两个函数运行完成以后, // 在函数中临时创建的引用也就不复存在了。 borrow_i32(&x); assert_eq!(x, 6); println!("{}", x); } fn borrow_box() { let x = Box::new(5_i32); borrow_i32(&x); // 退出作用域之后, 对x的引用不再存在, 所有权交还给x, // 接下来可以进行销毁 assert_eq!(*x, 5); destory_box(x); } fn borrow_ref_and_change() { let mut x: i32 = 5; { // 定义一个函数内作用域,说明作用域内如何借用引用 // 对引用的修改会作用到变量原型并一直生效 let r = &mut x; // 引用对象的值被修改 *r += 6; // NOTE: // // 在这个作用域中变量`x`被借用成immutable属性. // // 这个过程中x不可以被使用, 如: // // println!("var x({})", x); // // 否则编译报错: immutable borrow occurs here assert_eq!(*r, 11); // 此时还在作用域中, 但对x的引用已经完成, 这时可以 // 调用x: println!("var x({})", x); } // 退出作用域 assert_eq!(x, 11); destory_i32(x); } // 借用并修改引用参数 fn borrow_and_change() { let mut i: i32 = 5; two_sum(&mut i, 5); assert_eq!(i, 10); } fn two_sum(n: &mut i32, m: i32) { *n += m; }
pub mod deployment; pub mod service;
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; // Definitions of the functionality available in JS, which wasm-bindgen will // generate shims for today (and eventually these should be near-0 cost!) // // These definitions need to be hand-written today but the current vision is // that we'll use WebIDL to generate this `extern` block into a crate which you // can link and import. There's a tracking issue for this at // https://github.com/rustwasm/wasm-bindgen/issues/42 // // In the meantime these are written out by hand and correspond to the names and // signatures documented on MDN, for example #[wasm_bindgen] extern "C" { type HTMLDocument; static document: HTMLDocument; #[wasm_bindgen(method)] fn createElement(this: &HTMLDocument, tagName: &str) -> Element; #[wasm_bindgen(method, getter)] fn body(this: &HTMLDocument) -> Element; type Element; #[wasm_bindgen(method, setter = innerHTML)] fn set_inner_html(this: &Element, html: &str); #[wasm_bindgen(method, js_name = appendChild)] fn append_child(this: &Element, other: Element); } // Called by our JS entry point to run the example #[wasm_bindgen] pub fn run() { let val = document.createElement("p"); val.set_inner_html("Hello from Rust!"); document.body().append_child(val); }
// https://www.codewars.com/kata/5592e3bd57b64d00f3000047 fn find_nb(n: u64) -> i32 { let mut height: u64 = 0; let mut remaining_vol = n; let mut next_vol = (height + 1).pow(3); while remaining_vol >= next_vol { remaining_vol -= next_vol; height += 1; next_vol = (height + 1).pow(3); } if remaining_vol == 0 { return height as i32 } -1 } #[cfg(test)] mod tests { use super::*; fn testing(n: u64, exp: i32) -> () { assert_eq!(find_nb(n), exp); } #[test] fn basics_find_nb() { testing(1, 1); testing(4183059834009, 2022); testing(24723578342962, -1); testing(135440716410000, 4824); testing(40539911473216, 3568); testing(26825883955641, 3218); } }
#[doc = "Reader of register MDMA_C4IFCR"] pub type R = crate::R<u32, super::MDMA_C4IFCR>; #[doc = "Writer for register MDMA_C4IFCR"] pub type W = crate::W<u32, super::MDMA_C4IFCR>; #[doc = "Register MDMA_C4IFCR `reset()`'s with value 0"] impl crate::ResetValue for super::MDMA_C4IFCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `CTEIF4`"] pub struct CTEIF4_W<'a> { w: &'a mut W, } impl<'a> CTEIF4_W<'a> { #[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 } } #[doc = "Write proxy for field `CCTCIF4`"] pub struct CCTCIF4_W<'a> { w: &'a mut W, } impl<'a> CCTCIF4_W<'a> { #[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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `CBRTIF4`"] pub struct CBRTIF4_W<'a> { w: &'a mut W, } impl<'a> CBRTIF4_W<'a> { #[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 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `CBTIF4`"] pub struct CBTIF4_W<'a> { w: &'a mut W, } impl<'a> CBTIF4_W<'a> { #[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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `CLTCIF4`"] pub struct CLTCIF4_W<'a> { w: &'a mut W, } impl<'a> CLTCIF4_W<'a> { #[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 << 4)) | (((value as u32) & 0x01) << 4); self.w } } impl R {} impl W { #[doc = "Bit 0 - CTEIF4"] #[inline(always)] pub fn cteif4(&mut self) -> CTEIF4_W { CTEIF4_W { w: self } } #[doc = "Bit 1 - CCTCIF4"] #[inline(always)] pub fn cctcif4(&mut self) -> CCTCIF4_W { CCTCIF4_W { w: self } } #[doc = "Bit 2 - CBRTIF4"] #[inline(always)] pub fn cbrtif4(&mut self) -> CBRTIF4_W { CBRTIF4_W { w: self } } #[doc = "Bit 3 - CBTIF4"] #[inline(always)] pub fn cbtif4(&mut self) -> CBTIF4_W { CBTIF4_W { w: self } } #[doc = "Bit 4 - CLTCIF4"] #[inline(always)] pub fn cltcif4(&mut self) -> CLTCIF4_W { CLTCIF4_W { w: self } } }
macro_rules! pipe { ($e:expr) => ($e); ($e:expr => $f:ident) => ($f($e)); ($e:expr => $f:ident | $($rest:ident) | *) => ( pipe!($f($e) => $($rest) | *) ); } fn main() { let exclaim = |s| {s + "!"}; let capitalize = |s: String| { let mut c = s.chars(); c.next().unwrap().to_uppercase().collect::<String>() + c.as_str() }; let double_say = |s| String::new() + s + ", " + s; let s = pipe!("hello" => double_say | capitalize | exclaim); println!("{}", s); }
use std::{ collections::VecDeque, fs::File, io::{BufWriter, Write}, sync::{Arc, Mutex, RwLock}, time::Duration, }; use derive_more::From; use serde::Serialize; use time::OffsetDateTime; use tokio::sync::broadcast::error::SendError; use super::{subscriber::EventSubscriber, TestClient, TestClientBuilder}; use crate::{ bson::{doc, to_document, Document}, event::{ cmap::{ CmapEvent, CmapEventHandler, ConnectionCheckedInEvent, ConnectionCheckedOutEvent, ConnectionCheckoutFailedEvent, ConnectionCheckoutStartedEvent, ConnectionClosedEvent, ConnectionCreatedEvent, ConnectionReadyEvent, PoolClearedEvent, PoolClosedEvent, PoolCreatedEvent, PoolReadyEvent, }, command::{ CommandEvent, CommandEventHandler, CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent, }, sdam::{ SdamEventHandler, ServerClosedEvent, ServerDescriptionChangedEvent, ServerHeartbeatFailedEvent, ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent, ServerOpeningEvent, TopologyClosedEvent, TopologyDescriptionChangedEvent, TopologyOpeningEvent, }, }, options::ClientOptions, runtime, test::spec::ExpectedEventType, Client, }; pub(crate) type EventQueue<T> = Arc<RwLock<VecDeque<(T, OffsetDateTime)>>>; fn add_event_to_queue<T>(event_queue: &EventQueue<T>, event: T) { event_queue .write() .unwrap() .push_back((event, OffsetDateTime::now_utc())) } #[derive(Clone, Debug, From)] #[allow(clippy::large_enum_variant)] pub(crate) enum Event { Cmap(CmapEvent), Command(CommandEvent), Sdam(SdamEvent), } impl Event { pub(crate) fn unwrap_sdam_event(self) -> SdamEvent { if let Event::Sdam(e) = self { e } else { panic!("expected SDAM event, instead got {:#?}", self) } } #[cfg(feature = "in-use-encryption-unstable")] pub(crate) fn as_command_started_event(&self) -> Option<&CommandStartedEvent> { match self { Event::Command(CommandEvent::Started(e)) => Some(e), _ => None, } } #[cfg(feature = "in-use-encryption-unstable")] pub(crate) fn into_command_started_event(self) -> Option<CommandStartedEvent> { match self { Self::Command(CommandEvent::Started(ev)) => Some(ev), _ => None, } } } #[derive(Clone, Debug, Serialize)] #[serde(untagged)] pub(crate) enum SdamEvent { ServerDescriptionChanged(Box<ServerDescriptionChangedEvent>), ServerOpening(ServerOpeningEvent), ServerClosed(ServerClosedEvent), TopologyDescriptionChanged(Box<TopologyDescriptionChangedEvent>), TopologyOpening(TopologyOpeningEvent), TopologyClosed(TopologyClosedEvent), ServerHeartbeatStarted(ServerHeartbeatStartedEvent), ServerHeartbeatSucceeded(ServerHeartbeatSucceededEvent), ServerHeartbeatFailed(ServerHeartbeatFailedEvent), } impl SdamEvent { pub fn name(&self) -> &str { match self { Self::ServerDescriptionChanged(_) => "ServerDescriptionChangedEvent", Self::ServerOpening(_) => "ServerOpeningEvent", Self::ServerClosed(_) => "ServerClosedEvent", Self::TopologyDescriptionChanged(_) => "TopologyDescriptionChanged", Self::TopologyOpening(_) => "TopologyOpeningEvent", Self::TopologyClosed(_) => "TopologyClosedEvent", Self::ServerHeartbeatStarted(_) => "ServerHeartbeatStartedEvent", Self::ServerHeartbeatSucceeded(_) => "ServerHeartbeatSucceededEvent", Self::ServerHeartbeatFailed(_) => "ServerHeartbeatFailedEvent", } } } impl CommandEvent { pub fn name(&self) -> &str { match self { Self::Started(_) => "CommandStartedEvent", Self::Succeeded(_) => "CommandSucceededEvent", Self::Failed(_) => "CommandFailedEvent", } } pub(crate) fn command_name(&self) -> &str { match self { CommandEvent::Started(event) => event.command_name.as_str(), CommandEvent::Failed(event) => event.command_name.as_str(), CommandEvent::Succeeded(event) => event.command_name.as_str(), } } fn request_id(&self) -> i32 { match self { CommandEvent::Started(event) => event.request_id, CommandEvent::Failed(event) => event.request_id, CommandEvent::Succeeded(event) => event.request_id, } } pub(crate) fn as_command_started(&self) -> Option<&CommandStartedEvent> { match self { CommandEvent::Started(e) => Some(e), _ => None, } } pub(crate) fn as_command_succeeded(&self) -> Option<&CommandSucceededEvent> { match self { CommandEvent::Succeeded(e) => Some(e), _ => None, } } } #[derive(Clone, Debug)] pub(crate) struct EventHandler { command_events: EventQueue<CommandEvent>, sdam_events: EventQueue<SdamEvent>, cmap_events: EventQueue<CmapEvent>, event_broadcaster: tokio::sync::broadcast::Sender<Event>, connections_checked_out: Arc<Mutex<u32>>, } impl EventHandler { pub(crate) fn new() -> Self { let (event_broadcaster, _) = tokio::sync::broadcast::channel(10_000); Self { command_events: Default::default(), sdam_events: Default::default(), cmap_events: Default::default(), event_broadcaster, connections_checked_out: Arc::new(Mutex::new(0)), } } fn handle(&self, event: impl Into<Event>) { // this only errors if no receivers are listening which isn't a concern here. let _: std::result::Result<usize, SendError<Event>> = self.event_broadcaster.send(event.into()); } pub(crate) fn subscribe(&self) -> EventSubscriber<EventHandler, Event> { EventSubscriber::new(self, self.event_broadcaster.subscribe()) } pub(crate) fn broadcaster(&self) -> &tokio::sync::broadcast::Sender<Event> { &self.event_broadcaster } /// Gets all of the command started events for the specified command names. pub(crate) fn get_command_started_events( &self, command_names: &[&str], ) -> Vec<CommandStartedEvent> { let events = self.command_events.read().unwrap(); events .iter() .filter_map(|(event, _)| match event { CommandEvent::Started(event) => { if command_names.contains(&event.command_name.as_str()) { Some(event.clone()) } else { None } } _ => None, }) .collect() } /// Gets all of the command started events, excluding configureFailPoint events. pub(crate) fn get_all_command_started_events(&self) -> Vec<CommandStartedEvent> { let events = self.command_events.read().unwrap(); events .iter() .filter_map(|(event, _)| match event { CommandEvent::Started(event) if event.command_name != "configureFailPoint" => { Some(event.clone()) } _ => None, }) .collect() } pub(crate) fn get_filtered_events<F>( &self, event_type: ExpectedEventType, filter: F, ) -> Vec<Event> where F: Fn(&Event) -> bool, { match event_type { ExpectedEventType::Command => { let events = self.command_events.read().unwrap(); events .iter() .cloned() .map(|(event, _)| Event::Command(event)) .filter(|e| filter(e)) .collect() } ExpectedEventType::Cmap => { let events = self.cmap_events.read().unwrap(); events .iter() .cloned() .map(|(event, _)| Event::Cmap(event)) .filter(|e| filter(e)) .collect() } ExpectedEventType::CmapWithoutConnectionReady => { let mut events = self.get_filtered_events(ExpectedEventType::Cmap, filter); events.retain(|ev| !matches!(ev, Event::Cmap(CmapEvent::ConnectionReady(_)))); events } } } pub(crate) fn write_events_list_to_file(&self, names: &[&str], writer: &mut BufWriter<File>) { let mut add_comma = false; let mut write_json = |mut event: Document, name: &str, time: &OffsetDateTime| { event.insert("name", name); event.insert("observedAt", time.unix_timestamp()); let mut json_string = serde_json::to_string(&event).unwrap(); if add_comma { json_string.insert(0, ','); } else { add_comma = true; } write!(writer, "{}", json_string).unwrap(); }; for (command_event, time) in self.command_events.read().unwrap().iter() { let name = command_event.name(); if names.contains(&name) { let event = to_document(&command_event).unwrap(); write_json(event, name, time); } } for (sdam_event, time) in self.sdam_events.read().unwrap().iter() { let name = sdam_event.name(); if names.contains(&name) { let event = to_document(&sdam_event).unwrap(); write_json(event, name, time); } } for (cmap_event, time) in self.cmap_events.read().unwrap().iter() { let name = cmap_event.planned_maintenance_testing_name(); if names.contains(&name) { let event = to_document(&cmap_event).unwrap(); write_json(event, name, time); } } } pub(crate) fn connections_checked_out(&self) -> u32 { *self.connections_checked_out.lock().unwrap() } pub(crate) fn clear_cached_events(&self) { self.command_events.write().unwrap().clear(); self.cmap_events.write().unwrap().clear(); self.sdam_events.write().unwrap().clear(); } } impl CmapEventHandler for EventHandler { fn handle_connection_checked_out_event(&self, event: ConnectionCheckedOutEvent) { *self.connections_checked_out.lock().unwrap() += 1; let event = CmapEvent::ConnectionCheckedOut(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_checkout_failed_event(&self, event: ConnectionCheckoutFailedEvent) { let event = CmapEvent::ConnectionCheckoutFailed(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_pool_cleared_event(&self, pool_cleared_event: PoolClearedEvent) { let event = CmapEvent::PoolCleared(pool_cleared_event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_pool_ready_event(&self, event: PoolReadyEvent) { let event = CmapEvent::PoolReady(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_pool_created_event(&self, event: PoolCreatedEvent) { let event = CmapEvent::PoolCreated(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_pool_closed_event(&self, event: PoolClosedEvent) { let event = CmapEvent::PoolClosed(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_created_event(&self, event: ConnectionCreatedEvent) { let event = CmapEvent::ConnectionCreated(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_ready_event(&self, event: ConnectionReadyEvent) { let event = CmapEvent::ConnectionReady(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_closed_event(&self, event: ConnectionClosedEvent) { let event = CmapEvent::ConnectionClosed(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_checkout_started_event(&self, event: ConnectionCheckoutStartedEvent) { let event = CmapEvent::ConnectionCheckoutStarted(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } fn handle_connection_checked_in_event(&self, event: ConnectionCheckedInEvent) { *self.connections_checked_out.lock().unwrap() -= 1; let event = CmapEvent::ConnectionCheckedIn(event); self.handle(event.clone()); add_event_to_queue(&self.cmap_events, event); } } impl SdamEventHandler for EventHandler { fn handle_server_description_changed_event(&self, event: ServerDescriptionChangedEvent) { let event = SdamEvent::ServerDescriptionChanged(Box::new(event)); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_server_opening_event(&self, event: ServerOpeningEvent) { let event = SdamEvent::ServerOpening(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_server_closed_event(&self, event: ServerClosedEvent) { let event = SdamEvent::ServerClosed(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_topology_description_changed_event(&self, event: TopologyDescriptionChangedEvent) { let event = SdamEvent::TopologyDescriptionChanged(Box::new(event)); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_topology_opening_event(&self, event: TopologyOpeningEvent) { let event = SdamEvent::TopologyOpening(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_topology_closed_event(&self, event: TopologyClosedEvent) { let event = SdamEvent::TopologyClosed(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_server_heartbeat_started_event(&self, event: ServerHeartbeatStartedEvent) { let event = SdamEvent::ServerHeartbeatStarted(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_server_heartbeat_succeeded_event(&self, event: ServerHeartbeatSucceededEvent) { let event = SdamEvent::ServerHeartbeatSucceeded(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } fn handle_server_heartbeat_failed_event(&self, event: ServerHeartbeatFailedEvent) { let event = SdamEvent::ServerHeartbeatFailed(event); self.handle(event.clone()); add_event_to_queue(&self.sdam_events, event); } } impl CommandEventHandler for EventHandler { fn handle_command_started_event(&self, event: CommandStartedEvent) { let event = CommandEvent::Started(event); self.handle(event.clone()); add_event_to_queue(&self.command_events, event); } fn handle_command_failed_event(&self, event: CommandFailedEvent) { let event = CommandEvent::Failed(event); self.handle(event.clone()); add_event_to_queue(&self.command_events, event); } fn handle_command_succeeded_event(&self, event: CommandSucceededEvent) { let event = CommandEvent::Succeeded(event); self.handle(event.clone()); add_event_to_queue(&self.command_events, event); } } impl EventSubscriber<'_, EventHandler, Event> { /// Waits for the next CommandStartedEvent/CommandFailedEvent pair. /// If the next CommandStartedEvent is associated with a CommandFailedEvent, this method will /// panic. pub(crate) async fn wait_for_successful_command_execution( &mut self, timeout: Duration, command_name: impl AsRef<str>, ) -> Option<(CommandStartedEvent, CommandSucceededEvent)> { runtime::timeout(timeout, async { let started = self .filter_map_event(Duration::MAX, |event| match event { Event::Command(CommandEvent::Started(s)) if s.command_name == command_name.as_ref() => { Some(s) } _ => None, }) .await .unwrap(); let succeeded = self .filter_map_event(Duration::MAX, |event| match event { Event::Command(CommandEvent::Succeeded(s)) if s.request_id == started.request_id => { Some(s) } Event::Command(CommandEvent::Failed(f)) if f.request_id == started.request_id => { panic!( "expected {} to succeed but it failed: {:#?}", command_name.as_ref(), f ) } _ => None, }) .await .unwrap(); (started, succeeded) }) .await .ok() } } #[derive(Clone, Debug)] pub(crate) struct EventClient { client: TestClient, pub(crate) handler: Arc<EventHandler>, } impl std::ops::Deref for EventClient { type Target = TestClient; fn deref(&self) -> &Self::Target { &self.client } } impl std::ops::DerefMut for EventClient { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.client } } impl TestClientBuilder { pub(crate) fn event_client(self) -> EventClientBuilder { EventClientBuilder { inner: self } } } pub(crate) struct EventClientBuilder { inner: TestClientBuilder, } impl EventClientBuilder { pub(crate) async fn build(self) -> EventClient { let mut inner = self.inner; if inner.handler.is_none() { inner = inner.event_handler(Arc::new(EventHandler::new())); } let handler = inner.handler().unwrap().clone(); let client = inner.build().await; // clear events from commands used to set up client. handler.command_events.write().unwrap().clear(); EventClient { client, handler } } } impl EventClient { pub(crate) async fn new() -> Self { EventClient::with_options(None).await } async fn with_options_and_handler( options: impl Into<Option<ClientOptions>>, handler: impl Into<Option<EventHandler>>, ) -> Self { Client::test_builder() .options(options) .event_handler(handler.into().map(Arc::new)) .event_client() .build() .await } pub(crate) async fn with_options(options: impl Into<Option<ClientOptions>>) -> Self { Self::with_options_and_handler(options, None).await } pub(crate) async fn with_additional_options( options: impl Into<Option<ClientOptions>>, min_heartbeat_freq: Option<Duration>, use_multiple_mongoses: Option<bool>, event_handler: impl Into<Option<EventHandler>>, ) -> Self { Client::test_builder() .additional_options(options, use_multiple_mongoses.unwrap_or(false)) .await .min_heartbeat_freq(min_heartbeat_freq) .event_handler(event_handler.into().map(Arc::new)) .event_client() .build() .await } /// Gets the first started/succeeded pair of events for the given command name, popping off all /// events before and between them. /// /// Panics if the command failed or could not be found in the events. pub(crate) fn get_successful_command_execution( &self, command_name: &str, ) -> (CommandStartedEvent, CommandSucceededEvent) { let mut command_events = self.handler.command_events.write().unwrap(); let mut started: Option<CommandStartedEvent> = None; while let Some((event, _)) = command_events.pop_front() { if event.command_name() == command_name { match started { None => { let event = event .as_command_started() .unwrap_or_else(|| { panic!("first event not a command started event {:?}", event) }) .clone(); started = Some(event); continue; } Some(started) if event.request_id() == started.request_id => { let succeeded = event .as_command_succeeded() .expect("second event not a command succeeded event") .clone(); return (started, succeeded); } _ => continue, } } } panic!("could not find event for {} command", command_name); } /// Gets all of the command started events for the specified command names. pub(crate) fn get_command_started_events( &self, command_names: &[&str], ) -> Vec<CommandStartedEvent> { self.handler.get_command_started_events(command_names) } /// Gets all command started events, excluding configureFailPoint events. pub(crate) fn get_all_command_started_events(&self) -> Vec<CommandStartedEvent> { self.handler.get_all_command_started_events() } pub(crate) fn get_command_events(&self, command_names: &[&str]) -> Vec<CommandEvent> { self.handler .command_events .write() .unwrap() .drain(..) .map(|(event, _)| event) .filter(|event| command_names.contains(&event.command_name())) .collect() } pub(crate) fn count_pool_cleared_events(&self) -> usize { let mut out = 0; for (event, _) in self.handler.cmap_events.read().unwrap().iter() { if matches!(event, CmapEvent::PoolCleared(_)) { out += 1; } } out } #[allow(dead_code)] pub(crate) fn subscribe_to_events(&self) -> EventSubscriber<'_, EventHandler, Event> { self.handler.subscribe() } pub(crate) fn clear_cached_events(&self) { self.handler.clear_cached_events() } #[allow(dead_code)] pub(crate) fn into_client(self) -> crate::Client { self.client.into_client() } } #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn command_started_event_count() { let client = EventClient::new().await; let coll = client.database("foo").collection("bar"); for i in 0..10 { coll.insert_one(doc! { "x": i }, None).await.unwrap(); } assert_eq!(client.get_command_started_events(&["insert"]).len(), 10); }
//! [![Latest Version]][crates.io] //! [![Rust](https://github.com/ralfbiedert/ffsvm-rust/actions/workflows/rust.yml/badge.svg?branch=master)](https://github.com/ralfbiedert/ffsvm-rust/actions/workflows/rust.yml) //! [![deps.svg]][deps] //! [![docs]][docs.rs] //! ![MIT] //! //! # In One Sentence //! //! You trained a SVM using [libSVM](https://github.com/cjlin1/libsvm), now you want the highest possible performance during (real-time) classification, like games or VR. //! //! //! # Highlights //! //! * loads almost all [libSVM](https://github.com/cjlin1/libsvm) types (C-SVC, ν-SVC, ε-SVR, ν-SVR) and kernels (linear, poly, RBF and sigmoid) //! * produces practically same classification results as libSVM //! * optimized for [SIMD](https://github.com/rust-lang/rfcs/pull/2366) and can be mixed seamlessly with [Rayon](https://github.com/rayon-rs/rayon) //! * written in 100% Rust //! * allocation-free during classification for dense SVMs //! * **2.5x - 14x faster than libSVM for dense SVMs** //! * extremely low classification times for small models (e.g., 128 SV, 16 dense attributes, linear ~ 500ns) //! * successfully used in **Unity and VR** projects (Windows & Android) //! //! //! Note: Currently **requires Rust nightly** (March 2019 and later), because we depend on RFC 2366 (portable SIMD). Once that stabilizes we'll also go stable. //! //! //! # Usage //! //! Train with [libSVM](https://github.com/cjlin1/libsvm) (e.g., using the tool `svm-train`), then classify with `ffsvm-rust`. //! //! From Rust: //! //! ```rust //! # use std::convert::TryFrom; //! # use ffsvm::{DenseSVM, Predict, Problem, SAMPLE_MODEL, Solution}; //! # fn main() -> Result<(), ffsvm::Error> { //! // Replace `SAMPLE_MODEL` with a `&str` to your model. //! let svm = DenseSVM::try_from(SAMPLE_MODEL)?; //! //! let mut problem = Problem::from(&svm); //! let features = problem.features(); //! //! features[0] = 0.55838; //! features[1] = -0.157895; //! features[2] = 0.581292; //! features[3] = -0.221184; //! //! svm.predict_value(&mut problem)?; //! //! assert_eq!(problem.solution(), Solution::Label(42)); //! # Ok(()) //! # } //! //! ``` //! //! # Status //! * **March 10, 2023**: Reactivated for latest Rust nightly. //! * **June 7, 2019**: Gave up on 'no `unsafe`', but gained runtime SIMD selection. //! * **March 10, 2019**: As soon as we can move away from nightly we'll go beta. //! * **Aug 5, 2018**: Still in alpha, but finally on crates.io. //! * **May 27, 2018**: We're in alpha. Successfully used internally on Windows, Mac, Android and Linux //! on various machines and devices. Once SIMD stabilizes and we can cross-compile to WASM //! we'll move to beta. //! * **December 16, 2017**: We're in pre-alpha. It will probably not even work on your machine. //! //! //! # Performance //! //! ![performance](https://raw.githubusercontent.com/ralfbiedert/ffsvm-rust/master/docs/performance_relative.v3.png) //! //! All performance numbers reported for the `DenseSVM`. We also have support for `SparseSVM`s, which are slower for "mostly dense" models, and faster for "mostly sparse" models (and generally on the performance level of libSVM). //! //! [See here for details.](https://github.com/ralfbiedert/ffsvm-rust/blob/master/docs/performance.md) //! //! //! ### Tips //! //! * For an x-fold performance increase, create a number of `Problem` structures, and process them with [Rayon's](https://docs.rs/rayon/1.0.3/rayon/) `par_iter`. //! //! //! # FAQ //! //! [See here for details.](https://github.com/ralfbiedert/ffsvm-rust/blob/master/docs/FAQ.md) //! //! [Latest Version]: https://img.shields.io/crates/v/ffsvm.svg //! [crates.io]: https://crates.io/crates/ffsvm //! [MIT]: https://img.shields.io/badge/license-MIT-blue.svg //! [docs]: https://docs.rs/ffsvm/badge.svg //! [docs.rs]: https://docs.rs/ffsvm/ //! [deps]: https://deps.rs/repo/github/ralfbiedert/ffsvm-rust //! [deps.svg]: https://deps.rs/repo/github/ralfbiedert/ffsvm-rust/status.svg #![feature(portable_simd)] #![warn(clippy::all)] // Enable ALL the warnings ... #![warn(clippy::nursery)] #![warn(clippy::pedantic)] #![warn(clippy::cargo)] #![allow(clippy::cast_possible_truncation)] // All our casts are in a range where this doesn't matter. #![allow(clippy::cast_precision_loss)] #![allow(clippy::cast_possible_wrap)] #![allow(clippy::module_name_repetitions)] // We do that way too often #![allow(clippy::doc_markdown)] // Mainly for `libSVM` in the docs. mod errors; mod parser; mod sparse; mod svm; mod util; mod vectors; // Set float types to largest width we support instructions sets // (important to make sure we get max alignment of target_feature) when selecting // dynamically. #[allow(non_camel_case_types)] #[doc(hidden)] pub type f32s = simd_aligned::arch::x256::f32s; #[doc(hidden)] #[allow(non_camel_case_types)] pub type f64s = simd_aligned::arch::x256::f64s; #[doc(hidden)] pub static SAMPLE_MODEL: &str = include_str!("sample.model"); pub use crate::{ errors::Error, parser::{Attribute, Header, ModelFile, SupportVector}, svm::{ kernel::{KernelDense, KernelSparse, Linear, Poly, Rbf, Sigmoid}, predict::Predict, problem::{DenseProblem, Problem, Solution, SparseProblem}, DenseSVM, SVMType, SparseSVM, }, };
use crate::model::{Change, Changeable, Revertable, Watcher, SubWatcher, ChangeConstructor}; use std; /// A change for Option types. /*#[derive(Debug, Clone)] pub enum OptionChange<T: Revertable<C>, C> { Set(Option<T>), Change(C), } impl<T: Revertable<C>, C> Revertable<OptionChange<T, C>> for Option<T> { fn revertable_apply(&mut self, change: OptionChange<T, C>) -> OptionChange<T, C> { use self::OptionChange::*; match change { Set(mut item) => { std::mem::swap(self, &mut item); Set(item) }, Change(subchange) => { let revertchange = self.as_ref().unwrap().revertable_apply(subchange); Change(revertchange) }, } } }*/ #[derive(Debug, Clone, PartialEq)] pub enum OptionSignal<ST> { /// The Option's entire value changed. Reset, /// The value in the Some variant of the Option changed. Change(ST), } /// A change for Option types, which supports nested changes. #[derive(Debug, Clone, PartialEq)] pub enum OptionChange<T: Changeable<C>, C: Change> { /// Set the Option's entire value. Reset(Option<T>), /// Apply the given change to the value in the some variant of the Option. Change(C), } impl<T: 'static + Changeable<C> + Send, C: Change> Change for OptionChange<T, C> { type SignalType = OptionSignal<C::SignalType>; } impl<T: 'static + Changeable<C> + Send, C: Change> Changeable<OptionChange<T, C>> for Option<T> { fn changeable_apply(&mut self, change: OptionChange<T, C>, watcher: &mut Watcher<OptionSignal<C::SignalType>>) { use self::OptionChange::*; match change { Reset(value) => { *self = value; watcher.send_signal(OptionSignal::Reset); } Change(subchange) => { let mut watcher_fn = |signal| { watcher.send_signal(OptionSignal::Change(signal)); }; self.as_mut().unwrap().changeable_apply(subchange, &mut SubWatcher::new(&mut watcher_fn)); } } } fn reset_view_signals(&self) -> Vec<OptionSignal<C::SignalType>> { vec![OptionSignal::Reset] } } impl<T: 'static + Revertable<C> + Send, C: Change> Revertable<OptionChange<T, C>> for Option<T> { fn revertable_apply(&mut self, change: OptionChange<T, C>, watcher: &mut Watcher<OptionSignal<C::SignalType>>) -> OptionChange<T, C> { use self::OptionChange::*; match change { Reset(mut value) => { std::mem::swap(self, &mut value); watcher.send_signal(OptionSignal::Reset); Reset(value) } Change(subchange) => { let mut watcher_fn = |signal| { watcher.send_signal(OptionSignal::Change(signal)); }; let revertchange = self.as_mut().unwrap().revertable_apply(subchange, &mut SubWatcher::new(&mut watcher_fn)); Change(revertchange) } } } } pub struct OptionChangeConstructor<C: Change> { sub: Box<ChangeConstructor<C>>, } impl<C: Change> OptionChangeConstructor<C> { pub fn new(sub: Box<ChangeConstructor<C>>) -> OptionChangeConstructor<C> { OptionChangeConstructor{sub} } } impl<T: 'static + Changeable<C>, C: Change> ChangeConstructor<OptionChange<T, C>> for OptionChangeConstructor<C> { fn create(&self, leaf_change: Box<std::any::Any>) -> OptionChange<T, C> { OptionChange::Change(self.sub.create(leaf_change)) } fn update(&mut self, change: &OptionChange<T, C>) -> bool { use self::OptionChange::*; match *change { Reset(..) => { false } Change(ref change) => { self.sub.update(change) } } } fn debug_string(&self) -> String { format!("Some/{}", self.sub.debug_string()) } }
pub const METADATA_FILENAME: &str = "metadata.json"; pub const PARSER_FILE: &str = "parser";
use rsb_derive::Builder; use crate::errors::*; use crate::listener::signature_verifier::SlackEventSignatureVerifier; use crate::listener::SlackClientEventsListener; use crate::{SlackClient, SlackClientHttpApi}; use futures::future::{BoxFuture, FutureExt, TryFutureExt}; use hyper::body::*; use hyper::{Method, Request, Response, StatusCode}; pub use slack_morphism_models::events::*; use std::collections::HashMap; use std::future::Future; use std::sync::Arc; #[derive(Debug, PartialEq, Clone, Builder)] pub struct SlackInteractionEventsListenerConfig { pub events_signing_secret: String, #[default = "SlackInteractionEventsListenerConfig::DEFAULT_EVENTS_URL_VALUE.into()"] pub events_path: String, } impl SlackInteractionEventsListenerConfig { const DEFAULT_EVENTS_URL_VALUE: &'static str = "/interaction"; } impl SlackClientEventsListener { pub fn interaction_events_service_fn<'a, D, F, I, IF>( &self, config: Arc<SlackInteractionEventsListenerConfig>, interaction_service_fn: I, ) -> impl Fn( Request<Body>, D, ) -> BoxFuture< 'a, Result<Response<Body>, Box<dyn std::error::Error + Send + Sync + 'a>>, > + 'a + Send + Clone where D: Fn(Request<Body>) -> F + 'a + Send + Sync + Clone, F: Future<Output = Result<Response<Body>, Box<dyn std::error::Error + Send + Sync + 'a>>> + 'a + Send, I: Fn(SlackInteractionEvent, Arc<SlackClient>) -> IF + 'static + Send + Sync + Clone, IF: Future<Output = ()> + 'static + Send, { let signature_verifier: Arc<SlackEventSignatureVerifier> = Arc::new( SlackEventSignatureVerifier::new(&config.events_signing_secret), ); let client = self.client.clone(); let error_handler = self.error_handler.clone(); move |req: Request<Body>, chain: D| { let cfg = config.clone(); let serv = interaction_service_fn.clone(); let sign_verifier = signature_verifier.clone(); let sc = client.clone(); let thread_error_handler = error_handler.clone(); async move { match (req.method(), req.uri().path()) { (&Method::POST, url) if url == cfg.events_path => { SlackClientHttpApi::decode_signed_response(req, &sign_verifier) .map_ok(|body| { let body_params: HashMap<String, String> = url::form_urlencoded::parse(body.as_bytes()) .into_owned() .collect(); let payload = body_params .get("payload") .ok_or_else( || SlackClientError::SystemError( SlackClientSystemError::new( "Absent payload in the request from Slack".into(), ), )) .map_err(|e| e.into()); payload.and_then(|payload_value| { serde_json::from_str::<SlackInteractionEvent>(payload_value) .map_err(|e| SlackClientProtocolError{ json_error: e, http_response_body: payload_value.clone() }.into()) }) }) .and_then(|event| async move { match event { Ok(view_submission_event@SlackInteractionEvent::ViewSubmission(_)) => { serv(view_submission_event, sc).await; Response::builder() .status(StatusCode::OK) .body("".into()) .map_err(|e| e.into()) } Ok(interaction_event) => { serv(interaction_event, sc).await; Ok(Response::new(Body::empty())) } Err(event_err) => { thread_error_handler(event_err, sc); Response::builder() .status(StatusCode::FORBIDDEN) .body(Body::empty()) .map_err(|e| e.into()) } } }) .await } _ => chain(req).await, } } .boxed() } } }
use std::fs; use std::env; fn print_flag() { let contents = fs::read_to_string("flag.txt"); println!("{:?}", contents); } fn add_two_numbers(number1: i32,number2: i32) -> i32 { return number1 + number2; } fn main() { let args: Vec<String> = env::args().collect(); match args.len() { // no arguments passed 1 => { println!("Welcome to our super unhackable RUST example which sums up to a constant offset (1337)"); println!("Usage:"); println!("{} <number>", args[0]); }, 2 => { let n1 = &args[1]; let offset : i32 = 1337; // parse the number let number: i32 = match n1.parse() { Ok(n) => { n }, Err(_) => { eprintln!("error: second argument not an integer"); return; }, }; // we only allow positive numbers if number < 0 { println!("Nope"); return; } let sum = add_two_numbers(number, offset); // Sanity check, should never happen - RUST checks for OOB if sum < number { println!("What just happened?"); print_flag(); } else { println!("{:?}",sum); } }, // all the other cases _ => { // show a help message println!("Invalid arguments!"); } } }
use ::core; use ::core::fmt::*; use mantle::concurrency::SingleThreaded; use mantle::kio; use core::ops::DerefMut; use memory::Box; struct DebugOutput; const DEBUG_ON: bool = true; impl Write for DebugOutput { fn write_str(&mut self, s: &str) -> Result { if DEBUG_ON { for c in s.bytes() { kio::debug_put_char(c); } let mut rmut: core::cell::RefMut<Option<&'static mut Write>> = DEBUG_MIRROR.get().borrow_mut(); let rmutr: &mut Option<&'static mut Write> = rmut.deref_mut(); if let &mut Some(ref mut w) = rmutr { w.write_str(s); } } Ok(()) } } static mut DEBUG_OUT: DebugOutput = DebugOutput {}; static DEBUG_MIRROR: SingleThreaded<core::cell::RefCell<Option<&'static mut Write>>> = SingleThreaded(core::cell::RefCell::new(None)); pub fn out() -> &'static mut Write { unsafe { &mut DEBUG_OUT } } pub fn set_mirror<T: Write + 'static>(w: T) { // TODO: clean this up let rf: *mut T = Box::into_raw(Box::new(w)); let bxr: &mut T = unsafe { rf.as_mut() }.unwrap(); *DEBUG_MIRROR.get().borrow_mut() = Some(bxr); } macro_rules! debug { ($fmt:expr) => (write!(::mantle::debug::out(), concat!("[debug] ", $fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (write!(::mantle::debug::out(), concat!("[debug] ", $fmt, "\n"), $($arg)*)); } macro_rules! debugc { ($fmt:expr) => (write!(::mantle::debug::out(), concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => (write!(::mantle::debug::out(), concat!($fmt, "\n"), $($arg)*)); } macro_rules! debugnl { ($fmt:expr) => (write!(::mantle::debug::out(), concat!("[debug] ", $fmt))); ($fmt:expr, $($arg:tt)*) => (write!(::mantle::debug::out(), concat!("[debug] ", $fmt), $($arg)*)); }
mod add_basic; mod add_multiple; mod add_normalized_name_external; mod build; mod build_prefer_existing_version; mod change_rename_target; mod default_features; mod deprecated_default_features; mod deprecated_section; mod detect_workspace_inherit; mod detect_workspace_inherit_features; mod detect_workspace_inherit_optional; mod dev; mod dev_build_conflict; mod dev_prefer_existing_version; mod dry_run; mod features; mod features_empty; mod features_multiple_occurrences; mod features_preserve; mod features_spaced_values; mod features_unknown; mod git; mod git_branch; mod git_conflicts_namever; mod git_dev; mod git_inferred_name; mod git_inferred_name_multiple; mod git_multiple_names; mod git_normalized_name; mod git_registry; mod git_rev; mod git_tag; mod infer_prerelease; mod invalid_arg; mod invalid_git_external; mod invalid_git_name; mod invalid_key_inherit_dependency; mod invalid_key_overwrite_inherit_dependency; mod invalid_key_rename_inherit_dependency; mod invalid_manifest; mod invalid_name_external; mod invalid_path; mod invalid_path_name; mod invalid_path_self; mod invalid_target_empty; mod invalid_vers; mod list_features; mod list_features_path; mod list_features_path_no_default; mod manifest_path_package; mod merge_activated_features; mod multiple_conflicts_with_features; mod multiple_conflicts_with_rename; mod namever; mod no_args; mod no_default_features; mod no_optional; mod optional; mod overwrite_default_features; mod overwrite_default_features_with_no_default_features; mod overwrite_features; mod overwrite_git_with_path; mod overwrite_inherit_features_noop; mod overwrite_inherit_noop; mod overwrite_inherit_optional_noop; mod overwrite_inline_features; mod overwrite_name_dev_noop; mod overwrite_name_noop; mod overwrite_no_default_features; mod overwrite_no_default_features_with_default_features; mod overwrite_no_optional; mod overwrite_no_optional_with_optional; mod overwrite_optional; mod overwrite_optional_with_no_optional; mod overwrite_path_noop; mod overwrite_path_with_version; mod overwrite_rename_with_no_rename; mod overwrite_rename_with_rename; mod overwrite_rename_with_rename_noop; mod overwrite_version_with_git; mod overwrite_version_with_path; mod overwrite_with_rename; mod overwrite_workspace_dep; mod overwrite_workspace_dep_features; mod path; mod path_dev; mod path_inferred_name; mod path_inferred_name_conflicts_full_feature; mod path_normalized_name; mod preserve_sorted; mod preserve_unsorted; mod quiet; mod registry; mod rename; mod require_weak; mod target; mod target_cfg; mod unknown_inherited_feature; mod vers; mod workspace_name; mod workspace_path; mod workspace_path_dev; fn init_registry() { cargo_test_support::registry::init(); add_registry_packages(false); } fn init_alt_registry() { cargo_test_support::registry::alt_init(); add_registry_packages(true); } fn add_registry_packages(alt: bool) { for name in [ "my-package", "my-package1", "my-package2", "my-dev-package1", "my-dev-package2", "my-build-package1", "my-build-package2", "toml", "versioned-package", "cargo-list-test-fixture-dependency", "unrelateed-crate", ] { cargo_test_support::registry::Package::new(name, "0.1.1+my-package") .alternative(alt) .publish(); cargo_test_support::registry::Package::new(name, "0.2.3+my-package") .alternative(alt) .publish(); cargo_test_support::registry::Package::new(name, "0.4.1+my-package") .alternative(alt) .publish(); cargo_test_support::registry::Package::new(name, "20.0.0+my-package") .alternative(alt) .publish(); cargo_test_support::registry::Package::new(name, "99999.0.0+my-package") .alternative(alt) .publish(); cargo_test_support::registry::Package::new(name, "99999.0.0-alpha.1+my-package") .alternative(alt) .publish(); } cargo_test_support::registry::Package::new("prerelease_only", "0.2.0-alpha.1") .alternative(alt) .publish(); cargo_test_support::registry::Package::new("test_breaking", "0.2.0") .alternative(alt) .publish(); cargo_test_support::registry::Package::new("test_nonbreaking", "0.1.1") .alternative(alt) .publish(); // Normalization cargo_test_support::registry::Package::new("linked-hash-map", "0.5.4") .alternative(alt) .feature("clippy", &[]) .feature("heapsize", &[]) .feature("heapsize_impl", &[]) .feature("nightly", &[]) .feature("serde", &[]) .feature("serde_impl", &[]) .feature("serde_test", &[]) .publish(); cargo_test_support::registry::Package::new("inflector", "0.11.4") .alternative(alt) .feature("default", &["heavyweight", "lazy_static", "regex"]) .feature("heavyweight", &[]) .feature("lazy_static", &[]) .feature("regex", &[]) .feature("unstable", &[]) .publish(); cargo_test_support::registry::Package::new("your-face", "99999.0.0+my-package") .alternative(alt) .feature("nose", &[]) .feature("mouth", &[]) .feature("eyes", &[]) .feature("ears", &[]) .publish(); }
#[cfg(feature = "file_utils")] pub mod file_utils; #[cfg(feature = "text_utils")] pub mod text_utils; pub mod intcode; pub mod prelude; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
extern crate rand; use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { let num: i32 = rand::thread_rng().gen_range(0,100); println!("Guess the number!"); loop { // Get input from the user let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read from stdin"); // Convert input to an integer let guess = match guess.trim().parse::<i32>() { Ok(guess_num) => { guess_num }, Err(_) => { println!("BAD"); continue; }, }; println!("You guessed: {}", guess); // match returns an Ok or Err - use these for error checking match guess.cmp(&num) { Ordering::Less => println!("Too low!"), Ordering::Greater => println!("Too high! 420 Blaze it"), Ordering::Equal => { println!("You got it!"); break; }, // _ => println!("You got it"); // <- _ is like a default case in switch statements. } } }
use std::env; use std::fs; use std::path::Path; fn main() { let in_path = Path::new("ld"); let out_dir = env::var("OUT_DIR").unwrap(); let out_path = Path::new(&out_dir); for entry in fs::read_dir(&in_path).unwrap() { let ld_script = entry.unwrap(); fs::copy(ld_script.path(), out_path.join(ld_script.file_name())).unwrap(); } println!("cargo:rustc-link-search=native={}", out_dir); }
#[doc = "Reader of register PERFSEL0"] pub type R = crate::R<u32, super::PERFSEL0>; #[doc = "Writer for register PERFSEL0"] pub type W = crate::W<u32, super::PERFSEL0>; #[doc = "Register PERFSEL0 `reset()`'s with value 0x1f"] impl crate::ResetValue for super::PERFSEL0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x1f } } #[doc = "Select an event for PERFCTR0. Count either contested accesses, or all accesses, on a downstream port of the main crossbar.\n\nValue on reset: 31"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PERFSEL0_A { #[doc = "0: `0`"] APB_CONTESTED = 0, #[doc = "1: `1`"] APB = 1, #[doc = "2: `10`"] FASTPERI_CONTESTED = 2, #[doc = "3: `11`"] FASTPERI = 3, #[doc = "4: `100`"] SRAM5_CONTESTED = 4, #[doc = "5: `101`"] SRAM5 = 5, #[doc = "6: `110`"] SRAM4_CONTESTED = 6, #[doc = "7: `111`"] SRAM4 = 7, #[doc = "8: `1000`"] SRAM3_CONTESTED = 8, #[doc = "9: `1001`"] SRAM3 = 9, #[doc = "10: `1010`"] SRAM2_CONTESTED = 10, #[doc = "11: `1011`"] SRAM2 = 11, #[doc = "12: `1100`"] SRAM1_CONTESTED = 12, #[doc = "13: `1101`"] SRAM1 = 13, #[doc = "14: `1110`"] SRAM0_CONTESTED = 14, #[doc = "15: `1111`"] SRAM0 = 15, #[doc = "16: `10000`"] XIP_MAIN_CONTESTED = 16, #[doc = "17: `10001`"] XIP_MAIN = 17, #[doc = "18: `10010`"] ROM_CONTESTED = 18, #[doc = "19: `10011`"] ROM = 19, } impl From<PERFSEL0_A> for u8 { #[inline(always)] fn from(variant: PERFSEL0_A) -> Self { variant as _ } } #[doc = "Reader of field `PERFSEL0`"] pub type PERFSEL0_R = crate::R<u8, PERFSEL0_A>; impl PERFSEL0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, PERFSEL0_A> { use crate::Variant::*; match self.bits { 0 => Val(PERFSEL0_A::APB_CONTESTED), 1 => Val(PERFSEL0_A::APB), 2 => Val(PERFSEL0_A::FASTPERI_CONTESTED), 3 => Val(PERFSEL0_A::FASTPERI), 4 => Val(PERFSEL0_A::SRAM5_CONTESTED), 5 => Val(PERFSEL0_A::SRAM5), 6 => Val(PERFSEL0_A::SRAM4_CONTESTED), 7 => Val(PERFSEL0_A::SRAM4), 8 => Val(PERFSEL0_A::SRAM3_CONTESTED), 9 => Val(PERFSEL0_A::SRAM3), 10 => Val(PERFSEL0_A::SRAM2_CONTESTED), 11 => Val(PERFSEL0_A::SRAM2), 12 => Val(PERFSEL0_A::SRAM1_CONTESTED), 13 => Val(PERFSEL0_A::SRAM1), 14 => Val(PERFSEL0_A::SRAM0_CONTESTED), 15 => Val(PERFSEL0_A::SRAM0), 16 => Val(PERFSEL0_A::XIP_MAIN_CONTESTED), 17 => Val(PERFSEL0_A::XIP_MAIN), 18 => Val(PERFSEL0_A::ROM_CONTESTED), 19 => Val(PERFSEL0_A::ROM), i => Res(i), } } #[doc = "Checks if the value of the field is `APB_CONTESTED`"] #[inline(always)] pub fn is_apb_contested(&self) -> bool { *self == PERFSEL0_A::APB_CONTESTED } #[doc = "Checks if the value of the field is `APB`"] #[inline(always)] pub fn is_apb(&self) -> bool { *self == PERFSEL0_A::APB } #[doc = "Checks if the value of the field is `FASTPERI_CONTESTED`"] #[inline(always)] pub fn is_fastperi_contested(&self) -> bool { *self == PERFSEL0_A::FASTPERI_CONTESTED } #[doc = "Checks if the value of the field is `FASTPERI`"] #[inline(always)] pub fn is_fastperi(&self) -> bool { *self == PERFSEL0_A::FASTPERI } #[doc = "Checks if the value of the field is `SRAM5_CONTESTED`"] #[inline(always)] pub fn is_sram5_contested(&self) -> bool { *self == PERFSEL0_A::SRAM5_CONTESTED } #[doc = "Checks if the value of the field is `SRAM5`"] #[inline(always)] pub fn is_sram5(&self) -> bool { *self == PERFSEL0_A::SRAM5 } #[doc = "Checks if the value of the field is `SRAM4_CONTESTED`"] #[inline(always)] pub fn is_sram4_contested(&self) -> bool { *self == PERFSEL0_A::SRAM4_CONTESTED } #[doc = "Checks if the value of the field is `SRAM4`"] #[inline(always)] pub fn is_sram4(&self) -> bool { *self == PERFSEL0_A::SRAM4 } #[doc = "Checks if the value of the field is `SRAM3_CONTESTED`"] #[inline(always)] pub fn is_sram3_contested(&self) -> bool { *self == PERFSEL0_A::SRAM3_CONTESTED } #[doc = "Checks if the value of the field is `SRAM3`"] #[inline(always)] pub fn is_sram3(&self) -> bool { *self == PERFSEL0_A::SRAM3 } #[doc = "Checks if the value of the field is `SRAM2_CONTESTED`"] #[inline(always)] pub fn is_sram2_contested(&self) -> bool { *self == PERFSEL0_A::SRAM2_CONTESTED } #[doc = "Checks if the value of the field is `SRAM2`"] #[inline(always)] pub fn is_sram2(&self) -> bool { *self == PERFSEL0_A::SRAM2 } #[doc = "Checks if the value of the field is `SRAM1_CONTESTED`"] #[inline(always)] pub fn is_sram1_contested(&self) -> bool { *self == PERFSEL0_A::SRAM1_CONTESTED } #[doc = "Checks if the value of the field is `SRAM1`"] #[inline(always)] pub fn is_sram1(&self) -> bool { *self == PERFSEL0_A::SRAM1 } #[doc = "Checks if the value of the field is `SRAM0_CONTESTED`"] #[inline(always)] pub fn is_sram0_contested(&self) -> bool { *self == PERFSEL0_A::SRAM0_CONTESTED } #[doc = "Checks if the value of the field is `SRAM0`"] #[inline(always)] pub fn is_sram0(&self) -> bool { *self == PERFSEL0_A::SRAM0 } #[doc = "Checks if the value of the field is `XIP_MAIN_CONTESTED`"] #[inline(always)] pub fn is_xip_main_contested(&self) -> bool { *self == PERFSEL0_A::XIP_MAIN_CONTESTED } #[doc = "Checks if the value of the field is `XIP_MAIN`"] #[inline(always)] pub fn is_xip_main(&self) -> bool { *self == PERFSEL0_A::XIP_MAIN } #[doc = "Checks if the value of the field is `ROM_CONTESTED`"] #[inline(always)] pub fn is_rom_contested(&self) -> bool { *self == PERFSEL0_A::ROM_CONTESTED } #[doc = "Checks if the value of the field is `ROM`"] #[inline(always)] pub fn is_rom(&self) -> bool { *self == PERFSEL0_A::ROM } } #[doc = "Write proxy for field `PERFSEL0`"] pub struct PERFSEL0_W<'a> { w: &'a mut W, } impl<'a> PERFSEL0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PERFSEL0_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "`0`"] #[inline(always)] pub fn apb_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::APB_CONTESTED) } #[doc = "`1`"] #[inline(always)] pub fn apb(self) -> &'a mut W { self.variant(PERFSEL0_A::APB) } #[doc = "`10`"] #[inline(always)] pub fn fastperi_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::FASTPERI_CONTESTED) } #[doc = "`11`"] #[inline(always)] pub fn fastperi(self) -> &'a mut W { self.variant(PERFSEL0_A::FASTPERI) } #[doc = "`100`"] #[inline(always)] pub fn sram5_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM5_CONTESTED) } #[doc = "`101`"] #[inline(always)] pub fn sram5(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM5) } #[doc = "`110`"] #[inline(always)] pub fn sram4_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM4_CONTESTED) } #[doc = "`111`"] #[inline(always)] pub fn sram4(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM4) } #[doc = "`1000`"] #[inline(always)] pub fn sram3_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM3_CONTESTED) } #[doc = "`1001`"] #[inline(always)] pub fn sram3(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM3) } #[doc = "`1010`"] #[inline(always)] pub fn sram2_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM2_CONTESTED) } #[doc = "`1011`"] #[inline(always)] pub fn sram2(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM2) } #[doc = "`1100`"] #[inline(always)] pub fn sram1_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM1_CONTESTED) } #[doc = "`1101`"] #[inline(always)] pub fn sram1(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM1) } #[doc = "`1110`"] #[inline(always)] pub fn sram0_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM0_CONTESTED) } #[doc = "`1111`"] #[inline(always)] pub fn sram0(self) -> &'a mut W { self.variant(PERFSEL0_A::SRAM0) } #[doc = "`10000`"] #[inline(always)] pub fn xip_main_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::XIP_MAIN_CONTESTED) } #[doc = "`10001`"] #[inline(always)] pub fn xip_main(self) -> &'a mut W { self.variant(PERFSEL0_A::XIP_MAIN) } #[doc = "`10010`"] #[inline(always)] pub fn rom_contested(self) -> &'a mut W { self.variant(PERFSEL0_A::ROM_CONTESTED) } #[doc = "`10011`"] #[inline(always)] pub fn rom(self) -> &'a mut W { self.variant(PERFSEL0_A::ROM) } #[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 & !0x1f) | ((value as u32) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - Select an event for PERFCTR0. Count either contested accesses, or all accesses, on a downstream port of the main crossbar."] #[inline(always)] pub fn perfsel0(&self) -> PERFSEL0_R { PERFSEL0_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - Select an event for PERFCTR0. Count either contested accesses, or all accesses, on a downstream port of the main crossbar."] #[inline(always)] pub fn perfsel0(&mut self) -> PERFSEL0_W { PERFSEL0_W { w: self } } }
--- cargo-crates/openssl-sys-0.9.49/build/main.rs.orig 2019-08-16 02:18:38 UTC +++ cargo-crates/openssl-sys-0.9.49/build/main.rs @@ -202,6 +202,8 @@ See rust-openssl README for more informa (2, 9, 0) => ('2', '9', '0'), (2, 9, _) => ('2', '9', 'x'), (3, 0, 0) => ('3', '0', '0'), + (3, 0, 1) => ('3', '0', '1'), + (3, 0, _) => ('3', '0', 'x'), _ => version_error(), }; @@ -242,7 +244,7 @@ fn version_error() -> ! { " This crate is only compatible with OpenSSL 1.0.1 through 1.1.1, or LibreSSL 2.5 -through 2.9.x, but a different version of OpenSSL was found. The build is now aborting +through 3.0.x, but a different version of OpenSSL was found. The build is now aborting due to this version mismatch. "
#![crate_type = "lib"] #![crate_name = "rary"]
use core::cmp::Ordering::*; use crate::{map::Key, set::iterators::Iter, Segment, SegmentMap, SegmentSet}; impl<T> SegmentSet<T> { // TODO: into_intersection_iter pub fn iter_intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> { Intersection { iter_a: self.iter(), prev_a: None, iter_b: other.iter(), prev_b: None, } } // TODO: into_intersection pub fn intersection<'a>(&'a self, other: &'a Self) -> SegmentSet<&'a T> where T: Ord, { // Don't need to insert, since we know ranges produced by the iterator // aren't overlapping SegmentSet { map: SegmentMap { map: self .iter_intersection(other) .map(|r| (Key(r), ())) .collect(), store: alloc::vec::Vec::new(), }, } } } /// Set Intersection A & B impl<'a, T: Ord + Clone> core::ops::BitAnd<&'a SegmentSet<T>> for &'a SegmentSet<T> { type Output = SegmentSet<&'a T>; // TODO: docs /// Returns the intersection of `self` and `rhs` as a new `BTreeSet<T>`. /// /// # Examples /// /// ``` /// use std::collections::BTreeSet; /// /// let a: BTreeSet<_> = vec![1, 2, 3].into_iter().collect(); /// let b: BTreeSet<_> = vec![2, 3, 4].into_iter().collect(); /// /// let result = &a & &b; /// let result_vec: Vec<_> = result.into_iter().collect(); /// assert_eq!(result_vec, [2, 3]); /// ``` fn bitand(self, rhs: &'a SegmentSet<T>) -> SegmentSet<&'a T> { self.intersection(rhs) } } // TODO: into_intersection impl<'a, T: Ord + Clone> core::ops::BitAnd<SegmentSet<T>> for SegmentSet<T> { type Output = SegmentSet<T>; fn bitand(self, rhs: SegmentSet<T>) -> SegmentSet<T> { self.intersection(&rhs).cloned() } } /// Set in-place intersection // impl<T: Ord + Clone> core::ops::BitAndAssign<&SegmentSet<T>> for SegmentSet<T> { // fn bitxor_assign(&mut self, rhs: &SegmentSet<T>) {} // } // impl<T: Ord + Clone> core::ops::BitAndAssign<SegmentSet<T>> for SegmentSet<T> { // fn sub_assign(&mut self, rhs: SegmentSet<T>) { // for range in rhs.iter() { // self.remove(range); // } // } // } pub struct Intersection<'a, T> { iter_a: Iter<'a, T>, prev_a: Option<Segment<&'a T>>, iter_b: Iter<'a, T>, prev_b: Option<Segment<&'a T>>, } impl<'a, T: Ord> Iterator for Intersection<'a, T> { type Item = Segment<&'a T>; fn next(&mut self) -> Option<Self::Item> { // Get the next values. If either ran out, we're done let mut next_a = self .prev_a .take() .or_else(|| self.iter_a.next().map(|x| x.as_ref()))?; let mut next_b = self .prev_b .take() .or_else(|| self.iter_b.next().map(|x| x.as_ref()))?; // Otherwise, find the next common item loop { // If `next_a` is fully before `next_b`, grab another and loop if next_a.end.cmp_start(&next_b.start).is_gt() { next_a = self.iter_a.next()?.as_ref(); continue; } // Likewise the other way around if next_a.start.cmp_end(&next_b.end).is_gt() { next_b = self.iter_b.next()?.as_ref(); continue; } // Otherwise, we have some overlap match (next_a.start.cmp(&next_b.start), next_a.end.cmp(&next_b.end)) { // Partial overlap, but `a` doesn't extend beyond `b`. // Use the overlapped part of `a` and remember to remove it from // `b` for the next iteration. (Less, Less) => { next_a.start = core::mem::replace(&mut next_b.start, next_a.borrow_bound_after().unwrap()); self.prev_b.insert(next_b); return Some(next_a); } // Partial overlap where `a` extends just to the // end of `b` (just use `b`) (Less, Equal) => return Some(next_b), // `a` extends beyond `b` in both directions. // Return `b` but keep the last part of `a` (Less, Greater) => { next_a.start = next_b.borrow_bound_after().unwrap(); self.prev_a.insert(next_a); return Some(next_b); } // Partial overlap where `a` extends just to the // end of `b`. Use `a` and hold on to the end of `b` (Equal, Less) => { next_b.start = next_a.borrow_bound_after().unwrap(); self.prev_b.insert(next_b); return Some(next_a); } // Both exactly overlap each other (Equal, Equal) => return Some(next_a), // Partial overlap, but some `b` past `a` // Keep part of `a` and look for a new `b` (Equal, Greater) => { next_a.start = next_b.borrow_bound_after().unwrap(); self.prev_a.insert(next_a); return Some(next_b); } // `b` extends beyond `a` in both directions. // Use `a` and keep the end of `b` (Greater, Less) => { next_b.start = next_a.borrow_bound_after().unwrap(); self.prev_b.insert(next_b); return Some(next_a); } // Partial overlap, where `b` extends before `a`, but they // end together. Just return `a` (Greater, Equal) => return Some(next_a), // Partial overlap, but `b` doesn't extend beyond `a`. // Use the overlapped part of `b` and keep `a` for the next iteration. (Greater, Greater) => { next_b.start = core::mem::replace(&mut next_a.start, next_b.borrow_bound_after().unwrap()); self.prev_a.insert(next_a); return Some(next_b); } } } } }
extern crate rand; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; pub mod synth; use rand::prelude::*; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug)] pub struct Pitch(pub f32); impl Hash for Pitch { fn hash<H: Hasher>(&self, state: &mut H) { ((self.0 * 1000.0) as i32).hash(state); } } impl PartialEq for Pitch { fn eq(&self, other: &Pitch) -> bool { self.0 == other.0 } } impl Eq for Pitch {} impl Pitch { pub fn apply_interval(&self, interval: f64) -> Pitch { Pitch(self.0 * interval as f32) } } #[derive(Copy, Clone, Debug)] pub struct Interval(pub f64); #[derive(Clone, Debug)] pub struct Chord(pub Vec<Pitch>); impl Chord { pub fn invert(&self) -> Self { let mut chord = self.clone(); if chord.0[0].0 < chord.0[1].0 { chord.0[0] = chord.0[0].apply_interval(2.0); } else { chord.0[0] = chord.0[0].apply_interval(0.5); } chord } pub fn randomize_voicing(&self) -> Self { let mut chord = self.clone(); for pitch in chord.0[1..].iter_mut() { if thread_rng().gen::<f32>() > 0.5 { *pitch = pitch.apply_interval(2.0); } else { *pitch = pitch.apply_interval(0.5); } } chord } } pub struct Scale { interval_pattern: Vec<f32>, } impl Scale { pub fn new(interval_pattern: &[f32]) -> Self { Self { interval_pattern: interval_pattern.iter().cloned().collect(), } } pub fn pitch(&self, base_pitch: &Pitch, degree: i32) -> Pitch { let mut pitch = *base_pitch; let intervals: Vec<f32>; if degree < 0 { intervals = self .interval_pattern .iter() .rev() .map(|i| 1.0 - i) .collect(); } else { intervals = self.interval_pattern.iter().map(|i| 1.0 + i).collect(); } let mut degree = degree.abs(); for interval in intervals.iter().cycle() { if degree <= 0 { break; } pitch.0 *= interval; degree -= 1; } pitch } }
use crate::common::error::prelude::*; use crate::common::LIB_VERSION; use crate::config::PoolConfig; use crate::pool::ProtocolVersion; use crate::utils::validation::Validatable; use std::convert::TryFrom; use std::os::raw::c_char; use std::sync::RwLock; use serde_json; use ffi_support::{define_string_destructor, rust_string_to_c, FfiStr}; #[macro_use] mod macros; mod error; mod ledger; mod pool; mod requests; use error::{set_last_error, ErrorCode}; define_string_destructor!(indy_vdr_string_free); lazy_static! { pub static ref POOL_CONFIG: RwLock<PoolConfig> = RwLock::new(PoolConfig::default()); } #[no_mangle] pub extern "C" fn indy_vdr_set_config(config: FfiStr) -> ErrorCode { catch_err! { trace!("Loading new pool config"); let config: PoolConfig = serde_json::from_str(config.as_str()).with_input_err("Error deserializing config")?; config.validate()?; debug!("Updating pool config: {:?}", config); let mut gcfg = write_lock!(POOL_CONFIG)?; *gcfg = config; Ok(ErrorCode::Success) } } #[no_mangle] pub extern "C" fn indy_vdr_set_default_logger() -> ErrorCode { catch_err! { env_logger::init(); debug!("Initialized default logger"); Ok(ErrorCode::Success) } } #[no_mangle] pub extern "C" fn indy_vdr_set_protocol_version(version: usize) -> ErrorCode { catch_err! { debug!("Setting pool protocol version: {}", version); let version = ProtocolVersion::try_from(version as u64)?; let mut gcfg = write_lock!(POOL_CONFIG)?; gcfg.protocol_version = version; Ok(ErrorCode::Success) } } #[no_mangle] pub extern "C" fn indy_vdr_version() -> *mut c_char { rust_string_to_c(LIB_VERSION.to_owned()) } /* - indy_vdr_get_current_error - indy_vdr_set_protocol_version (for new pools) -> error code - indy_vdr_set_config (for new pools) -> error code - indy_vdr_set_custom_logger(callback) -> error code - indy_vdr_pool_create_from_transactions(char[], *pool_handle) -> error code - indy_vdr_pool_create_from_genesis_file(char[]) -> error code - indy_vdr_pool_get_transactions(pool_handle, char[]*) -> error code - indy_vdr_pool_refresh(pool_handle, callback(command_handle, err, new_txns)) -> error code - indy_vdr_pool_close(pool_handle) -> error code (^ no more requests allowed on this pool, but existing ones may be completed) - indy_vdr_build_{nym, schema, etc}_request(..., *request_handle) -> error code - indy_vdr_build_custom_request(char[] json, *request_handle) -> error code - indy_vdr_pool_submit_request(pool_handle, request_handle, callback(command_handle, err, result_json)) -> error code - indy_vdr_pool_submit_action(pool_handle, request_handle, nodes, timeout, callback(command_handle, err, result_json)) -> error code - indy_vdr_request_free(request_handle) -> error code (^ only needed for a request that isn't submitted) - indy_vdr_request_get_body(request_handle, *char[]) -> error code - indy_vdr_request_get_signature_input(request_handle, *char[]) -> error code - indy_vdr_request_set_signature(request_handle, *char[]) -> error code - indy_vdr_request_add_multi_signature(request_handle, *char[]) -> error code */
mod cm_com; fn main() { cm_com::connect("/dev/ttyUSB0".to_string()); }
use std::convert::TryInto; use std::f32::consts::PI; use std::mem; use std::result; use std::str::FromStr; use cssparser::{Color as CSSColor, Parser, ParserInput}; use napi::*; use crate::error::SkError; use crate::font::Font; use crate::gradient::CanvasGradient; use crate::image::*; use crate::pattern::Pattern; use crate::sk::*; use crate::state::Context2dRenderingState; impl From<SkError> for Error { fn from(err: SkError) -> Error { Error::new(Status::InvalidArg, format!("{}", err)) } } pub struct Context { pub(crate) surface: Surface, path: Path, pub alpha: bool, pub(crate) states: Vec<Context2dRenderingState>, pub collection: FontCollection, } impl Context { #[inline(always)] pub fn create_js_class(env: &Env) -> Result<JsFunction> { env.define_class( "CanvasRenderingContext2D", context_2d_constructor, &vec![ Property::new(&env, "canvas")?.with_value(env.get_null()?), // properties Property::new(&env, "miterLimit")? .with_getter(get_miter_limit) .with_setter(set_miter_limit), Property::new(&env, "globalAlpha")? .with_getter(get_global_alpha) .with_setter(set_global_alpha), Property::new(&env, "globalCompositeOperation")? .with_getter(get_global_composite_operation) .with_setter(set_global_composite_operation), Property::new(&env, "imageSmoothingEnabled")? .with_getter(get_image_smoothing_enabled) .with_setter(set_image_smoothing_enabled), Property::new(&env, "imageSmoothingQuality")? .with_getter(get_image_smoothing_quality) .with_setter(set_image_smoothing_quality), Property::new(&env, "lineCap")? .with_setter(set_line_cap) .with_getter(get_line_cap), Property::new(&env, "lineDashOffset")? .with_setter(set_line_dash_offset) .with_getter(get_line_dash_offset), Property::new(&env, "lineJoin")? .with_setter(set_line_join) .with_getter(get_line_join), Property::new(&env, "lineWidth")? .with_setter(set_line_width) .with_getter(get_line_width), Property::new(&env, "fillStyle")? .with_setter(set_fill_style) .with_getter(get_fill_style), Property::new(&env, "font")? .with_setter(set_font) .with_getter(get_font), Property::new(&env, "strokeStyle")? .with_setter(set_stroke_style) .with_getter(get_stroke_style), Property::new(&env, "shadowBlur")? .with_setter(set_shadow_blur) .with_getter(get_shadow_blur), Property::new(&env, "shadowColor")? .with_setter(set_shadow_color) .with_getter(get_shadow_color), Property::new(&env, "shadowOffsetX")? .with_setter(set_shadow_offset_x) .with_getter(get_shadow_offset_x), Property::new(&env, "shadowOffsetY")? .with_setter(set_shadow_offset_y) .with_getter(get_shadow_offset_y), Property::new(&env, "textAlign")? .with_setter(set_text_align) .with_getter(get_text_align), Property::new(&env, "textBaseline")? .with_setter(set_text_baseline) .with_getter(get_text_baseline), // methods Property::new(&env, "arc")?.with_method(arc), Property::new(&env, "arcTo")?.with_method(arc_to), Property::new(&env, "beginPath")?.with_method(begin_path), Property::new(&env, "bezierCurveTo")?.with_method(bezier_curve_to), Property::new(&env, "clearRect")?.with_method(clear_rect), Property::new(&env, "clip")?.with_method(clip), Property::new(&env, "closePath")?.with_method(close_path), Property::new(&env, "createLinearGradient")?.with_method(create_linear_gradient), Property::new(&env, "createRadialGradient")?.with_method(create_radial_gradient), Property::new(&env, "drawImage")?.with_method(draw_image), Property::new(&env, "getContextAttributes")?.with_method(get_context_attributes), Property::new(&env, "isPointInPath")?.with_method(is_point_in_path), Property::new(&env, "isPointInStroke")?.with_method(is_point_in_stroke), Property::new(&env, "ellipse")?.with_method(ellipse), Property::new(&env, "lineTo")?.with_method(line_to), Property::new(&env, "moveTo")?.with_method(move_to), Property::new(&env, "fill")?.with_method(fill), Property::new(&env, "fillRect")?.with_method(fill_rect), Property::new(&env, "fillText")?.with_method(fill_text), Property::new(&env, "_getImageData")?.with_method(get_image_data), Property::new(&env, "getLineDash")?.with_method(get_line_dash), Property::new(&env, "putImageData")?.with_method(put_image_data), Property::new(&env, "quadraticCurveTo")?.with_method(quadratic_curve_to), Property::new(&env, "rect")?.with_method(rect), Property::new(&env, "resetTransform")?.with_method(reset_transform), Property::new(&env, "restore")?.with_method(restore), Property::new(&env, "rotate")?.with_method(rotate), Property::new(&env, "save")?.with_method(save), Property::new(&env, "scale")?.with_method(scale), Property::new(&env, "setLineDash")?.with_method(set_line_dash), Property::new(&env, "stroke")?.with_method(stroke), Property::new(&env, "strokeRect")?.with_method(stroke_rect), Property::new(&env, "strokeText")?.with_method(stroke_text), Property::new(&env, "translate")?.with_method(translate), Property::new(&env, "transform")?.with_method(transform), // getter setter method Property::new(&env, "getTransform")?.with_method(get_current_transform), Property::new(&env, "setTransform")?.with_method(set_current_transform), ], ) } #[inline(always)] pub fn new(width: u32, height: u32, collection: &mut FontCollection) -> Result<Self> { let surface = Surface::new_rgba(width, height) .ok_or_else(|| Error::from_reason("Create skia surface failed".to_owned()))?; let states = vec![Context2dRenderingState::default()]; Ok(Context { surface, alpha: true, path: Path::new(), states, collection: collection.clone(), }) } #[inline(always)] pub fn clip(&mut self, path: Option<&mut Path>, fill_rule: FillType) { let clip = match path { Some(path) => path, None => &mut self.path, }; clip.set_fill_type(fill_rule); self.surface.canvas.set_clip_path(clip); } #[inline(always)] pub fn save(&mut self) { self.surface.save(); self.states.push(self.states.last().unwrap().clone()); } #[inline(always)] pub fn restore(&mut self) { self.surface.restore(); if self.states.len() > 1 { mem::drop(self.states.pop().unwrap()); } } #[inline(always)] pub fn stroke_rect(&mut self, x: f32, y: f32, w: f32, h: f32) -> result::Result<(), SkError> { let stroke_paint = self.stroke_paint()?; if let Some(shadow_paint) = self.shadow_blur_paint(&stroke_paint) { let surface = &mut self.surface; let last_state = self.states.last().unwrap(); surface.save(); Self::apply_shadow_offset_matrix( surface, last_state.shadow_offset_x, last_state.shadow_offset_y, )?; surface.draw_rect(x, y, w, h, &shadow_paint); surface.restore(); }; self.surface.draw_rect(x, y, w, h, &stroke_paint); Ok(()) } #[inline(always)] pub fn stroke_text(&mut self, text: &str, x: f32, y: f32) -> result::Result<(), SkError> { let stroke_paint = self.stroke_paint()?; self.draw_text(text, x, y, &stroke_paint)?; Ok(()) } #[inline(always)] pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32) -> result::Result<(), SkError> { let fill_paint = self.fill_paint()?; if let Some(shadow_paint) = self.shadow_blur_paint(&fill_paint) { let surface = &mut self.surface; let last_state = self.states.last().unwrap(); surface.save(); Self::apply_shadow_offset_matrix( surface, last_state.shadow_offset_x, last_state.shadow_offset_y, )?; surface.draw_rect(x, y, w, h, &shadow_paint); surface.restore(); }; self.surface.draw_rect(x, y, w, h, &fill_paint); Ok(()) } #[inline(always)] pub fn fill_text(&mut self, text: &str, x: f32, y: f32) -> result::Result<(), SkError> { let fill_paint = self.fill_paint()?; self.draw_text(text, x, y, &fill_paint)?; Ok(()) } #[inline(always)] pub fn stroke(&mut self, path: Option<&Path>) -> Result<()> { let p = path.unwrap_or(&self.path); let stroke_paint = self.stroke_paint()?; if let Some(shadow_paint) = self.shadow_blur_paint(&stroke_paint) { let surface = &mut self.surface; let last_state = self.states.last().unwrap(); surface.save(); Self::apply_shadow_offset_matrix( surface, last_state.shadow_offset_x, last_state.shadow_offset_y, )?; self.surface.canvas.draw_path(p, &shadow_paint); self.surface.restore(); mem::drop(shadow_paint); } self.surface.canvas.draw_path(p, &stroke_paint); Ok(()) } #[inline(always)] pub fn fill( &mut self, path: Option<&mut Path>, fill_rule: FillType, ) -> result::Result<(), SkError> { let p = if let Some(p) = path { p.set_fill_type(fill_rule); p } else { self.path.set_fill_type(fill_rule); &self.path }; let fill_paint = self.fill_paint()?; if let Some(shadow_paint) = self.shadow_blur_paint(&fill_paint) { let surface = &mut self.surface; let last_state = self.states.last().unwrap(); surface.save(); Self::apply_shadow_offset_matrix( surface, last_state.shadow_offset_x, last_state.shadow_offset_y, )?; self.surface.canvas.draw_path(p, &shadow_paint); self.surface.restore(); mem::drop(shadow_paint); } self.surface.draw_path(p, &fill_paint); Ok(()) } #[inline(always)] pub fn fill_paint(&self) -> result::Result<Paint, SkError> { let current_paint = &self.states.last().unwrap().paint; let mut paint = current_paint.clone(); paint.set_style(PaintStyle::Fill); let last_state = self.states.last().unwrap(); let alpha = current_paint.get_alpha(); match &last_state.fill_style { Pattern::Color(c, _) => { let mut color = *c; color.alpha = ((color.alpha as f32) * (alpha as f32 / 255.0)).round() as u8; paint.set_color(color.red, color.green, color.blue, color.alpha); } Pattern::Gradient(g) => { let current_transform = self.surface.canvas.get_transform(); let shader = g.get_shader(&current_transform)?; paint.set_color(0, 0, 0, alpha); paint.set_shader(&shader); } Pattern::ImagePattern(p) => { if let Some(shader) = p.get_shader() { paint.set_color(0, 0, 0, alpha); paint.set_shader(&shader); } } }; if !last_state.line_dash_list.is_empty() { let path_effect = PathEffect::new_dash_path( last_state.line_dash_list.as_slice(), last_state.line_dash_offset, ) .ok_or_else(|| SkError::Generic("Make line dash path effect failed".to_string()))?; paint.set_path_effect(&path_effect); } Ok(paint) } #[inline(always)] fn stroke_paint(&self) -> result::Result<Paint, SkError> { let current_paint = &self.states.last().unwrap().paint; let mut paint = current_paint.clone(); paint.set_style(PaintStyle::Stroke); let last_state = self.states.last().unwrap(); let global_alpha = current_paint.get_alpha(); match &last_state.stroke_style { Pattern::Color(c, _) => { let mut color = *c; color.alpha = ((color.alpha as f32) * (global_alpha as f32 / 255.0)).round() as u8; paint.set_color(color.red, color.green, color.blue, color.alpha); } Pattern::Gradient(g) => { let current_transform = self.surface.canvas.get_transform(); let shader = g.get_shader(&current_transform)?; paint.set_color(0, 0, 0, global_alpha); paint.set_shader(&shader); } Pattern::ImagePattern(p) => { if let Some(shader) = p.get_shader() { paint.set_color(0, 0, 0, current_paint.get_alpha()); paint.set_shader(&shader); } } }; if !last_state.line_dash_list.is_empty() { let path_effect = PathEffect::new_dash_path( last_state.line_dash_list.as_slice(), last_state.line_dash_offset, ) .ok_or_else(|| SkError::Generic("Make line dash path effect failed".to_string()))?; paint.set_path_effect(&path_effect); } Ok(paint) } #[inline(always)] fn drop_shadow_paint(&self, paint: &Paint) -> Option<Paint> { let alpha = paint.get_alpha(); let last_state = self.states.last().unwrap(); let shadow_color = &last_state.shadow_color; let mut shadow_alpha = shadow_color.alpha; shadow_alpha = ((shadow_alpha as f32) * (alpha as f32 / 255.0)) as u8; if shadow_alpha == 0 { return None; } if last_state.shadow_blur == 0f32 && last_state.shadow_offset_x == 0f32 && last_state.shadow_offset_y == 0f32 { return None; } let mut drop_shadow_paint = paint.clone(); let sigma = last_state.shadow_blur / 2f32; let a = shadow_color.alpha; let r = shadow_color.red; let g = shadow_color.green; let b = shadow_color.blue; let shadow_effect = ImageFilter::make_drop_shadow( last_state.shadow_offset_x, last_state.shadow_offset_y, sigma, sigma, (a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | b as u32, )?; drop_shadow_paint.set_alpha(shadow_alpha); drop_shadow_paint.set_image_filter(&shadow_effect); Some(drop_shadow_paint) } #[inline(always)] fn shadow_blur_paint(&self, paint: &Paint) -> Option<Paint> { let alpha = paint.get_alpha(); let last_state = self.states.last().unwrap(); let shadow_color = &last_state.shadow_color; let mut shadow_alpha = shadow_color.alpha; shadow_alpha = ((shadow_alpha as f32) * (alpha as f32 / 255.0)) as u8; if shadow_alpha == 0 { return None; } if last_state.shadow_blur == 0f32 && last_state.shadow_offset_x == 0f32 && last_state.shadow_offset_y == 0f32 { return None; } let mut drop_shadow_paint = paint.clone(); drop_shadow_paint.set_color( shadow_color.red, shadow_color.green, shadow_color.blue, shadow_color.alpha, ); drop_shadow_paint.set_alpha(shadow_alpha); let blur_effect = MaskFilter::make_blur(last_state.shadow_blur / 2f32)?; drop_shadow_paint.set_mask_filter(&blur_effect); Some(drop_shadow_paint) } #[inline(always)] fn draw_image( &mut self, image: &Image, sx: f32, sy: f32, s_width: f32, s_height: f32, dx: f32, dy: f32, d_width: f32, d_height: f32, ) -> Result<()> { let bitmap = image.bitmap.as_ref().unwrap().bitmap; let paint = self.fill_paint()?; if let Some(drop_shadow_paint) = self.drop_shadow_paint(&paint) { let surface = &mut self.surface; surface.canvas.draw_image( bitmap, sx, sy, s_width, s_height, dx, dy, d_width, d_height, &drop_shadow_paint, ); } self.surface.canvas.draw_image( bitmap, sx, sy, s_width, s_height, dx, dy, d_width, d_height, &paint, ); Ok(()) } #[inline(always)] fn draw_text( &mut self, text: &str, x: f32, y: f32, paint: &Paint, ) -> result::Result<(), SkError> { let state = self.states.last().unwrap(); if let Some(shadow_paint) = self.shadow_blur_paint(&paint) { let surface = &mut self.surface; surface.save(); Self::apply_shadow_offset_matrix(surface, state.shadow_offset_x, state.shadow_offset_y)?; surface.canvas.draw_text( text, x, y, &self.collection, state.font_style.size, &state.font_style.family, state.text_baseline, state.text_align, &shadow_paint, ); surface.restore(); } self.surface.canvas.draw_text( text, x, y, &self.collection, state.font_style.size, &state.font_style.family, state.text_baseline, state.text_align, &paint, ); Ok(()) } #[inline(always)] fn apply_shadow_offset_matrix( surface: &mut Surface, shadow_offset_x: f32, shadow_offset_y: f32, ) -> result::Result<(), SkError> { let current_transform = surface.canvas.get_transform_matrix(); let invert = current_transform .invert() .ok_or_else(|| SkError::Generic("Invert matrix failed".to_owned()))?; surface.canvas.concat(invert.into_transform()); let mut shadow_offset = current_transform.clone(); shadow_offset.pre_translate(shadow_offset_x, shadow_offset_y); surface.canvas.concat(shadow_offset.into_transform()); surface.canvas.concat(current_transform.into_transform()); Ok(()) } } #[js_function(3)] fn context_2d_constructor(ctx: CallContext) -> Result<JsUndefined> { let width: u32 = ctx.get::<JsNumber>(0)?.try_into()?; let height: u32 = ctx.get::<JsNumber>(1)?.try_into()?; let collection_js = ctx.get::<JsObject>(2)?; let collection = ctx.env.unwrap::<FontCollection>(&collection_js)?; let mut this = ctx.this_unchecked::<JsObject>(); let context_2d = Context::new(width, height, collection)?; ctx.env.wrap(&mut this, context_2d)?; ctx.env.get_undefined() } #[js_function(6)] fn arc(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let center_x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let center_y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let radius: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let start_angle: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let end_angle: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let from_end = if ctx.length == 6 { ctx.get::<JsBoolean>(5)?.get_value()? } else { false }; context_2d.path.arc( center_x as f32, center_y as f32, radius as f32, start_angle as f32, end_angle as f32, from_end, ); ctx.env.get_undefined() } #[js_function(5)] fn arc_to(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let ctrl_x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let ctrl_y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let to_x: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let to_y: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let radius: f64 = ctx.get::<JsNumber>(4)?.try_into()?; context_2d.path.arc_to_tangent( ctrl_x as f32, ctrl_y as f32, to_x as f32, to_y as f32, radius as f32, ); ctx.env.get_undefined() } #[js_function] fn begin_path(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let new_sub_path = Path::new(); mem::drop(mem::replace(&mut context_2d.path, new_sub_path)); ctx.env.get_undefined() } #[js_function(6)] fn bezier_curve_to(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let cp1x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let cp1y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let cp2x: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let cp2y: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let x: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(5)?.try_into()?; context_2d.path.cubic_to( cp1x as f32, cp1y as f32, cp2x as f32, cp2y as f32, x as f32, y as f32, ); ctx.env.get_undefined() } #[js_function(4)] fn quadratic_curve_to(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let cpx: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let cpy: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let x: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(3)?.try_into()?; context_2d .path .quad_to(cpx as f32, cpy as f32, x as f32, y as f32); ctx.env.get_undefined() } #[js_function(2)] fn clip(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; if ctx.length == 0 { context_2d.clip(None, FillType::Winding); } else if ctx.length == 1 { let rule = ctx.get::<JsString>(0)?; context_2d.clip(None, FillType::from_str(rule.into_utf8()?.as_str()?)?); } else { let path = ctx.get::<JsObject>(0)?; let rule = ctx.get::<JsString>(1)?; context_2d.clip( Some(ctx.env.unwrap::<Path>(&path)?), FillType::from_str(rule.into_utf8()?.as_str()?)?, ); }; ctx.env.get_undefined() } #[js_function(4)] fn rect(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let width: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let height: f64 = ctx.get::<JsNumber>(3)?.try_into()?; context_2d .path .add_rect(x as f32, y as f32, width as f32, height as f32); ctx.env.get_undefined() } #[js_function(2)] fn fill(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; if ctx.length == 0 { context_2d.fill(None, FillType::Winding)?; } else if ctx.length == 1 { let input = ctx.get::<JsUnknown>(0)?; match input.get_type()? { ValueType::String => { let fill_rule_js = unsafe { input.cast::<JsString>() }.into_utf8()?; context_2d.fill(None, FillType::from_str(fill_rule_js.as_str()?)?)?; } ValueType::Object => { let path_js = ctx.get::<JsObject>(0)?; let path = ctx.env.unwrap::<Path>(&path_js)?; context_2d.fill(Some(path), FillType::Winding)?; } _ => { return Err(Error::new( Status::InvalidArg, "Invalid fill argument".to_string(), )) } } } else { let path_js = ctx.get::<JsObject>(0)?; let fill_rule_js = ctx.get::<JsString>(1)?.into_utf8()?; let path = ctx.env.unwrap::<Path>(&path_js)?; context_2d.fill(Some(path), FillType::from_str(fill_rule_js.as_str()?)?)?; }; ctx.env.get_undefined() } #[js_function] fn save(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.save(); ctx.env.get_undefined() } #[js_function] fn restore(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.restore(); ctx.env.get_undefined() } #[js_function(1)] fn rotate(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let angle: f64 = ctx.get::<JsNumber>(0)?.try_into()?; context_2d.path.transform(&Transform::rotate(-angle as f32)); context_2d.surface.canvas.rotate(angle as f32 / PI * 180f32); ctx.env.get_undefined() } #[js_function(4)] fn clear_rect(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let width: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let height: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let mut paint = Paint::new(); paint.set_style(PaintStyle::Fill); paint.set_color(0, 0, 0, 0); paint.set_stroke_miter(10.0); paint.set_blend_mode(BlendMode::Clear); context_2d .surface .draw_rect(x as f32, y as f32, width as f32, height as f32, &paint); ctx.env.get_undefined() } #[js_function(4)] fn create_linear_gradient(ctx: CallContext) -> Result<JsObject> { let x0: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y0: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let x1: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let y1: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let linear_gradient = CanvasGradient::create_linear_gradient(x0 as f32, y0 as f32, x1 as f32, y1 as f32); linear_gradient.into_js_instance(ctx.env) } #[js_function(6)] fn create_radial_gradient(ctx: CallContext) -> Result<JsObject> { let x0: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y0: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let r0: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let x1: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let y1: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let r1: f64 = ctx.get::<JsNumber>(5)?.try_into()?; let radial_gradient = CanvasGradient::create_radial_gradient( x0 as f32, y0 as f32, r0 as f32, x1 as f32, y1 as f32, r1 as f32, ); radial_gradient.into_js_instance(ctx.env) } #[js_function] fn close_path(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.path.close(); ctx.env.get_undefined() } #[js_function(9)] fn draw_image(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let image_js = ctx.get::<JsObject>(0)?; let image = ctx.env.unwrap::<Image>(&image_js)?; let image_w = image.bitmap.as_ref().unwrap().width as f32; let image_h = image.bitmap.as_ref().unwrap().height as f32; if ctx.length == 3 { let dx: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let dy: f64 = ctx.get::<JsNumber>(2)?.try_into()?; context_2d.draw_image( image, 0f32, 0f32, image_w, image_h, dx as f32, dy as f32, image_w, image_h, )?; } else if ctx.length == 5 { let dx: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let dy: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let d_width: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let d_height: f64 = ctx.get::<JsNumber>(4)?.try_into()?; context_2d.draw_image( image, 0f32, 0f32, image_w, image_h, dx as f32, dy as f32, d_width as f32, d_height as f32, )?; } else if ctx.length == 9 { let sx: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let sy: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let s_width: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let s_height: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let dx: f64 = ctx.get::<JsNumber>(5)?.try_into()?; let dy: f64 = ctx.get::<JsNumber>(6)?.try_into()?; let d_width: f64 = ctx.get::<JsNumber>(7)?.try_into()?; let d_height: f64 = ctx.get::<JsNumber>(8)?.try_into()?; context_2d.draw_image( image, sx as f32, sy as f32, s_width as f32, s_height as f32, dx as f32, dy as f32, d_width as f32, d_height as f32, )?; } ctx.env.get_undefined() } #[js_function] fn get_context_attributes(ctx: CallContext) -> Result<JsObject> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let mut obj = ctx.env.create_object()?; obj.set_named_property("alpha", ctx.env.get_boolean(context_2d.alpha)?)?; obj.set_named_property("desynchronized", ctx.env.get_boolean(false)?)?; Ok(obj) } #[js_function(4)] fn is_point_in_path(ctx: CallContext) -> Result<JsBoolean> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let result; if ctx.length == 2 { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; result = context_2d .path .hit_test(y as f32, x as f32, FillType::Winding); ctx.env.get_boolean(result) } else if ctx.length == 3 { let input = ctx.get::<JsUnknown>(0)?; match input.get_type()? { ValueType::Number => { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let fill_rule_js = ctx.get::<JsString>(2)?.into_utf8()?; result = context_2d.path.hit_test( y as f32, x as f32, FillType::from_str(fill_rule_js.as_str()?)?, ); } ValueType::Object => { let x: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let path_js = ctx.get::<JsObject>(0)?; let path = ctx.env.unwrap::<Path>(&path_js)?; result = path.hit_test(x as f32, y as f32, FillType::Winding); } _ => { return Err(Error::new( Status::InvalidArg, "Invalid isPointInPath argument".to_string(), )) } } ctx.env.get_boolean(result) } else if ctx.length == 4 { let path_js = ctx.get::<JsObject>(0)?; let path = ctx.env.unwrap::<Path>(&path_js)?; let x: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let fill_rule_js = ctx.get::<JsString>(3)?.into_utf8()?; result = path.hit_test( y as f32, x as f32, FillType::from_str(fill_rule_js.as_str()?)?, ); ctx.env.get_boolean(result) } else { Err(Error::new( Status::InvalidArg, "Invalid isPointInPath arguments length".to_string(), )) } } #[js_function(3)] fn is_point_in_stroke(ctx: CallContext) -> Result<JsBoolean> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let mut result = false; if ctx.length == 2 { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let stroke_w = context_2d.states.last().unwrap().paint.get_stroke_width() as f32; result = context_2d .path .stroke_hit_test(x as f32, y as f32, stroke_w); } else if ctx.length == 3 { let path_js = ctx.get::<JsObject>(0)?; let path = ctx.env.unwrap::<Path>(&path_js)?; let x: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let stroke_w = context_2d.states.last().unwrap().paint.get_stroke_width() as f32; result = path.stroke_hit_test(x as f32, y as f32, stroke_w); } ctx.env.get_boolean(result) } #[js_function(8)] fn ellipse(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let radius_x: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let radius_y: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let rotation: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let start_angle: f64 = ctx.get::<JsNumber>(5)?.try_into()?; let end_angle: f64 = ctx.get::<JsNumber>(6)?.try_into()?; let from_end = if ctx.length == 8 { ctx.get::<JsBoolean>(7)?.get_value()? } else { false }; context_2d.path.ellipse( x as f32, y as f32, radius_x as f32, radius_y as f32, rotation as f32, start_angle as f32, end_angle as f32, from_end, ); ctx.env.get_undefined() } #[js_function(2)] fn line_to(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; context_2d.path.line_to(x as f32, y as f32); ctx.env.get_undefined() } #[js_function(2)] fn move_to(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; context_2d.path.move_to(x as f32, y as f32); ctx.env.get_undefined() } #[js_function(1)] fn set_miter_limit(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let miter: f64 = ctx.get::<JsNumber>(0)?.try_into()?; context_2d .states .last_mut() .unwrap() .paint .set_stroke_miter(miter as f32); ctx.env.get_undefined() } #[js_function] fn get_miter_limit(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_double(context_2d.states.last().unwrap().paint.get_stroke_miter() as f64) } #[js_function(4)] fn stroke_rect(ctx: CallContext) -> Result<JsUndefined> { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let w: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let h: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.stroke_rect(x as f32, y as f32, w as f32, h as f32)?; ctx.env.get_undefined() } #[js_function(4)] fn stroke_text(ctx: CallContext) -> Result<JsUndefined> { let text = ctx.get::<JsString>(0)?.into_utf8()?; let x: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.stroke_text(text.as_str()?, x as f32, y as f32)?; ctx.env.get_undefined() } #[js_function(4)] fn fill_rect(ctx: CallContext) -> Result<JsUndefined> { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let w: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let h: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.fill_rect(x as f32, y as f32, w as f32, h as f32)?; ctx.env.get_undefined() } #[js_function(4)] fn fill_text(ctx: CallContext) -> Result<JsUndefined> { let text = ctx.get::<JsString>(0)?.into_utf8()?; let x: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.fill_text(text.as_str()?, x as f32, y as f32)?; ctx.env.get_undefined() } #[js_function(4)] fn get_image_data(ctx: CallContext) -> Result<JsTypedArray> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let x: u32 = ctx.get::<JsNumber>(0)?.try_into()?; let y: u32 = ctx.get::<JsNumber>(1)?.try_into()?; let width: u32 = ctx.get::<JsNumber>(2)?.try_into()?; let height: u32 = ctx.get::<JsNumber>(3)?.try_into()?; let pixels = context_2d .surface .read_pixels(x, y, width, height) .ok_or_else(|| { Error::new( Status::GenericFailure, "Read pixels from canvas failed".to_string(), ) })?; let length = pixels.len(); ctx.env.create_arraybuffer_with_data(pixels).and_then(|ab| { ab.into_raw() .into_typedarray(TypedArrayType::Uint8Clamped, length, 0) }) } #[js_function] fn get_line_dash(ctx: CallContext) -> Result<JsObject> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let line_dash_list = &context_2d.states.last().unwrap().line_dash_list; let mut arr = ctx.env.create_array_with_length(line_dash_list.len())?; for (index, a) in line_dash_list.iter().enumerate() { arr.set_element(index as u32, ctx.env.create_double(*a as f64)?)?; } Ok(arr) } #[js_function(7)] fn put_image_data(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let image_data_js = ctx.get::<JsObject>(0)?; let image_data = ctx.env.unwrap::<ImageData>(&image_data_js)?; let dx: u32 = ctx.get::<JsNumber>(1)?.try_into()?; let dy: u32 = ctx.get::<JsNumber>(2)?.try_into()?; if ctx.length == 3 { context_2d.surface.canvas.write_pixels(image_data, dx, dy); } else { let mut dirty_x: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let mut dirty_y = if ctx.length >= 5 { ctx.get::<JsNumber>(4)?.try_into()? } else { 0f64 }; let mut dirty_width = if ctx.length >= 6 { ctx.get::<JsNumber>(5)?.try_into()? } else { image_data.width as f64 }; let mut dirty_height = if ctx.length == 7 { ctx.get::<JsNumber>(6)?.try_into()? } else { image_data.height as f64 }; // as per https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata if dirty_width < 0f64 { dirty_x += dirty_width; dirty_width = dirty_width.abs(); } if dirty_height < 0f64 { dirty_y += dirty_height; dirty_height = dirty_height.abs(); } if dirty_x < 0f64 { dirty_width += dirty_x; dirty_x = 0f64; } if dirty_y < 0f64 { dirty_height += dirty_y; dirty_y = 0f64; } if dirty_width <= 0f64 || dirty_height <= 0f64 { return ctx.env.get_undefined(); } let inverted = context_2d.surface.canvas.get_transform().invert(); context_2d.surface.canvas.save(); if let Some(inverted) = inverted { context_2d.surface.canvas.concat(inverted); }; context_2d.surface.canvas.write_pixels_dirty( image_data, dx, dy, dirty_x, dirty_y, dirty_width, dirty_height, ); context_2d.surface.canvas.restore(); }; ctx.env.get_undefined() } #[js_function(1)] fn set_global_alpha(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let alpha: f64 = ctx.get::<JsNumber>(0)?.try_into()?; if !(0.0..=1.0).contains(&alpha) { return Err(Error::new( Status::InvalidArg, format!( "Alpha value out of range, expected 0.0 - 1.0, but got : {}", alpha ), )); } context_2d .states .last_mut() .unwrap() .paint .set_alpha((alpha * 255.0) as u8); ctx.env.get_undefined() } #[js_function] fn get_global_alpha(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_double((context_2d.states.last().unwrap().paint.get_alpha() as f64) / 255.0) } #[js_function(1)] fn set_global_composite_operation(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let blend_string = ctx.get::<JsString>(0)?.into_utf8()?; context_2d .states .last_mut() .unwrap() .paint .set_blend_mode(BlendMode::from_str(blend_string.as_str()?).map_err(Error::from)?); ctx.env.get_undefined() } #[js_function] fn get_global_composite_operation(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx.env.create_string( context_2d .states .last() .unwrap() .paint .get_blend_mode() .as_str(), ) } #[js_function(1)] fn set_image_smoothing_enabled(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let enabled = ctx.get::<JsBoolean>(0)?; context_2d .states .last_mut() .unwrap() .image_smoothing_enabled = enabled.get_value()?; ctx.env.get_undefined() } #[js_function] fn get_image_smoothing_enabled(ctx: CallContext) -> Result<JsBoolean> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .get_boolean(context_2d.states.last().unwrap().image_smoothing_enabled) } #[js_function(1)] fn set_image_smoothing_quality(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let quality = ctx.get::<JsString>(0)?.into_utf8()?; context_2d .states .last_mut() .unwrap() .image_smoothing_quality = FilterQuality::from_str(quality.as_str()?).map_err(Error::from)?; ctx.env.get_undefined() } #[js_function] fn get_image_smoothing_quality(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx.env.create_string( context_2d .states .last() .unwrap() .image_smoothing_quality .as_str(), ) } #[js_function] fn get_current_transform(ctx: CallContext) -> Result<JsObject> { let mut transform_object = ctx.env.create_object()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let current_transform = context_2d.surface.canvas.get_transform(); transform_object.set_named_property("a", ctx.env.create_double(current_transform.a as f64)?)?; transform_object.set_named_property("b", ctx.env.create_double(current_transform.b as f64)?)?; transform_object.set_named_property("c", ctx.env.create_double(current_transform.c as f64)?)?; transform_object.set_named_property("d", ctx.env.create_double(current_transform.d as f64)?)?; transform_object.set_named_property("e", ctx.env.create_double(current_transform.e as f64)?)?; transform_object.set_named_property("f", ctx.env.create_double(current_transform.f as f64)?)?; Ok(transform_object) } #[js_function(6)] fn set_current_transform(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let transform = if ctx.length == 1 { let transform_object = ctx.get::<JsObject>(0)?; let a: f64 = transform_object .get_named_property::<JsNumber>("a")? .try_into()?; let b: f64 = transform_object .get_named_property::<JsNumber>("b")? .try_into()?; let c: f64 = transform_object .get_named_property::<JsNumber>("c")? .try_into()?; let d: f64 = transform_object .get_named_property::<JsNumber>("d")? .try_into()?; let e: f64 = transform_object .get_named_property::<JsNumber>("e")? .try_into()?; let f: f64 = transform_object .get_named_property::<JsNumber>("f")? .try_into()?; Transform::new(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32) } else if ctx.length == 6 { let a: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let b: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let c: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let d: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let e: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let f: f64 = ctx.get::<JsNumber>(5)?.try_into()?; Transform::new(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32) } else { return Err(Error::new( Status::InvalidArg, "Invalid argument length in setTransform".to_string(), )); }; context_2d.surface.canvas.set_transform(transform); ctx.env.get_undefined() } #[js_function(2)] fn scale(ctx: CallContext) -> Result<JsUndefined> { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.surface.canvas.scale(x as f32, y as f32); ctx.env.get_undefined() } #[js_function(1)] fn set_line_dash(ctx: CallContext) -> Result<JsUndefined> { let dash = ctx.get::<JsObject>(0)?; let len = dash.get_array_length()? as usize; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let is_odd = len & 1 != 0; let mut dash_list = if is_odd { vec![0f32; len * 2] } else { vec![0f32; len] }; for idx in 0..len { let dash_value: f64 = dash.get_element::<JsNumber>(idx as u32)?.try_into()?; dash_list[idx] = dash_value as f32; if is_odd { dash_list[idx + len] = dash_value as f32; } } context_2d.states.last_mut().unwrap().line_dash_list = dash_list; ctx.env.get_undefined() } #[js_function(1)] fn stroke(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let path = if ctx.length == 0 { None } else { let js_path = ctx.get::<JsObject>(0)?; let path = ctx.env.unwrap::<Path>(&js_path)?; Some(path) }; context_2d.stroke(path.as_deref())?; ctx.env.get_undefined() } #[js_function(2)] fn translate(ctx: CallContext) -> Result<JsUndefined> { let x: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let y: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let mut inverted = Matrix::identity(); inverted.pre_translate(-x as f32, -y as f32); context_2d.path.transform_matrix(&inverted); context_2d.surface.canvas.translate(x as f32, y as f32); ctx.env.get_undefined() } #[js_function(6)] fn transform(ctx: CallContext) -> Result<JsUndefined> { let a: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let b: f64 = ctx.get::<JsNumber>(1)?.try_into()?; let c: f64 = ctx.get::<JsNumber>(2)?.try_into()?; let d: f64 = ctx.get::<JsNumber>(3)?.try_into()?; let e: f64 = ctx.get::<JsNumber>(4)?.try_into()?; let f: f64 = ctx.get::<JsNumber>(5)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let new_transform = Transform::new(a as f32, b as f32, c as f32, d as f32, e as f32, f as f32); let inverted = new_transform .invert() .ok_or_else(|| Error::new(Status::InvalidArg, "Invalid transform".to_owned()))?; context_2d.path.transform(&inverted); context_2d.surface.canvas.concat(new_transform); ctx.env.get_undefined() } #[js_function] fn reset_transform(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.surface.canvas.reset_transform(); ctx.env.get_undefined() } #[js_function] fn get_line_cap(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx.env.create_string( context_2d .states .last() .unwrap() .paint .get_stroke_cap() .as_str(), ) } #[js_function(1)] fn set_line_cap(ctx: CallContext) -> Result<JsUndefined> { let line_cap_string = ctx.get::<JsString>(0)?; let line_cap = line_cap_string.into_utf8()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d .states .last_mut() .unwrap() .paint .set_stroke_cap(StrokeCap::from_str(line_cap.as_str()?)?); ctx.env.get_undefined() } #[js_function] fn get_line_dash_offset(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_double(context_2d.states.last_mut().unwrap().line_dash_offset as f64) } #[js_function(1)] fn set_line_dash_offset(ctx: CallContext) -> Result<JsUndefined> { let line_offset_number = ctx.get::<JsNumber>(0)?; let offset: f64 = line_offset_number.get_double()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.states.last_mut().unwrap().line_dash_offset = offset as f32; ctx.env.get_undefined() } #[js_function] fn get_line_join(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx.env.create_string( context_2d .states .last() .unwrap() .paint .get_stroke_join() .as_str(), ) } #[js_function(1)] fn set_line_join(ctx: CallContext) -> Result<JsUndefined> { let line_join_string = ctx.get::<JsString>(0)?; let line_join = line_join_string.into_utf8()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d .states .last_mut() .unwrap() .paint .set_stroke_join(StrokeJoin::from_str(line_join.as_str()?)?); ctx.env.get_undefined() } #[js_function] fn get_line_width(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_double(context_2d.states.last().unwrap().paint.get_stroke_width() as f64) } #[js_function(1)] fn set_line_width(ctx: CallContext) -> Result<JsUndefined> { let width: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d .states .last_mut() .unwrap() .paint .set_stroke_width(width as f32); ctx.env.get_undefined() } #[js_function(1)] fn set_fill_style(ctx: CallContext) -> Result<JsUndefined> { let mut this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let js_fill_style = ctx.get::<JsUnknown>(0)?; let last_state = context_2d.states.last_mut().unwrap(); match js_fill_style.get_type()? { ValueType::String => { let js_color = unsafe { js_fill_style.cast::<JsString>() }.into_utf8()?; last_state.fill_style = Pattern::from_color(js_color.as_str()?)?; } ValueType::Object => { let fill_object = unsafe { js_fill_style.cast::<JsObject>() }; let pattern = ctx.env.unwrap::<Pattern>(&fill_object)?; last_state.fill_style = pattern.clone(); } _ => { return Err(Error::new( Status::InvalidArg, "Invalid fillStyle".to_string(), )) } } this.set_named_property("_fillStyle", js_fill_style)?; ctx.env.get_undefined() } #[js_function] fn get_fill_style(ctx: CallContext) -> Result<JsUnknown> { let this = ctx.this_unchecked::<JsObject>(); this.get_named_property("_fillStyle") } #[js_function] fn get_font(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_string(context_2d.states.last().unwrap().font.as_str()) } #[js_function(1)] fn set_font(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); let font_style = ctx.get::<JsString>(0)?.into_utf8()?.into_owned()?; last_state.font_style = Font::new(font_style.as_str()).map_err(|e| Error::new(Status::InvalidArg, format!("{}", e)))?; last_state.font = font_style; ctx.env.get_undefined() } #[js_function(1)] fn set_stroke_style(ctx: CallContext) -> Result<JsUndefined> { let mut this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let js_stroke_style = ctx.get::<JsUnknown>(0)?; let last_state = context_2d.states.last_mut().unwrap(); match js_stroke_style.get_type()? { ValueType::String => { let js_color = unsafe { JsString::from_raw_unchecked(ctx.env.raw(), js_stroke_style.raw()) } .into_utf8()?; last_state.stroke_style = Pattern::from_color(js_color.as_str()?)?; } ValueType::Object => { let stroke_object = unsafe { js_stroke_style.cast::<JsObject>() }; let pattern = ctx.env.unwrap::<Pattern>(&stroke_object)?; last_state.stroke_style = pattern.clone(); } _ => { return Err(Error::new( Status::InvalidArg, "Invalid strokeStyle".to_string(), )) } } this.set_named_property("_strokeStyle", js_stroke_style)?; ctx.env.get_undefined() } #[js_function] fn get_stroke_style(ctx: CallContext) -> Result<JsUnknown> { let this = ctx.this_unchecked::<JsObject>(); this.get_named_property("_strokeStyle") } #[js_function] fn get_shadow_blur(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); ctx.env.create_double(last_state.shadow_blur as f64) } #[js_function(1)] fn set_shadow_blur(ctx: CallContext) -> Result<JsUndefined> { let blur: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.states.last_mut().unwrap().shadow_blur = blur as f32; ctx.env.get_undefined() } #[js_function] fn get_shadow_color(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx.env.create_string( context_2d .states .last() .unwrap() .shadow_color_string .as_str(), ) } #[js_function(1)] fn set_shadow_color(ctx: CallContext) -> Result<JsUndefined> { let shadow_color_string = ctx.get::<JsString>(0)?; let shadow_color = shadow_color_string.into_utf8()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); let shadow_color_str = shadow_color.as_str()?; last_state.shadow_color_string = shadow_color_str.to_owned(); let mut parser_input = ParserInput::new(shadow_color_str); let mut parser = Parser::new(&mut parser_input); let color = CSSColor::parse(&mut parser).map_err(|e| SkError::Generic(format!("Invalid color {:?}", e)))?; match color { CSSColor::CurrentColor => { return Err(Error::new( Status::InvalidArg, "Color should not be `currentcolor` keyword".to_owned(), )) } CSSColor::RGBA(rgba) => { last_state.shadow_color = rgba; } } ctx.env.get_undefined() } #[js_function] fn get_shadow_offset_x(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); ctx.env.create_double(last_state.shadow_offset_x as f64) } #[js_function(1)] fn set_shadow_offset_x(ctx: CallContext) -> Result<JsUndefined> { let offset: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); last_state.shadow_offset_x = offset as f32; ctx.env.get_undefined() } #[js_function] fn get_shadow_offset_y(ctx: CallContext) -> Result<JsNumber> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); ctx.env.create_double(last_state.shadow_offset_y as f64) } #[js_function(1)] fn set_shadow_offset_y(ctx: CallContext) -> Result<JsUndefined> { let offset: f64 = ctx.get::<JsNumber>(0)?.try_into()?; let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; let last_state = context_2d.states.last_mut().unwrap(); last_state.shadow_offset_y = offset as f32; ctx.env.get_undefined() } #[js_function(1)] fn set_text_align(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.states.last_mut().unwrap().text_align = TextAlign::from_str(ctx.get::<JsString>(0)?.into_utf8()?.as_str()?)?; ctx.env.get_undefined() } #[js_function] fn get_text_align(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_string(context_2d.states.last().unwrap().text_align.as_str()) } #[js_function(1)] fn set_text_baseline(ctx: CallContext) -> Result<JsUndefined> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; context_2d.states.last_mut().unwrap().text_baseline = TextBaseline::from_str(ctx.get::<JsString>(0)?.into_utf8()?.as_str()?)?; ctx.env.get_undefined() } #[js_function] fn get_text_baseline(ctx: CallContext) -> Result<JsString> { let this = ctx.this_unchecked::<JsObject>(); let context_2d = ctx.env.unwrap::<Context>(&this)?; ctx .env .create_string(context_2d.states.last().unwrap().text_baseline.as_str()) } pub enum ContextData { PNG(SurfaceRef), JPEG(SurfaceRef, u8), } unsafe impl Send for ContextData {} unsafe impl Sync for ContextData {} impl Task for ContextData { type Output = SurfaceDataRef; type JsValue = JsBuffer; fn compute(&mut self) -> Result<Self::Output> { match self { ContextData::PNG(surface) => surface.png_data().ok_or_else(|| { Error::new( Status::GenericFailure, "Get png data from surface failed".to_string(), ) }), ContextData::JPEG(surface, quality) => surface.jpeg_data(*quality).ok_or_else(|| { Error::new( Status::GenericFailure, "Get png data from surface failed".to_string(), ) }), } } fn resolve(self, env: Env, output: Self::Output) -> Result<Self::JsValue> { unsafe { env .create_buffer_with_borrowed_data( output.0.ptr, output.0.size, output, |data_ref: Self::Output, _| data_ref.unref(), ) .map(|value| value.into_raw()) } } }
use super::{Command, CMD_GROUPS}; use crate::{ arguments::Stream, database::Prefix, util::{constants::common_literals::HELP, CowUtils}, }; use std::borrow::Cow; #[derive(Debug)] pub enum Invoke { Command { cmd: &'static Command, num: Option<usize>, }, SubCommand { main: &'static Command, sub: &'static Command, }, Help(Option<&'static Command>), FailedHelp(String), None, } impl Invoke { pub fn name(&self) -> Cow<'_, str> { match self { Invoke::Command { cmd, .. } => Cow::Borrowed(cmd.names[0]), Invoke::SubCommand { main, sub } => { Cow::Owned(format!("{}-{}", main.names[0], sub.names[0])) } Invoke::Help(_) | Invoke::FailedHelp(_) => Cow::Borrowed(HELP), Invoke::None => Cow::default(), } } } pub fn find_prefix<'a>(prefixes: &[Prefix], stream: &mut Stream<'a>) -> bool { prefixes.iter().any(|p| { if stream.starts_with(p) { stream.increment(p.len()); true } else { false } }) } pub fn parse_invoke(stream: &mut Stream<'_>) -> Invoke { let mut name = stream .take_until_char(|c| c.is_whitespace() || c.is_numeric()) .cow_to_ascii_lowercase(); let num_str = stream.take_while_char(char::is_numeric); let num = if num_str.is_empty() { None } else if name.is_empty() { name = Cow::Borrowed(num_str); None } else { let n = num_str.chars().fold(0_usize, |n, c| { n.wrapping_mul(10).wrapping_add((c as u8 & 0xF) as usize) }); Some(n) }; stream.take_while_char(char::is_whitespace); match name.as_ref() { "h" | HELP => { let name = stream .take_until_char(char::is_whitespace) .cow_to_ascii_lowercase(); stream.take_while_char(char::is_whitespace); if name.is_empty() { Invoke::Help(None) } else if let Some(cmd) = CMD_GROUPS.get(name.as_ref()) { Invoke::Help(Some(cmd)) } else { Invoke::FailedHelp(name.into_owned()) } } _ => { if let Some(cmd) = CMD_GROUPS.get(name.as_ref()) { let name = stream .peek_until_char(|c| c.is_whitespace()) .cow_to_ascii_lowercase(); for sub_cmd in cmd.sub_commands { if sub_cmd.names.contains(&name.as_ref()) { stream.increment(name.chars().count()); stream.take_while_char(char::is_whitespace); return Invoke::SubCommand { main: cmd, sub: sub_cmd, }; } } Invoke::Command { cmd, num } } else { Invoke::None } } } }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `EN` reader - AES enable This bit enables/disables the AES peripheral: At any moment, clearing then setting the bit re-initializes the AES peripheral. This bit is automatically cleared by hardware upon the completion of the key preparation (Mode 2) and upon the completion of GCM/GMAC/CCM initial phase."] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - AES enable This bit enables/disables the AES peripheral: At any moment, clearing then setting the bit re-initializes the AES peripheral. This bit is automatically cleared by hardware upon the completion of the key preparation (Mode 2) and upon the completion of GCM/GMAC/CCM initial phase."] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DATATYPE` reader - Data type selection This bitfield defines the format of data written in the AES_DINR register or read from the AES_DOUTR register, through selecting the mode of data swapping: For more details, refer to . Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type DATATYPE_R = crate::FieldReader; #[doc = "Field `DATATYPE` writer - Data type selection This bitfield defines the format of data written in the AES_DINR register or read from the AES_DOUTR register, through selecting the mode of data swapping: For more details, refer to . Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type DATATYPE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `MODE` reader - AES operating mode This bitfield selects the AES operating mode: Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access. Any attempt to selecting Mode 4 while either ECB or CBC chaining mode is not selected, defaults to effective selection of Mode 3. It is not possible to select a Mode 3 following a Mode 4."] pub type MODE_R = crate::FieldReader; #[doc = "Field `MODE` writer - AES operating mode This bitfield selects the AES operating mode: Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access. Any attempt to selecting Mode 4 while either ECB or CBC chaining mode is not selected, defaults to effective selection of Mode 3. It is not possible to select a Mode 3 following a Mode 4."] pub type MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CHMOD1` reader - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type CHMOD1_R = crate::FieldReader; #[doc = "Field `CHMOD1` writer - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type CHMOD1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CCFC` reader - Computation complete flag clear Upon written to 1, this bit clears the computation complete flag (CCF) in the AES_SR register: Reading the flag always returns zero."] pub type CCFC_R = crate::BitReader; #[doc = "Field `CCFC` writer - Computation complete flag clear Upon written to 1, this bit clears the computation complete flag (CCF) in the AES_SR register: Reading the flag always returns zero."] pub type CCFC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ERRC` reader - Error flag clear Upon written to 1, this bit clears the RDERR and WRERR error flags in the AES_SR register: Reading the flag always returns zero."] pub type ERRC_R = crate::BitReader; #[doc = "Field `ERRC` writer - Error flag clear Upon written to 1, this bit clears the RDERR and WRERR error flags in the AES_SR register: Reading the flag always returns zero."] pub type ERRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CCFIE` reader - CCF interrupt enable This bit enables or disables (masks) the AES interrupt generation when CCF (computation complete flag) is set:"] pub type CCFIE_R = crate::BitReader; #[doc = "Field `CCFIE` writer - CCF interrupt enable This bit enables or disables (masks) the AES interrupt generation when CCF (computation complete flag) is set:"] pub type CCFIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ERRIE` reader - Error interrupt enable This bit enables or disables (masks) the AES interrupt generation when RDERR and/or WRERR is set:"] pub type ERRIE_R = crate::BitReader; #[doc = "Field `ERRIE` writer - Error interrupt enable This bit enables or disables (masks) the AES interrupt generation when RDERR and/or WRERR is set:"] pub type ERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMAINEN` reader - DMA input enable This bit enables/disables data transferring with DMA, in the input phase: When the bit is set, DMA requests are automatically generated by AES during the input data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] pub type DMAINEN_R = crate::BitReader; #[doc = "Field `DMAINEN` writer - DMA input enable This bit enables/disables data transferring with DMA, in the input phase: When the bit is set, DMA requests are automatically generated by AES during the input data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] pub type DMAINEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMAOUTEN` reader - DMA output enable This bit enables/disables data transferring with DMA, in the output phase: When the bit is set, DMA requests are automatically generated by AES during the output data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] pub type DMAOUTEN_R = crate::BitReader; #[doc = "Field `DMAOUTEN` writer - DMA output enable This bit enables/disables data transferring with DMA, in the output phase: When the bit is set, DMA requests are automatically generated by AES during the output data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] pub type DMAOUTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GCMPH` reader - GCM or CCM phase selection This bitfield selects the phase of GCM, GMAC or CCM algorithm: The bitfield has no effect if other than GCM, GMAC or CCM algorithms are selected (through the ALGOMODE bitfield)."] pub type GCMPH_R = crate::FieldReader; #[doc = "Field `GCMPH` writer - GCM or CCM phase selection This bitfield selects the phase of GCM, GMAC or CCM algorithm: The bitfield has no effect if other than GCM, GMAC or CCM algorithms are selected (through the ALGOMODE bitfield)."] pub type GCMPH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CHMOD2` reader - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type CHMOD2_R = crate::BitReader; #[doc = "Field `CHMOD2` writer - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type CHMOD2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `KEYSIZE` reader - Key size selection This bitfield defines the length of the key used in the AES cryptographic core, in bits: Attempts to write the bit are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type KEYSIZE_R = crate::BitReader; #[doc = "Field `KEYSIZE` writer - Key size selection This bitfield defines the length of the key used in the AES cryptographic core, in bits: Attempts to write the bit are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] pub type KEYSIZE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `NPBLB` reader - Number of padding bytes in last block The bitfield sets the number of padding bytes in last block of payload: ..."] pub type NPBLB_R = crate::FieldReader; #[doc = "Field `NPBLB` writer - Number of padding bytes in last block The bitfield sets the number of padding bytes in last block of payload: ..."] pub type NPBLB_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bit 0 - AES enable This bit enables/disables the AES peripheral: At any moment, clearing then setting the bit re-initializes the AES peripheral. This bit is automatically cleared by hardware upon the completion of the key preparation (Mode 2) and upon the completion of GCM/GMAC/CCM initial phase."] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 1) != 0) } #[doc = "Bits 1:2 - Data type selection This bitfield defines the format of data written in the AES_DINR register or read from the AES_DOUTR register, through selecting the mode of data swapping: For more details, refer to . Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] pub fn datatype(&self) -> DATATYPE_R { DATATYPE_R::new(((self.bits >> 1) & 3) as u8) } #[doc = "Bits 3:4 - AES operating mode This bitfield selects the AES operating mode: Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access. Any attempt to selecting Mode 4 while either ECB or CBC chaining mode is not selected, defaults to effective selection of Mode 3. It is not possible to select a Mode 3 following a Mode 4."] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new(((self.bits >> 3) & 3) as u8) } #[doc = "Bits 5:6 - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] pub fn chmod1(&self) -> CHMOD1_R { CHMOD1_R::new(((self.bits >> 5) & 3) as u8) } #[doc = "Bit 7 - Computation complete flag clear Upon written to 1, this bit clears the computation complete flag (CCF) in the AES_SR register: Reading the flag always returns zero."] #[inline(always)] pub fn ccfc(&self) -> CCFC_R { CCFC_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Error flag clear Upon written to 1, this bit clears the RDERR and WRERR error flags in the AES_SR register: Reading the flag always returns zero."] #[inline(always)] pub fn errc(&self) -> ERRC_R { ERRC_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - CCF interrupt enable This bit enables or disables (masks) the AES interrupt generation when CCF (computation complete flag) is set:"] #[inline(always)] pub fn ccfie(&self) -> CCFIE_R { CCFIE_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Error interrupt enable This bit enables or disables (masks) the AES interrupt generation when RDERR and/or WRERR is set:"] #[inline(always)] pub fn errie(&self) -> ERRIE_R { ERRIE_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - DMA input enable This bit enables/disables data transferring with DMA, in the input phase: When the bit is set, DMA requests are automatically generated by AES during the input data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] #[inline(always)] pub fn dmainen(&self) -> DMAINEN_R { DMAINEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - DMA output enable This bit enables/disables data transferring with DMA, in the output phase: When the bit is set, DMA requests are automatically generated by AES during the output data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] #[inline(always)] pub fn dmaouten(&self) -> DMAOUTEN_R { DMAOUTEN_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bits 13:14 - GCM or CCM phase selection This bitfield selects the phase of GCM, GMAC or CCM algorithm: The bitfield has no effect if other than GCM, GMAC or CCM algorithms are selected (through the ALGOMODE bitfield)."] #[inline(always)] pub fn gcmph(&self) -> GCMPH_R { GCMPH_R::new(((self.bits >> 13) & 3) as u8) } #[doc = "Bit 16 - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] pub fn chmod2(&self) -> CHMOD2_R { CHMOD2_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 18 - Key size selection This bitfield defines the length of the key used in the AES cryptographic core, in bits: Attempts to write the bit are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] pub fn keysize(&self) -> KEYSIZE_R { KEYSIZE_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bits 20:23 - Number of padding bytes in last block The bitfield sets the number of padding bytes in last block of payload: ..."] #[inline(always)] pub fn npblb(&self) -> NPBLB_R { NPBLB_R::new(((self.bits >> 20) & 0x0f) as u8) } } impl W { #[doc = "Bit 0 - AES enable This bit enables/disables the AES peripheral: At any moment, clearing then setting the bit re-initializes the AES peripheral. This bit is automatically cleared by hardware upon the completion of the key preparation (Mode 2) and upon the completion of GCM/GMAC/CCM initial phase."] #[inline(always)] #[must_use] pub fn en(&mut self) -> EN_W<CR_SPEC, 0> { EN_W::new(self) } #[doc = "Bits 1:2 - Data type selection This bitfield defines the format of data written in the AES_DINR register or read from the AES_DOUTR register, through selecting the mode of data swapping: For more details, refer to . Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] #[must_use] pub fn datatype(&mut self) -> DATATYPE_W<CR_SPEC, 1> { DATATYPE_W::new(self) } #[doc = "Bits 3:4 - AES operating mode This bitfield selects the AES operating mode: Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access. Any attempt to selecting Mode 4 while either ECB or CBC chaining mode is not selected, defaults to effective selection of Mode 3. It is not possible to select a Mode 3 following a Mode 4."] #[inline(always)] #[must_use] pub fn mode(&mut self) -> MODE_W<CR_SPEC, 3> { MODE_W::new(self) } #[doc = "Bits 5:6 - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] #[must_use] pub fn chmod1(&mut self) -> CHMOD1_W<CR_SPEC, 5> { CHMOD1_W::new(self) } #[doc = "Bit 7 - Computation complete flag clear Upon written to 1, this bit clears the computation complete flag (CCF) in the AES_SR register: Reading the flag always returns zero."] #[inline(always)] #[must_use] pub fn ccfc(&mut self) -> CCFC_W<CR_SPEC, 7> { CCFC_W::new(self) } #[doc = "Bit 8 - Error flag clear Upon written to 1, this bit clears the RDERR and WRERR error flags in the AES_SR register: Reading the flag always returns zero."] #[inline(always)] #[must_use] pub fn errc(&mut self) -> ERRC_W<CR_SPEC, 8> { ERRC_W::new(self) } #[doc = "Bit 9 - CCF interrupt enable This bit enables or disables (masks) the AES interrupt generation when CCF (computation complete flag) is set:"] #[inline(always)] #[must_use] pub fn ccfie(&mut self) -> CCFIE_W<CR_SPEC, 9> { CCFIE_W::new(self) } #[doc = "Bit 10 - Error interrupt enable This bit enables or disables (masks) the AES interrupt generation when RDERR and/or WRERR is set:"] #[inline(always)] #[must_use] pub fn errie(&mut self) -> ERRIE_W<CR_SPEC, 10> { ERRIE_W::new(self) } #[doc = "Bit 11 - DMA input enable This bit enables/disables data transferring with DMA, in the input phase: When the bit is set, DMA requests are automatically generated by AES during the input data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] #[inline(always)] #[must_use] pub fn dmainen(&mut self) -> DMAINEN_W<CR_SPEC, 11> { DMAINEN_W::new(self) } #[doc = "Bit 12 - DMA output enable This bit enables/disables data transferring with DMA, in the output phase: When the bit is set, DMA requests are automatically generated by AES during the output data phase. This feature is only effective when Mode 1 or Mode 3 is selected through the MODE\\[1:0\\] bitfield. It is not effective for Mode 2 (key derivation). Usage of DMA with Mode 4 (single decryption) is not recommended."] #[inline(always)] #[must_use] pub fn dmaouten(&mut self) -> DMAOUTEN_W<CR_SPEC, 12> { DMAOUTEN_W::new(self) } #[doc = "Bits 13:14 - GCM or CCM phase selection This bitfield selects the phase of GCM, GMAC or CCM algorithm: The bitfield has no effect if other than GCM, GMAC or CCM algorithms are selected (through the ALGOMODE bitfield)."] #[inline(always)] #[must_use] pub fn gcmph(&mut self) -> GCMPH_W<CR_SPEC, 13> { GCMPH_W::new(self) } #[doc = "Bit 16 - Chaining mode selection, bit \\[2\\] Refer to the bits \\[5:6\\] of the register for the description of the CHMOD\\[2:0\\] bitfield CHMOD\\[1:0\\]: Chaining mode selection, bits \\[1:0\\] This bitfield, together with the bit CHMOD\\[2\\] forming CHMOD\\[2:0\\], selects the AES chaining mode: others: Reserved Attempts to write the bitfield are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] #[must_use] pub fn chmod2(&mut self) -> CHMOD2_W<CR_SPEC, 16> { CHMOD2_W::new(self) } #[doc = "Bit 18 - Key size selection This bitfield defines the length of the key used in the AES cryptographic core, in bits: Attempts to write the bit are ignored when the EN bit of the AES_CR register is set before the write access and it is not cleared by that write access."] #[inline(always)] #[must_use] pub fn keysize(&mut self) -> KEYSIZE_W<CR_SPEC, 18> { KEYSIZE_W::new(self) } #[doc = "Bits 20:23 - Number of padding bytes in last block The bitfield sets the number of padding bytes in last block of payload: ..."] #[inline(always)] #[must_use] pub fn npblb(&mut self) -> NPBLB_W<CR_SPEC, 20> { NPBLB_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "AES control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! A module which contains [`Color`] trait and its implementation [`AnsiColor`]. #[cfg(feature = "std")] mod ansi_color; mod static_color; #[cfg(feature = "std")] pub use ansi_color::AnsiColor; pub use static_color::StaticColor; use core::fmt::{self, Write}; #[allow(unreachable_pub)] /// A trait which prints an ANSI prefix and suffix. pub trait Color { /// Print ANSI prefix. fn fmt_prefix<W: Write>(&self, f: &mut W) -> fmt::Result; /// Print ANSI suffix. fn fmt_suffix<W: Write>(&self, f: &mut W) -> fmt::Result { f.write_str("\u{1b}[0m") } /// Print colored text. /// /// It may not handle `\n` (new lines). fn colorize<W: Write>(&self, f: &mut W, text: &str) -> fmt::Result { self.fmt_prefix(f)?; f.write_str(text)?; self.fmt_suffix(f)?; Ok(()) } } impl<C> Color for &C where C: Color, { fn fmt_prefix<W: Write>(&self, f: &mut W) -> fmt::Result { C::fmt_prefix(self, f) } fn fmt_suffix<W: Write>(&self, f: &mut W) -> fmt::Result { C::fmt_suffix(self, f) } fn colorize<W: Write>(&self, f: &mut W, text: &str) -> fmt::Result { C::colorize(self, f, text) } }
use std::io::Cursor; use byteorder::{LittleEndian, ReadBytesExt}; use encoding::codec::utf_16::{self, Little}; use failure::{ensure, format_err, Error}; #[derive(Debug)] pub struct PackageWrapper<'a> { raw_data: &'a [u8], } impl<'a> PackageWrapper<'a> { pub fn new(raw_data: &'a [u8]) -> Self { Self { raw_data } } pub fn get_id(&self) -> Result<u32, Error> { let mut cursor = Cursor::new(self.raw_data); cursor.set_position(8); Ok(cursor.read_u32::<LittleEndian>()?) } pub fn get_name(&self) -> Result<String, Error> { let mut cursor = Cursor::new(self.raw_data); cursor.set_position(12); let initial_position = cursor.position(); ensure!( ((initial_position + 256) as usize) < self.raw_data.len(), "cursor position out of bounds" ); let final_position = self.find_end_position(initial_position as usize); ensure!( self.raw_data.len() >= (initial_position + 256) as usize, "not enough bytes to retrieve package name" ); let raw_str = &cursor.get_ref()[initial_position as usize..final_position]; let mut decoder = utf_16::UTF16Decoder::<Little>::new(); let mut o = String::new(); decoder.raw_feed(raw_str, &mut o); let decode_error = decoder.raw_finish(&mut o); match decode_error { None => Ok(o), Some(_) => Err(format_err!("error decoding UTF8 string")), } } fn find_end_position(&self, initial_position: usize) -> usize { let buffer = &self.raw_data[initial_position..initial_position + 256]; let mut zeros = 0; let mut i = 0; for c in buffer { if *c == 0 { zeros += 1; } else { zeros = 0; } if zeros > 1 { break; } i += 1; } initial_position + i } }
extern crate hyper; extern crate rustc_serialize; extern crate bbs; use std::io::{self, Write}; use bbs::{UserClient, HTML_ADDR}; fn main() { let mut username: String = String::new(); println!("Enter your username."); print!("$ "); io::stdout().flush().unwrap(); io::stdin().read_line(&mut username).unwrap(); username = username.trim_right().to_string(); println!("Aha! Hello {}. What do you want to say?", username); let client: UserClient = UserClient::new(username.clone(), HTML_ADDR.to_string()); loop { print!("{}$ ", username); io::stdout().flush().unwrap(); let mut text: String = String::new(); match io::stdin().read_line(&mut text).unwrap() { 0 => break, _ => { let code = client.send_msg(text).unwrap(); println!("Server reply: {}.", code); } } } }
use super::responses::WereAddressesSpentFromResponse; use crate::utils::{self, input_validator}; use crate::Result; use reqwest::Client; /// Check if a list of addresses was ever spent from. pub async fn were_addresses_spent_from( client: Client, uri: String, addresses: Vec<String>, ) -> Result<WereAddressesSpentFromResponse> { let addresses: Vec<String> = addresses .iter() .filter(|address| input_validator::is_address(address)) .map(|address| utils::remove_checksum(address)) .collect(); ensure!(!addresses.is_empty(), "No valid addresses provided."); let body = json!({ "command": "wereAddressesSpentFrom", "addresses": addresses, }); Ok(client .post(&uri) .header("ContentType", "application/json") .header("X-IOTA-API-Version", "1") .body(body.to_string()) .send()? .json()?) }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Fault structure"] pub struct0: STRUCT, _reserved1: [u8; 48usize], #[doc = "0x100 - Fault structure"] pub struct1: STRUCT, } #[doc = r"Register block"] #[repr(C)] pub struct STRUCT { #[doc = "0x00 - Fault control"] pub ctl: self::struct_::CTL, _reserved1: [u8; 8usize], #[doc = "0x0c - Fault status"] pub status: self::struct_::STATUS, #[doc = "0x10 - Fault data"] pub data: [self::struct_::DATA; 4], _reserved3: [u8; 32usize], #[doc = "0x40 - Fault pending 0"] pub pending0: self::struct_::PENDING0, #[doc = "0x44 - Fault pending 1"] pub pending1: self::struct_::PENDING1, #[doc = "0x48 - Fault pending 2"] pub pending2: self::struct_::PENDING2, _reserved6: [u8; 4usize], #[doc = "0x50 - Fault mask 0"] pub mask0: self::struct_::MASK0, #[doc = "0x54 - Fault mask 1"] pub mask1: self::struct_::MASK1, #[doc = "0x58 - Fault mask 2"] pub mask2: self::struct_::MASK2, _reserved9: [u8; 100usize], #[doc = "0xc0 - Interrupt"] pub intr: self::struct_::INTR, #[doc = "0xc4 - Interrupt set"] pub intr_set: self::struct_::INTR_SET, #[doc = "0xc8 - Interrupt mask"] pub intr_mask: self::struct_::INTR_MASK, #[doc = "0xcc - Interrupt masked"] pub intr_masked: self::struct_::INTR_MASKED, } #[doc = r"Register block"] #[doc = "Fault structure"] pub mod struct_;
mod client; mod commands; mod enums; mod events; pub use client::*; pub use commands::Command; pub use enums::*; pub use events::Event;
// Copyright 2018 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 futures::prelude::*; pub struct State<E>(Box<Future<Item = State<E>, Error = E> + Send>); impl<E> State<E> { pub fn into_future(self) -> StateMachine<E> { StateMachine{ cur_state: self } } } pub struct StateMachine<E>{ cur_state: State<E> } impl<E> Future for StateMachine<E> { type Item = Never; type Error = E; fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> { loop { match self.cur_state.0.poll(cx) { Ok(Async::Ready(next)) => self.cur_state = next, Ok(Async::Pending) => return Ok(Async::Pending), Err(e) => return Err(e) } } } } pub trait IntoStateExt<E>: Future<Item = State<E>, Error = E> { fn into_state(self) -> State<E> where Self: Sized + Send + 'static { State(Box::new(self)) } } impl<F, E> IntoStateExt<E> for F where F: Future<Item = State<E>, Error = E> {} #[cfg(test)] mod tests { use super::*; use async; use futures::channel::mpsc; use std::mem; #[test] fn state_machine() { let mut exec = async::Executor::new().expect("Failed to create an executor"); let (sender, receiver) = mpsc::unbounded(); let mut state_machine = sum_state(0, receiver).into_future(); let r = exec.run_until_stalled(&mut state_machine); assert_eq!(Ok(Async::Pending), r); sender.unbounded_send(2).unwrap(); sender.unbounded_send(3).unwrap(); mem::drop(sender); let r = exec.run_until_stalled(&mut state_machine); assert_eq!(Err(5), r); } fn sum_state(current: u32, stream: mpsc::UnboundedReceiver<u32>) -> State<u32> { stream.next() .map_err(|(e, _stream)| e.never_into()) .and_then(move |(number, stream)| match number { Some(number) => Ok(sum_state(current + number, stream)), None => Err(current), }) .into_state() } }
#![no_main] #![no_std] extern crate cortex_m_rt; extern crate panic_halt; use cortex_m_rt::entry; #[entry(foo)] //~ ERROR This attribute accepts no arguments fn foo() -> ! { loop {} }
use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use glob::*; use regex::Regex; const BASEPATH: &str = "/sys/bus/w1/devices/28*/w1_slave"; fn open() -> io::Result<String> { let paths = glob(BASEPATH).unwrap(); let p = paths.last().unwrap().unwrap(); let mut file = File::open(&Path::new(&p))?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } pub fn read_str() -> io::Result<String> { let contents = open()?; let regex = Regex::new(r"t=([0-9]+)").unwrap(); let caps = regex.captures(&contents).unwrap(); Ok(String::from(caps.get(1).unwrap().as_str())) } pub fn read_f32() -> io::Result<f32> { let temp = read_str()?.parse::<f32>().unwrap(); Ok(temp / 1000.0) } pub fn read_u32() -> io::Result<u32> { let temp = read_str()?.parse::<u32>().unwrap(); Ok(temp) }
#[derive(Debug)] pub struct ScoreExpression { #[allow(dead_code)] expression: String, ops: Vec<OperatorType>, } #[derive(Debug)] enum OperatorType { Division, Mul, Add, Sub, _Score_, Float(f32), } #[derive(Debug)] #[allow(dead_code)] enum OperationStep { OperatorType, Value, } impl ScoreExpression { pub fn get_score(&self, rank: f32) -> f32 { let left = match self.ops[0] { OperatorType::_Score_ => rank, OperatorType::Float(val) => val, _ => panic!("Need to start with float oder $SCORE"), }; let right = match self.ops[2] { OperatorType::_Score_ => rank, OperatorType::Float(val) => val, _ => panic!("Need to end with float oder $SCORE"), }; match self.ops[1] { OperatorType::Division => left / right, OperatorType::Mul => left * right, OperatorType::Add => left + right, OperatorType::Sub => left - right, _ => panic!("Need to be an operator [*, +, -, /]"), } } fn parse(expression: &str) -> Vec<OperatorType> { let mut operations: Vec<OperatorType> = vec![]; let mut current = "".to_string(); // let currVal = None; for next_char in expression.chars() { if let ' ' = next_char { let val = current.parse::<f32>(); // trace!("{:?}", val); if let Ok(val) = val { operations.push(OperatorType::Float(val)); } current.clear(); } if next_char != ' ' { current += &next_char.to_string(); } match current.as_ref() { "+" => { operations.push(OperatorType::Add); current.clear(); } "-" => { operations.push(OperatorType::Sub); current.clear(); } "/" => { operations.push(OperatorType::Division); current.clear(); } "*" => { operations.push(OperatorType::Mul); current.clear(); } "$SCORE" => { operations.push(OperatorType::_Score_); current.clear(); } _ => {} } } if let Ok(val) = current.parse::<f32>() { operations.push(OperatorType::Float(val)); } // trace!("{:?}", operations); operations } pub fn new(expression: String) -> Self { let ops = ScoreExpression::parse(&expression); ScoreExpression { expression, ops } } } #[allow(dead_code)] fn mult(val: f32) -> f32 { val * val } #[cfg(test)] mod tests { use super::*; #[test] fn test_parser() { let expre = ScoreExpression::new("$SCORE + 2.0".to_string()); assert_eq!(expre.get_score(10.0), 12.0); let expre = ScoreExpression::new("10.0 / $SCORE".to_string()); assert_eq!(expre.get_score(10.0), 1.0); let expre = ScoreExpression::new("$SCORE * $SCORE".to_string()); assert_eq!(expre.get_score(10.0), 100.0); } } #[cfg(all(test, feature = "unstable"))] mod bench { use super::*; use crate::test::Bencher; #[bench] fn bench_expr_mult(b: &mut Bencher) { let expre = ScoreExpression::new("$SCORE * $SCORE".to_string()); b.iter(|| expre.get_score(10.0)); } #[bench] fn bench_mult(b: &mut Bencher) { b.iter(|| mult(10.0)); } }
//! #[cfg(test)] //! mod tests { //! #[test] //! fn it_works() { //! assert_eq!(2 + 2, 4); //! } //! } //! 初始代码 删除 尕写成我们自己的 //! 一些可能用到,而又不好找库的数据结构 //! //! 以及有多种实现,会留作业的数据结构 #![no_std] // 2021-3-12 extern crate alloc; // 2021-3-12 mod allocator; pub use allocator::*;
use std::io::{self, BufRead}; use std::collections::BTreeSet; fn read_nums() -> Vec<i64> { let stdin = io::stdin(); let locked = stdin.lock(); let result = locked.lines().filter_map(|line| line.ok()).filter_map(|line| line.parse::<i64>().ok()).collect(); result } fn find_first_repeat(nums: &[i64]) -> i64 { let mut seen = BTreeSet::new(); let mut total = 0; seen.insert(total); loop { for &num in nums { total += num; if !seen.insert(total) { return total; } } } } fn main() { let nums = read_nums(); println!("part 1: {}", nums.iter().sum::<i64>()); println!("part 2: {}", find_first_repeat(&nums)); }
use std::{ collections::HashMap, error::Error, path::Path, sync::{mpsc, Arc}, thread, time::Duration, }; use bytesize::ByteSize; use framework::CursorIcon; use futures::{ channel::{ mpsc::{channel, Receiver, Sender}, oneshot, }, executor::{LocalPool, LocalSpawner}, task::LocalSpawnExt, StreamExt, }; use futures_timer::Delay; use itertools::Itertools; use skia_safe::{Canvas, Font, FontStyle, Typeface}; use wasmtime::{ AsContextMut, Caller, Config, Engine, Instance, Linker, Memory, Module, Store, Val, WasmParams, WasmResults, }; use wasmtime_wasi::{Dir, WasiCtxBuilder}; use crate::{ editor::Value, event::Event, keyboard::KeyboardInput, widget::{Color, Position, Size, decode_base64, encode_base64}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] struct PointerLengthString { ptr: u32, len: u32, } pub type WasmId = u64; #[derive(Debug, Clone)] enum Payload { #[allow(unused)] NewInstance(String), OnClick(Position), Draw(String), SetState(String), OnScroll(f64, f64), OnKey(KeyboardInput), Reload, SaveState, UpdatePosition(Position), ProcessMessage(usize, String), Event(String, String), OnSizeChange(f32, f32), OnMouseMove(Position), PartialState(Option<String>), } #[derive(Clone, Debug)] struct Message { message_id: usize, wasm_id: WasmId, payload: Payload, } enum OutPayload { DrawCommands(Vec<Command>), Saved(SaveState), ErrorPayload(String), Complete, NeededValue(String, oneshot::Sender<String>), } struct OutMessage { message_id: usize, wasm_id: WasmId, payload: OutPayload, } #[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum SaveState { Unsaved, Empty, Saved(String), } pub struct WasmMessenger { local_pool: futures::executor::LocalPool, local_spawner: LocalSpawner, last_wasm_id: u64, wasm_draw_commands: HashMap<WasmId, Vec<Command>>, wasm_non_draw_commands: HashMap<WasmId, Vec<Command>>, wasm_states: HashMap<WasmId, SaveState>, last_message_id: usize, // Not a huge fan of this solution, // but couldn't find a better way to dedup draws // Ideally, you can draw in the middle of click commands // I have some ideas. outstanding_messages: HashMap<WasmId, HashMap<usize, Message>>, engine: Arc<Engine>, receivers: HashMap<WasmId, Receiver<OutMessage>>, senders: HashMap<WasmId, Sender<Message>>, external_sender: Option<mpsc::Sender<Event>>, } impl WasmMessenger { pub fn new(external_sender: Option<mpsc::Sender<Event>>) -> Self { let local_pool = LocalPool::new(); let local_spawner = local_pool.spawner(); let mut config = Config::new(); config.dynamic_memory_guard_size(ByteSize::mb(500).as_u64()); config.static_memory_guard_size(ByteSize::mb(500).as_u64()); config.epoch_interruption(true); config.async_support(true); let engine = Arc::new(Engine::new(&config).unwrap()); let engine_clone = engine.clone(); thread::spawn(move || loop { thread::sleep(Duration::from_millis(4)); engine_clone.increment_epoch(); }); Self { local_pool, local_spawner, last_wasm_id: 0, wasm_draw_commands: HashMap::new(), wasm_non_draw_commands: HashMap::new(), wasm_states: HashMap::new(), last_message_id: 1, outstanding_messages: HashMap::new(), engine, receivers: HashMap::new(), senders: HashMap::new(), external_sender, } } pub fn set_external_sender(&mut self, external_sender: mpsc::Sender<Event>) { self.external_sender = Some(external_sender); } pub fn number_of_outstanding_messages(&self) -> String { let mut stats: Vec<&str> = vec![]; for messages_per in self.outstanding_messages.values() { for message in messages_per.values() { stats.push(match message.payload { Payload::NewInstance(_) => "NewInstance", Payload::OnClick(_) => "OnClick", Payload::Draw(_) => "Draw", Payload::SetState(_) => "SetState", Payload::OnScroll(_, _) => "OnScroll", Payload::OnKey(_) => "OnKey", Payload::Reload => "Reload", Payload::SaveState => "SaveState", Payload::UpdatePosition(_) => "UpdatePosition", Payload::ProcessMessage(_, _) => "ProcessMessage", Payload::Event(_, _) => "Event", Payload::OnSizeChange(_, _) => "OnSizeChange", Payload::OnMouseMove(_) => "OnMouseMove", Payload::PartialState(_) => "PartialState", }); } } let mut output = String::new(); let counts = stats.iter().counts(); for (category, count) in counts.iter().sorted() { output.push_str(&format!("{} : {}\n", category, count)); } output } fn next_message_id(&mut self) -> usize { self.last_message_id += 1; self.last_message_id } fn next_wasm_id(&mut self) -> WasmId { self.last_wasm_id += 1; self.last_wasm_id } pub fn new_instance(&mut self, wasm_path: &str, partial_state: Option<String>) -> WasmId { let id = self.next_wasm_id(); let (sender, receiver) = channel::<Message>(100000); let (out_sender, out_receiver) = channel::<OutMessage>(100000); self.receivers.insert(id, out_receiver); self.senders.insert(id, sender); async fn spawn_instance( engine: Arc<Engine>, wasm_id: WasmId, wasm_path: String, receiver: Receiver<Message>, sender: Sender<OutMessage>, ) { let mut instance = WasmManager::new( engine.clone(), wasm_id, wasm_path.to_string(), receiver, sender, ) .await; instance.init().await; } self.local_spawner .spawn_local(spawn_instance( self.engine.clone(), id, wasm_path.to_string(), receiver, out_sender, )) .unwrap(); let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id: id, payload: Payload::PartialState(partial_state), }); id } pub fn draw_widget( &mut self, wasm_id: WasmId, canvas: &mut Canvas, bounds: Size, ) -> Option<Size> { if let Some(commands) = self.wasm_draw_commands.get_mut(&wasm_id) { let mut current_width = 0.0; let mut current_height = 0.0; let mut current_height_stack = vec![]; let mut paint = skia_safe::Paint::default(); let mut non_draw_commands = vec![]; for command in commands.iter() { match command { Command::SetColor(r, g, b, a) => { let color = Color::new(*r, *g, *b, *a); paint.set_color(color.to_color4f().to_color()); } Command::DrawRect(x, y, width, height) => { canvas .draw_rect(skia_safe::Rect::from_xywh(*x, *y, *width, *height), &paint); } Command::DrawString(str, x, y) => { let mut paint = paint.clone(); paint.set_shader(None); if current_height > bounds.height { continue; } if current_height < 0.0 { continue; } let font = Font::new( Typeface::new("Ubuntu Mono", FontStyle::normal()).unwrap(), 32.0, ); // No good way right now to find bounds. Need to think about this properly canvas.draw_str(str, (*x, *y), &font, &paint); } Command::ClipRect(x, y, width, height) => { canvas.clip_rect( skia_safe::Rect::from_xywh(*x, *y, *width, *height), None, None, ); } Command::DrawRRect(x, y, width, height, radius) => { let rrect = skia_safe::RRect::new_rect_xy( skia_safe::Rect::from_xywh(*x, *y, *width, *height), *radius, *radius, ); canvas.draw_rrect(rrect, &paint); } Command::Translate(x, y) => { current_height += *y; current_width += *x; canvas.translate((*x, *y)); } Command::Save => { canvas.save(); current_height_stack.push(current_height); } Command::Restore => { canvas.restore(); current_height = current_height_stack.pop().unwrap(); } Command::SetCursor(cursor) => { self.external_sender .as_mut() .unwrap() .send(Event::SetCursor(*cursor)) .unwrap(); } c => { non_draw_commands.push(c.clone()); } } } commands.retain(|x| x.is_draw()); self.wasm_non_draw_commands .insert(wasm_id, non_draw_commands); Some(Size { width: current_width, height: current_height, }) } else { None } } pub fn process_non_draw_commands(&mut self, values: &mut HashMap<String, Value>) { for (wasm_id, commands) in self.wasm_non_draw_commands.iter() { for command in commands.iter() { match command { Command::Restore => println!("Unhandled"), Command::Save => println!("Unhandled"), Command::StartProcess(process_id, process_command) => { self.external_sender .as_mut() .unwrap() .send(Event::StartProcess( *process_id as usize, // TODO: I probably actually want widget id? *wasm_id as usize, process_command.clone(), )) .unwrap(); } Command::SendProcessMessage(process_id, message) => { self.external_sender .as_mut() .unwrap() .send(Event::SendProcessMessage( *process_id as usize, message.clone(), )) .unwrap(); } Command::ReceiveLastProcessMessage(_) => println!("Unhandled"), Command::ProvideF32(name, val) => { values.insert(name.to_string(), Value::F32(*val)); } Command::ProvideBytes(name, data) => { // TODO: Get rid of clone here values.insert(name.to_string(), Value::Bytes(data.clone())); } Command::Event(kind, event) => { self.external_sender .as_mut() .unwrap() .send(Event::Event(kind.clone(), event.clone())) .unwrap(); } Command::Subscribe(kind) => { self.external_sender .as_mut() .unwrap() .send(Event::Subscribe( // TODO: I probably actually want widget id? *wasm_id as usize, kind.clone(), )) .unwrap(); } Command::Unsubscribe(kind) => { self.external_sender .as_mut() .unwrap() .send(Event::Unsubscribe( // TODO: I probably actually want widget id? *wasm_id as usize, kind.clone(), )) .unwrap(); } _ => println!("Draw command ended up here"), } } } self.wasm_non_draw_commands.clear(); } pub fn tick(&mut self, values: &mut HashMap<String, Value>) { self.process_non_draw_commands(values); self.local_pool .run_until(Delay::new(Duration::from_millis(4))); // I need to do this slightly differently because I need to draw in the context // of the widget. // But on tick I could get the pending drawings and then draw them // for each widget // TODO: need to time this out for out_receiver in self.receivers.values_mut() { while let Ok(Some(message)) = out_receiver.try_next() { // Note: Right now if a message doesn't have a corresponding in-message // I am just setting the out message to id: 0. if let Some(record) = self.outstanding_messages.get_mut(&message.wasm_id) { record.remove(&message.message_id); } match message.payload { OutPayload::DrawCommands(commands) => { self.wasm_draw_commands.insert(message.wasm_id, commands); } OutPayload::Saved(saved) => { self.wasm_states.insert(message.wasm_id, saved); } OutPayload::ErrorPayload(error_message) => { println!("Error: {}", error_message); } OutPayload::NeededValue(name, sender) => { // If I don't have the value, what should I do? // Should I save this message and re-enqueue or signal failure? if let Some(value) = values.get(&name) { let serialized = serde_json::to_string(value).unwrap(); sender.send(serialized).unwrap(); } else { // println!("Can't find value {}", name); } } OutPayload::Complete => {} } } } } fn send_message(&mut self, message: Message) { let records = self .outstanding_messages .entry(message.wasm_id) .or_insert(HashMap::new()); let mut already_drawing = false; if matches!(message.payload, Payload::Draw(_)) { for record in records.values() { if matches!(record.payload, Payload::Draw(_)) { already_drawing = true; break; } } } if !already_drawing { records.insert(message.message_id, message.clone()); if let Some(sender) = self.senders.get_mut(&message.wasm_id) { sender.start_send(message).unwrap(); } else { println!("Can't find wasm instance for message {:?}", message); } } } pub fn send_on_click(&mut self, wasm_id: WasmId, position: &Position) { let message_id = self.next_message_id(); println!("Sending on click!"); self.send_message(Message { message_id, wasm_id, payload: Payload::OnClick(*position), }); } pub fn send_on_mouse_move(&mut self, wasm_id: WasmId, position: &Position) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::OnMouseMove(*position), }); } pub fn send_update_position(&mut self, wasm_id: WasmId, position: &Position) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::UpdatePosition(*position), }); } pub fn send_draw(&mut self, wasm_id: WasmId, fn_name: &str) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::Draw(fn_name.to_string()), }); } pub fn send_set_state(&mut self, wasm_id: WasmId, state: &str) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::SetState(state.to_string()), }); } pub fn send_on_scroll(&mut self, wasm_id: u64, x: f64, y: f64) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::OnScroll(x, y), }); } pub fn send_on_key(&mut self, wasm_id: u64, input: KeyboardInput) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::OnKey(input), }); } pub fn send_reload(&mut self, wasm_id: u64) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::Reload, }); } pub fn send_process_message(&mut self, wasm_id: u64, process_id: usize, buf: &str) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::ProcessMessage(process_id, buf.to_string()), }); } // Sometimes state is corrupt by going too long on the string. Not sure why. // Need to track down the issue pub fn save_state(&mut self, wasm_id: WasmId) -> SaveState { self.wasm_states.insert(wasm_id, SaveState::Unsaved); let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::SaveState, }); // TODO: Maybe not the best design, but I also want to ensure I save loop { // TODO: Fix this self.tick(&mut HashMap::new()); if let Some(state) = self.wasm_states.get(&wasm_id) { match state { SaveState::Saved(state) => { if state.starts_with('\"') { assert!(state.ends_with('\"'), "State is corrupt: {}", state); } break; } SaveState::Empty => { break; } _ => {} } } } self.wasm_states .get(&wasm_id) .unwrap_or(&SaveState::Empty) .clone() } pub fn send_event(&mut self, wasm_id: u64, kind: String, event: String) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::Event(kind, event), }); } pub fn send_on_size_change(&mut self, wasm_id: u64, width: f32, height: f32) { let message_id = self.next_message_id(); self.send_message(Message { message_id, wasm_id, payload: Payload::OnSizeChange(width, height), }); } } // I think I need to: // 1. Spawn a task per wasm instance // 2. Have senders and receivers per instance struct WasmManager { #[allow(unused)] id: WasmId, instance: WasmInstance, receiver: Receiver<Message>, #[allow(unused)] engine: Arc<Engine>, sender: Sender<OutMessage>, } impl WasmManager { pub async fn new( engine: Arc<Engine>, wasm_id: WasmId, wasm_path: String, receiver: Receiver<Message>, sender: Sender<OutMessage>, ) -> Self { let instance = WasmInstance::new(engine.clone(), &wasm_path, sender.clone(), wasm_id) .await .unwrap(); Self { id: wasm_id, instance, receiver, engine, sender, } } pub async fn init(&mut self) { loop { let message = self.receiver.select_next_some().await; let out_message = self.process_message(message).await; match out_message { Ok(out_message) => { self.sender.start_send(out_message).unwrap(); } Err(err) => { println!("Error processing message: {}", err); } } } } pub async fn process_message( &mut self, message: Message, ) -> Result<OutMessage, Box<dyn Error>> { let id = message.wasm_id; let default_return = Ok(OutMessage { wasm_id: message.wasm_id, message_id: message.message_id, payload: OutPayload::Complete, }); match message.payload { Payload::NewInstance(_) => { panic!("Shouldn't get here") } Payload::OnClick(position) => { self.instance.on_click(position.x, position.y).await?; default_return } Payload::OnMouseMove(position) => { self.instance.on_mouse_move(position.x, position.y).await?; default_return } Payload::Draw(fn_name) => { let result = self.instance.draw(&fn_name).await; match result { Ok(result) => Ok(OutMessage { message_id: message.message_id, wasm_id: id, payload: OutPayload::DrawCommands(result), }), Err(error) => { println!("Error drawing {:?}", error); default_return } } } Payload::SetState(state) => { self.instance.set_state(state.as_bytes()).await?; default_return } Payload::OnScroll(x, y) => { self.instance.on_scroll(x, y).await?; default_return } Payload::ProcessMessage(process_id, message) => { self.instance .on_process_message(process_id as i32, message) .await?; default_return } Payload::OnKey(input) => { let (key_code, state, modifiers) = input.to_u32_tuple(); let result = self.instance.on_key(key_code, state, modifiers).await; match result { Ok(_) => default_return, Err(err) => Ok(OutMessage { wasm_id: message.wasm_id, message_id: message.message_id, payload: OutPayload::ErrorPayload(err.to_string()), }), } } Payload::Reload => { match self.instance.reload().await { Ok(_) => {} Err(e) => { println!("Error reloading {}", e); } } default_return } Payload::SaveState => { let state = self.instance.get_state().await; match state { Some(state) => { if state.starts_with('\"') { assert!(state.ends_with('\"'), "State is corrupt: {}", state); } Ok(OutMessage { message_id: message.message_id, wasm_id: id, payload: OutPayload::Saved(SaveState::Saved(state)), }) } None => Ok(OutMessage { message_id: message.message_id, wasm_id: id, payload: OutPayload::Saved(SaveState::Empty), }), } } Payload::PartialState(partial_state) => { let state = self.instance.get_state().await; if let Some(state) = state { let base64_decoded = decode_base64(&state.as_bytes().to_vec())?; let state = String::from_utf8(base64_decoded)?; let merged_state = merge_json(partial_state, state); let encoded_state = encode_base64(&merged_state); self.instance.set_state(&encoded_state.as_bytes()).await?; } default_return } Payload::UpdatePosition(position) => { self.instance.store.data_mut().position = position; default_return } Payload::Event(kind, event) => { self.instance.on_event(kind, event).await?; default_return } Payload::OnSizeChange(width, height) => { self.instance.on_size_change(width, height).await?; default_return } } } } fn merge_json(partial_state: Option<String>, state: String) -> String { if let Some(partial_state) = partial_state { let mut partial_state: serde_json::Value = serde_json::from_str(&partial_state).unwrap(); let mut state: serde_json::Value = serde_json::from_str(&state).unwrap(); merge(&mut state, &mut partial_state); serde_json::to_string(&state).unwrap() } else { state } } fn merge(state: &mut serde_json::Value, partial_state: &mut serde_json::Value) { match (state, partial_state) { (serde_json::Value::Object(state), serde_json::Value::Object(partial_state)) => { for (key, value) in partial_state.iter_mut() { if let Some(entry) = state.get_mut(key) { merge(entry, value); } else { state.insert(key.clone(), value.clone()); } } } (state, partial_state) => { *state = partial_state.clone(); } } } struct State { wasi: wasmtime_wasi::WasiCtx, commands: Vec<Command>, get_state_info: (u32, u32), // Probably not the best structure // but lets start here process_messages: HashMap<i32, String>, position: Position, sender: Sender<OutMessage>, wasm_id: u64, } impl State { fn new(wasi: wasmtime_wasi::WasiCtx, sender: Sender<OutMessage>, wasm_id: u64) -> Self { Self { wasi, commands: Vec::new(), process_messages: HashMap::new(), get_state_info: (0, 0), position: Position { x: 0.0, y: 0.0 }, sender, wasm_id, } } } #[derive(Debug, Clone)] enum Command { DrawRect(f32, f32, f32, f32), DrawString(String, f32, f32), ClipRect(f32, f32, f32, f32), DrawRRect(f32, f32, f32, f32, f32), Translate(f32, f32), SetColor(f32, f32, f32, f32), Restore, Save, StartProcess(u32, String), SendProcessMessage(i32, String), ReceiveLastProcessMessage(i32), ProvideF32(String, f32), ProvideBytes(String, Vec<u8>), Event(String, String), Subscribe(String), Unsubscribe(String), SetCursor(CursorIcon), } impl Command { fn is_draw(&self) -> bool { match &self { Command::DrawRect(_, _, _, _) => true, Command::DrawString(_, _, _) => true, Command::ClipRect(_, _, _, _) => true, Command::DrawRRect(_, _, _, _, _) => true, Command::Translate(_, _) => true, Command::SetColor(_, _, _, _) => true, Command::Restore => true, Command::Save => true, _ => false, } } } fn get_bytes_from_caller<'a>(caller: &mut Caller<State>, ptr: i32, len: i32) -> Vec<u8> { // Use our `caller` context to learn about the memory export of the // module which called this host function. let mem = caller.get_export("memory").unwrap(); // Use the `ptr` and `len` values to get a subslice of the wasm-memory // which we'll attempt to interpret as utf-8. let store = &mut caller.as_context_mut(); let ptr = ptr as u32 as usize; let len = len as u32 as usize; // println!("caller ptr: {}, len: {}", ptr, len); let data = mem.into_memory().unwrap().data(store).get(ptr..(ptr + len)); data.unwrap().to_vec() } fn get_string_from_caller(caller: &mut Caller<State>, ptr: i32, len: i32) -> String { use core::str::from_utf8; // I allocate a vector here I didn't need to for code reuse sake. // There is probably a better way to do this. let data = get_bytes_from_caller(caller, ptr, len); let string = from_utf8(&data).unwrap(); string.to_string() } fn get_string_from_memory( memory: &Memory, store: &mut Store<State>, ptr: i32, len: i32, ) -> Option<String> { use core::str::from_utf8; let ptr = ptr as u32 as usize; let len = len as u32 as usize; let data = memory.data(store).get(ptr..(ptr + len)); let string = from_utf8(data.unwrap()); match string { Ok(string) => Some(string.to_string()), Err(err) => { println!("Error getting utf8 data: {:?}", err); None } } } struct WasmInstance { instance: Instance, store: Store<State>, engine: Arc<Engine>, linker: Linker<State>, path: String, } impl WasmInstance { async fn new( engine: Arc<Engine>, wasm_path: &str, sender: Sender<OutMessage>, wasm_id: u64, ) -> Result<Self, Box<dyn std::error::Error>> { let dir = Dir::from_std_file( std::fs::File::open(Path::new(wasm_path).parent().unwrap()).unwrap(), ); let code_dir = Dir::from_std_file( std::fs::File::open("/Users/jimmyhmiller/Documents/Code/PlayGround/rust/editor2") .unwrap(), ); let vs_code_extension_dir = Dir::from_std_file( std::fs::File::open("/Users/jimmyhmiller/.vscode/extensions/").unwrap(), ); let root_dir = Dir::from_std_file(std::fs::File::open("/").unwrap()); let wasi = WasiCtxBuilder::new() .inherit_stdio() .inherit_args()? .preopened_dir(dir, ".")? .preopened_dir(code_dir, "/code")? .preopened_dir(root_dir, "/")? // TODO: How do we handle this in the general case? .preopened_dir( vs_code_extension_dir, "/Users/jimmyhmiller/.vscode/extensions/", )? .build(); let mut linker: Linker<State> = Linker::new(&engine); wasmtime_wasi::add_to_linker(&mut linker, |s| &mut s.wasi)?; Self::setup_host_functions(&mut linker)?; let mut store = Store::new(&engine, State::new(wasi, sender, wasm_id)); let module = Module::from_file(&engine, wasm_path)?; let instance = linker.instantiate_async(&mut store, &module).await?; Ok(Self { instance, store, engine, linker, path: wasm_path.to_string(), }) } async fn call_typed_func<Params, Results>( &mut self, name: &str, params: Params, deadline: u64, ) -> anyhow::Result<Results> where Params: WasmParams, Results: WasmResults, { self.store.epoch_deadline_async_yield_and_update(deadline); let func = self .instance .get_typed_func::<Params, Results>(&mut self.store, name)?; let result = func.call_async(&mut self.store, params).await?; Ok(result) } fn setup_host_functions(linker: &mut Linker<State>) -> Result<(), Box<dyn Error>> { linker.func_wrap( "host", "draw_rect", |mut caller: Caller<'_, State>, x: f32, y: f32, width: f32, height: f32| { let state = caller.data_mut(); state.commands.push(Command::DrawRect(x, y, width, height)); }, )?; linker.func_wrap2_async( "host", "get_value", |mut caller: Caller<'_, State>, ptr: i32, len: i32| { let name = get_string_from_caller(&mut caller, ptr, len); Box::new(async move { let state = caller.data_mut(); let (sender, receiver) = oneshot::channel(); // Handle when it blocks and when it doesn't. // Probably want a try_ version state.sender.start_send(OutMessage { message_id: 0, wasm_id: state.wasm_id, payload: OutPayload::NeededValue(name, sender), })?; // The value is serialized and will need to be deserialized let result = receiver.await; match result { Ok(result) => { let (ptr, _len) = WasmInstance::transfer_string_to_wasm(&mut caller, result) .await .unwrap(); Ok(ptr) } Err(_e) => { // TODO: Actually handle // println!("Cancelled"); Ok(0) } } }) }, )?; linker.func_wrap2_async( "host", "try_get_value", |mut caller: Caller<'_, State>, ptr: i32, len: i32| { let name = get_string_from_caller(&mut caller, ptr, len); Box::new(async move { let state = caller.data_mut(); let (sender, mut receiver) = oneshot::channel(); // Handle when it blocks and when it doesn't. // Probably want a try_ version state.sender.start_send(OutMessage { message_id: 0, wasm_id: state.wasm_id, payload: OutPayload::NeededValue(name, sender), })?; // TODO: This will probably cause problems for the sender let result = receiver.try_recv(); if result.is_err() { return Ok(0); } let result = result.unwrap(); match result { Some(result) => { let (ptr, _len) = WasmInstance::transfer_string_to_wasm(&mut caller, result) .await .unwrap(); Ok(ptr) } None => { // TODO: Actually handle println!("Cancelled"); Ok(0) } } }) }, )?; linker.func_wrap( "host", "draw_str", |mut caller: Caller<'_, State>, ptr: i32, len: i32, x: f32, y: f32| { let string = get_string_from_caller(&mut caller, ptr, len); let state = caller.data_mut(); state.commands.push(Command::DrawString(string, x, y)); }, )?; linker.func_wrap( "host", "provide_f32", |mut caller: Caller<'_, State>, ptr: i32, len: i32, val: f32| { let string = get_string_from_caller(&mut caller, ptr, len); let state = caller.data_mut(); state.commands.push(Command::ProvideF32(string, val)); }, )?; linker.func_wrap( "host", "send_event", |mut caller: Caller<'_, State>, kind_ptr: i32, kind_len: i32, event_ptr: i32, event_len: i32| { let kind = get_string_from_caller(&mut caller, kind_ptr, kind_len); let event = get_string_from_caller(&mut caller, event_ptr, event_len); let state = caller.data_mut(); state.commands.push(Command::Event(kind, event)); }, )?; linker.func_wrap( "host", "subscribe", |mut caller: Caller<'_, State>, kind_ptr: i32, kind_len: i32| { let kind = get_string_from_caller(&mut caller, kind_ptr, kind_len); let state = caller.data_mut(); state.commands.push(Command::Subscribe(kind)); }, )?; linker.func_wrap( "host", "unsubscribe", |mut caller: Caller<'_, State>, kind_ptr: i32, kind_len: i32| { let kind = get_string_from_caller(&mut caller, kind_ptr, kind_len); let state = caller.data_mut(); state.commands.push(Command::Unsubscribe(kind)); }, )?; linker.func_wrap( "host", "provide_bytes", |mut caller: Caller<'_, State>, name_ptr: i32, name_len: i32, ptr: i32, len: i32| { let string = get_string_from_caller(&mut caller, name_ptr, name_len); let data = get_bytes_from_caller(&mut caller, ptr, len).to_vec(); let state = caller.data_mut(); state.commands.push(Command::ProvideBytes(string, data)); }, )?; linker.func_wrap("host", "get_x", |mut caller: Caller<'_, State>| { let state = caller.data_mut(); state.position.x })?; linker.func_wrap("host", "get_y", |mut caller: Caller<'_, State>| { let state = caller.data_mut(); state.position.y })?; linker.func_wrap( "host", "clip_rect", |mut caller: Caller<'_, State>, x: f32, y: f32, width: f32, height: f32| { let state = caller.data_mut(); state.commands.push(Command::ClipRect(x, y, width, height)); }, )?; linker.func_wrap( "host", "draw_rrect", |mut caller: Caller<'_, State>, x: f32, y: f32, width: f32, height: f32, radius: f32| { let state = caller.data_mut(); state .commands .push(Command::DrawRRect(x, y, width, height, radius)); }, )?; linker.func_wrap( "host", "translate", |mut caller: Caller<'_, State>, x: f32, y: f32| { let state = caller.data_mut(); state.commands.push(Command::Translate(x, y)); }, )?; linker.func_wrap("host", "save", |mut caller: Caller<'_, State>| { let state = caller.data_mut(); state.commands.push(Command::Save); })?; linker.func_wrap("host", "restore", |mut caller: Caller<'_, State>| { let state = caller.data_mut(); state.commands.push(Command::Restore); })?; linker.func_wrap( "host", "set_color", |mut caller: Caller<'_, State>, r: f32, g: f32, b: f32, a: f32| { let state = caller.data_mut(); state.commands.push(Command::SetColor(r, g, b, a)); }, )?; linker.func_wrap( "host", "set_cursor_icon", |mut caller: Caller<'_, State>, cursor: u32| { let cursor_icon = CursorIcon::from(cursor); let state = caller.data_mut(); state.commands.push(Command::SetCursor(cursor_icon)); }, )?; linker.func_wrap( "host", "start_process_low_level", |mut caller: Caller<'_, State>, ptr: i32, len: i32| -> u32 { let process = get_string_from_caller(&mut caller, ptr, len); let state = caller.data_mut(); // TODO: Real process id let process_id = 0; state .commands .push(Command::StartProcess(process_id, process)); process_id }, )?; linker.func_wrap( "host", "set_get_state", |mut caller: Caller<'_, State>, ptr: u32, len: u32| { let state = caller.data_mut(); state.get_state_info = (ptr, len); }, )?; linker.func_wrap( "host", "send_message_low_level", |mut caller: Caller<'_, State>, process_id: i32, ptr: i32, len: i32| { let message = get_string_from_caller(&mut caller, ptr, len); let state = caller.data_mut(); state .commands .push(Command::SendProcessMessage(process_id, message)); }, )?; linker.func_wrap( "host", "recieve_last_message_low_level", |mut caller: Caller<'_, State>, ptr: i32, process_id: i32| { { let state = caller.data_mut(); state .commands .push(Command::ReceiveLastProcessMessage(process_id)); } let state = caller.data_mut(); let message = state .process_messages .get(&process_id) .unwrap_or(&"test".to_string()) .clone(); let message = message.as_bytes(); let memory = caller.get_export("memory").unwrap().into_memory().unwrap(); // This is wrong. I need to figure out how I'm supposed to encode this stuff let store = caller.as_context_mut(); memory.write(store, 0, message).unwrap(); let mut bytes = [0u8; 8]; bytes[0..4].copy_from_slice(&0_i32.to_le_bytes()); bytes[4..8].copy_from_slice(&(message.len() as i32).to_le_bytes()); let store = caller.as_context_mut(); memory.write(store, ptr as usize, &bytes).unwrap(); }, )?; // TODO: Need to deal with paints Ok(()) } pub async fn draw(&mut self, fn_name: &str) -> Result<Vec<Command>, Box<dyn Error>> { let _max_width = 0.0; let _max_height = 0.0; self.call_typed_func(fn_name, (), 1).await?; let state = &mut self.store.data_mut(); let _paint = skia_safe::Paint::default(); let commands = state.commands.clone(); state.commands.clear(); Ok(commands) } pub async fn on_click(&mut self, x: f32, y: f32) -> Result<(), Box<dyn Error>> { self.call_typed_func::<(f32, f32), ()>("on_click", (x, y), 1) .await?; Ok(()) } pub async fn on_mouse_move(&mut self, x: f32, y: f32) -> Result<(), Box<dyn Error>> { self.call_typed_func::<(f32, f32), ()>("on_mouse_move", (x, y), 1) .await?; Ok(()) } pub async fn on_scroll(&mut self, x: f64, y: f64) -> Result<(), Box<dyn Error>> { self.call_typed_func::<(f64, f64), ()>("on_scroll", (x, y), 1) .await?; Ok(()) } pub async fn on_key( &mut self, key_code: u32, state: u32, modifiers: u32, ) -> Result<(), Box<dyn Error>> { self.call_typed_func::<(u32, u32, u32), ()>("on_key", (key_code, state, modifiers), 1) .await?; Ok(()) } pub async fn on_process_message( &mut self, process_id: i32, message: String, ) -> Result<(), Box<dyn Error>> { let (ptr, _len) = self.transfer_string_to_wasm2(message).await?; self.call_typed_func::<(i32, u32), ()>("on_process_message", (process_id, ptr), 1) .await?; Ok(()) } pub async fn reload(&mut self) -> Result<(), Box<dyn Error>> { if let Ok(json_string) = self.get_state().await.ok_or("no get state function") { let data = json_string.as_bytes(); let module = Module::from_file(&self.engine, &self.path)?; let instance = self .linker .instantiate_async(&mut self.store, &module) .await?; self.instance = instance; self.set_state(data).await?; } else { let module = Module::from_file(&self.engine, &self.path)?; let instance = self .linker .instantiate_async(&mut self.store, &module) .await?; self.instance = instance; } Ok(()) } pub async fn transfer_string_to_wasm( caller: &mut Caller<'_, State>, data: String, ) -> Result<(u32, u32), Box<dyn Error>> { let memory = caller.get_export("memory").unwrap().into_memory().unwrap(); let memory_size = (memory.data_size(caller.as_context_mut()) as f32 / ByteSize::kb(64).as_u64() as f32) .ceil() as usize; let data_length_in_64k_multiples = (data.len() as f32 / ByteSize::kb(64).as_u64() as f32).ceil() as usize; if data_length_in_64k_multiples > memory_size { let delta = data_length_in_64k_multiples; memory .grow(caller.as_context_mut(), delta as u64 + 10) .unwrap(); } let func = caller.get_export("alloc_string").unwrap(); let func = func.into_func().unwrap(); let results = &mut [Val::I32(0)]; func.call_async( caller.as_context_mut(), &[Val::I32(data.len() as i32)], results, ) .await .unwrap(); let ptr = results[0].clone().i32().unwrap() as u32; let memory = caller.get_export("memory").unwrap().into_memory().unwrap(); memory .write(caller.as_context_mut(), ptr as usize, data.as_bytes()) .unwrap(); Ok((ptr, data.len() as u32)) } // Instance vs caller. Can I collapse these? // super ugly that I right now have 3 pub async fn transfer_string_to_wasm2( &mut self, data: String, ) -> Result<(u32, u32), Box<dyn Error>> { let memory = self .instance .get_export(&mut self.store, "memory") .unwrap() .into_memory() .unwrap(); let memory_size = (memory.data_size(&mut self.store) as f32 / ByteSize::kb(64).as_u64() as f32) .ceil() as usize; let data_length_in_64k_multiples = (data.len() as f32 / ByteSize::kb(64).as_u64() as f32).ceil() as usize; if data_length_in_64k_multiples > memory_size { let delta = data_length_in_64k_multiples; memory.grow(&mut self.store, delta as u64 + 10).unwrap(); } let ptr = self .call_typed_func::<u32, u32>("alloc_string", data.len() as u32, 1) .await?; let memory = self .instance .get_export(&mut self.store, "memory") .unwrap() .into_memory() .unwrap(); memory .write(&mut self.store, ptr as usize, data.as_bytes()) .unwrap(); Ok((ptr, data.len() as u32)) } pub async fn set_state(&mut self, data: &[u8]) -> Result<(), Box<dyn Error>> { let memory = self .instance .get_export(&mut self.store, "memory") .unwrap() .into_memory() .unwrap(); let memory_size = (memory.data_size(&mut self.store) as f32 / ByteSize::kb(64).as_u64() as f32) .ceil() as usize; let data_length_in_64k_multiples = (data.len() as f32 / ByteSize::kb(64).as_u64() as f32).ceil() as usize; if data_length_in_64k_multiples > memory_size { let delta = data_length_in_64k_multiples; memory.grow(&mut self.store, delta as u64 + 10).unwrap(); } let ptr = self .call_typed_func::<u32, u32>("alloc_state", data.len() as u32, 1) .await?; let memory = self .instance .get_export(&mut self.store, "memory") .unwrap() .into_memory() .unwrap(); // let memory_size = memory.data_size(&mut self.store); memory.write(&mut self.store, ptr as usize, data).unwrap(); self.call_typed_func::<(u32, u32), ()>("set_state", (ptr, data.len() as u32), 1) .await .unwrap(); Ok(()) } pub async fn get_state(&mut self) -> Option<String> { self.call_typed_func::<(), ()>("get_state", (), 1) .await .ok()?; let (ptr, len) = self.store.data().get_state_info; let memory = self .instance .get_export(&mut self.store, "memory") .unwrap() .into_memory() .unwrap(); let json_string = get_string_from_memory(&memory, &mut self.store, ptr as i32, len as i32); if json_string.is_none() { println!("No json string"); } json_string } pub async fn on_event(&mut self, kind: String, event: String) -> Result<(), Box<dyn Error>> { let (kind_ptr, _len) = self.transfer_string_to_wasm2(kind).await?; let (event_ptr, _len) = self.transfer_string_to_wasm2(event).await?; self.call_typed_func::<(u32, u32), ()>("on_event", (kind_ptr, event_ptr), 1) .await?; Ok(()) } pub async fn on_size_change(&mut self, width: f32, height: f32) -> Result<(), Box<dyn Error>> { self.call_typed_func::<(f32, f32), ()>("on_size_change", (width, height), 1) .await?; Ok(()) } }
// Copyright 2016 rust-fuzz 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 anyhow::Result; use clap::Parser; #[macro_use] mod templates; mod options; mod project; mod utils; static FUZZ_TARGETS_DIR_OLD: &str = "fuzzers"; static FUZZ_TARGETS_DIR: &str = "fuzz_targets"; // It turns out that `clap`'s `long_about()` makes `cargo fuzz --help` // unreadable, and its `before_help()` injects our long about text before the // version, so change the default template slightly. const LONG_ABOUT_TEMPLATE: &str = "\ {bin} {version} {about} USAGE: {usage} {before-help} {all-args} {after-help}"; const RUN_BEFORE_HELP: &str = "\ The fuzz target name is the same as the name of the fuzz target script in fuzz/fuzz_targets/, i.e. the name picked when running `cargo fuzz add`. This will run the script inside the fuzz target with varying inputs until it finds a crash, at which point it will save the crash input to the artifact directory, print some output, and exit. Unless you configure it otherwise (see libFuzzer options below), this will run indefinitely. By default fuzz targets are built with optimizations equivalent to `cargo build --release`, but with debug assertions and overflow checks enabled. Address Sanitizer is also enabled by default."; const RUN_AFTER_HELP: &str = "\ A full list of libFuzzer options can be found at http://llvm.org/docs/LibFuzzer.html#options You can also get this by running `cargo fuzz run fuzz_target -- -help=1` Some useful options (to be used as `cargo fuzz run fuzz_target -- <options>`) include: * `-max_len=<len>`: Will limit the length of the input string to `<len>` * `-runs=<number>`: Will limit the number of tries (runs) before it gives up * `-max_total_time=<time>`: Will limit the amount of time (seconds) to fuzz before it gives up * `-timeout=<time>`: Will limit the amount of time (seconds) for a single run before it considers that run a failure * `-only_ascii`: Only provide ASCII input * `-dict=<file>`: Use a keyword dictionary from specified file. See http://llvm.org/docs/LibFuzzer.html#dictionaries\ "; const BUILD_BEFORE_HELP: &str = "\ By default fuzz targets are built with optimizations equivalent to `cargo build --release`, but with debug assertions and overflow checks enabled. Address Sanitizer is also enabled by default."; const BUILD_AFTER_HELP: &str = "\ Sanitizers perform checks necessary for detecting bugs in unsafe code at the cost of some performance. For more information on sanitizers see https://doc.rust-lang.org/unstable-book/compiler-flags/sanitizer.html\ "; /// A trait for running our various commands. trait RunCommand { /// Run this command! fn run_command(&mut self) -> Result<()>; } #[derive(Clone, Debug, Parser)] #[command(version, about)] #[command(subcommand_required = true)] #[command(arg_required_else_help = true)] #[command(propagate_version = true)] // Cargo passes in the subcommand name to the invoked executable. // Use a hidden, optional positional argument to deal with it. #[command( arg(clap::Arg::new("dummy") .value_parser(["fuzz"]) .required(false) .hide(true)) )] enum Command { /// Initialize the fuzz directory Init(options::Init), /// Add a new fuzz target Add(options::Add), #[command( help_template(LONG_ABOUT_TEMPLATE), before_help(BUILD_BEFORE_HELP), after_help(BUILD_AFTER_HELP) )] /// Build fuzz targets Build(options::Build), #[command(help_template(LONG_ABOUT_TEMPLATE))] /// Type-check the fuzz targets Check(options::Check), /// Print the `std::fmt::Debug` output for an input Fmt(options::Fmt), /// List all the existing fuzz targets List(options::List), #[command( help_template(LONG_ABOUT_TEMPLATE), before_help(RUN_BEFORE_HELP), after_help(RUN_AFTER_HELP) )] /// Run a fuzz target Run(options::Run), /// Minify a corpus Cmin(options::Cmin), /// Minify a test case Tmin(options::Tmin), /// Run program on the generated corpus and generate coverage information Coverage(options::Coverage), } impl RunCommand for Command { fn run_command(&mut self) -> Result<()> { match self { Command::Init(x) => x.run_command(), Command::Add(x) => x.run_command(), Command::Build(x) => x.run_command(), Command::Check(x) => x.run_command(), Command::List(x) => x.run_command(), Command::Fmt(x) => x.run_command(), Command::Run(x) => x.run_command(), Command::Cmin(x) => x.run_command(), Command::Tmin(x) => x.run_command(), Command::Coverage(x) => x.run_command(), } } } fn main() -> Result<()> { Command::parse().run_command() }
// #![allow(unused)] use std::io::BufReader; use std::io::prelude::*; use std::fs::File; // Exo 1 // fn main() { // for line in file_to_vec() { // println!("{} : {} : {}", line.0, line.1, line.2); // } // let mut vec = file_to_vec(); // let mut index: i32 = 0; // let mut acc: i32 = 0; // loop { // if vec[index as usize].2 == true { // println!("infinite loop detected !"); // break; // } // match vec[index as usize].0.as_ref() { // "nop" => { // vec[index as usize].2 = true; // index += 1; // }, // "acc" => { // acc += vec[index as usize].1; // vec[index as usize].2 = true; // index += 1; // }, // "jmp" => { // vec[index as usize].2 = true; // index += vec[index as usize].1; // }, // &_ => { // panic!("error"); // } // } // } // println!("acc: {}", acc); // } // Exo 2 fn main() { for line in file_to_vec() { println!("{} : {} : {}", line.0, line.1, line.2); } println!(""); // let mut vec = file_to_vec(); // for line in &vec { // println!("{} : {} : {}", line.0, line.1, line.2); // } let mut index = 0; loop { index += 1; let mut vec = change_nth_instr(index); println!("index: {}", index); try_game(&mut vec); } } fn try_game(vec: &mut Vec<(String, i32, bool)>) { let mut index: i32 = 0; let mut acc: i32 = 0; loop { if vec[index as usize].2 == true { println!("infinite loop detected !"); println!("acc: {}", acc); return; } match vec[index as usize].0.as_ref() { "nop" => { vec[index as usize].2 = true; index += 1; }, "acc" => { acc += vec[index as usize].1; vec[index as usize].2 = true; index += 1; }, "jmp" => { vec[index as usize].2 = true; index += vec[index as usize].1; }, &_ => { panic!("error"); } } println!("acc: {}", acc); } panic!("found an exit"); } fn file_to_vec() -> Vec<(String, i32, bool)> { let file = File::open("input").unwrap(); let buf = BufReader::new(file); let mut input = Vec::new(); for line in buf.lines() { let line = line.unwrap(); input.push((line[0..3].to_string(), line[4..].to_string().parse().unwrap(), false)); } return input; } fn change_nth_instr(n: usize) -> Vec<(String, i32, bool)> { let mut vec = file_to_vec(); let mut index = 0; for (i, line) in vec.iter().enumerate() { if line.0 == "nop" || line.0 == "jmp" { index += 1; if index == n { if line.0 == "nop" { vec[i].0 = "jmp".to_string(); } else { vec[i].0 = "nop".to_string(); } break; } } } for line in &vec { println!("{} : {} : {}", line.0, line.1, line.2); } return vec; }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License.. extern crate sgx_types; extern crate sgx_urts; extern crate serde; extern crate serde_json; use sgx_types::*; mod query_data; use query_data::*; mod ecalls; use ecalls::{upload_query_data, init_enclave, private_contact_trace}; mod central_data; use central_data::*; fn main() { /* parameters */ let threashould: usize = 1000; let q_filename = "data/query.json"; let query_data = QueryData::read_raw_from_file(q_filename); let c_filename = "data/central.json"; let external_data = PCTHash::read_raw_from_file(c_filename); let mut chunked_buf: Vec<PCTHash> = Vec::with_capacity(10000); external_data.disribute(&mut chunked_buf, threashould); /* initialize enclave */ let enclave = match init_enclave() { Ok(r) => { println!("[+] Init Enclave Successful {}!", r.geteid()); r }, Err(x) => { println!("[-] Init Enclave Failed {}!", x.as_str()); return; }, }; /* upload query mock data */ let mut retval = sgx_status_t::SGX_SUCCESS; let result = unsafe { upload_query_data( enclave.geteid(), &mut retval, query_data.total_data_to_u8().as_ptr() as * const u8, query_data.total_size(), query_data.size_list().as_ptr() as * const usize, query_data.client_size, query_data.query_id_list().as_ptr() as * const u64 ) }; match result { sgx_status_t::SGX_SUCCESS => { println!("[+] upload_query_data Succes!"); }, _ => { println!("[-] upload_query_data Failed {}!", result.as_str()); return; } } /* main logic contact tracing */ let mut chunk_index: usize = 0; let last = chunked_buf.len() - 1; while last >= chunk_index { let chunk = &chunked_buf[chunk_index]; let mut geohash_u8: Vec<u8> = Vec::with_capacity(100000); let mut unixepoch_u64: Vec<u64> = Vec::with_capacity(100000); let mut size_list: Vec<usize> = Vec::with_capacity(chunk.size()); let epoch_data_size = chunk.prepare_sgx_data(&mut geohash_u8, &mut unixepoch_u64, &mut size_list); let result = unsafe { private_contact_trace( enclave.geteid(), &mut retval, geohash_u8.as_ptr() as * const u8, geohash_u8.len(), unixepoch_u64.as_ptr() as * const u64, unixepoch_u64.len(), size_list.as_ptr() as * const usize, epoch_data_size ) }; match result { sgx_status_t::SGX_SUCCESS => { println!("[+] private_contact_trace Succes! {} th iteration", chunk_index); }, _ => { println!("[-] private_contact_trace Failed {}!", result.as_str()); return; } } chunk_index += 1; } /* finish */ enclave.destroy(); println!("All process is successful!!"); }
#![feature(phase)] #[phase(plugin, link)] extern crate log; extern crate websocket; use std::comm; use std::thread::Thread; use std::io::{Listener, Acceptor}; use std::error; use std::iter::count; use websocket::{WebSocketServer, WebSocketMessage}; use websocket::header::WebSocketProtocol; fn main() { let addr = "192.168.137.42:8080"; match serve(addr) { Ok(_) => {println!("server exited")}, Err(msg) => {println!("server panic with: {}", msg.description())} } } fn serve(addr: &'static str) -> Result<(), Box<error::Error>> { let server = try!(WebSocketServer::bind(addr)); let mut acceptor = try!(server.listen()); let mut all_clients = Vec::new(); let (tx, rx) = comm::channel(); let (ctx, crx) = comm::channel(); Thread::spawn(move || { for (req, id) in acceptor.incoming().zip(count(1u,1u)) { debug!("Connection [{}]", id); let request; match req { Ok(req) => request = req, Err(msg) => { warn!("unwrap request fail! {}", msg); continue; } } // Let's also check the protocol - if it's not what we want, then fail the connection if request.protocol().is_none() || !request.protocol().unwrap().as_slice().contains(&"irccc".to_string()) { warn!("got bad request with id {}", id); let response = request.fail(); let _ = response.send_into_inner(); continue; } let mut response = request.accept(); // Generate a response object response.headers.set(WebSocketProtocol(vec!["irccc".to_string()])); // Send a Sec-WebSocket-Protocol header let mut client; // create a client match response.send() { Ok(c) => client = c, Err(msg) => { warn!("cannot create client for id: {}, err: {}", id, msg); continue; } } ctx.send(client.clone()); // send the welcome msg let message = WebSocketMessage::Text("Welcome to rust irccc server".to_string()); let _ = client.send_message(message); let task_tx = tx.clone(); Thread::spawn(move || { while let Some(Ok(message)) = client.incoming_messages().next() { // main body of websocket communication // message is the msg object from client // and here can do logic process after receiving msg info!("Recv [{}]: {}", id, message); match message { // Handle Ping messages by sending Pong messages WebSocketMessage::Ping(data) => { let message = WebSocketMessage::Pong(data); let _ = client.send_message(message); println!("Closed connection {}", id); // Close the connection break; } // Handle when the client wants to disconnect WebSocketMessage::Close(_) => { // Send a close message let message = WebSocketMessage::Close(None); let _ = client.send_message(message); println!("Closed connection {}", id); // Close the connection break; } _ => { } } task_tx.send("123"); } }).detach(); } }).detach(); loop { select!( msg = rx.recv() => { println!("--- {}", msg); }, client = crx.recv() => { all_clients.push(client); }); println!("ourter_all_clients.len {}", all_clients.len()); } }
use fnv::FnvHashSet; use specs::prelude::*; use types::collision::*; use types::*; use component::channel::*; use component::event::PlayerMissileCollision; use component::flag::IsSpectating; pub struct PlayerMissileCollisionSystem; #[derive(SystemData)] pub struct PlayerMissileCollisionSystemData<'a> { pub channel: Write<'a, OnPlayerMissileCollision>, pub config: Read<'a, Config>, pub ent: Entities<'a>, pub pos: ReadStorage<'a, Position>, pub rot: ReadStorage<'a, Rotation>, pub team: ReadStorage<'a, Team>, pub plane: ReadStorage<'a, Plane>, pub player_flag: ReadStorage<'a, IsPlayer>, pub isspec: ReadStorage<'a, IsSpectating>, pub isdead: ReadStorage<'a, IsDead>, pub mob: ReadStorage<'a, Mob>, pub missile_flag: ReadStorage<'a, IsMissile>, } impl PlayerMissileCollisionSystem { pub fn new() -> Self { Self {} } } impl<'a> System<'a> for PlayerMissileCollisionSystem { type SystemData = PlayerMissileCollisionSystemData<'a>; fn run(&mut self, data: Self::SystemData) { let Self::SystemData { mut channel, config, ent, pos, rot, team, plane, player_flag, isspec, isdead, mob, missile_flag, } = data; let mut buckets = Array2D::<Bucket>::new(BUCKETS_X, BUCKETS_Y); (&*ent, &pos, &rot, &team, &plane, &player_flag) .join() .filter(|(ent, _, _, _, _, _)| isspec.get(*ent).is_none() && isdead.get(*ent).is_none()) .for_each(|(ent, pos, rot, team, plane, _)| { let ref cfg = config.planes[*plane]; cfg.hit_circles.iter().for_each(|hc| { let offset = hc.offset.rotate(*rot); let circle = HitCircle { pos: *pos + offset, rad: hc.radius, layer: team.0, ent: ent, }; for coord in intersected_buckets(circle.pos, circle.rad) { buckets.get_or_insert(coord).push(circle); } }); }); let collisions = (&*ent, &pos, &team, &mob, &missile_flag) .par_join() .map(|(ent, pos, team, mob, _)| { let mut collisions = vec![]; for (offset, rad) in COLLIDERS[mob].iter() { let hc = HitCircle { pos: *pos + *offset, rad: *rad, layer: team.0, ent: ent, }; for coord in intersected_buckets(hc.pos, hc.rad) { match buckets.get(coord) { Some(bucket) => bucket.collide(hc, &mut collisions), None => (), } } } collisions }) .flatten() .map(|x| PlayerMissileCollision(x)) .collect::<FnvHashSet<PlayerMissileCollision>>(); channel.iter_write(collisions.into_iter()); } } use dispatch::SystemInfo; use systems::PositionUpdate; impl SystemInfo for PlayerMissileCollisionSystem { type Dependencies = PositionUpdate; fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self::new() } }
fn main() { let numero: i32 = 55; let mensaje = match numero { // valor => sentencia / tarea, 1 => "El numero es uno", //println!("El numero es uno."), 2 => "El numero es dos", //println!("El numero es dos."), 3 => "El numero es tres", //println!("El numero es tres."), 4 | 5 | 6 => "El numero se encuentra entre cuatro y seis", //println!("El numero se encuentra entre cuatro y seis"),, 7..=100 => { let mensaje = "El numero se evalua mediante un rango del 7 al 100"; mensaje //{ //println!("El numero es mayor o igual a 7"); //rintln!("El numero se evalue mendiante un rango") //}, } _ => "numero"//println!("{}", numero)// Default }; println!("El resultado es: {}", mensaje); for numero in 1..31 { match (numero % 3, numero % 5) { (0, 0) => println!("Fizz Buzz"), (0, _) => println!("Fizz"), (_, 0) => println!("Buzz"), _ => println!("{}", numero) //(_, _) } } }
use web3::types::{H160, H256}; use crate::core::Chain; use crate::ethereum::{ contract::{ MEMORY_PAGE_FACT_CONTINUOUS_EVENT, MEMORY_PAGE_HASHES_EVENT, STATE_TRANSITION_FACT_EVENT, STATE_UPDATE_EVENT, }, log::{ MemoryPageFactContinuousLog, MemoryPagesHashesLog, StateTransitionFactLog, StateUpdateLog, }, EthOrigin, }; mod backward; mod forward; pub use backward::*; pub use forward::*; /// May contain one of two types of [MetaLog]. /// /// Used by [BackwardLogFetcher]. #[derive(Debug, PartialEq, Eq, Clone)] pub enum EitherMetaLog<L, R> where L: MetaLog + PartialEq + std::fmt::Debug + Clone, R: MetaLog + PartialEq + std::fmt::Debug + Clone, { Left(L), Right(R), } /// Trait used by [LogFetcher] and indirectly by [BackwardLogFetcher] (via [EitherMetaLog]). /// /// Contains metadata for a log such as its point-of-origin on L1 and it's /// emitting contract and event signature. /// /// Implemented for the four Starknet log types, /// - [StateUpdateLog] /// - [StateTransitionFactLog] /// - [MemoryPagesHashesLog] /// - [MemoryPageFactContinuousLog] pub trait MetaLog: TryFrom<web3::types::Log, Error = anyhow::Error> { fn contract_address(chain: Chain) -> H160; fn signature() -> H256; fn origin(&self) -> &EthOrigin; } impl MetaLog for StateUpdateLog { fn contract_address(chain: Chain) -> H160 { crate::ethereum::contract::addresses(chain).core } fn signature() -> H256 { STATE_UPDATE_EVENT.signature() } fn origin(&self) -> &EthOrigin { &self.origin } } impl MetaLog for StateTransitionFactLog { fn contract_address(chain: Chain) -> web3::types::H160 { crate::ethereum::contract::addresses(chain).core } fn signature() -> H256 { STATE_TRANSITION_FACT_EVENT.signature() } fn origin(&self) -> &EthOrigin { &self.origin } } impl MetaLog for MemoryPagesHashesLog { fn contract_address(chain: Chain) -> web3::types::H160 { crate::ethereum::contract::addresses(chain).gps } fn signature() -> H256 { MEMORY_PAGE_HASHES_EVENT.signature() } fn origin(&self) -> &EthOrigin { &self.origin } } impl MetaLog for MemoryPageFactContinuousLog { fn contract_address(chain: Chain) -> web3::types::H160 { crate::ethereum::contract::addresses(chain).mempage } fn signature() -> H256 { MEMORY_PAGE_FACT_CONTINUOUS_EVENT.signature() } fn origin(&self) -> &EthOrigin { &self.origin } } impl<L, R> TryFrom<web3::types::Log> for EitherMetaLog<L, R> where L: MetaLog + PartialEq + std::fmt::Debug + Clone, R: MetaLog + PartialEq + std::fmt::Debug + Clone, { type Error = anyhow::Error; fn try_from(value: web3::types::Log) -> Result<Self, Self::Error> { match value.topics.first() { Some(signature) if signature == &L::signature() => Ok(Self::Left(L::try_from(value)?)), Some(signature) if signature == &R::signature() => Ok(Self::Right(R::try_from(value)?)), Some(signature) => Err(anyhow::anyhow!("Unknown log signature: {}", signature)), None => Err(anyhow::anyhow!("Missing log signature")), } } } impl<L, R> EitherMetaLog<L, R> where L: MetaLog + PartialEq + std::fmt::Debug + Clone, R: MetaLog + PartialEq + std::fmt::Debug + Clone, { fn origin(&self) -> &EthOrigin { match self { EitherMetaLog::Left(left) => left.origin(), EitherMetaLog::Right(right) => right.origin(), } } }
mod connect; mod create_game; mod game_browser; mod mainmenu; mod rockpaperscissors; mod tictactoe; pub use connect::Connect; pub use create_game::CreateGame; pub use game_browser::GameBrowser; pub use mainmenu::MainMenu; pub use rockpaperscissors::RockPaperScissors; pub use tictactoe::TicTacToe;
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! # Primitives for transaction weighting. //! //! Every dispatchable function is responsible for providing `#[weight = $x]` attribute. In this //! snipped, `$x` can be any user provided struct that implements the following traits: //! //! - [`WeighData`]: the weight amount. //! - [`ClassifyDispatch`]: class of the dispatch. //! - [`PaysFee`]: weather this weight should be translated to fee and deducted upon dispatch. //! //! Substrate then bundles then output information of the two traits into [`DispatchInfo`] struct //! and provides it by implementing the [`GetDispatchInfo`] for all `Call` both inner and outer call //! types. //! //! Substrate provides two pre-defined ways to annotate weight: //! //! ### 1. Fixed values //! //! This can only be used when all 3 traits can be resolved statically. You have 3 degrees of //! configuration: //! //! 1. Define only weight, **in which case `ClassifyDispatch` will be `Normal` and `PaysFee` will be //! `Yes`**. //! //! ``` //! # use frame_system::Trait; //! frame_support::decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! #[weight = 1000] //! fn dispatching(origin) { unimplemented!() } //! } //! } //! # fn main() {} //! ``` //! //! 2.1 Define weight and class, **in which case `PaysFee` would be `Yes`**. //! //! ``` //! # use frame_system::Trait; //! # use frame_support::weights::DispatchClass; //! frame_support::decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! #[weight = (1000, DispatchClass::Operational)] //! fn dispatching(origin) { unimplemented!() } //! } //! } //! # fn main() {} //! ``` //! //! 2.2 Define weight and `PaysFee`, **in which case `ClassifyDispatch` would be `Normal`**. //! //! ``` //! # use frame_system::Trait; //! # use frame_support::weights::Pays; //! frame_support::decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! #[weight = (1000, Pays::No)] //! fn dispatching(origin) { unimplemented!() } //! } //! } //! # fn main() {} //! ``` //! //! 3. Define all 3 parameters. //! //! ``` //! # use frame_system::Trait; //! # use frame_support::weights::{DispatchClass, Pays}; //! frame_support::decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! #[weight = (1000, DispatchClass::Operational, Pays::No)] //! fn dispatching(origin) { unimplemented!() } //! } //! } //! # fn main() {} //! ``` //! //! ### 2. Define weights as a function of input arguments using `FunctionOf` tuple struct. This //! struct works in a similar manner as above. 3 items must be provided and each can be either a //! fixed value or a function/closure with the same parameters list as the dispatchable function //! itself, wrapper in a tuple. //! //! Using this only makes sense if you want to use a function for at least one of the elements. If //! all 3 are static values, providing a raw tuple is easier. //! //! ``` //! # use frame_system::Trait; //! # use frame_support::weights::{DispatchClass, FunctionOf, Pays}; //! frame_support::decl_module! { //! pub struct Module<T: Trait> for enum Call where origin: T::Origin { //! #[weight = FunctionOf( //! // weight, function. //! |args: (&u32, &u64)| *args.0 as u64 + args.1, //! // class, fixed. //! DispatchClass::Operational, //! // pays fee, function. //! |args: (&u32, &u64)| if *args.0 > 1000 { Pays::Yes } else { Pays::No }, //! )] //! fn dispatching(origin, a: u32, b: u64) { unimplemented!() } //! } //! } //! # fn main() {} //! ``` //! FRAME assumes a weight of `1_000_000_000_000` equals 1 second of compute on a standard machine. //! //! Latest machine specification used to benchmark are: //! - Digital Ocean: ubuntu-s-2vcpu-4gb-ams3-01 //! - 2x Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz //! - 4GB RAM //! - Ubuntu 19.10 (GNU/Linux 5.3.0-18-generic x86_64) //! - rustc 1.42.0 (b8cedc004 2020-03-09) use crate::dispatch::{DispatchError, DispatchErrorWithPostInfo, DispatchResultWithPostInfo}; use codec::{Decode, Encode}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use smallvec::{smallvec, SmallVec}; use sp_arithmetic::{ traits::{BaseArithmetic, Saturating, Unsigned}, Perbill, }; use sp_runtime::traits::SaturatedConversion; use sp_runtime::{ generic::{CheckedExtrinsic, UncheckedExtrinsic}, traits::SignedExtension, RuntimeDebug, }; /// Re-export priority as type pub use sp_runtime::transaction_validity::TransactionPriority; /// Numeric range of a transaction weight. pub type Weight = u64; /// These constants are specific to FRAME, and the current implementation of its various components. /// For example: FRAME System, FRAME Executive, our FRAME support libraries, etc... pub mod constants { use super::{RuntimeDbWeight, Weight}; use crate::parameter_types; pub const WEIGHT_PER_SECOND: Weight = 1_000_000_000_000; pub const WEIGHT_PER_MILLIS: Weight = WEIGHT_PER_SECOND / 1000; // 1_000_000_000 pub const WEIGHT_PER_MICROS: Weight = WEIGHT_PER_MILLIS / 1000; // 1_000_000 pub const WEIGHT_PER_NANOS: Weight = WEIGHT_PER_MICROS / 1000; // 1_000 parameter_types! { /// Importing a block with 0 txs takes ~5 ms pub const BlockExecutionWeight: Weight = 5 * WEIGHT_PER_MILLIS; /// Executing 10,000 System remarks (no-op) txs takes ~1.26 seconds -> ~125 µs per tx pub const ExtrinsicBaseWeight: Weight = 125 * WEIGHT_PER_MICROS; /// By default, Substrate uses RocksDB, so this will be the weight used throughout /// the runtime. pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 25 * WEIGHT_PER_MICROS, // ~25 µs @ 200,000 items write: 100 * WEIGHT_PER_MICROS, // ~100 µs @ 200,000 items }; /// ParityDB can be enabled with a feature flag, but is still experimental. These weights /// are available for brave runtime engineers who may want to try this out as default. pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 8 * WEIGHT_PER_MICROS, // ~8 µs @ 200,000 items write: 50 * WEIGHT_PER_MICROS, // ~50 µs @ 200,000 items }; } } /// Means of weighing some particular kind of data (`T`). pub trait WeighData<T> { /// Weigh the data `T` given by `target`. When implementing this for a dispatchable, `T` will be /// a tuple of all arguments given to the function (except origin). fn weigh_data(&self, target: T) -> Weight; } /// Means of classifying a dispatchable function. pub trait ClassifyDispatch<T> { /// Classify the dispatch function based on input data `target` of type `T`. When implementing /// this for a dispatchable, `T` will be a tuple of all arguments given to the function (except /// origin). fn classify_dispatch(&self, target: T) -> DispatchClass; } /// Indicates if dispatch function should pay fees or not. /// If set to `Pays::No`, the block resource limits are applied, yet no fee is deducted. pub trait PaysFee<T> { fn pays_fee(&self, _target: T) -> Pays; } /// Explicit enum to denote if a transaction pays fee or not. #[derive(Clone, Copy, Eq, PartialEq, RuntimeDebug, Encode, Decode)] pub enum Pays { /// Transactor will pay related fees. Yes, /// Transactor will NOT pay related fees. No, } impl Default for Pays { fn default() -> Self { Self::Yes } } /// A generalized group of dispatch types. #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[cfg_attr(feature = "std", serde(rename_all = "camelCase"))] #[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug)] pub enum DispatchClass { /// A normal dispatch. Normal, /// An operational dispatch. Operational, /// A mandatory dispatch. These kinds of dispatch are always included regardless of their /// weight, therefore it is critical that they are separately validated to ensure that a /// malicious validator cannot craft a valid but impossibly heavy block. Usually this just /// means ensuring that the extrinsic can only be included once and that it is always very /// light. /// /// Do *NOT* use it for extrinsics that can be heavy. /// /// The only real use case for this is inherent extrinsics that are required to execute in a /// block for the block to be valid, and it solves the issue in the case that the block /// initialization is sufficiently heavy to mean that those inherents do not fit into the /// block. Essentially, we assume that in these exceptional circumstances, it is better to /// allow an overweight block to be created than to not allow any block at all to be created. Mandatory, } impl Default for DispatchClass { fn default() -> Self { Self::Normal } } /// Primitives related to priority management of Frame. pub mod priority { /// The starting point of all Operational transactions. 3/4 of u64::max_value(). pub const LIMIT: u64 = 13_835_058_055_282_163_711_u64; /// Wrapper for priority of different dispatch classes. /// /// This only makes sure that any value created for the operational dispatch class is /// incremented by [`LIMIT`]. pub enum FrameTransactionPriority { Normal(u64), Operational(u64), } impl From<FrameTransactionPriority> for u64 { fn from(priority: FrameTransactionPriority) -> Self { match priority { FrameTransactionPriority::Normal(inner) => inner, FrameTransactionPriority::Operational(inner) => inner.saturating_add(LIMIT), } } } } /// A bundle of static information collected from the `#[weight = $x]` attributes. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct DispatchInfo { /// Weight of this transaction. pub weight: Weight, /// Class of this transaction. pub class: DispatchClass, /// Does this transaction pay fees. pub pays_fee: Pays, } /// A `Dispatchable` function (aka transaction) that can carry some static information along with /// it, using the `#[weight]` attribute. pub trait GetDispatchInfo { /// Return a `DispatchInfo`, containing relevant information of this dispatch. /// /// This is done independently of its encoded size. fn get_dispatch_info(&self) -> DispatchInfo; } /// Weight information that is only available post dispatch. /// NOTE: This can only be used to reduce the weight or fee, not increase it. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct PostDispatchInfo { /// Actual weight consumed by a call or `None` which stands for the worst case static weight. pub actual_weight: Option<Weight>, /// Whether this transaction should pay fees when all is said and done. pub pays_fee: Pays, } impl PostDispatchInfo { /// Calculate how much (if any) weight was not used by the `Dispatchable`. pub fn calc_unspent(&self, info: &DispatchInfo) -> Weight { info.weight - self.calc_actual_weight(info) } /// Calculate how much weight was actually spent by the `Dispatchable`. pub fn calc_actual_weight(&self, info: &DispatchInfo) -> Weight { if let Some(actual_weight) = self.actual_weight { actual_weight.min(info.weight) } else { info.weight } } /// Determine if user should actually pay fees at the end of the dispatch. pub fn pays_fee(&self, info: &DispatchInfo) -> Pays { // If they originally were not paying fees, or the post dispatch info // says they should not pay fees, then they don't pay fees. // This is because the pre dispatch information must contain the // worst case for weight and fees paid. if info.pays_fee == Pays::No || self.pays_fee == Pays::No { Pays::No } else { // Otherwise they pay. Pays::Yes } } } /// Extract the actual weight from a dispatch result if any or fall back to the default weight. pub fn extract_actual_weight(result: &DispatchResultWithPostInfo, info: &DispatchInfo) -> Weight { match result { Ok(post_info) => &post_info, Err(err) => &err.post_info, } .calc_actual_weight(info) } impl From<(Option<Weight>, Pays)> for PostDispatchInfo { fn from(post_weight_info: (Option<Weight>, Pays)) -> Self { let (actual_weight, pays_fee) = post_weight_info; Self { actual_weight, pays_fee } } } impl From<Pays> for PostDispatchInfo { fn from(pays_fee: Pays) -> Self { Self { actual_weight: None, pays_fee } } } impl From<Option<Weight>> for PostDispatchInfo { fn from(actual_weight: Option<Weight>) -> Self { Self { actual_weight, pays_fee: Default::default() } } } impl From<()> for PostDispatchInfo { fn from(_: ()) -> Self { Self { actual_weight: None, pays_fee: Default::default() } } } impl sp_runtime::traits::Printable for PostDispatchInfo { fn print(&self) { "actual_weight=".print(); match self.actual_weight { Some(weight) => weight.print(), None => "max-weight".print(), }; "pays_fee=".print(); match self.pays_fee { Pays::Yes => "Yes".print(), Pays::No => "No".print(), } } } /// Allows easy conversion from `DispatchError` to `DispatchErrorWithPostInfo` for dispatchables /// that want to return a custom a posterior weight on error. pub trait WithPostDispatchInfo { /// Call this on your modules custom errors type in order to return a custom weight on error. /// /// # Example /// /// ```ignore /// let who = ensure_signed(origin).map_err(|e| e.with_weight(100))?; /// ensure!(who == me, Error::<T>::NotMe.with_weight(200_000)); /// ``` fn with_weight(self, actual_weight: Weight) -> DispatchErrorWithPostInfo; } impl<T> WithPostDispatchInfo for T where T: Into<DispatchError>, { fn with_weight(self, actual_weight: Weight) -> DispatchErrorWithPostInfo { DispatchErrorWithPostInfo { post_info: PostDispatchInfo { actual_weight: Some(actual_weight), pays_fee: Default::default(), }, error: self.into(), } } } impl<T> WeighData<T> for Weight { fn weigh_data(&self, _: T) -> Weight { return *self } } impl<T> ClassifyDispatch<T> for Weight { fn classify_dispatch(&self, _: T) -> DispatchClass { DispatchClass::Normal } } impl<T> PaysFee<T> for Weight { fn pays_fee(&self, _: T) -> Pays { Pays::Yes } } impl<T> WeighData<T> for (Weight, DispatchClass, Pays) { fn weigh_data(&self, _: T) -> Weight { return self.0 } } impl<T> ClassifyDispatch<T> for (Weight, DispatchClass, Pays) { fn classify_dispatch(&self, _: T) -> DispatchClass { self.1 } } impl<T> PaysFee<T> for (Weight, DispatchClass, Pays) { fn pays_fee(&self, _: T) -> Pays { self.2 } } impl<T> WeighData<T> for (Weight, DispatchClass) { fn weigh_data(&self, _: T) -> Weight { return self.0 } } impl<T> ClassifyDispatch<T> for (Weight, DispatchClass) { fn classify_dispatch(&self, _: T) -> DispatchClass { self.1 } } impl<T> PaysFee<T> for (Weight, DispatchClass) { fn pays_fee(&self, _: T) -> Pays { Pays::Yes } } impl<T> WeighData<T> for (Weight, Pays) { fn weigh_data(&self, _: T) -> Weight { return self.0 } } impl<T> ClassifyDispatch<T> for (Weight, Pays) { fn classify_dispatch(&self, _: T) -> DispatchClass { DispatchClass::Normal } } impl<T> PaysFee<T> for (Weight, Pays) { fn pays_fee(&self, _: T) -> Pays { self.1 } } /// A struct to represent a weight which is a function of the input arguments. The given items have /// the following types: /// /// - `WD`: a raw `Weight` value or a closure that returns a `Weight` with the same argument list as /// the dispatched, wrapped in a tuple. /// - `CD`: a raw `DispatchClass` value or a closure that returns a `DispatchClass` with the same /// argument list as the dispatched, wrapped in a tuple. /// - `PF`: a `Pays` variant for whether this dispatch pays fee or not or a closure that returns a /// `Pays` variant with the same argument list as the dispatched, wrapped in a tuple. #[deprecated = "Function arguments are available directly inside the annotation now."] pub struct FunctionOf<WD, CD, PF>(pub WD, pub CD, pub PF); // `WeighData` as a raw value #[allow(deprecated)] impl<Args, CD, PF> WeighData<Args> for FunctionOf<Weight, CD, PF> { fn weigh_data(&self, _: Args) -> Weight { self.0 } } // `WeighData` as a closure #[allow(deprecated)] impl<Args, WD, CD, PF> WeighData<Args> for FunctionOf<WD, CD, PF> where WD: Fn(Args) -> Weight, { fn weigh_data(&self, args: Args) -> Weight { (self.0)(args) } } // `ClassifyDispatch` as a raw value #[allow(deprecated)] impl<Args, WD, PF> ClassifyDispatch<Args> for FunctionOf<WD, DispatchClass, PF> { fn classify_dispatch(&self, _: Args) -> DispatchClass { self.1 } } // `ClassifyDispatch` as a raw value #[allow(deprecated)] impl<Args, WD, CD, PF> ClassifyDispatch<Args> for FunctionOf<WD, CD, PF> where CD: Fn(Args) -> DispatchClass, { fn classify_dispatch(&self, args: Args) -> DispatchClass { (self.1)(args) } } // `PaysFee` as a raw value #[allow(deprecated)] impl<Args, WD, CD> PaysFee<Args> for FunctionOf<WD, CD, Pays> { fn pays_fee(&self, _: Args) -> Pays { self.2 } } // `PaysFee` as a closure #[allow(deprecated)] impl<Args, WD, CD, PF> PaysFee<Args> for FunctionOf<WD, CD, PF> where PF: Fn(Args) -> Pays, { fn pays_fee(&self, args: Args) -> Pays { (self.2)(args) } } /// Implementation for unchecked extrinsic. impl<Address, Call, Signature, Extra> GetDispatchInfo for UncheckedExtrinsic<Address, Call, Signature, Extra> where Call: GetDispatchInfo, Extra: SignedExtension, { fn get_dispatch_info(&self) -> DispatchInfo { self.function.get_dispatch_info() } } /// Implementation for checked extrinsic. impl<AccountId, Call, Extra> GetDispatchInfo for CheckedExtrinsic<AccountId, Call, Extra> where Call: GetDispatchInfo, { fn get_dispatch_info(&self) -> DispatchInfo { self.function.get_dispatch_info() } } /// Implementation for test extrinsic. #[cfg(feature = "std")] impl<Call: Encode, Extra: Encode> GetDispatchInfo for sp_runtime::testing::TestXt<Call, Extra> { fn get_dispatch_info(&self) -> DispatchInfo { // for testing: weight == size. DispatchInfo { weight: self.encode().len() as _, pays_fee: Pays::Yes, ..Default::default() } } } /// The weight of database operations that the runtime can invoke. #[derive(Clone, Copy, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] pub struct RuntimeDbWeight { pub read: Weight, pub write: Weight, } impl RuntimeDbWeight { pub fn reads(self, r: Weight) -> Weight { self.read.saturating_mul(r) } pub fn writes(self, w: Weight) -> Weight { self.write.saturating_mul(w) } pub fn reads_writes(self, r: Weight, w: Weight) -> Weight { let read_weight = self.read.saturating_mul(r); let write_weight = self.write.saturating_mul(w); read_weight.saturating_add(write_weight) } } /// One coefficient and its position in the `WeightToFeePolynomial`. /// /// One term of polynomial is calculated as: /// /// ```ignore /// coeff_integer * x^(degree) + coeff_frac * x^(degree) /// ``` /// /// The `negative` value encodes whether the term is added or substracted from the /// overall polynomial result. #[derive(Clone, Encode, Decode)] pub struct WeightToFeeCoefficient<Balance> { /// The integral part of the coefficient. pub coeff_integer: Balance, /// The fractional part of the coefficient. pub coeff_frac: Perbill, /// True iff the coefficient should be interpreted as negative. pub negative: bool, /// Degree/exponent of the term. pub degree: u8, } /// A list of coefficients that represent one polynomial. pub type WeightToFeeCoefficients<T> = SmallVec<[WeightToFeeCoefficient<T>; 4]>; /// A trait that describes the weight to fee calculation as polynomial. /// /// An implementor should only implement the `polynomial` function. pub trait WeightToFeePolynomial { /// The type that is returned as result from polynomial evaluation. type Balance: BaseArithmetic + From<u32> + Copy + Unsigned; /// Returns a polynomial that describes the weight to fee conversion. /// /// This is the only function that should be manually implemented. Please note /// that all calculation is done in the probably unsigned `Balance` type. This means /// that the order of coefficients is important as putting the negative coefficients /// first will most likely saturate the result to zero mid evaluation. fn polynomial() -> WeightToFeeCoefficients<Self::Balance>; /// Calculates the fee from the passed `weight` according to the `polynomial`. /// /// This should not be overriden in most circumstances. Calculation is done in the /// `Balance` type and never overflows. All evaluation is saturating. fn calc(weight: &Weight) -> Self::Balance { Self::polynomial().iter().fold(Self::Balance::saturated_from(0u32), |mut acc, args| { let w = Self::Balance::saturated_from(*weight).saturating_pow(args.degree.into()); // The sum could get negative. Therefore we only sum with the accumulator. // The Perbill Mul implementation is non overflowing. let frac = args.coeff_frac * w; let integer = args.coeff_integer.saturating_mul(w); if args.negative { acc = acc.saturating_sub(frac); acc = acc.saturating_sub(integer); } else { acc = acc.saturating_add(frac); acc = acc.saturating_add(integer); } acc }) } } /// Implementor of `WeightToFeePolynomial` that maps one unit of weight to one unit of fee. pub struct IdentityFee<T>(sp_std::marker::PhantomData<T>); impl<T> WeightToFeePolynomial for IdentityFee<T> where T: BaseArithmetic + From<u32> + Copy + Unsigned, { type Balance = T; fn polynomial() -> WeightToFeeCoefficients<Self::Balance> { smallvec!(WeightToFeeCoefficient { coeff_integer: 1u32.into(), coeff_frac: Perbill::zero(), negative: false, degree: 1, }) } } #[cfg(test)] #[allow(dead_code)] mod tests { use super::*; use crate::{decl_module, parameter_types, traits::Get}; pub trait Trait { type Origin; type Balance; type BlockNumber; type DbWeight: Get<RuntimeDbWeight>; } pub struct TraitImpl {} parameter_types! { pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 100, write: 1000, }; } impl Trait for TraitImpl { type Origin = u32; type BlockNumber = u32; type Balance = u32; type DbWeight = DbWeight; } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { // no arguments, fixed weight #[weight = 1000] fn f00(_origin) { unimplemented!(); } #[weight = (1000, DispatchClass::Mandatory)] fn f01(_origin) { unimplemented!(); } #[weight = (1000, Pays::No)] fn f02(_origin) { unimplemented!(); } #[weight = (1000, DispatchClass::Operational, Pays::No)] fn f03(_origin) { unimplemented!(); } // weight = a x 10 + b #[weight = ((_a * 10 + _eb * 1) as Weight, DispatchClass::Normal, Pays::Yes)] fn f11(_origin, _a: u32, _eb: u32) { unimplemented!(); } #[weight = (0, DispatchClass::Operational, Pays::Yes)] fn f12(_origin, _a: u32, _eb: u32) { unimplemented!(); } #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + 10_000] fn f2(_origin) { unimplemented!(); } #[weight = T::DbWeight::get().reads_writes(6, 5) + 40_000] fn f21(_origin) { unimplemented!(); } } } #[test] fn weights_are_correct() { // #[weight = 1000] let info = Call::<TraitImpl>::f00().get_dispatch_info(); assert_eq!(info.weight, 1000); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = (1000, DispatchClass::Mandatory)] let info = Call::<TraitImpl>::f01().get_dispatch_info(); assert_eq!(info.weight, 1000); assert_eq!(info.class, DispatchClass::Mandatory); assert_eq!(info.pays_fee, Pays::Yes); // #[weight = (1000, Pays::No)] let info = Call::<TraitImpl>::f02().get_dispatch_info(); assert_eq!(info.weight, 1000); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::No); // #[weight = (1000, DispatchClass::Operational, Pays::No)] let info = Call::<TraitImpl>::f03().get_dispatch_info(); assert_eq!(info.weight, 1000); assert_eq!(info.class, DispatchClass::Operational); assert_eq!(info.pays_fee, Pays::No); assert_eq!(Call::<TraitImpl>::f11(10, 20).get_dispatch_info().weight, 120); assert_eq!(Call::<TraitImpl>::f11(10, 20).get_dispatch_info().class, DispatchClass::Normal); assert_eq!(Call::<TraitImpl>::f12(10, 20).get_dispatch_info().weight, 0); assert_eq!( Call::<TraitImpl>::f12(10, 20).get_dispatch_info().class, DispatchClass::Operational ); assert_eq!(Call::<TraitImpl>::f2().get_dispatch_info().weight, 12300); assert_eq!(Call::<TraitImpl>::f21().get_dispatch_info().weight, 45600); assert_eq!(Call::<TraitImpl>::f2().get_dispatch_info().class, DispatchClass::Normal); } #[test] fn extract_actual_weight_works() { let pre = DispatchInfo { weight: 1000, ..Default::default() }; assert_eq!(extract_actual_weight(&Ok(Some(7).into()), &pre), 7); assert_eq!(extract_actual_weight(&Ok(Some(1000).into()), &pre), 1000); assert_eq!(extract_actual_weight(&Err(DispatchError::BadOrigin.with_weight(9)), &pre), 9); } #[test] fn extract_actual_weight_caps_at_pre_weight() { let pre = DispatchInfo { weight: 1000, ..Default::default() }; assert_eq!(extract_actual_weight(&Ok(Some(1250).into()), &pre), 1000); assert_eq!( extract_actual_weight(&Err(DispatchError::BadOrigin.with_weight(1300)), &pre), 1000 ); } type Balance = u64; // 0.5x^3 + 2.333x2 + 7x - 10_000 struct Poly; impl WeightToFeePolynomial for Poly { type Balance = Balance; fn polynomial() -> WeightToFeeCoefficients<Self::Balance> { smallvec![ WeightToFeeCoefficient { coeff_integer: 0, coeff_frac: Perbill::from_fraction(0.5), negative: false, degree: 3 }, WeightToFeeCoefficient { coeff_integer: 2, coeff_frac: Perbill::from_rational_approximation(1u32, 3u32), negative: false, degree: 2 }, WeightToFeeCoefficient { coeff_integer: 7, coeff_frac: Perbill::zero(), negative: false, degree: 1 }, WeightToFeeCoefficient { coeff_integer: 10_000, coeff_frac: Perbill::zero(), negative: true, degree: 0 }, ] } } #[test] fn polynomial_works() { assert_eq!(Poly::calc(&100), 514033); assert_eq!(Poly::calc(&10_123), 518917034928); } #[test] fn polynomial_does_not_underflow() { assert_eq!(Poly::calc(&0), 0); } #[test] fn polynomial_does_not_overflow() { assert_eq!(Poly::calc(&Weight::max_value()), Balance::max_value() - 10_000); } #[test] fn identity_fee_works() { assert_eq!(IdentityFee::<Balance>::calc(&0), 0); assert_eq!(IdentityFee::<Balance>::calc(&50), 50); assert_eq!(IdentityFee::<Balance>::calc(&Weight::max_value()), Balance::max_value()); } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomAssessmentAutomationsListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CustomAssessmentAutomation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomAssessmentAutomation { #[serde(flatten)] pub resource: Resource, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CustomAssessmentAutomationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomAssessmentAutomationRequest { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CustomAssessmentAutomationRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomAssessmentAutomationProperties { #[serde(rename = "compressedQuery", default, skip_serializing_if = "Option::is_none")] pub compressed_query: Option<String>, #[serde(rename = "supportedCloud", default, skip_serializing_if = "Option::is_none")] pub supported_cloud: Option<custom_assessment_automation_properties::SupportedCloud>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<custom_assessment_automation_properties::Severity>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "remediationDescription", default, skip_serializing_if = "Option::is_none")] pub remediation_description: Option<String>, #[serde(rename = "assessmentKey", default, skip_serializing_if = "Option::is_none")] pub assessment_key: Option<String>, } pub mod custom_assessment_automation_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SupportedCloud { #[serde(rename = "AWS")] Aws, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Severity { High, Medium, Low, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomAssessmentAutomationRequestProperties { #[serde(rename = "compressedQuery", default, skip_serializing_if = "Option::is_none")] pub compressed_query: Option<String>, #[serde(rename = "supportedCloud", default, skip_serializing_if = "Option::is_none")] pub supported_cloud: Option<custom_assessment_automation_request_properties::SupportedCloud>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<custom_assessment_automation_request_properties::Severity>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "remediationDescription", default, skip_serializing_if = "Option::is_none")] pub remediation_description: Option<String>, } pub mod custom_assessment_automation_request_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SupportedCloud { #[serde(rename = "AWS")] Aws, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Severity { High, Medium, Low, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomEntityStoreAssignmentsListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CustomEntityStoreAssignment>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomEntityStoreAssignment { #[serde(flatten)] pub resource: Resource, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CustomEntityStoreAssignmentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomEntityStoreAssignmentProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub principal: Option<String>, #[serde(rename = "entityStoreDatabaseLink", default, skip_serializing_if = "Option::is_none")] pub entity_store_database_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomEntityStoreAssignmentRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CustomEntityStoreAssignmentRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomEntityStoreAssignmentRequestProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub principal: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudErrorBody { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<CloudErrorBody>, #[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")] pub additional_info: Vec<ErrorAdditionalInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorAdditionalInfo { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub info: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, }
fn main() { println!("So many types!"); } fn scalar_types() { // Floating-Point Types // f64 let x = 2.0; // f32 let y: f32 = 3.0; // Numeric Operations // addition let sum = 5 + 10; // subtraction let difference = 95.5 - 4.3; // multiplication let product = 4 * 30; //division let quotient = 56.7 / 32.2; // remainder let remainder = 43 % 5; // Boolean Type let t = true; // with explicit type annotation let f: bool = true; // Character Type // char type is specified with single quotes // strings use double quotes // char type represents a Unicode Scalar Value let c = 'z'; let z = 'ℤ'; let heart_eyed_cat = '😻'; } fn compound_types() { // Tuples let tup = (500, 6.4, 1); let (x, y, z) = tup; // will print 6.4 println!("The value of y is: {}", y); // accessing directly with a period let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; // Arrays // all elements must be the same type // fixed length // once declared cannot grow or shrink in size let a = [1, 2, 3, 4, 5]; // accessing elements let first = a[0]; let second = a[1]; }
use std::io; use rand::prelude::*; fn main() { let secret_number = rand::thread_rng().gen_range(1, 101); println!("I'm thinking of a number between 1 and 100..."); println!("Guess the number:"); loop { let mut guess = String::new(); let read_result = io::stdin().read_line(&mut guess); match read_result { Ok(_) => {()} Err(e) => { eprintln!("There was some error reading input from the user. The error was \"{}\". Try again.", e); continue; } } let guess_value: i32; let guess_parse_result = guess.trim().parse::<i32>(); match guess_parse_result { Ok(ok_guess) => { guess_value = ok_guess; } Err(e) => { eprintln!("There was some error with the input. The error was \"{}\". Try again.",e); continue; } } if guess_value > secret_number { println!("\n{} is too high! Guess lower:", guess); } else if guess_value < secret_number { println!("\n{} is too low! Guess higher:", guess); } else { println!("\nYou got it! The secret number was {}.", secret_number); break; } } }
#[cfg(not(unix))] compile_error!("only unix systems are supported"); use anyhow::{Context, Result}; use libc::pid_t; use log::{warn, error}; use procfs::process::Process; use std::collections::HashMap; use std::path::PathBuf; use std::str::FromStr; pub(crate) const ANANICY_CONFIG_DIR: &str = "/etc/ananicy.d"; mod cgroup; mod class; mod parse; mod proc_type; mod rule; pub use cgroup::*; pub use class::*; pub use proc_type::*; pub use rule::*; use std::ffi::OsStr; pub fn apply_all_rules<'a>(rules: &'a HashMap<String, Rule>, cgroups: &'a mut HashMap<String, Cgroup>) -> Result<impl Iterator<Item=Result<()>> + 'a> { Ok(all_procs()? .filter_map(move |p| { match p.exe() { Ok(path) => path .file_name() .and_then(OsStr::to_str) .and_then(|f| rules.get(f)), Err(e) => { error!("Are you root? {} [{:?}]", e, p.pid); None } } .map(|r| (r, p)) }) .map(move |(r, p)| apply_rule(r, &p, cgroups))) } pub fn apply_rule(r: &Rule, p: &Process, cgroups: &mut HashMap<String, Cgroup>) -> Result<()> { r.apply(&p)?; if let Some(cgroup_name) = r.cgroup_name() { if let Some(cgroup) = cgroups.get_mut(cgroup_name) { cgroup.apply(&p)?; } } Ok(()) } pub fn all_procs() -> Result<impl Iterator<Item = Process>> { let mut iter = ::std::fs::read_dir("/proc/") .context("failed to read /proc")? .filter_map(|p| p.ok()) .filter(|p| p.path().is_dir()) .filter_map(|p| pid_t::from_str(p.file_name().to_str()?).ok()) .map(Process::new) .filter_map(|p| p.ok()) .filter_map(|p| { let pid = p.pid; match all_threads(pid) { Ok(t) => Some(t.chain(::std::iter::once(p))), Err(e) => { warn!("failed to read threads {}", e); None } } }) .flatten() .filter(|p| p.exe().is_ok()); if iter.by_ref().peekable().peek().is_none() { Err(anyhow::anyhow!("no valid processes found")) } else { Ok(iter) } } fn all_threads(pid: pid_t) -> Result<impl Iterator<Item = Process>> { let path = format!("/proc/{}/task", pid); Ok(::std::fs::read_dir(&path) .with_context(|| format!("failed to read {}", path))? .filter_map(|p| p.ok()) .filter(|p| p.path().is_dir()) .filter_map(|p| pid_t::from_str(p.file_name().to_str()?).ok()) .map(move |p| Process::new_with_root(PathBuf::from(path.as_str()).join(p.to_string()))) .filter_map(|p| match p { Ok(proc) => Some(proc), Err(e) => { warn!("failed to parse thread {}", e); None } })) }