file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
pending.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use interrupt::Hardware; #[derive(Copy, Clone, Debug)] pub struct ISPR(u32); #[derive(Copy, Clone, Debug)] pub struct ICPR(u32); impl ISPR { pub fn set_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } pub fn interrupt_is_pending(&self, hardware: Hardware) -> bool
} impl ICPR { pub fn clear_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ispr_set_pending() { let mut ispr = ISPR(0); ispr.set_pending(Hardware::Flash); assert_eq!(ispr.0, 0b1 << 3); } #[test] fn test_ispr_interrupt_is_pending() { let ispr = ISPR(0b1 << 5); assert!(ispr.interrupt_is_pending(Hardware::Exti01)); assert!(!ispr.interrupt_is_pending(Hardware::Usb)); } #[test] fn test_icpr_clear_pending() { let mut icpr = ICPR(0); icpr.clear_pending(Hardware::Flash); assert_eq!(icpr.0, 0b1 << 3); } }
{ let interrupt = hardware as u8; self.0 & (0b1 << interrupt) != 0 }
identifier_body
pending.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ use interrupt::Hardware; #[derive(Copy, Clone, Debug)] pub struct ISPR(u32); #[derive(Copy, Clone, Debug)] pub struct ICPR(u32); impl ISPR { pub fn set_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } pub fn interrupt_is_pending(&self, hardware: Hardware) -> bool {
} impl ICPR { pub fn clear_pending(&mut self, hardware: Hardware) { let interrupt = hardware as u8; self.0 |= 0b1 << interrupt; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ispr_set_pending() { let mut ispr = ISPR(0); ispr.set_pending(Hardware::Flash); assert_eq!(ispr.0, 0b1 << 3); } #[test] fn test_ispr_interrupt_is_pending() { let ispr = ISPR(0b1 << 5); assert!(ispr.interrupt_is_pending(Hardware::Exti01)); assert!(!ispr.interrupt_is_pending(Hardware::Usb)); } #[test] fn test_icpr_clear_pending() { let mut icpr = ICPR(0); icpr.clear_pending(Hardware::Flash); assert_eq!(icpr.0, 0b1 << 3); } }
let interrupt = hardware as u8; self.0 & (0b1 << interrupt) != 0 }
random_line_split
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Add::add) } /// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." } define_gas_unit! { name: GasUnits, carrier: GasCarrier, doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn
(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
new
identifier_name
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Add::add) } /// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." }
doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn new(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
define_gas_unit! { name: GasUnits, carrier: GasCarrier,
random_line_split
gas_schedule.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module lays out the basic abstract costing schedule for bytecode instructions. //! //! It is important to note that the cost schedule defined in this file does not track hashing //! operations or other native operations; the cost of each native operation will be returned by the //! native function itself. use mirai_annotations::*; use serde::{Deserialize, Serialize}; use std::{ ops::{Add, Div, Mul, Sub}, u64, }; /// The underlying carrier for gas-related units and costs. Data with this type should not be /// manipulated directly, but instead be manipulated using the newtype wrappers defined around /// them and the functions defined in the `GasAlgebra` trait. pub type GasCarrier = u64; /// A trait encoding the operations permitted on the underlying carrier for the gas unit, and how /// other gas-related units can interact with other units -- operations can only be performed /// across units with the same underlying carrier (i.e. as long as the underlying data is /// the same). pub trait GasAlgebra<GasCarrier>: Sized where GasCarrier: Add<Output = GasCarrier> + Sub<Output = GasCarrier> + Div<Output = GasCarrier> + Mul<Output = GasCarrier> + Copy, { /// Project a value into the gas algebra. fn new(carrier: GasCarrier) -> Self; /// Get the carrier. fn get(&self) -> GasCarrier; /// Map a function `f` of one argument over the underlying data. fn map<F: Fn(GasCarrier) -> GasCarrier>(self, f: F) -> Self { Self::new(f(self.get())) } /// Map a function `f` of two arguments over the underlying carrier. Note that this function /// can take two different implementations of the trait -- one for `self` the other for the /// second argument. But, we enforce that they have the same underlying carrier. fn map2<F: Fn(GasCarrier, GasCarrier) -> GasCarrier>( self, other: impl GasAlgebra<GasCarrier>, f: F, ) -> Self { Self::new(f(self.get(), other.get())) } /// Apply a function `f` of two arguments to the carrier. Since `f` is not an endomorphism, we /// return the resulting value, as opposed to the result wrapped up in ourselves. fn app<T, F: Fn(GasCarrier, GasCarrier) -> T>( &self, other: &impl GasAlgebra<GasCarrier>, f: F, ) -> T { f(self.get(), other.get()) } /// We allow casting between GasAlgebras as long as they have the same underlying carrier -- /// i.e. they use the same type to store the underlying value. fn unitary_cast<T: GasAlgebra<GasCarrier>>(self) -> T { T::new(self.get()) } /// Add the two `GasAlgebra`s together. fn add(self, right: impl GasAlgebra<GasCarrier>) -> Self
/// Subtract one `GasAlgebra` from the other. fn sub(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Sub::sub) } /// Multiply two `GasAlgebra`s together. fn mul(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Mul::mul) } /// Divide one `GasAlgebra` by the other. fn div(self, right: impl GasAlgebra<GasCarrier>) -> Self { self.map2(right, Div::div) } } // We would really like to be able to implement the standard arithmetic traits over the GasAlgebra // trait, but that isn't possible. macro_rules! define_gas_unit { { name: $name: ident, carrier: $carrier: ty, doc: $comment: literal } => { #[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[doc=$comment] pub struct $name<GasCarrier>(GasCarrier); impl GasAlgebra<$carrier> for $name<$carrier> { fn new(c: GasCarrier) -> Self { Self(c) } fn get(&self) -> GasCarrier { self.0 } } } } define_gas_unit! { name: AbstractMemorySize, carrier: GasCarrier, doc: "A newtype wrapper that represents the (abstract) memory size that the instruction will take up." } define_gas_unit! { name: GasUnits, carrier: GasCarrier, doc: "Units of gas as seen by clients of the Move VM." } define_gas_unit! { name: InternalGasUnits, carrier: GasCarrier, doc: "Units of gas used within the Move VM, scaled for fine-grained accounting." } define_gas_unit! { name: GasPrice, carrier: GasCarrier, doc: "A newtype wrapper around the gas price for each unit of gas consumed." } /// One unit of gas pub const ONE_GAS_UNIT: InternalGasUnits<GasCarrier> = InternalGasUnits(1); /// The maximum size representable by AbstractMemorySize pub const MAX_ABSTRACT_MEMORY_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(std::u64::MAX); /// The size in bytes for a non-string or address constant on the stack pub const CONST_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(16); /// The size in bytes for a reference on the stack pub const REFERENCE_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(8); /// The size of a struct in bytes pub const STRUCT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(2); /// For V1 all accounts will be ~800 bytes pub const DEFAULT_ACCOUNT_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(800); /// Any transaction over this size will be charged `INTRINSIC_GAS_PER_BYTE` per byte pub const LARGE_TRANSACTION_CUTOFF: AbstractMemorySize<GasCarrier> = AbstractMemorySize(600); /// For exists checks on data that doesn't exists this is the multiplier that is used. pub const MIN_EXISTS_DATA_SIZE: AbstractMemorySize<GasCarrier> = AbstractMemorySize(100); pub const MAX_TRANSACTION_SIZE_IN_BYTES: GasCarrier = 4096; #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct GasConstants { /// The cost per-byte read from global storage. pub global_memory_per_byte_cost: InternalGasUnits<GasCarrier>, /// The cost per-byte written to storage. pub global_memory_per_byte_write_cost: InternalGasUnits<GasCarrier>, /// The flat minimum amount of gas required for any transaction. /// Charged at the start of execution. pub min_transaction_gas_units: InternalGasUnits<GasCarrier>, /// Any transaction over this size will be charged an additional amount per byte. pub large_transaction_cutoff: AbstractMemorySize<GasCarrier>, /// The units of gas that to be charged per byte over the `large_transaction_cutoff` in addition to /// `min_transaction_gas_units` for transactions whose size exceeds `large_transaction_cutoff`. pub intrinsic_gas_per_byte: InternalGasUnits<GasCarrier>, /// ~5 microseconds should equal one unit of computational gas. We bound the maximum /// computational time of any given transaction at roughly 20 seconds. We want this number and /// `MAX_PRICE_PER_GAS_UNIT` to always satisfy the inequality that /// MAXIMUM_NUMBER_OF_GAS_UNITS * MAX_PRICE_PER_GAS_UNIT < min(u64::MAX, GasUnits<GasCarrier>::MAX) /// NB: The bound is set quite high since custom scripts aren't allowed except from predefined /// and vetted senders. pub maximum_number_of_gas_units: GasUnits<GasCarrier>, /// The minimum gas price that a transaction can be submitted with. pub min_price_per_gas_unit: GasPrice<GasCarrier>, /// The maximum gas unit price that a transaction can be submitted with. pub max_price_per_gas_unit: GasPrice<GasCarrier>, pub max_transaction_size_in_bytes: GasCarrier, pub gas_unit_scaling_factor: GasCarrier, pub default_account_size: AbstractMemorySize<GasCarrier>, } impl GasConstants { pub fn to_internal_units(&self, units: GasUnits<GasCarrier>) -> InternalGasUnits<GasCarrier> { InternalGasUnits::new(units.get() * self.gas_unit_scaling_factor) } pub fn to_external_units(&self, units: InternalGasUnits<GasCarrier>) -> GasUnits<GasCarrier> { GasUnits::new(units.get() / self.gas_unit_scaling_factor) } } impl Default for GasConstants { fn default() -> Self { Self { global_memory_per_byte_cost: InternalGasUnits(4), global_memory_per_byte_write_cost: InternalGasUnits(9), min_transaction_gas_units: InternalGasUnits(600), large_transaction_cutoff: LARGE_TRANSACTION_CUTOFF, intrinsic_gas_per_byte: InternalGasUnits(8), maximum_number_of_gas_units: GasUnits(4_000_000), min_price_per_gas_unit: GasPrice(0), max_price_per_gas_unit: GasPrice(10_000), max_transaction_size_in_bytes: MAX_TRANSACTION_SIZE_IN_BYTES, gas_unit_scaling_factor: 1000, default_account_size: DEFAULT_ACCOUNT_SIZE, } } } /// The cost tables, keyed by the serialized form of the bytecode instruction. We use the /// serialized form as opposed to the instruction enum itself as the key since this will be the /// on-chain representation of bytecode instructions in the future. #[derive(Clone, Debug, Serialize, PartialEq, Deserialize)] pub struct CostTable { pub instruction_table: Vec<GasCost>, pub native_table: Vec<GasCost>, pub gas_constants: GasConstants, } impl CostTable { #[inline] pub fn instruction_cost(&self, instr_index: u8) -> &GasCost { precondition!(instr_index > 0 && instr_index <= (self.instruction_table.len() as u8)); &self.instruction_table[(instr_index - 1) as usize] } #[inline] pub fn native_cost(&self, native_index: u8) -> &GasCost { precondition!(native_index < (self.native_table.len() as u8)); &self.native_table[native_index as usize] } } /// The `GasCost` tracks: /// - instruction cost: how much time/computational power is needed to perform the instruction /// - memory cost: how much memory is required for the instruction, and storage overhead #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct GasCost { pub instruction_gas: InternalGasUnits<GasCarrier>, pub memory_gas: InternalGasUnits<GasCarrier>, } impl GasCost { pub fn new(instr_gas: GasCarrier, mem_gas: GasCarrier) -> Self { Self { instruction_gas: InternalGasUnits::new(instr_gas), memory_gas: InternalGasUnits::new(mem_gas), } } /// Convert a GasCost to a total gas charge in `InternalGasUnits`. #[inline] pub fn total(&self) -> InternalGasUnits<GasCarrier> { self.instruction_gas.add(self.memory_gas) } }
{ self.map2(right, Add::add) }
identifier_body
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn generate(&mut self, value: u8) -> GeneratedIcon
fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => { ((0, 0), Scale { x: 120.0, y: 120.0 }) } _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
{ if self.icon_cache.contains_key(&value) && value != 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } }
identifier_body
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn generate(&mut self, value: u8) -> GeneratedIcon { if self.icon_cache.contains_key(&value) && value!= 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } } fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => {
} _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
((0, 0), Scale { x: 120.0, y: 120.0 })
random_line_split
icon.rs
use image::{Rgba, RgbaImage}; use imageproc::drawing::draw_text_mut; use image::imageops::resize; use rusttype::{Scale, Font}; use std::ptr::null_mut; use std::collections::HashMap; pub type GeneratedIcon = *mut winapi::shared::windef::HICON__; pub struct IconGenerator { icon_cache: HashMap<u8, GeneratedIcon>, } impl IconGenerator { pub fn new() -> Self { IconGenerator { icon_cache: HashMap::with_capacity(100), } } pub fn
(&mut self, value: u8) -> GeneratedIcon { if self.icon_cache.contains_key(&value) && value!= 0 { return self.icon_cache[&value]; } else { let new_icon = IconGenerator::create_icon(value); self.icon_cache.insert(value, new_icon); new_icon } } fn scale_params(n: usize) -> ((u32, u32), Scale) { match n { 1 => { ((24, 0), Scale { x: 128.0, y: 128.0 }) } 2 => { ((0, 0), Scale { x: 120.0, y: 120.0 }) } _ => { ((0, 20), Scale { x: 80.0, y: 80.0 }) } } } fn create_icon(value: u8) -> GeneratedIcon { let value_to_draw = value.to_string(); let mut image = RgbaImage::new(128, 128); let font = Font::try_from_bytes(include_bytes!("fonts/Arial.ttf")).unwrap(); let scale_params = IconGenerator::scale_params(value_to_draw.len()); let coord = scale_params.0; draw_text_mut( &mut image, Rgba([255u8, 255u8, 255u8, 255u8]), coord.0, coord.1, scale_params.1, &font, &value_to_draw, ); let resized_image = resize( &mut image, 32, 32, image::imageops::FilterType::Lanczos3, ); unsafe { let hbm_mask = winapi::um::wingdi::CreateCompatibleBitmap( winapi::um::winuser::GetDC(null_mut()), 32, 32, ); let bytes_raw = resized_image.into_raw().as_mut_ptr(); let transmuted = std::mem::transmute::<*mut u8, *mut winapi::ctypes::c_void>(bytes_raw); let bitmap: winapi::shared::windef::HBITMAP = winapi::um::wingdi::CreateBitmap(32, 32, 2, 16, transmuted); let mut h_icon = winapi::um::winuser::ICONINFO { fIcon: 1, hbmColor: bitmap, hbmMask: hbm_mask, xHotspot: 0, yHotspot: 0, }; winapi::um::winuser::CreateIconIndirect(&mut h_icon) } } }
generate
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum
<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
SVGStrokeDashArray
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else
} else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
{ Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) }
conditional_block
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use crate::values::{Either, None_}; use cssparser::Parser; use style_traits::{ParseError, StyleParseErrorKind}; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub struct SVGPaint<ColorType, UrlPaintServer> { /// The paint source pub kind: SVGPaintKind<ColorType, UrlPaintServer>, /// The fallback color. It would be empty, the `none` keyword or <color>. pub fallback: Option<Either<ColorType, None_>>, } /// An SVG paint value without the fallback /// /// Whereas the spec only allows PaintServer /// to have a fallback, Gecko lets the context /// properties have a fallback as well. #[animation(no_bound(UrlPaintServer))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGPaintKind<ColorType, UrlPaintServer> { /// `none` #[animation(error)] None, /// `<color>` Color(ColorType), /// `url(...)` #[animation(error)] PaintServer(UrlPaintServer), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } impl<ColorType, UrlPaintServer> SVGPaintKind<ColorType, UrlPaintServer> { /// Parse a keyword value only fn parse_ident<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { try_match_ident_ignore_ascii_case! { input, "none" => Ok(SVGPaintKind::None), "context-fill" => Ok(SVGPaintKind::ContextFill), "context-stroke" => Ok(SVGPaintKind::ContextStroke), } } } /// Parse SVGPaint's fallback. /// fallback is keyword(none), Color or empty. /// <https://svgwg.org/svg2-draft/painting.html#SpecifyingPaint> fn parse_fallback<'i, 't, ColorType: Parse>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Option<Either<ColorType, None_>> { if input.try(|i| i.expect_ident_matching("none")).is_ok() { Some(Either::Second(None_)) } else { if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Some(Either::First(color)) } else { None } } } impl<ColorType: Parse, UrlPaintServer: Parse> Parse for SVGPaint<ColorType, UrlPaintServer> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { if let Ok(url) = input.try(|i| UrlPaintServer::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::PaintServer(url), fallback: parse_fallback(context, input), }) } else if let Ok(kind) = input.try(SVGPaintKind::parse_ident) { if let SVGPaintKind::None = kind { Ok(SVGPaint { kind: kind, fallback: None, }) } else { Ok(SVGPaint { kind: kind, fallback: parse_fallback(context, input), }) } } else if let Ok(color) = input.try(|i| ColorType::parse(context, i)) { Ok(SVGPaint { kind: SVGPaintKind::Color(color), fallback: None, }) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone,
MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] Vec<L>), /// `context-value` ContextValue, } /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, }
ComputeSquaredDistance, Copy, Debug,
random_line_split
overloaded-autoderef-count.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell;
struct DerefCounter<T> { count_imm: Cell<uint>, count_mut: uint, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (uint, uint) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref<T> for DerefCounter<T> { fn deref(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut<T> for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } #[deriving(PartialEq, Show)] struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } } pub fn main() { let mut p = DerefCounter::new(Point {x: 0, y: 0}); let _ = p.x; assert_eq!(p.counts(), (1, 0)); let _ = &p.x; assert_eq!(p.counts(), (2, 0)); let _ = &mut p.y; assert_eq!(p.counts(), (2, 1)); p.x += 3; assert_eq!(p.counts(), (2, 2)); p.get(); assert_eq!(p.counts(), (3, 2)); // Check the final state. assert_eq!(*p, Point {x: 3, y: 0}); }
use std::ops::{Deref, DerefMut}; #[deriving(PartialEq)]
random_line_split
overloaded-autoderef-count.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::Cell; use std::ops::{Deref, DerefMut}; #[deriving(PartialEq)] struct DerefCounter<T> { count_imm: Cell<uint>, count_mut: uint, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (uint, uint) { (self.count_imm.get(), self.count_mut) } } impl<T> Deref<T> for DerefCounter<T> { fn
(&self) -> &T { self.count_imm.set(self.count_imm.get() + 1); &self.value } } impl<T> DerefMut<T> for DerefCounter<T> { fn deref_mut(&mut self) -> &mut T { self.count_mut += 1; &mut self.value } } #[deriving(PartialEq, Show)] struct Point { x: int, y: int } impl Point { fn get(&self) -> (int, int) { (self.x, self.y) } } pub fn main() { let mut p = DerefCounter::new(Point {x: 0, y: 0}); let _ = p.x; assert_eq!(p.counts(), (1, 0)); let _ = &p.x; assert_eq!(p.counts(), (2, 0)); let _ = &mut p.y; assert_eq!(p.counts(), (2, 1)); p.x += 3; assert_eq!(p.counts(), (2, 2)); p.get(); assert_eq!(p.counts(), (3, 2)); // Check the final state. assert_eq!(*p, Point {x: 3, y: 0}); }
deref
identifier_name
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function()
else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i]!= t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
{ if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } }
conditional_block
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i]!= t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn
() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
lpo_gt_2
identifier_name
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool { s == t || lpo_gt(precedence, s, t) } fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i]!= t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]);
#[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); }
random_line_split
lpo.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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. // // Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>. // use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; /// Checks if s is greater than t according to the ordering. pub fn lpo_gt(precedence: &Precedence, s: &Term, t: &Term) -> bool { if s.is_function() && t.is_function() { if s.iter().any(|arg| lpo_ge(precedence, arg, t)) { true } else if t.iter().all(|arg| lpo_gt(precedence, s, arg)) { if s.get_id() == t.get_id() && lexical_ordering(precedence, s, t) { true } else { precedence.gt(s, t) } } else { false } } else if s.is_function() && t.is_variable() { s.occurs_proper(t) } else { false } } /// Checks if s is greater than or equal to t according to the ordering. pub fn lpo_ge(precedence: &Precedence, s: &Term, t: &Term) -> bool
fn lexical_ordering(precedence: &Precedence, s: &Term, t: &Term) -> bool { assert_eq!(s.get_id(), t.get_id()); assert_eq!(s.get_arity(), t.get_arity()); for i in 0..s.get_arity() { if lpo_gt(precedence, &s[i], &t[i]) { return true; } else if s[i]!= t[i] { return false; } } false } #[cfg(test)] mod test { use super::{lpo_gt, lpo_ge}; use prover::data_structures::term::Term; use prover::ordering::precedence::Precedence; #[test] fn lpo_gt_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); assert!(!lpo_gt(&precedence, &x, &y)); assert!(!lpo_gt(&precedence, &y, &x)); } #[test] fn lpo_gt_2() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); assert!(lpo_gt(&precedence, &f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_x)); } #[test] fn lpo_gt_3() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let y = Term::new_variable(-2); let f_y = Term::new_function(1, vec![y]); assert!(!lpo_gt(&precedence, &f_y, &x)); assert!(!lpo_gt(&precedence, &x, &f_y)); } #[test] fn lpo_gt_4() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x.clone()]); let f_f_x = Term::new_function(1, vec![f_x.clone()]); assert!(lpo_gt(&precedence, &f_f_x, &f_x)); assert!(!lpo_gt(&precedence, &f_x, &f_f_x)); assert!(lpo_gt(&precedence, &f_f_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_f_x)); } #[test] fn lpo_gt_5() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_g_x = Term::new_function(1, vec![Term::new_function(2, vec![x.clone()])]); assert!(lpo_gt(&precedence, &f_g_x, &x)); assert!(!lpo_gt(&precedence, &x, &f_g_x)); } #[test] fn lpo_gt_6() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x_x = Term::new_function(1, vec![x.clone(), x]); let t = Term::new_truth(); assert!(lpo_gt(&precedence, &f_x_x, &t)); assert!(!lpo_gt(&precedence, &t, &f_x_x)); } #[test] fn lpo_ge_1() { let precedence = Precedence::default(); let x = Term::new_variable(-1); let f_x = Term::new_function(1, vec![x]); assert!(!lpo_gt(&precedence, &f_x, &f_x)); assert!(lpo_ge(&precedence, &f_x, &f_x)); } }
{ s == t || lpo_gt(precedence, s, t) }
identifier_body
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn
() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
plain_charset
identifier_name
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64()
#[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
{ assert_parse( "data:;base64,C62+7w==", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); }
identifier_body
data_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::fetch; use headers_core::HeaderMapExt; use headers_ext::ContentType; use hyper_serde::Serde; use mime::{self, Mime}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] fn assert_parse( url: &'static str, content_type: Option<ContentType>, charset: Option<&str>, data: Option<&[u8]>, ) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); let response = fetch(&mut request, None); match data { Some(data) => { assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); let header_content_type = response.headers.typed_get::<ContentType>(); assert_eq!(header_content_type, content_type); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); assert_eq!(metadata.charset.as_ref().map(String::deref), charset); let resp_body = response.body.lock().unwrap(); match *resp_body { ResponseBody::Done(ref val) => { assert_eq!(val, &data); }, _ => panic!(), } }, None => { assert!(response.is_network_error()); assert_eq!( response.metadata().err(), Some(NetworkError::Internal( "Decoding data URL failed".to_owned() )) ); }, } } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )), Some("us-ascii"), Some(b"hello world"), ); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", Some(ContentType::from(mime::TEXT_PLAIN)), None, Some(b"hello"), ); } #[test] fn plain_html() { assert_parse( "data:text/html,<p>Servo</p>", Some(ContentType::from(mime::TEXT_HTML)), None, Some(b"<p>Servo</p>"), ); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", Some(ContentType::from( "text/plain; charset=latin1".parse::<Mime>().unwrap(), )), Some("latin1"), Some(b"hello"), ); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), Some("utf-8"), Some(b"hello"), ); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==",
Some("us-ascii"), Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), None, Some(&[0x0B, 0xAD, 0xBE, 0xEF]), ); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType::from( "text/plain; charset=koi8-r".parse::<Mime>().unwrap(), )), Some("koi8-r"), Some(&[ 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, ]), ); }
Some(ContentType::from( "text/plain; charset=US-ASCII".parse::<Mime>().unwrap(), )),
random_line_split
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } }
test_variants!(); test_variants2!(); }
x!(test_variants, test_variants2, MyEnum, Variant); pub fn check_variants() {
random_line_split
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } } x!(test_variants, test_variants2, MyEnum, Variant); pub fn
() { test_variants!(); test_variants2!(); }
check_variants
identifier_name
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } } x!(test_variants, test_variants2, MyEnum, Variant); pub fn check_variants()
{ test_variants!(); test_variants2!(); }
identifier_body
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self { W(writer) } } #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> {
self.w.bits = (self.w.bits &!0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w|..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W {
random_line_split
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn
(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self { W(writer) } } #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits &!0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w|..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
deref_mut
identifier_name
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self
} #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits &!0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w|..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
{ W(writer) }
identifier_body
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum
{ /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35.. 0] we always have [0.. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } } // If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum!= _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum!= _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum!= _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else { buf[i as usize] = value2ascii(0); i -= 1; } } } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if!exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if!exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
SignFormat
identifier_name
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum SignFormat { /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35.. 0] we always have [0.. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } } // If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum!= _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum!= _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum!= _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else
} } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if!exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if!exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
{ buf[i as usize] = value2ascii(0); i -= 1; }
conditional_block
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum SignFormat { /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35.. 0] we always have [0.. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } }
// If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum!= _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum!= _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum!= _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else { buf[i as usize] = value2ascii(0); i -= 1; } } } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if!exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if!exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
random_line_split
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn {.. } => write!(f, "[function]"), &Value::BuiltInFn { ref name,.. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display()
Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
{ assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}",
identifier_body
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn {.. } => write!(f, "[function]"), &Value::BuiltInFn { ref name,.. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn
(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
eq
identifier_name
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn {.. } => write!(f, "[function]"), &Value::BuiltInFn { ref name,.. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b),
pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
&Hashable::String(ref s) => Value::String(s.clone()), }) } }
random_line_split
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) =>
, &Value::Fn {.. } => write!(f, "[function]"), &Value::BuiltInFn { ref name,.. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
{ let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }
conditional_block
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter() .map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main()
.unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration!= 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
{ let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur")
identifier_body
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter() .map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn
() { let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration!= 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
main
identifier_name
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone +'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter()
for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main() { let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration!= 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
.map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len());
random_line_split
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn
() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
main
identifier_name
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&`
if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||`
random_line_split
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main()
// The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
{ use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&`
identifier_body
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false
//~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
{ }
conditional_block
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()>
.replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
{ let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or(""))
identifier_body
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 ";
hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
pub struct Bootstrap {
random_line_split
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password
else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
{ sess.userauth_password(u, p).unwrap(); }
conditional_block
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn
(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
new
identifier_name
main.rs
#![feature(plugin, no_std, start, core_intrinsics)]
use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
#![no_std] #![plugin(macro_platformtree)] extern crate zinc;
random_line_split
main.rs
#![feature(plugin, no_std, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn
(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
run
identifier_name
main.rs
#![feature(plugin, no_std, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args)
{ use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
identifier_body
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { let element = HTMLDataListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) } } impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn
(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
Options
identifier_name
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { let element = HTMLDataListElement::new_inherited(localName, prefix, document);
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) }
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement>
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
{ let element = HTMLDataListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) }
identifier_body
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hexed_key = key.as_bytes().to_hex(); let amount = hexed_key.as_bytes() .iter() .fold(0u8, |amt, &byte| amt.wrapping_add(byte)); match mode { Mode::Encrypt => { // well, this won't be useful since the library is meant to only decrypt files (for now) let text = data.to_hex().into_bytes(); let stuff = cbc(mode, text); let shifted_text = shift(&stuff, amount); xor(&shifted_text, &key) }, Mode::Decrypt => { let amount = 0u8.wrapping_sub(amount); // shift by (256 - amount) for the reverse let shifted_text = xor(data, &key); let stuff = shift(&shifted_text, amount); charred(cbc(mode, stuff)) }, } } // Hex-decoding function fn charred(decode: Vec<u8>) -> Vec<u8> { // Mostly, I try to stick to immutable borrows, but from_utf8() requires Vec<u8> // An error means that the decryption has failed! (which should be due to wrong keys) String::from_utf8(decode) .map_err(|_| ()) .and_then(|hexed_stuff| hexed_stuff.from_hex().map_err(|_| ())) .unwrap_or(Vec::new()) } // Shifts the elements by the given amount fn shift(text: &[u8], amount: u8) -> Vec<u8> { text.iter() // wrap around the boundary if the sum overflows .map(|byte| amount.wrapping_add(*byte)) .collect() } // Byte-wise XOR fn xor(text: &[u8], key: &str) -> Vec<u8> { let key_array = key.as_bytes(); let (text_size, key_size) = (text.len(), key.len()); (0..text_size).map(|i| text[i] ^ key_array[i % key_size]).collect() } // CBC mode as a seed to scramble the final ciphertext fn cbc(mode: Mode, mut data: Vec<u8>) -> Vec<u8> { let size = 2usize.pow(BLOCK_SIZE_EXP); // Well, there's no encryption going on here - just some fireworks to introduce randomness match mode { Mode::Encrypt => { let mut cbc_vec: Vec<u8> = sample(&mut thread_rng(), 1..255, size); // hex the bytes until the vector has the required length (an integral multiple of block size) for _ in 0..BLOCK_SIZE_EXP { data = data.to_hex().into_bytes(); } cbc_vec.extend(&data); for i in size..(data.len() + size) { cbc_vec[i] = cbc_vec[i] ^ cbc_vec[i - size]; } cbc_vec }, Mode::Decrypt =>
, } }
{ let mut i = data.len() - 1; while i >= size { data[i] = data[i] ^ data[i - size]; i -= 1; } let mut stuff = data[size..].to_owned(); for _ in 0..BLOCK_SIZE_EXP { stuff = charred(stuff); } stuff }
conditional_block
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hexed_key = key.as_bytes().to_hex(); let amount = hexed_key.as_bytes() .iter() .fold(0u8, |amt, &byte| amt.wrapping_add(byte)); match mode { Mode::Encrypt => { // well, this won't be useful since the library is meant to only decrypt files (for now) let text = data.to_hex().into_bytes(); let stuff = cbc(mode, text); let shifted_text = shift(&stuff, amount); xor(&shifted_text, &key) }, Mode::Decrypt => { let amount = 0u8.wrapping_sub(amount); // shift by (256 - amount) for the reverse let shifted_text = xor(data, &key); let stuff = shift(&shifted_text, amount); charred(cbc(mode, stuff)) }, } } // Hex-decoding function fn charred(decode: Vec<u8>) -> Vec<u8> { // Mostly, I try to stick to immutable borrows, but from_utf8() requires Vec<u8> // An error means that the decryption has failed! (which should be due to wrong keys) String::from_utf8(decode) .map_err(|_| ()) .and_then(|hexed_stuff| hexed_stuff.from_hex().map_err(|_| ())) .unwrap_or(Vec::new()) } // Shifts the elements by the given amount fn shift(text: &[u8], amount: u8) -> Vec<u8> { text.iter() // wrap around the boundary if the sum overflows .map(|byte| amount.wrapping_add(*byte)) .collect() } // Byte-wise XOR fn
(text: &[u8], key: &str) -> Vec<u8> { let key_array = key.as_bytes(); let (text_size, key_size) = (text.len(), key.len()); (0..text_size).map(|i| text[i] ^ key_array[i % key_size]).collect() } // CBC mode as a seed to scramble the final ciphertext fn cbc(mode: Mode, mut data: Vec<u8>) -> Vec<u8> { let size = 2usize.pow(BLOCK_SIZE_EXP); // Well, there's no encryption going on here - just some fireworks to introduce randomness match mode { Mode::Encrypt => { let mut cbc_vec: Vec<u8> = sample(&mut thread_rng(), 1..255, size); // hex the bytes until the vector has the required length (an integral multiple of block size) for _ in 0..BLOCK_SIZE_EXP { data = data.to_hex().into_bytes(); } cbc_vec.extend(&data); for i in size..(data.len() + size) { cbc_vec[i] = cbc_vec[i] ^ cbc_vec[i - size]; } cbc_vec }, Mode::Decrypt => { let mut i = data.len() - 1; while i >= size { data[i] = data[i] ^ data[i - size]; i -= 1; } let mut stuff = data[size..].to_owned(); for _ in 0..BLOCK_SIZE_EXP { stuff = charred(stuff); } stuff }, } }
xor
identifier_name
cipher.rs
use random::{thread_rng, sample}; use serialize::hex::{FromHex, ToHex}; const BLOCK_SIZE_EXP: u32 = 3; // pow(2, 3) == 8 byte blocks pub enum Mode { Encrypt, Decrypt, } // Invokes the helper functions and does its shifting thing pub fn zombify(mode: Mode, data: &[u8], key: &str) -> Vec<u8> { let hexed_key = key.as_bytes().to_hex(); let amount = hexed_key.as_bytes() .iter() .fold(0u8, |amt, &byte| amt.wrapping_add(byte)); match mode { Mode::Encrypt => { // well, this won't be useful since the library is meant to only decrypt files (for now) let text = data.to_hex().into_bytes(); let stuff = cbc(mode, text); let shifted_text = shift(&stuff, amount); xor(&shifted_text, &key) }, Mode::Decrypt => { let amount = 0u8.wrapping_sub(amount); // shift by (256 - amount) for the reverse let shifted_text = xor(data, &key); let stuff = shift(&shifted_text, amount); charred(cbc(mode, stuff)) }, } } // Hex-decoding function fn charred(decode: Vec<u8>) -> Vec<u8> { // Mostly, I try to stick to immutable borrows, but from_utf8() requires Vec<u8> // An error means that the decryption has failed! (which should be due to wrong keys) String::from_utf8(decode) .map_err(|_| ()) .and_then(|hexed_stuff| hexed_stuff.from_hex().map_err(|_| ())) .unwrap_or(Vec::new()) } // Shifts the elements by the given amount fn shift(text: &[u8], amount: u8) -> Vec<u8> { text.iter() // wrap around the boundary if the sum overflows .map(|byte| amount.wrapping_add(*byte)) .collect() } // Byte-wise XOR fn xor(text: &[u8], key: &str) -> Vec<u8> { let key_array = key.as_bytes(); let (text_size, key_size) = (text.len(), key.len()); (0..text_size).map(|i| text[i] ^ key_array[i % key_size]).collect() } // CBC mode as a seed to scramble the final ciphertext fn cbc(mode: Mode, mut data: Vec<u8>) -> Vec<u8> { let size = 2usize.pow(BLOCK_SIZE_EXP);
match mode { Mode::Encrypt => { let mut cbc_vec: Vec<u8> = sample(&mut thread_rng(), 1..255, size); // hex the bytes until the vector has the required length (an integral multiple of block size) for _ in 0..BLOCK_SIZE_EXP { data = data.to_hex().into_bytes(); } cbc_vec.extend(&data); for i in size..(data.len() + size) { cbc_vec[i] = cbc_vec[i] ^ cbc_vec[i - size]; } cbc_vec }, Mode::Decrypt => { let mut i = data.len() - 1; while i >= size { data[i] = data[i] ^ data[i - size]; i -= 1; } let mut stuff = data[size..].to_owned(); for _ in 0..BLOCK_SIZE_EXP { stuff = charred(stuff); } stuff }, } }
// Well, there's no encryption going on here - just some fireworks to introduce randomness
random_line_split
errors.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> { fn next(&mut self) -> Option<T> { let ErrorLoggerIterator(ref mut this) = *self; loop { match this.next() { Some(Ok(v)) => return Some(v), Some(Err(error)) => log_css_error(error.location, format!("{:?}", error.reason)), None => return None, } } } } // FIXME: go back to `()` instead of `bool` after upgrading Rust // past 898669c4e203ae91e2048fb6c0f8591c867bccc6 // Using bool is a work-around for https://github.com/mozilla/rust/issues/13322 local_data_key!(silence_errors: bool) pub fn log_css_error(location: SourceLocation, message: &str) { // TODO eventually this will got into a "web console" or something. if local_data::get(silence_errors, |silenced| silenced.is_none()) { error!("{:u}:{:u} {:s}", location.line, location.column, message) } } pub fn with_errors_silenced<T>(f: || -> T) -> T
{ local_data::set(silence_errors, true); let result = f(); local_data::pop(silence_errors); result }
identifier_body
errors.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> { fn next(&mut self) -> Option<T> { let ErrorLoggerIterator(ref mut this) = *self; loop { match this.next() { Some(Ok(v)) => return Some(v), Some(Err(error)) => log_css_error(error.location, format!("{:?}", error.reason)), None => return None, } } } } // FIXME: go back to `()` instead of `bool` after upgrading Rust // past 898669c4e203ae91e2048fb6c0f8591c867bccc6 // Using bool is a work-around for https://github.com/mozilla/rust/issues/13322 local_data_key!(silence_errors: bool) pub fn log_css_error(location: SourceLocation, message: &str) { // TODO eventually this will got into a "web console" or something. if local_data::get(silence_errors, |silenced| silenced.is_none()) { error!("{:u}:{:u} {:s}", location.line, location.column, message) } } pub fn
<T>(f: || -> T) -> T { local_data::set(silence_errors, true); let result = f(); local_data::pop(silence_errors); result }
with_errors_silenced
identifier_name
errors.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::local_data; use cssparser::ast::{SyntaxError, SourceLocation}; pub struct ErrorLoggerIterator<I>(I); impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator<I> { fn next(&mut self) -> Option<T> { let ErrorLoggerIterator(ref mut this) = *self; loop { match this.next() {
} } } } // FIXME: go back to `()` instead of `bool` after upgrading Rust // past 898669c4e203ae91e2048fb6c0f8591c867bccc6 // Using bool is a work-around for https://github.com/mozilla/rust/issues/13322 local_data_key!(silence_errors: bool) pub fn log_css_error(location: SourceLocation, message: &str) { // TODO eventually this will got into a "web console" or something. if local_data::get(silence_errors, |silenced| silenced.is_none()) { error!("{:u}:{:u} {:s}", location.line, location.column, message) } } pub fn with_errors_silenced<T>(f: || -> T) -> T { local_data::set(silence_errors, true); let result = f(); local_data::pop(silence_errors); result }
Some(Ok(v)) => return Some(v), Some(Err(error)) => log_css_error(error.location, format!("{:?}", error.reason)), None => return None,
random_line_split
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// /// fn main() { /// TestRobot::main(); /// } /// ``` pub trait Robot: Sized { /// Run the robot class. This will be called once, at the beginning of the program, after /// initialization. fn run(self);
fn main() { // Initialize HAL unsafe { let status = HAL_Initialize(0); if status!= 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); } }
/// Create an instance of the robot class. fn new() -> Self; /// Run the robot statically.
random_line_split
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// /// fn main() { /// TestRobot::main(); /// } /// ``` pub trait Robot: Sized { /// Run the robot class. This will be called once, at the beginning of the program, after /// initialization. fn run(self); /// Create an instance of the robot class. fn new() -> Self; /// Run the robot statically. fn
() { // Initialize HAL unsafe { let status = HAL_Initialize(0); if status!= 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); } }
main
identifier_name
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// /// fn main() { /// TestRobot::main(); /// } /// ``` pub trait Robot: Sized { /// Run the robot class. This will be called once, at the beginning of the program, after /// initialization. fn run(self); /// Create an instance of the robot class. fn new() -> Self; /// Run the robot statically. fn main() { // Initialize HAL unsafe { let status = HAL_Initialize(0); if status!= 1
} let robot = Self::new(); robot.run(); } }
{ panic!("WPILib HAL failed to initialize!"); }
conditional_block
robot.rs
use wpilib::wpilib_hal::*; /// The base class from which all robots should be derived. /// /// # Usage /// /// ``` /// struct TestRobot {}; /// /// impl Robot for TestRobot { /// fn new() -> TestRobot { /// TestRobot{} /// } /// /// fn run(self) { /// // Do something... /// } /// } /// /// fn main() { /// TestRobot::main(); /// } /// ``` pub trait Robot: Sized { /// Run the robot class. This will be called once, at the beginning of the program, after /// initialization. fn run(self); /// Create an instance of the robot class. fn new() -> Self; /// Run the robot statically. fn main()
}
{ // Initialize HAL unsafe { let status = HAL_Initialize(0); if status != 1 { panic!("WPILib HAL failed to initialize!"); } } let robot = Self::new(); robot.run(); }
identifier_body
flat.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Flat trace module use std::collections::VecDeque; use rlp::*; use util::HeapSizeOf; use basic_types::LogBloom; use super::trace::{Action, Res}; /// Trace localized in vector of traces produced by a single transaction. /// /// Parent and children indexes refer to positions in this vector. #[derive(Debug, PartialEq, Clone, Binary)] pub struct FlatTrace { /// Type of action performed by a transaction. pub action: Action, /// Result of this action. pub result: Res, /// Number of subtraces. pub subtraces: usize, /// Exact location of trace. /// /// [index in root, index in first CALL, index in second CALL,...] pub trace_address: VecDeque<usize>, } impl FlatTrace { /// Returns bloom of the trace. pub fn
(&self) -> LogBloom { self.action.bloom() | self.result.bloom() } } impl HeapSizeOf for FlatTrace { fn heap_size_of_children(&self) -> usize { self.trace_address.heap_size_of_children() } } impl Encodable for FlatTrace { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(4); s.append(&self.action); s.append(&self.result); s.append(&self.subtraces); s.append(&self.trace_address.clone().into_iter().collect::<Vec<_>>()); } } impl Decodable for FlatTrace { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); let v: Vec<usize> = try!(d.val_at(3)); let res = FlatTrace { action: try!(d.val_at(0)), result: try!(d.val_at(1)), subtraces: try!(d.val_at(2)), trace_address: v.into_iter().collect(), }; Ok(res) } } /// Represents all traces produced by a single transaction. #[derive(Debug, PartialEq, Clone)] pub struct FlatTransactionTraces(Vec<FlatTrace>); impl From<Vec<FlatTrace>> for FlatTransactionTraces { fn from(v: Vec<FlatTrace>) -> Self { FlatTransactionTraces(v) } } impl HeapSizeOf for FlatTransactionTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl FlatTransactionTraces { /// Returns bloom of all traces in the collection. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, trace | bloom | trace.bloom()) } } impl Encodable for FlatTransactionTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatTransactionTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatTransactionTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTrace>> for FlatTransactionTraces { fn into(self) -> Vec<FlatTrace> { self.0 } } /// Represents all traces produced by transactions in a single block. #[derive(Debug, PartialEq, Clone, Default)] pub struct FlatBlockTraces(Vec<FlatTransactionTraces>); impl HeapSizeOf for FlatBlockTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl From<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn from(v: Vec<FlatTransactionTraces>) -> Self { FlatBlockTraces(v) } } impl FlatBlockTraces { /// Returns bloom of all traces in the block. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, tx_traces | bloom | tx_traces.bloom()) } } impl Encodable for FlatBlockTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatBlockTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatBlockTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn into(self) -> Vec<FlatTransactionTraces> { self.0 } } #[cfg(test)] mod tests { use super::{FlatBlockTraces, FlatTransactionTraces, FlatTrace}; use trace::trace::{Action, Res, CallResult, Call, Suicide}; use types::executed::CallType; #[test] fn test_trace_serialization() { // block #51921 let flat_trace = FlatTrace { action: Action::Call(Call { from: "8dda5e016e674683241bf671cced51e7239ea2bc".parse().unwrap(), to: "37a5e19cc2d49f244805d5c268c0e6f321965ab9".parse().unwrap(), value: "3627e8f712373c0000".parse().unwrap(), gas: 0x03e8.into(), input: vec![], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0.into(), output: vec![], }), trace_address: Default::default(), subtraces: 0, }; let flat_trace1 = FlatTrace { action: Action::Call(Call { from: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(), to: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), value: 0.into(), gas: 0x010c78.into(), input: vec![0x41, 0xc0, 0xe1, 0xb5], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0x0127.into(), output: vec![], }), trace_address: Default::default(), subtraces: 1, }; let flat_trace2 = FlatTrace { action: Action::Suicide(Suicide { address: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), balance: 0.into(), refund_address: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(), }), result: Res::None, trace_address: vec![0].into_iter().collect(), subtraces: 0, }; let block_traces = FlatBlockTraces(vec![ FlatTransactionTraces(vec![flat_trace]), FlatTransactionTraces(vec![flat_trace1, flat_trace2]) ]); let encoded = ::rlp::encode(&block_traces); let decoded = ::rlp::decode(&encoded); assert_eq!(block_traces, decoded); } }
bloom
identifier_name
flat.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Flat trace module use std::collections::VecDeque; use rlp::*; use util::HeapSizeOf; use basic_types::LogBloom; use super::trace::{Action, Res}; /// Trace localized in vector of traces produced by a single transaction. /// /// Parent and children indexes refer to positions in this vector. #[derive(Debug, PartialEq, Clone, Binary)] pub struct FlatTrace { /// Type of action performed by a transaction. pub action: Action, /// Result of this action. pub result: Res, /// Number of subtraces. pub subtraces: usize, /// Exact location of trace. /// /// [index in root, index in first CALL, index in second CALL,...] pub trace_address: VecDeque<usize>, } impl FlatTrace { /// Returns bloom of the trace. pub fn bloom(&self) -> LogBloom { self.action.bloom() | self.result.bloom() } } impl HeapSizeOf for FlatTrace { fn heap_size_of_children(&self) -> usize { self.trace_address.heap_size_of_children() } } impl Encodable for FlatTrace { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(4); s.append(&self.action); s.append(&self.result); s.append(&self.subtraces); s.append(&self.trace_address.clone().into_iter().collect::<Vec<_>>()); } } impl Decodable for FlatTrace { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); let v: Vec<usize> = try!(d.val_at(3)); let res = FlatTrace { action: try!(d.val_at(0)), result: try!(d.val_at(1)), subtraces: try!(d.val_at(2)), trace_address: v.into_iter().collect(), }; Ok(res) } } /// Represents all traces produced by a single transaction. #[derive(Debug, PartialEq, Clone)] pub struct FlatTransactionTraces(Vec<FlatTrace>); impl From<Vec<FlatTrace>> for FlatTransactionTraces { fn from(v: Vec<FlatTrace>) -> Self { FlatTransactionTraces(v) } } impl HeapSizeOf for FlatTransactionTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl FlatTransactionTraces { /// Returns bloom of all traces in the collection. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, trace | bloom | trace.bloom()) } } impl Encodable for FlatTransactionTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatTransactionTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatTransactionTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTrace>> for FlatTransactionTraces { fn into(self) -> Vec<FlatTrace> { self.0 } } /// Represents all traces produced by transactions in a single block. #[derive(Debug, PartialEq, Clone, Default)] pub struct FlatBlockTraces(Vec<FlatTransactionTraces>); impl HeapSizeOf for FlatBlockTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl From<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn from(v: Vec<FlatTransactionTraces>) -> Self { FlatBlockTraces(v) } } impl FlatBlockTraces { /// Returns bloom of all traces in the block. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, tx_traces | bloom | tx_traces.bloom()) } } impl Encodable for FlatBlockTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatBlockTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatBlockTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn into(self) -> Vec<FlatTransactionTraces> { self.0 } } #[cfg(test)] mod tests { use super::{FlatBlockTraces, FlatTransactionTraces, FlatTrace}; use trace::trace::{Action, Res, CallResult, Call, Suicide}; use types::executed::CallType; #[test] fn test_trace_serialization() { // block #51921 let flat_trace = FlatTrace { action: Action::Call(Call { from: "8dda5e016e674683241bf671cced51e7239ea2bc".parse().unwrap(), to: "37a5e19cc2d49f244805d5c268c0e6f321965ab9".parse().unwrap(), value: "3627e8f712373c0000".parse().unwrap(), gas: 0x03e8.into(), input: vec![], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0.into(), output: vec![], }), trace_address: Default::default(), subtraces: 0, };
to: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), value: 0.into(), gas: 0x010c78.into(), input: vec![0x41, 0xc0, 0xe1, 0xb5], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0x0127.into(), output: vec![], }), trace_address: Default::default(), subtraces: 1, }; let flat_trace2 = FlatTrace { action: Action::Suicide(Suicide { address: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), balance: 0.into(), refund_address: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(), }), result: Res::None, trace_address: vec![0].into_iter().collect(), subtraces: 0, }; let block_traces = FlatBlockTraces(vec![ FlatTransactionTraces(vec![flat_trace]), FlatTransactionTraces(vec![flat_trace1, flat_trace2]) ]); let encoded = ::rlp::encode(&block_traces); let decoded = ::rlp::decode(&encoded); assert_eq!(block_traces, decoded); } }
let flat_trace1 = FlatTrace { action: Action::Call(Call { from: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(),
random_line_split
flat.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Flat trace module use std::collections::VecDeque; use rlp::*; use util::HeapSizeOf; use basic_types::LogBloom; use super::trace::{Action, Res}; /// Trace localized in vector of traces produced by a single transaction. /// /// Parent and children indexes refer to positions in this vector. #[derive(Debug, PartialEq, Clone, Binary)] pub struct FlatTrace { /// Type of action performed by a transaction. pub action: Action, /// Result of this action. pub result: Res, /// Number of subtraces. pub subtraces: usize, /// Exact location of trace. /// /// [index in root, index in first CALL, index in second CALL,...] pub trace_address: VecDeque<usize>, } impl FlatTrace { /// Returns bloom of the trace. pub fn bloom(&self) -> LogBloom { self.action.bloom() | self.result.bloom() } } impl HeapSizeOf for FlatTrace { fn heap_size_of_children(&self) -> usize { self.trace_address.heap_size_of_children() } } impl Encodable for FlatTrace { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(4); s.append(&self.action); s.append(&self.result); s.append(&self.subtraces); s.append(&self.trace_address.clone().into_iter().collect::<Vec<_>>()); } } impl Decodable for FlatTrace { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); let v: Vec<usize> = try!(d.val_at(3)); let res = FlatTrace { action: try!(d.val_at(0)), result: try!(d.val_at(1)), subtraces: try!(d.val_at(2)), trace_address: v.into_iter().collect(), }; Ok(res) } } /// Represents all traces produced by a single transaction. #[derive(Debug, PartialEq, Clone)] pub struct FlatTransactionTraces(Vec<FlatTrace>); impl From<Vec<FlatTrace>> for FlatTransactionTraces { fn from(v: Vec<FlatTrace>) -> Self
} impl HeapSizeOf for FlatTransactionTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl FlatTransactionTraces { /// Returns bloom of all traces in the collection. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, trace | bloom | trace.bloom()) } } impl Encodable for FlatTransactionTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatTransactionTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatTransactionTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTrace>> for FlatTransactionTraces { fn into(self) -> Vec<FlatTrace> { self.0 } } /// Represents all traces produced by transactions in a single block. #[derive(Debug, PartialEq, Clone, Default)] pub struct FlatBlockTraces(Vec<FlatTransactionTraces>); impl HeapSizeOf for FlatBlockTraces { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() } } impl From<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn from(v: Vec<FlatTransactionTraces>) -> Self { FlatBlockTraces(v) } } impl FlatBlockTraces { /// Returns bloom of all traces in the block. pub fn bloom(&self) -> LogBloom { self.0.iter().fold(Default::default(), | bloom, tx_traces | bloom | tx_traces.bloom()) } } impl Encodable for FlatBlockTraces { fn rlp_append(&self, s: &mut RlpStream) { s.append(&self.0); } } impl Decodable for FlatBlockTraces { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { Ok(FlatBlockTraces(try!(Decodable::decode(decoder)))) } } impl Into<Vec<FlatTransactionTraces>> for FlatBlockTraces { fn into(self) -> Vec<FlatTransactionTraces> { self.0 } } #[cfg(test)] mod tests { use super::{FlatBlockTraces, FlatTransactionTraces, FlatTrace}; use trace::trace::{Action, Res, CallResult, Call, Suicide}; use types::executed::CallType; #[test] fn test_trace_serialization() { // block #51921 let flat_trace = FlatTrace { action: Action::Call(Call { from: "8dda5e016e674683241bf671cced51e7239ea2bc".parse().unwrap(), to: "37a5e19cc2d49f244805d5c268c0e6f321965ab9".parse().unwrap(), value: "3627e8f712373c0000".parse().unwrap(), gas: 0x03e8.into(), input: vec![], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0.into(), output: vec![], }), trace_address: Default::default(), subtraces: 0, }; let flat_trace1 = FlatTrace { action: Action::Call(Call { from: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(), to: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), value: 0.into(), gas: 0x010c78.into(), input: vec![0x41, 0xc0, 0xe1, 0xb5], call_type: CallType::Call, }), result: Res::Call(CallResult { gas_used: 0x0127.into(), output: vec![], }), trace_address: Default::default(), subtraces: 1, }; let flat_trace2 = FlatTrace { action: Action::Suicide(Suicide { address: "412fda7643b37d436cb40628f6dbbb80a07267ed".parse().unwrap(), balance: 0.into(), refund_address: "3d0768da09ce77d25e2d998e6a7b6ed4b9116c2d".parse().unwrap(), }), result: Res::None, trace_address: vec![0].into_iter().collect(), subtraces: 0, }; let block_traces = FlatBlockTraces(vec![ FlatTransactionTraces(vec![flat_trace]), FlatTransactionTraces(vec![flat_trace1, flat_trace2]) ]); let encoded = ::rlp::encode(&block_traces); let decoded = ::rlp::decode(&encoded); assert_eq!(block_traces, decoded); } }
{ FlatTransactionTraces(v) }
identifier_body
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, //? One, // And, // & // Not, //! } #[derive(Copy, Clone)] enum Character{ Char(char), Any //. } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if!(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if!occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence
fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32.. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
{ Occurence{ choice: vec![] } }
identifier_body
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, //? One, // And, // & // Not, //! } #[derive(Copy, Clone)] enum Character{ Char(char), Any //. } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if!(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if!occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32.. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] }
Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
} fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{
random_line_split
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, //? One, // And, // & // Not, //! } #[derive(Copy, Clone)] enum Character{ Char(char), Any //. } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if!(target.success_with(seq))
} res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if!occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32.. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn visit_non_terminal_symbol(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
{ res = false; break; }
conditional_block
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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. #![macro_use] use std::char::*; use middle::analysis::ast::*; use self::Pattern::*; use self::Character::*; #[derive(Copy, Clone)] enum Pattern { // OneOrMore, // + // ZeroOrMore, // * // ZeroOrOne, //? One, // And, // & // Not, //! } #[derive(Copy, Clone)] enum Character{ Char(char), Any //. } struct Occurence { choice: Vec<Vec<(Character,Pattern)>> } impl Occurence { fn push_sequence(&self, other: Occurence) -> Occurence{ let mut res = vec![]; for choice1 in other.choice.clone(){ for choice2 in self.choice.clone(){ let mut tmp = choice2.clone(); for couple in choice1.clone(){ tmp.push(couple) } res.push(tmp) } } Occurence{ choice: res } } fn merge_choice(&self, other: Occurence) -> Occurence { let mut res = self.choice.clone(); for choice in other.choice.clone(){ res.push(choice) } Occurence{ choice: res } } fn copy(&self) -> Occurence{ Occurence{ choice: self.choice.to_vec() } } fn is_unreachable_with(&self, target: Occurence) -> bool { let mut res = true; for seq in self.choice.clone(){ if!(target.success_with(seq)) { res = false; break; } } res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(Character, Pattern)>) -> bool{ let mut res = true; if seq2.len()<seq1.len() { res=false; } else{ for (i,character_pattern1) in seq1.iter().enumerate(){ if let Some(character_pattern2) = seq2.get(i) { let &(c1,_p1) = character_pattern1; let &(c2,_p2) = character_pattern2; match c1 { Char(character1) => { match c2 { Char(character2) => { if character1!=character2 { res=false; break; } } Any => { res=false; break; } } } Any => { continue; } } } } } res } } pub struct UnreachableRule<'a: 'c, 'b: 'a, 'c> { grammar: &'c AGrammar<'a, 'b> } impl <'a, 'b, 'c> UnreachableRule<'a, 'b, 'c> { pub fn analyse(grammar: AGrammar<'a, 'b>) -> Partial<AGrammar<'a, 'b>> { UnreachableRule::check_unreachable_rule(&grammar); Partial::Value(grammar) } fn check_unreachable_rule(grammar: &'c AGrammar<'a, 'b>){ let mut analyser = UnreachableRule{ grammar: grammar }; for rule in &grammar.rules { analyser.visit_expr(rule.expr_idx); } } } impl<'a, 'b, 'c> ExprByIndex for UnreachableRule<'a, 'b, 'c> { fn expr_by_index(&self, index: usize) -> Expression { self.grammar.expr_by_index(index).clone() } } impl<'a, 'b, 'c> Visitor<Occurence> for UnreachableRule<'a, 'b, 'c> { fn visit_choice(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut occurences_of_children = vec![]; for child in children.clone(){ let occ = self.visit_expr(child); if!occ.choice.is_empty() { occurences_of_children.push((occ,child)); } } for (i, cp1) in occurences_of_children.iter().enumerate(){ let (_left, right) = occurences_of_children.split_at(i+1); let &(ref occ1, child1) = cp1; for cp2 in right{ let &(ref occ2, child2) = cp2; if occ2.is_unreachable_with(occ1.copy()) { self.grammar.span_warn( self.grammar[child2].span(), format!("This alternative will nerver succeed.") ); self.grammar.span_note( self.grammar[child1].span(), format!("Because this alternative succeeded before reaching the previous one.") ); } } } let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.merge_choice(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_sequence(&mut self, _this: usize, children: Vec<usize>) -> Occurence{ let mut res = vec![]; if let Some((first, rest)) = children.split_first(){ let mut occ = self.visit_expr(*first); for child in rest{ occ = occ.push_sequence(self.visit_expr(*child)) } res = occ.choice; } Occurence{ choice: res } } fn visit_atom(&mut self, _this: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ let mut seq = vec![]; seq.push((Any,One)); let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_character_class(&mut self, _this: usize, char_class: CharacterClassExpr) -> Occurence{ let mut res = vec![]; for intervals in char_class.intervals{ for i in intervals.lo as u32.. intervals.hi as u32 +1 { if let Some(c) = from_u32(i) { res.push(vec![(Char(c),One)]) } } } Occurence{ choice: res } } fn
(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_and_predicate(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } }
visit_non_terminal_symbol
identifier_name
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) ->! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3
else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid!= cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
{ let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) }
conditional_block
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) ->! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else {
//TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid!= cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
Err(Error::new(EINVAL)) } }
random_line_split
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) ->! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize>
/// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid!= cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
{ unsafe { context_switch(); } Ok(0) }
identifier_body
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Error, Result, ECHILD, EINVAL, EACCES}; use super::execute::execute; use fs::SupervisorResource; pub fn clone(regs: &Regs) -> Result<usize> { unsafe { context_clone(regs) } } pub fn execve(path: *const u8, args: *const *const u8) -> Result<usize> { let mut args_vec = Vec::new(); args_vec.push(c_string_to_str(path).to_string()); for arg in c_array_to_slice(args) { args_vec.push(c_string_to_str(*arg).to_string()); } execute(args_vec) } /// Exit context pub fn exit(status: usize) ->! { { let contexts = unsafe { &mut *::env().contexts.get() }; let mut statuses = BTreeMap::new(); let (pid, ppid) = { if let Ok(mut current) = contexts.current_mut() { mem::swap(&mut statuses, &mut unsafe { current.statuses.inner() }.deref_mut()); current.exit(); (current.pid, current.ppid) } else { (0, 0) } }; for mut context in contexts.iter_mut() { // Add exit status to parent if context.pid == ppid { context.statuses.send(pid, status, "exit parent status"); for (pid, status) in statuses.iter() { context.statuses.send(*pid, *status, "exit child status"); } } // Move children to parent if context.ppid == pid { context.ppid = ppid; } } } loop { unsafe { context_switch() }; } } pub fn getpid() -> Result<usize> { let contexts = unsafe { & *::env().contexts.get() }; let current = try!(contexts.current()); Ok(current.pid) } #[cfg(target_arch = "x86")] pub fn
(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } #[cfg(target_arch = "x86_64")] pub fn iopl(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) } else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { let status = current.statuses.receive(&(pid as usize), "waitpid status"); if let Ok(status_safe) = current.get_ref_mut(status_ptr) { *status_safe = status; } Ok(pid as usize) } else { Err(Error::new(ECHILD)) } } pub fn sched_yield() -> Result<usize> { unsafe { context_switch(); } Ok(0) } /// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by having a field defining whether the process is blocked by a syscall. /// When the syscall is read from the file handle, this field is set to false, but the process is /// still stopped (because it is marked as `blocked`), until the new value of the EAX register is /// written to the file handle. pub fn supervise(pid: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let cur_pid = try!(contexts.current_mut()).pid; let procc; { let jailed = try!(contexts.find_mut(pid)); // Make sure that this is actually a child process of the invoker. if jailed.ppid!= cur_pid { return Err(Error::new(EACCES)); } jailed.supervised = true; procc = &mut **jailed as *mut _; } let current = try!(contexts.current_mut()); let fd = current.next_fd(); unsafe { (*current.files.get()).push(ContextFile { fd: fd, resource: box try!(SupervisorResource::new(procc)), }); } Ok(fd) }
iopl
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>, { EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } } pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } } pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn
(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
enrichment
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>, { EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } } pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } }
S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn enrichment(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where
random_line_split
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!(EnrichmentData { query: String }); request_struct!(EnrichmentOsint { query: String }); request_struct!(EnrichmentMalware { query: String }); request_struct!(EnrichmentSubdomains { query: String }); impl<'a> EnrichmentRequest<'a> { pub fn data<S>(self, query: S) -> EnrichmentData<'a> where S: Into<String>,
pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<String>, { EnrichmentMalware { pt: self.pt, url: URL_MALWARE, query: query.into(), } } pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { pub fn enrichment(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
{ EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } }
identifier_body
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn zero() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering> { self.name.partial_cmp(&other.name) } } impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1,.. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None =>
, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None,.. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems,.. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items,.. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(),.. summarize_item(item).val1().unwrap() } } }
{ Counts::zero() }
conditional_block
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn zero() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering>
} impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1,.. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None => { Counts::zero() }, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None,.. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems,.. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items,.. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(),.. summarize_item(item).val1().unwrap() } } }
{ self.name.partial_cmp(&other.name) }
identifier_body
stability_summary.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module crawls a `clean::Crate` and produces a summarization of the //! stability levels within the crate. The summary contains the module //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. use std::ops::Add; use std::num::Zero; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, EnumItem, Enum}; use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem, Stability}; use html::render::cache; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] /// The counts for each stability level. pub struct Counts { pub deprecated: uint, pub experimental: uint, pub unstable: uint, pub stable: uint, pub frozen: uint, pub locked: uint, /// No stability level, inherited or otherwise. pub unmarked: uint, } impl Copy for Counts {} impl Add<Counts, Counts> for Counts { fn add(&self, other: &Counts) -> Counts { Counts { deprecated: self.deprecated + other.deprecated, experimental: self.experimental + other.experimental, unstable: self.unstable + other.unstable, stable: self.stable + other.stable, frozen: self.frozen + other.frozen, locked: self.locked + other.locked, unmarked: self.unmarked + other.unmarked, } } } impl Counts { fn
() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.experimental + self.unstable + self.stable + self.frozen + self.locked + self.unmarked } } #[deriving(Encodable, Decodable, PartialEq, Eq)] /// A summarized module, which includes total counts and summarized children /// modules. pub struct ModuleSummary { pub name: String, pub counts: Counts, pub submodules: Vec<ModuleSummary>, } impl PartialOrd for ModuleSummary { fn partial_cmp(&self, other: &ModuleSummary) -> Option<Ordering> { self.name.partial_cmp(&other.name) } } impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn count_stability(stab: Option<&Stability>) -> Counts { match stab { None => Counts { unmarked: 1, .. Counts::zero() }, Some(ref stab) => match stab.level { Deprecated => Counts { deprecated: 1, .. Counts::zero() }, Experimental => Counts { experimental: 1,.. Counts::zero() }, Unstable => Counts { unstable: 1, .. Counts::zero() }, Stable => Counts { stable: 1, .. Counts::zero() }, Frozen => Counts { frozen: 1, .. Counts::zero() }, Locked => Counts { locked: 1, .. Counts::zero() }, } } } fn summarize_methods(item: &Item) -> Counts { match cache().impls.get(&item.def_id) { Some(v) => { v.iter().map(|i| { let count = count_stability(i.stability.as_ref()); if i.impl_.trait_.is_none() { count + i.impl_.items.iter() .map(|ti| summarize_item(ti).0) .fold(Counts::zero(), |acc, c| acc + c) } else { count } }).fold(Counts::zero(), |acc, c| acc + c) }, None => { Counts::zero() }, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(item.stability.as_ref()) + summarize_methods(item); // Count this item's children, if any. Note that a trait impl is // considered to have no children. match item.inner { // Require explicit `pub` to be visible ImplItem(Impl { items: ref subitems, trait_: None,.. }) => { let subcounts = subitems.iter().filter(|i| visible(*i)) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (subcounts, None) } // `pub` automatically EnumItem(Enum { variants: ref subitems,.. }) => { let subcounts = subitems.iter().map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } TraitItem(Trait { items: ref trait_items, .. }) => { fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | TypeTraitItem(ref item) => item } } let subcounts = trait_items.iter() .map(extract_item) .map(summarize_item) .map(|s| s.val0()) .fold(Counts::zero(), |acc, x| acc + x); (item_counts + subcounts, None) } ModuleItem(Module { ref items,.. }) => { let mut counts = item_counts; let mut submodules = Vec::new(); for (subcounts, submodule) in items.iter().filter(|i| visible(*i)) .map(summarize_item) { counts = counts + subcounts; submodule.map(|m| submodules.push(m)); } submodules.sort(); (counts, Some(ModuleSummary { name: item.name.as_ref().map_or("".to_string(), |n| n.clone()), counts: counts, submodules: submodules, })) } // no stability information for the following items: ViewItemItem(_) | PrimitiveItem(_) => (Counts::zero(), None), _ => (item_counts, None) } } /// Summarizes the stability levels in a crate. pub fn build(krate: &Crate) -> ModuleSummary { match krate.module { None => ModuleSummary { name: krate.name.clone(), counts: Counts::zero(), submodules: Vec::new(), }, Some(ref item) => ModuleSummary { name: krate.name.clone(),.. summarize_item(item).val1().unwrap() } } }
zero
identifier_name
into_iterator.rs
#![allow(dead_code, unused_imports)] #[macro_use] extern crate derive_more; #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct
{ #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } #[derive(IntoIterator)] struct Numbers3 { #[into_iterator(ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } // Test that owned is not enabled when ref/ref_mut are enabled without owned impl ::core::iter::IntoIterator for Numbers3 { type Item = <Vec<i32> as ::core::iter::IntoIterator>::Item; type IntoIter = <Vec<i32> as ::core::iter::IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { <Vec<i32> as ::core::iter::IntoIterator>::into_iter(self.numbers) } }
Numbers2
identifier_name
into_iterator.rs
#![allow(dead_code, unused_imports)]
#[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct Numbers2 { #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } #[derive(IntoIterator)] struct Numbers3 { #[into_iterator(ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } // Test that owned is not enabled when ref/ref_mut are enabled without owned impl ::core::iter::IntoIterator for Numbers3 { type Item = <Vec<i32> as ::core::iter::IntoIterator>::Item; type IntoIter = <Vec<i32> as ::core::iter::IntoIterator>::IntoIter; #[inline] fn into_iter(self) -> Self::IntoIter { <Vec<i32> as ::core::iter::IntoIterator>::into_iter(self.numbers) } }
#[macro_use] extern crate derive_more;
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>;... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400
has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure,
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>;... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn
(x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
fun
identifier_name
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>;... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int) { println!("{}", x) } let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max
; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
{ max = x }
conditional_block
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid definition fn fun () -> () { println!("{}", x) } // cannot capture from enclosing scope let closure = || -> () { println!("{}", x) }; // can capture from enclosing scope // `fun_arg` is an invalid definition fn fun_arg (arg: int) -> () { println!("{}", arg + x) } // cannot capture let closure_arg = |arg: int| -> () { println!("{}", arg + x) }; // can capture // ^ // Requires a type because the implementation needs to know which `+` to use. // In the future, the implementation may not need the help. fun(); // Still won't work closure(); // Prints: 3 fun_arg(7); // Still won't work closure_arg(7); // Prints: 10 /*Closures begin with the argument list between vertical bars and are followed by a single expression. Remember that a block, { <expr1>; <expr2>;... }, is considered a single expression: it evaluates to the result of the last expression it contains if that expression is not followed by a semicolon, otherwise the block evaluates to (), the unit value. In general, return types and all argument types must be specified explicitly for function definitions.*/ fn fun (x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer both the argument and return types for a closure expression; therefore they are often omitted, since both a human reader and the compiler can deduce the types from the immediate context. This is in contrast to function declarations, which require types to be specified and are not subject to type inference.*/ // `fun` as a function declaration cannot infer the type of `x`, so it must be provided fn fun (x: int)
let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); // Prints 33 fun("String"); // Error: mismatched types // Error: mismatched types // inference already assigned `closure` the type `|int| -> ()` closure("String"); /*In cases where the compiler needs assistance, the arguments and return types may be annotated on closures, using the same notation as shown earlier. In the example below, since different types provide an implementation for the operator *, the argument type for the x parameter must be explicitly provided.*/ // Error: the type of `x` must be known to be used with `x * x` let square = |x | -> uint { (x * x) as uint }; let square_explicit = |x: int| -> uint { (x * x) as uint }; let square_infer = |x: int| { (x * x) as uint }; println!("{}", square_explicit(20)); // 400 println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure, has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can only be used in argument position; they cannot be stored in data structures or returned from functions. Despite these limitations, stack closures are used pervasively in Rust code.*/ // -- Owned closures /*Owned closures, written proc, hold on to things that can safely be sent between processes. They copy the values they close over, but they also own them: that is, no other code can access them. Owned closures are used in concurrent code, particularly for spawning tasks. Closures can be used to spawn tasks. A practical example of this pattern is found when using the spawn function, which starts a new task.*/ use std::task::spawn; // proc is the closure which will be spawned. spawn(proc() { println!("I'm a new task") }); // -- Closure compatibility /*Rust closures have a convenient subtyping property: you can pass any kind of closure (as long as the arguments and return types match) to functions that expect a ||. Thus, when writing a higher-order function that only calls its function argument, and does nothing else with it, you should almost always declare the type of that argument as ||. That way, callers may pass any kind of closure.*/ fn call_twice(f: ||) { f(); f(); } let closure = || { "I'm a closure, and it doesn't matter what type I am"; }; fn function() { "I'm a normal function"; } call_twice(closure); call_twice(function);
{ println!("{}", x) }
identifier_body
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) }
}) } } #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..],
random_line_split
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) } fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result
} #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
{ f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..], }) }
identifier_body
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was not defined until /// > HTTP/1.1). When the Cache-Control header field is also present and /// > understood in a request, Pragma is ignored. /// > In HTTP/1.0, Pragma was defined as an extensible field for /// > implementation-specified directives for recipients. This /// > specification deprecates such extensions to improve interoperability. /// /// Spec: https://tools.ietf.org/html/rfc7234#section-5.4 /// /// # Examples /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::NoCache); /// ``` /// ``` /// use hyper::header::{Headers, Pragma}; /// /// let mut headers = Headers::new(); /// headers.set(Pragma::Ext("foobar".to_owned())); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum Pragma { /// Corresponds to the `no-cache` value. NoCache, /// Every value other than `no-cache`. Ext(String), } impl Header for Pragma { fn header_name() -> &'static str { static NAME: &'static str = "Pragma"; NAME } fn parse_header(raw: &Raw) -> ::Result<Pragma> { parsing::from_one_raw_str(raw).and_then(|s: String| { let slice = &s.to_ascii_lowercase()[..]; match slice { "no-cache" => Ok(Pragma::NoCache), _ => Ok(Pragma::Ext(s)), } }) } fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..], }) } } #[test] fn
() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".into()); assert_eq!(e.ok(), None); }
test_parse_header
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt:'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } }
}
random_line_split
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt:'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn
<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } }
set_secondary_markup
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt:'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I)
fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } }
{ let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } }
identifier_body
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBranch { matches: Vec::new(), result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseBranch, mut chariter: Chars, result: &str, case_sensitive: bool)
go_down_moses(&mut branch.children[i], chariter, result, case_sensitive); }, None => { assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }, } } ; for &(key, result) in options.iter() { go_down_moses(&mut root, key.chars(), result, case_sensitive); } root.children } macro_rules! branchify( (case sensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], true) ); (case insensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], false) ); ); /// Prints the contents to stdout. /// /// :param branches: the branches to search through /// :param indent: the level of indentation (each level representing four leading spaces) /// :param read_call: the function call to read a byte /// :param end: the byte which marks the end of the sequence /// :param max_len: the maximum length a value may be before giving up and returning ``None`` /// :param valid: the function call to if a byte ``b`` is valid /// :param unknown: the expression to call for an unknown value; in this string, ``{}`` will be /// replaced with an expression (literal or non-literal) evaluating to a ``String`` (it is /// ``{}`` only, not arbitrary format strings) pub fn generate_branchified_method( writer: &mut Writer, branches: Vec<ParseBranch>, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { fn r(writer: &mut Writer, branch: &ParseBranch, prefix: &str, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); for &c in branch.matches.iter() { let next_prefix = format!("{}{}", prefix, c as char); w!(format!("Ok(b'{}') => match {} {{", c as char, read_call)); for b in branch.children.iter() { try!(r(writer, b, &next_prefix[], indent + 1, read_call, end, max_len, valid, unknown)); } match branch.result { Some(ref result) => w!(format!(" Ok(b' ') => return Ok({}),", *result)), None => w!(format!(" Ok(b' ') => return Ok({}),", unknown.replace("{}", &format!("String::from_str(\"{}\")", next_prefix)[]))), } w!(format!(" Ok(b) if {} => (\"{}\", b),", valid, next_prefix)); w!(" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),"); w!(" Err(err) => return Err(err),"); w!("},"); } Ok(()) } let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); w!(format!("let (s, next_byte) = match {} {{", read_call)); for b in branches.iter() { try!(r(writer, b, "", indent + 1, read_call, end, max_len, valid, unknown)); } w!(format!(" Ok(b) if {} => (\"\", b),", valid)); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( ("};")); w!( ("// OK, that didn't pan out. Let's read the rest and see what we get.")); w!( ("let mut s = String::from_str(s);")); w!( ("s.push(next_byte as char);")); w!( ("loop {")); w!(format!(" match {} {{", read_call)); w!(format!(" Ok(b) if b == {} => return Ok({}),", end, unknown.replace("{}", "s"))); w!(format!(" Ok(b) if {} => {{", valid)); w!(format!(" if s.len() == {} {{", max_len)); w!( (" // Too long; bad request")); w!( (" return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"too long, bad request\", detail: None });")); w!( (" }")); w!( (" s.push(b as char);")); w!( (" },")); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( (" }")); w!( ("}")); Ok(()) }
{ match chariter.next() { Some(c) => { let first_case = if case_sensitive { c as u8 } else { c.to_ascii_uppercase() as u8 }; for next_branch in branch.children.iter_mut() { if next_branch.matches[0] == first_case { go_down_moses(next_branch, chariter, result, case_sensitive); return; } } let mut subbranch = ParseBranch::new(); subbranch.matches.push(first_case); if !case_sensitive { let second_case = c.to_ascii_lowercase() as u8; if first_case != second_case { subbranch.matches.push(second_case); } } branch.children.push(subbranch); let i = branch.children.len() - 1;
identifier_body
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBranch { matches: Vec::new(),
result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseBranch, mut chariter: Chars, result: &str, case_sensitive: bool) { match chariter.next() { Some(c) => { let first_case = if case_sensitive { c as u8 } else { c.to_ascii_uppercase() as u8 }; for next_branch in branch.children.iter_mut() { if next_branch.matches[0] == first_case { go_down_moses(next_branch, chariter, result, case_sensitive); return; } } let mut subbranch = ParseBranch::new(); subbranch.matches.push(first_case); if!case_sensitive { let second_case = c.to_ascii_lowercase() as u8; if first_case!= second_case { subbranch.matches.push(second_case); } } branch.children.push(subbranch); let i = branch.children.len() - 1; go_down_moses(&mut branch.children[i], chariter, result, case_sensitive); }, None => { assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }, } }; for &(key, result) in options.iter() { go_down_moses(&mut root, key.chars(), result, case_sensitive); } root.children } macro_rules! branchify( (case sensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], true) ); (case insensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], false) ); ); /// Prints the contents to stdout. /// /// :param branches: the branches to search through /// :param indent: the level of indentation (each level representing four leading spaces) /// :param read_call: the function call to read a byte /// :param end: the byte which marks the end of the sequence /// :param max_len: the maximum length a value may be before giving up and returning ``None`` /// :param valid: the function call to if a byte ``b`` is valid /// :param unknown: the expression to call for an unknown value; in this string, ``{}`` will be /// replaced with an expression (literal or non-literal) evaluating to a ``String`` (it is /// ``{}`` only, not arbitrary format strings) pub fn generate_branchified_method( writer: &mut Writer, branches: Vec<ParseBranch>, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { fn r(writer: &mut Writer, branch: &ParseBranch, prefix: &str, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); for &c in branch.matches.iter() { let next_prefix = format!("{}{}", prefix, c as char); w!(format!("Ok(b'{}') => match {} {{", c as char, read_call)); for b in branch.children.iter() { try!(r(writer, b, &next_prefix[], indent + 1, read_call, end, max_len, valid, unknown)); } match branch.result { Some(ref result) => w!(format!(" Ok(b' ') => return Ok({}),", *result)), None => w!(format!(" Ok(b' ') => return Ok({}),", unknown.replace("{}", &format!("String::from_str(\"{}\")", next_prefix)[]))), } w!(format!(" Ok(b) if {} => (\"{}\", b),", valid, next_prefix)); w!(" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),"); w!(" Err(err) => return Err(err),"); w!("},"); } Ok(()) } let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); w!(format!("let (s, next_byte) = match {} {{", read_call)); for b in branches.iter() { try!(r(writer, b, "", indent + 1, read_call, end, max_len, valid, unknown)); } w!(format!(" Ok(b) if {} => (\"\", b),", valid)); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( ("};")); w!( ("// OK, that didn't pan out. Let's read the rest and see what we get.")); w!( ("let mut s = String::from_str(s);")); w!( ("s.push(next_byte as char);")); w!( ("loop {")); w!(format!(" match {} {{", read_call)); w!(format!(" Ok(b) if b == {} => return Ok({}),", end, unknown.replace("{}", "s"))); w!(format!(" Ok(b) if {} => {{", valid)); w!(format!(" if s.len() == {} {{", max_len)); w!( (" // Too long; bad request")); w!( (" return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"too long, bad request\", detail: None });")); w!( (" }")); w!( (" s.push(b as char);")); w!( (" },")); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( (" }")); w!( ("}")); Ok(()) }
random_line_split
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn
() -> ParseBranch { ParseBranch { matches: Vec::new(), result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseBranch, mut chariter: Chars, result: &str, case_sensitive: bool) { match chariter.next() { Some(c) => { let first_case = if case_sensitive { c as u8 } else { c.to_ascii_uppercase() as u8 }; for next_branch in branch.children.iter_mut() { if next_branch.matches[0] == first_case { go_down_moses(next_branch, chariter, result, case_sensitive); return; } } let mut subbranch = ParseBranch::new(); subbranch.matches.push(first_case); if!case_sensitive { let second_case = c.to_ascii_lowercase() as u8; if first_case!= second_case { subbranch.matches.push(second_case); } } branch.children.push(subbranch); let i = branch.children.len() - 1; go_down_moses(&mut branch.children[i], chariter, result, case_sensitive); }, None => { assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }, } }; for &(key, result) in options.iter() { go_down_moses(&mut root, key.chars(), result, case_sensitive); } root.children } macro_rules! branchify( (case sensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], true) ); (case insensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], false) ); ); /// Prints the contents to stdout. /// /// :param branches: the branches to search through /// :param indent: the level of indentation (each level representing four leading spaces) /// :param read_call: the function call to read a byte /// :param end: the byte which marks the end of the sequence /// :param max_len: the maximum length a value may be before giving up and returning ``None`` /// :param valid: the function call to if a byte ``b`` is valid /// :param unknown: the expression to call for an unknown value; in this string, ``{}`` will be /// replaced with an expression (literal or non-literal) evaluating to a ``String`` (it is /// ``{}`` only, not arbitrary format strings) pub fn generate_branchified_method( writer: &mut Writer, branches: Vec<ParseBranch>, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { fn r(writer: &mut Writer, branch: &ParseBranch, prefix: &str, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); for &c in branch.matches.iter() { let next_prefix = format!("{}{}", prefix, c as char); w!(format!("Ok(b'{}') => match {} {{", c as char, read_call)); for b in branch.children.iter() { try!(r(writer, b, &next_prefix[], indent + 1, read_call, end, max_len, valid, unknown)); } match branch.result { Some(ref result) => w!(format!(" Ok(b' ') => return Ok({}),", *result)), None => w!(format!(" Ok(b' ') => return Ok({}),", unknown.replace("{}", &format!("String::from_str(\"{}\")", next_prefix)[]))), } w!(format!(" Ok(b) if {} => (\"{}\", b),", valid, next_prefix)); w!(" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),"); w!(" Err(err) => return Err(err),"); w!("},"); } Ok(()) } let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); w!(format!("let (s, next_byte) = match {} {{", read_call)); for b in branches.iter() { try!(r(writer, b, "", indent + 1, read_call, end, max_len, valid, unknown)); } w!(format!(" Ok(b) if {} => (\"\", b),", valid)); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( ("};")); w!( ("// OK, that didn't pan out. Let's read the rest and see what we get.")); w!( ("let mut s = String::from_str(s);")); w!( ("s.push(next_byte as char);")); w!( ("loop {")); w!(format!(" match {} {{", read_call)); w!(format!(" Ok(b) if b == {} => return Ok({}),", end, unknown.replace("{}", "s"))); w!(format!(" Ok(b) if {} => {{", valid)); w!(format!(" if s.len() == {} {{", max_len)); w!( (" // Too long; bad request")); w!( (" return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"too long, bad request\", detail: None });")); w!( (" }")); w!( (" s.push(b as char);")); w!( (" },")); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( (" }")); w!( ("}")); Ok(()) }
new
identifier_name
branchify.rs
#![macro_use] use std::str::Chars; use std::vec::Vec; use std::io::IoResult; use std::iter::repeat; use std::ascii::AsciiExt; #[derive(Clone)] pub struct ParseBranch { matches: Vec<u8>, result: Option<String>, children: Vec<ParseBranch>, } impl ParseBranch { fn new() -> ParseBranch { ParseBranch { matches: Vec::new(), result: None, children: Vec::new() } } } pub fn branchify(options: &[(&str, &str)], case_sensitive: bool) -> Vec<ParseBranch> { let mut root = ParseBranch::new(); fn go_down_moses(branch: &mut ParseBranch, mut chariter: Chars, result: &str, case_sensitive: bool) { match chariter.next() { Some(c) => { let first_case = if case_sensitive { c as u8 } else { c.to_ascii_uppercase() as u8 }; for next_branch in branch.children.iter_mut() { if next_branch.matches[0] == first_case { go_down_moses(next_branch, chariter, result, case_sensitive); return; } } let mut subbranch = ParseBranch::new(); subbranch.matches.push(first_case); if!case_sensitive { let second_case = c.to_ascii_lowercase() as u8; if first_case!= second_case { subbranch.matches.push(second_case); } } branch.children.push(subbranch); let i = branch.children.len() - 1; go_down_moses(&mut branch.children[i], chariter, result, case_sensitive); }, None =>
, } }; for &(key, result) in options.iter() { go_down_moses(&mut root, key.chars(), result, case_sensitive); } root.children } macro_rules! branchify( (case sensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], true) ); (case insensitive, $($key:expr => $value:ident),*) => ( ::branchify::branchify(&[$(($key, stringify!($value))),*], false) ); ); /// Prints the contents to stdout. /// /// :param branches: the branches to search through /// :param indent: the level of indentation (each level representing four leading spaces) /// :param read_call: the function call to read a byte /// :param end: the byte which marks the end of the sequence /// :param max_len: the maximum length a value may be before giving up and returning ``None`` /// :param valid: the function call to if a byte ``b`` is valid /// :param unknown: the expression to call for an unknown value; in this string, ``{}`` will be /// replaced with an expression (literal or non-literal) evaluating to a ``String`` (it is /// ``{}`` only, not arbitrary format strings) pub fn generate_branchified_method( writer: &mut Writer, branches: Vec<ParseBranch>, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { fn r(writer: &mut Writer, branch: &ParseBranch, prefix: &str, indent: usize, read_call: &str, end: &str, max_len: &str, valid: &str, unknown: &str) -> IoResult<()> { let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); for &c in branch.matches.iter() { let next_prefix = format!("{}{}", prefix, c as char); w!(format!("Ok(b'{}') => match {} {{", c as char, read_call)); for b in branch.children.iter() { try!(r(writer, b, &next_prefix[], indent + 1, read_call, end, max_len, valid, unknown)); } match branch.result { Some(ref result) => w!(format!(" Ok(b' ') => return Ok({}),", *result)), None => w!(format!(" Ok(b' ') => return Ok({}),", unknown.replace("{}", &format!("String::from_str(\"{}\")", next_prefix)[]))), } w!(format!(" Ok(b) if {} => (\"{}\", b),", valid, next_prefix)); w!(" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),"); w!(" Err(err) => return Err(err),"); w!("},"); } Ok(()) } let indentstr = repeat(' ').take(indent * 4).collect::<String>(); macro_rules! w ( ($s:expr) => { try!(write!(writer, "{}{}\n", indentstr, $s)) } ); w!(format!("let (s, next_byte) = match {} {{", read_call)); for b in branches.iter() { try!(r(writer, b, "", indent + 1, read_call, end, max_len, valid, unknown)); } w!(format!(" Ok(b) if {} => (\"\", b),", valid)); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( ("};")); w!( ("// OK, that didn't pan out. Let's read the rest and see what we get.")); w!( ("let mut s = String::from_str(s);")); w!( ("s.push(next_byte as char);")); w!( ("loop {")); w!(format!(" match {} {{", read_call)); w!(format!(" Ok(b) if b == {} => return Ok({}),", end, unknown.replace("{}", "s"))); w!(format!(" Ok(b) if {} => {{", valid)); w!(format!(" if s.len() == {} {{", max_len)); w!( (" // Too long; bad request")); w!( (" return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"too long, bad request\", detail: None });")); w!( (" }")); w!( (" s.push(b as char);")); w!( (" },")); w!( (" Ok(_) => return Err(::std::io::IoError { kind: ::std::io::OtherIoError, desc: \"bad value\", detail: None }),")); w!( (" Err(err) => return Err(err),")); w!( (" }")); w!( ("}")); Ok(()) }
{ assert!(branch.result.is_none()); branch.result = Some(String::from_str(result)); }
conditional_block
fixed_length_vec_glue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// xfail-fast: check-fast screws up repr paths use std::repr; struct Struc { a: u8, b: [int,..3], c: int } pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
fixed_length_vec_glue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast: check-fast screws up repr paths use std::repr; struct
{ a: u8, b: [int,..3], c: int } pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
Struc
identifier_name
fixed_length_vec_glue.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast: check-fast screws up repr paths use std::repr; struct Struc { a: u8, b: [int,..3], c: int } pub fn main()
{ let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = repr::repr_to_str(&struc); assert_eq!(s, ~"Struc{a: 13u8, b: [1, 2, 3], c: 42}"); }
identifier_body
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { Hypergeometric { N: total, m: n_different, n: n_picked, } } } impl Distribution<u64> for Hypergeometric { fn sample(&self) -> RandomVariable<u64> { let prob = rand::random::<f64>(); let low_lim = if self.n < self.m { self.n } else { self.m }; let mut cum_prob: f64 = 0.0f64; let mut k: u64 = 0u64; for _ in 0..low_lim { cum_prob += self.pdf(k); if cum_prob > prob { break; } k += 1 } RandomVariable { value: Cell::new(k) } } fn mu(&self) -> f64 { ((self.n * self.m) as f64) / (self.N as f64) } fn sigma(&self) -> f64 { let mean = self.mu(); let failure = ((self.N - self.m) as f64) / (self.N as f64); let remaining = ((self.N - self.n) as f64) / ((self.N - 1) as f64); (mean * failure * remaining).sqrt() } fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomial_coeff(self.N - self.m, self.N - x) / binomial_coeff(self.N, self.n) } fn cdf(&self, x: u64) -> f64
}
{ (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) }
identifier_body
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { Hypergeometric { N: total, m: n_different, n: n_picked, } } } impl Distribution<u64> for Hypergeometric { fn sample(&self) -> RandomVariable<u64> { let prob = rand::random::<f64>(); let low_lim = if self.n < self.m { self.n } else { self.m }; let mut cum_prob: f64 = 0.0f64; let mut k: u64 = 0u64; for _ in 0..low_lim { cum_prob += self.pdf(k); if cum_prob > prob { break; } k += 1 } RandomVariable { value: Cell::new(k) } } fn mu(&self) -> f64 { ((self.n * self.m) as f64) / (self.N as f64) } fn sigma(&self) -> f64 { let mean = self.mu(); let failure = ((self.N - self.m) as f64) / (self.N as f64); let remaining = ((self.N - self.n) as f64) / ((self.N - 1) as f64); (mean * failure * remaining).sqrt()
} fn cdf(&self, x: u64) -> f64 { (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) } }
} fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomial_coeff(self.N - self.m, self.N - x) / binomial_coeff(self.N, self.n)
random_line_split
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { Hypergeometric { N: total, m: n_different, n: n_picked, } } } impl Distribution<u64> for Hypergeometric { fn sample(&self) -> RandomVariable<u64> { let prob = rand::random::<f64>(); let low_lim = if self.n < self.m { self.n } else
; let mut cum_prob: f64 = 0.0f64; let mut k: u64 = 0u64; for _ in 0..low_lim { cum_prob += self.pdf(k); if cum_prob > prob { break; } k += 1 } RandomVariable { value: Cell::new(k) } } fn mu(&self) -> f64 { ((self.n * self.m) as f64) / (self.N as f64) } fn sigma(&self) -> f64 { let mean = self.mu(); let failure = ((self.N - self.m) as f64) / (self.N as f64); let remaining = ((self.N - self.n) as f64) / ((self.N - 1) as f64); (mean * failure * remaining).sqrt() } fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomial_coeff(self.N - self.m, self.N - x) / binomial_coeff(self.N, self.n) } fn cdf(&self, x: u64) -> f64 { (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) } }
{ self.m }
conditional_block
hypergeometric.rs
extern crate rand; use crate::distribs::distribution::*; use crate::util::math::*; #[allow(non_snake_case)] #[allow(dead_code)] pub struct Hypergeometric { N: u64, m: u64, n: u64, } #[allow(dead_code)] impl Hypergeometric { pub fn new(total: u64, n_different: u64, n_picked: u64) -> Hypergeometric { Hypergeometric { N: total, m: n_different, n: n_picked, } } } impl Distribution<u64> for Hypergeometric { fn sample(&self) -> RandomVariable<u64> { let prob = rand::random::<f64>(); let low_lim = if self.n < self.m { self.n } else { self.m }; let mut cum_prob: f64 = 0.0f64; let mut k: u64 = 0u64; for _ in 0..low_lim { cum_prob += self.pdf(k); if cum_prob > prob { break; } k += 1 } RandomVariable { value: Cell::new(k) } } fn mu(&self) -> f64 { ((self.n * self.m) as f64) / (self.N as f64) } fn
(&self) -> f64 { let mean = self.mu(); let failure = ((self.N - self.m) as f64) / (self.N as f64); let remaining = ((self.N - self.n) as f64) / ((self.N - 1) as f64); (mean * failure * remaining).sqrt() } fn pdf(&self, x: u64) -> f64 { binomial_coeff(self.m, x) * binomial_coeff(self.N - self.m, self.N - x) / binomial_coeff(self.N, self.n) } fn cdf(&self, x: u64) -> f64 { (0..x).fold(0.0f64, |sum, next| sum + self.pdf(next)) } }
sigma
identifier_name