text stringlengths 8 4.13M |
|---|
use std::collections::HashMap;
#[derive(Debug)]
enum Instruction {
Mask(String),
Mem(Mem),
}
#[derive(Debug)]
struct Mem {
ptr: usize,
value: String,
}
const BITS: usize = 36;
pub fn solve_part_one(input: &str) -> usize {
let instructions = process(input);
let mut memory = HashMap::new();
let mut mask = String::new();
for instruction in instructions {
match instruction {
Instruction::Mask(value) => mask = value,
Instruction::Mem(mem) => {
let masked_value = mask_value(&mem.value, &mask);
memory.insert(mem.ptr, masked_value);
}
}
}
memory.iter().fold(0, |sum, (_, value)| {
sum + to_decimal(value)
})
}
fn process(input: &str) -> Vec<Instruction> {
input
.lines()
.map(|line| {
let parts: Vec<&str> = line.split(" = ").collect();
match parts[0] {
"mask" => Instruction::Mask(parts[1].to_string()),
_ => {
let ptr = parts[0][4..(parts[0].len() - 1)].parse().unwrap();
let value_binary = to_binary(parts[1].parse().unwrap());
let value = add_leading_zeros(&value_binary);
Instruction::Mem(Mem {
ptr,
value,
})
}
}
})
.collect()
}
fn to_binary(decimal: usize) -> String {
let mut remainder = decimal;
let mut bit_val = 2usize.pow((BITS - 1) as u32);
let mut binary = String::new();
for _ in 0..BITS {
if remainder >= bit_val {
binary.push('1');
remainder -= bit_val;
}
else {
binary.push('0');
}
bit_val /= 2;
}
binary
}
fn add_leading_zeros(value: &str) -> String {
let leading_zeros = vec!["0"; BITS - value.len()].join("");
format!("{}{}", leading_zeros, value)
}
fn mask_value(value: &str, mask: &str) -> String {
let mask_chars: Vec<char> = mask.chars().collect();
let mut value_chars: Vec<char> = value.chars().collect();
for i in 0..mask_chars.len() {
if mask_chars[i] != 'X' {
value_chars[i] = mask_chars[i];
}
}
value_chars.iter().collect()
}
fn to_decimal(binary: &str) -> usize {
let mut bit_val = 2usize.pow(BITS as u32);
binary.chars().fold(0, |sum, bit| {
bit_val /= 2;
match bit {
'0' => sum,
'1' => sum + bit_val,
_ => panic!("not a binary string"),
}
})
}
pub fn solve(input: &str) -> usize {
let instructions = process(input);
let mut memory = HashMap::new();
let mut mask = String::new();
for instruction in instructions {
match instruction {
Instruction::Mask(value) => mask = value,
Instruction::Mem(mem) => {
let ptrs = get_ptrs(mem.ptr, &mask);
for ptr in ptrs {
memory.insert(ptr, mem.value.clone());
}
}
}
}
memory.iter().fold(0, |sum, (_, value)| {
sum + to_decimal(value)
})
}
fn get_ptrs(ptr: usize, mask: &str) -> Vec<usize> {
let ptr_chars: Vec<char> = to_binary(ptr).chars().collect();
let mask_chars: Vec<char> = mask.chars().collect();
let mut ptrs = vec![ptr_chars];
for c in 0..mask_chars.len() {
match mask_chars[c] {
'1' => {
for p in 0..ptrs.len() {
ptrs[p][c] = '1';
}
},
'X' => {
let mut ptrs_copy = ptrs.clone();
for p in 0..ptrs.len() {
ptrs[p][c] = '0';
ptrs_copy[p][c] = '1';
}
ptrs.extend(ptrs_copy);
},
_ => ()
}
}
ptrs
.iter()
.map(|ptr_chars| {
let ptr_str: String = ptr_chars.iter().collect();
to_decimal(&ptr_str)
})
.collect()
}
|
#[doc = "Reader of register RED_CTL01"]
pub type R = crate::R<u32, super::RED_CTL01>;
#[doc = "Writer for register RED_CTL01"]
pub type W = crate::W<u32, super::RED_CTL01>;
#[doc = "Register RED_CTL01 `reset()`'s with value 0"]
impl crate::ResetValue for super::RED_CTL01 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RED_ADDR_0`"]
pub type RED_ADDR_0_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RED_ADDR_0`"]
pub struct RED_ADDR_0_W<'a> {
w: &'a mut W,
}
impl<'a> RED_ADDR_0_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff);
self.w
}
}
#[doc = "Reader of field `RED_EN_0`"]
pub type RED_EN_0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RED_EN_0`"]
pub struct RED_EN_0_W<'a> {
w: &'a mut W,
}
impl<'a> RED_EN_0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `RED_ADDR_1`"]
pub type RED_ADDR_1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RED_ADDR_1`"]
pub struct RED_ADDR_1_W<'a> {
w: &'a mut W,
}
impl<'a> RED_ADDR_1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16);
self.w
}
}
#[doc = "Reader of field `RED_EN_1`"]
pub type RED_EN_1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RED_EN_1`"]
pub struct RED_EN_1_W<'a> {
w: &'a mut W,
}
impl<'a> RED_EN_1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Bad Row Pair Address for Sector 0"]
#[inline(always)]
pub fn red_addr_0(&self) -> RED_ADDR_0_R {
RED_ADDR_0_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bit 8 - '1': Redundancy Enable for Sector 0"]
#[inline(always)]
pub fn red_en_0(&self) -> RED_EN_0_R {
RED_EN_0_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bits 16:23 - Bad Row Pair Address for Sector 1"]
#[inline(always)]
pub fn red_addr_1(&self) -> RED_ADDR_1_R {
RED_ADDR_1_R::new(((self.bits >> 16) & 0xff) as u8)
}
#[doc = "Bit 24 - '1': Redundancy Enable for Sector 1"]
#[inline(always)]
pub fn red_en_1(&self) -> RED_EN_1_R {
RED_EN_1_R::new(((self.bits >> 24) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:7 - Bad Row Pair Address for Sector 0"]
#[inline(always)]
pub fn red_addr_0(&mut self) -> RED_ADDR_0_W {
RED_ADDR_0_W { w: self }
}
#[doc = "Bit 8 - '1': Redundancy Enable for Sector 0"]
#[inline(always)]
pub fn red_en_0(&mut self) -> RED_EN_0_W {
RED_EN_0_W { w: self }
}
#[doc = "Bits 16:23 - Bad Row Pair Address for Sector 1"]
#[inline(always)]
pub fn red_addr_1(&mut self) -> RED_ADDR_1_W {
RED_ADDR_1_W { w: self }
}
#[doc = "Bit 24 - '1': Redundancy Enable for Sector 1"]
#[inline(always)]
pub fn red_en_1(&mut self) -> RED_EN_1_W {
RED_EN_1_W { w: self }
}
}
|
///// chapter 4 "structuring data and matching patterns"
///// program section:
//
fn main() {
let aliens =
["cherfer", "fynock", "shirack", "zuxu"];
for a in aliens.iter() {
println!("the next alien is {}", a);
}
}
///// output should be:
/*
*/// end of output
|
mod client_actor;
pub use client_actor::{ClientActor, ClientRouting};
pub mod control_messages;
pub mod config;
|
extern crate rand;
use std::cmp::Ordering;
use rand::Rng;
use std::io;
use std::io::Write;
fn main() {
println!("A Guessing Game!");
println!("Guess the number and let see how much steps would you get?");
let mut step = 1;
let number = rand::thread_rng().gen_range(-1000, 1000);
loop {
println!();
print!("Guess the number: ");
io::stdout().flush().unwrap();
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("failed to read line");
if guess.trim() == "exit" {
break;
}
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("Yas! You win!\n");
println!("Took you {} times.", step);
break;
},
}
step += 1;
}
}
|
use wrapped2d::{self, b2};
use conniecs::Entity;
pub use self::body::Body;
pub use self::run::PhysicsRun;
pub use self::update::PhysicsUpdate;
pub mod ext;
pub mod body;
pub mod run;
pub mod update;
pub const GRAVITY: b2::Vec2 = b2::Vec2 { x: 0.0, y: -15.0 };
pub struct World {
pub world: b2::World<EntityUserData>,
}
impl World {
pub fn new() -> Self {
let world = b2::World::new(&GRAVITY);
World { world }
}
}
impl Default for World {
fn default() -> Self {
World::new()
}
}
pub struct EntityUserData;
impl wrapped2d::user_data::UserDataTypes for EntityUserData {
type BodyData = Entity;
type JointData = ();
type FixtureData = Entity;
}
|
use std::os::raw;
use super::ErrorCode;
extern "C" {
pub fn c_Logger_Close();
pub fn c_Logger_Open(language: raw::c_int, logDriverStation: bool);
pub fn c_Logger_Log(
code: ErrorCode,
origin: *const raw::c_char,
hierarchy: raw::c_int,
stacktrace: *const raw::c_char,
) -> ErrorCode;
}
|
#[derive(Debug, Default, Copy, Clone)]
pub struct Scores {
pub hits: u16,
pub misses: u16,
}
|
use crate::vm::bytecode;
use super::prelude::*;
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct CompiledFunction {
pub instructions: bytecode::Instructions,
pub num_locals: u16,
pub num_parameters: u8,
}
impl Display for CompiledFunction {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "CompiledFunction[{}]", self.instructions)
}
}
|
#[doc = "Register `SCSR` reader"]
pub type R = crate::R<SCSR_SPEC>;
#[doc = "Register `SCSR` writer"]
pub type W = crate::W<SCSR_SPEC>;
#[doc = "Field `SRAM2ER` reader - SRAM2 Erase"]
pub type SRAM2ER_R = crate::BitReader<SRAM2ER_A>;
#[doc = "SRAM2 Erase\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SRAM2ER_A {
#[doc = "1: Setting this bit starts a hardware SRAM2 erase operation"]
Erase = 1,
}
impl From<SRAM2ER_A> for bool {
#[inline(always)]
fn from(variant: SRAM2ER_A) -> Self {
variant as u8 != 0
}
}
impl SRAM2ER_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<SRAM2ER_A> {
match self.bits {
true => Some(SRAM2ER_A::Erase),
_ => None,
}
}
#[doc = "Setting this bit starts a hardware SRAM2 erase operation"]
#[inline(always)]
pub fn is_erase(&self) -> bool {
*self == SRAM2ER_A::Erase
}
}
#[doc = "Field `SRAM2ER` writer - SRAM2 Erase"]
pub type SRAM2ER_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SRAM2ER_A>;
impl<'a, REG, const O: u8> SRAM2ER_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Setting this bit starts a hardware SRAM2 erase operation"]
#[inline(always)]
pub fn erase(self) -> &'a mut crate::W<REG> {
self.variant(SRAM2ER_A::Erase)
}
}
#[doc = "Field `SRAM2BS` reader - SRAM2 busy by erase operation"]
pub type SRAM2BS_R = crate::BitReader<SRAM2BS_A>;
#[doc = "SRAM2 busy by erase operation\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SRAM2BS_A {
#[doc = "0: No SRAM2 erase operation is on going"]
NotBusy = 0,
#[doc = "1: SRAM2 erase operation is on going"]
Busy = 1,
}
impl From<SRAM2BS_A> for bool {
#[inline(always)]
fn from(variant: SRAM2BS_A) -> Self {
variant as u8 != 0
}
}
impl SRAM2BS_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SRAM2BS_A {
match self.bits {
false => SRAM2BS_A::NotBusy,
true => SRAM2BS_A::Busy,
}
}
#[doc = "No SRAM2 erase operation is on going"]
#[inline(always)]
pub fn is_not_busy(&self) -> bool {
*self == SRAM2BS_A::NotBusy
}
#[doc = "SRAM2 erase operation is on going"]
#[inline(always)]
pub fn is_busy(&self) -> bool {
*self == SRAM2BS_A::Busy
}
}
impl R {
#[doc = "Bit 0 - SRAM2 Erase"]
#[inline(always)]
pub fn sram2er(&self) -> SRAM2ER_R {
SRAM2ER_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - SRAM2 busy by erase operation"]
#[inline(always)]
pub fn sram2bs(&self) -> SRAM2BS_R {
SRAM2BS_R::new(((self.bits >> 1) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - SRAM2 Erase"]
#[inline(always)]
#[must_use]
pub fn sram2er(&mut self) -> SRAM2ER_W<SCSR_SPEC, 0> {
SRAM2ER_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "SCSR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`scsr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`scsr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SCSR_SPEC;
impl crate::RegisterSpec for SCSR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`scsr::R`](R) reader structure"]
impl crate::Readable for SCSR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`scsr::W`](W) writer structure"]
impl crate::Writable for SCSR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SCSR to value 0"]
impl crate::Resettable for SCSR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
//
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
logger::Logger,
server::{
AbiPointer, AbiPointerOffset, BoxedExtension, ExtensionFactory, OakApiNativeExtension,
WasmState, ABI_USIZE,
},
};
use oak_functions_abi::proto::OakStatus;
use anyhow::Context;
use log::Level;
use rand::{distributions::Open01, rngs::StdRng, thread_rng, Rng, SeedableRng};
use serde::Deserialize;
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use wasmi::ValueType;
/// Host function name for reporting private metrics.
const METRICS_ABI_FUNCTION_NAME: &str = "report_metric";
/// Configuration for differentially-private metrics reporting.
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct PrivateMetricsConfig {
/// The privacy budget. See
/// https://desfontain.es/privacy/differential-privacy-in-practice.html for more information
/// on epsilon-differential privacy and Laplacian noise.
pub epsilon: f64,
/// The number of requests that will be aggregated into each batch.
pub batch_size: usize,
/// The labels and configurations of buckets for which metrics can be reported.
pub buckets: HashMap<String, BucketConfig>,
}
impl PrivateMetricsConfig {
pub fn validate(&self) -> anyhow::Result<()> {
anyhow::ensure!(self.epsilon > 0.0, "Epsilon must be positive",);
for (label, bucket_config) in &self.buckets {
if let BucketConfig::Sum { min, max } = bucket_config {
anyhow::ensure!(
max > min,
"Max must be bigger than min for bucket {}",
label,
);
}
}
Ok(())
}
}
/// Configuration for metrics buckets.
#[derive(Clone, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub enum BucketConfig {
/// A bucket used for counting of events. This is equivalent to `Sum { min: 0, max: 1 }`.
Count,
/// A bucket used for summing integer values in a range. Values outside of the range are
/// clamped at the minimum or maximum values. The noise added to the bucket is scaled by the
/// size of the range (`max - min`).
Sum { min: i64, max: i64 },
}
/// Combined configuration and data storage for a metrics bucket.
struct Bucket {
config: BucketConfig,
value: i64,
}
impl Bucket {
/// Adds the input value to the bucket value. If the value is outside of the configured range it
/// is clamped to the minimum or maximum.
fn add(&mut self, input: i64) {
self.value += match self.config {
BucketConfig::Count => input.clamp(0, 1),
BucketConfig::Sum { min, max } => input.clamp(min, max),
}
}
}
/// Aggregator for count- and sum-based differentially private metrics. The request metrics are
/// released in aggregated batches after differentially private noise has been added. Once the
/// number of requests reaches the batch threshold the metrics are logged and the request count and
/// bucket counts are reset to 0.
pub struct PrivateMetricsAggregator {
/// The request count.
count: usize,
/// The privacy budget.
epsilon: f64,
/// The number of requests that will be aggregated into each batch.
batch_size: usize,
/// The storage for the buckets.
buckets: HashMap<String, Bucket>,
/// The random number generator used for sampling the noise.
rng: StdRng,
}
impl PrivateMetricsAggregator {
pub fn new(config: &PrivateMetricsConfig) -> anyhow::Result<Self> {
Self::new_with_rng(
config,
StdRng::from_rng(thread_rng()).context("Couldn't create rng")?,
)
}
#[cfg(test)]
pub fn new_for_test(config: &PrivateMetricsConfig, rng: StdRng) -> anyhow::Result<Self> {
Self::new_with_rng(config, rng)
}
fn new_with_rng(config: &PrivateMetricsConfig, rng: StdRng) -> anyhow::Result<Self> {
anyhow::ensure!(config.epsilon > 0.0, "Epsilon must be positive.");
Ok(Self {
count: 0,
epsilon: config.epsilon,
batch_size: config.batch_size,
buckets: config
.buckets
.iter()
.map(|(label, bucket_config)| {
(
label.clone(),
Bucket {
config: bucket_config.clone(),
value: 0,
},
)
})
.collect(),
rng,
})
}
/// Reports new metrics for a single request that should be included in the aggregated counts.
///
/// If the data contains entries with labels for buckets that are not configured those entries
/// are ignored. If data does not include entries for some configured buckets, it will be
/// treated as if values of 0 (or the minimum values where the minimum values are larger than 0)
/// were included for those buckets.
///
/// If the number of requests do not yet match the batch size `None` is returned. If the
/// batch threshold is reached the aggregated metrics for the batch are returned and the
/// request count and bucket values are reset to 0. Each Wasm instance can only call this
/// function once, as it consumes its PrivateMetricsProxy in the process of reporting metrics.
///
/// Laplacian noise is added to each of the aggregated bucket values that are returned. The
/// noise is scaled by the size of the range allowed for the bucket.
///
/// The metrics are returned as a tuple containing the batch size and a vector of tuples
/// cotaining the label and value for each bucket.
pub fn report_metrics(
&mut self,
data: HashMap<String, i64>,
) -> Option<(usize, Vec<(String, i64)>)> {
self.count += 1;
for (label, bucket) in self.buckets.iter_mut() {
bucket.add(*data.get(label).unwrap_or(&0));
}
if self.count == self.batch_size {
let beta = self.buckets.len() as f64 / self.epsilon;
let rng = &mut self.rng;
let metrics = self
.buckets
.iter()
.map(|(label, bucket)| {
let scale = match bucket.config {
BucketConfig::Count => 1.0,
BucketConfig::Sum { min, max } => (max - min) as f64,
};
(
label.to_string(),
add_laplace_noise(rng, beta, bucket.value, scale),
)
})
.collect();
self.reset();
Some((self.batch_size, metrics))
} else {
None
}
}
/// Resets the request count and all the bucket values to 0.
fn reset(&mut self) {
self.count = 0;
for (_, bucket) in self.buckets.iter_mut() {
bucket.value = 0;
}
}
}
/// Adds Laplacian noise with parameter `beta` scaled by `scale` to a `value`. The Laplacian noise
/// is sampled by sampling from a uniform distribution and calculating the inverse of the Laplace
/// cummulative distribution function on the sampled value.
///
/// Rounding of the noise is allowed as acceptable post-processing.
pub fn add_laplace_noise(rng: &mut StdRng, beta: f64, value: i64, scale: f64) -> i64 {
// Split the budget evenly over all of the labeled buckets.
let p: f64 = rng.sample(Open01);
value + (scale * inverse_laplace(beta, p)).round() as i64
}
/// Applies the inverse of the Laplace cummulative distribution function with mu = 0.
///
/// See https://en.wikipedia.org/wiki/Laplace_distribution
fn inverse_laplace(beta: f64, p: f64) -> f64 {
if p >= 1.0 {
return f64::INFINITY;
}
if p <= 0.0 {
return f64::NEG_INFINITY;
}
let u = p - 0.5;
-beta * u.signum() * (1.0 - 2.0 * u.abs()).ln()
}
pub struct PrivateMetricsProxyFactory {
aggregator: Arc<Mutex<PrivateMetricsAggregator>>,
logger: Logger,
}
impl PrivateMetricsProxyFactory {
pub fn new(config: &PrivateMetricsConfig, logger: Logger) -> anyhow::Result<Self> {
let aggregator = PrivateMetricsAggregator::new(config)?;
Ok(Self {
aggregator: Arc::new(Mutex::new(aggregator)),
logger,
})
}
}
impl ExtensionFactory for PrivateMetricsProxyFactory {
fn create(&self) -> anyhow::Result<BoxedExtension> {
let metrics_proxy = PrivateMetricsProxy::new(self.aggregator.clone());
let extension = PrivateMetricsExtension {
metrics_proxy: Some(metrics_proxy),
logger: self.logger.clone(),
};
Ok(Box::new(extension))
}
}
struct PrivateMetricsExtension {
metrics_proxy: Option<PrivateMetricsProxy>,
logger: Logger,
}
impl PrivateMetricsExtension {
fn publish_metrics(&mut self) -> anyhow::Result<()> {
let metrics_proxy = self
.metrics_proxy
.take()
.context("metrics_proxy is consumed")?;
if let Some((batch_size, metrics)) = metrics_proxy.publish() {
let buckets: Vec<String> = metrics
.iter()
.map(|(label, count)| format!("{}={}", label, count))
.collect();
let message = format!(
"metrics export: batch size: {}; counts: {}",
batch_size,
buckets.join(";"),
);
// The differentially private metrics can be treated as non-sensitive
// information and therefore logged as public. This assumes
// that the client has validated that the configured privacy
// budget provides sufficient privacy protection before
// sending any data to the server.
self.logger.log_public(Level::Info, &message);
}
Ok(())
}
}
impl OakApiNativeExtension for PrivateMetricsExtension {
fn invoke(
&mut self,
wasm_state: &mut WasmState,
args: wasmi::RuntimeArgs,
) -> Result<Result<(), OakStatus>, wasmi::Trap> {
Ok(report_metric(
wasm_state,
self,
args.nth_checked(0)?,
args.nth_checked(1)?,
args.nth_checked(2)?,
))
}
/// Each Oak Functions application can have at most one instance of PrivateMetricsProxy. So it
/// is fine to return a constant name in the metadata.
fn get_metadata(&self) -> (String, wasmi::Signature) {
let signature = wasmi::Signature::new(
&[
ABI_USIZE, // buf_ptr
ABI_USIZE, // buf_len
ValueType::I64,
][..],
Some(ValueType::I32),
);
(METRICS_ABI_FUNCTION_NAME.to_string(), signature)
}
fn terminate(&mut self) -> anyhow::Result<()> {
self.publish_metrics()
}
}
/// Proxy for use by request handler instances to push per-request metrics to the
/// `PrivateMetricsAggregator`.
struct PrivateMetricsProxy {
aggregator: Arc<Mutex<PrivateMetricsAggregator>>,
data: HashMap<String, i64>,
}
impl PrivateMetricsProxy {
pub fn new(aggregator: Arc<Mutex<PrivateMetricsAggregator>>) -> Self {
Self {
aggregator,
data: HashMap::new(),
}
}
/// Sets the value for the labeled metric. If a value was previously set for the label it will
/// be overwritten.
fn report_metric(&mut self, label: &str, value: i64) {
self.data.insert(label.to_owned(), value);
}
/// Consumes the proxy and publishes the local request-specific data to the aggregator. If
/// publishing the metrics to the aggregator causes the batch threshold to be reached the
/// aggregated metrics are returned.
///
/// See [PrivateMetricsAggregator::report_metrics] for more details.
fn publish(self) -> Option<(usize, Vec<(String, i64)>)> {
if let Ok(mut aggregator) = self.aggregator.lock() {
aggregator.report_metrics(self.data)
} else {
None
}
}
}
/// Corresponds to the host ABI function [`report_metric`](https://github.com/project-oak/oak/blob/main/docs/oak_functions_abi.md#report_metric).
fn report_metric(
wasm_state: &mut WasmState,
extension: &mut PrivateMetricsExtension,
buf_ptr: AbiPointer,
buf_len: AbiPointerOffset,
value: i64,
) -> Result<(), OakStatus> {
let raw_label = wasm_state
.get_memory()
.get(buf_ptr, buf_len as usize)
.map_err(|err| {
extension.logger.log_sensitive(
Level::Error,
&format!(
"report_metric(): Unable to read label from guest memory: {:?}",
err
),
);
OakStatus::ErrInvalidArgs
})?;
let label = std::str::from_utf8(raw_label.as_slice()).map_err(|err| {
extension.logger.log_sensitive(
Level::Warn,
&format!(
"report_metric(): Not a valid UTF-8 encoded string: {:?}\nContent: {:?}",
err, raw_label
),
);
OakStatus::ErrInvalidArgs
})?;
extension
.logger
.log_sensitive(Level::Debug, &format!("report_metric(): {}", label));
if let Some(metrics_proxy) = extension.metrics_proxy.as_mut() {
metrics_proxy.report_metric(label, value);
Ok(())
} else {
extension.logger.log_sensitive(
Level::Error,
&format!("report_metric(): Missing metrics proxy",),
);
Err(OakStatus::ErrInternal)
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_private_metrics_aggregator_count() {
let epsilon = 1.0;
let batch_size = 4;
let config = PrivateMetricsConfig {
epsilon,
batch_size,
buckets: hashmap! {
"a".to_string() => BucketConfig::Count,
"b".to_string() => BucketConfig::Count,
"c".to_string() => BucketConfig::Count,
"d".to_string() => BucketConfig::Count,
},
};
// Use a fixed seed for the random number generators so the errors are predicatable.
let seed = 0;
let rng = StdRng::seed_from_u64(seed);
let aggregator = Arc::new(Mutex::new(
PrivateMetricsAggregator::new_for_test(&config, rng).unwrap(),
));
let expected = hashmap! {
"a".to_string() => 3,
"b".to_string() => 2,
"c".to_string() => 1,
"d".to_string() => 0,
};
// Calculate expected noise using a fixed seeded rng.
let mut rng = StdRng::seed_from_u64(seed);
let noise: Vec<i64> = (0..4)
.map(|_| add_laplace_noise(&mut rng, config.buckets.len() as f64 / epsilon, 0, 1.0))
.collect();
let mut proxy1 = PrivateMetricsProxy::new(aggregator.clone());
proxy1.report_metric("a", 1); // Expect +1 for "a".
assert_eq!(proxy1.publish(), None);
let mut proxy2 = PrivateMetricsProxy::new(aggregator.clone());
proxy2.report_metric("a", 2); // Expect +1 for "a".
proxy2.report_metric("b", 3); // Expect +1 for "b".
assert_eq!(proxy2.publish(), None);
let mut proxy3 = PrivateMetricsProxy::new(aggregator.clone());
proxy3.report_metric("c", 1); // Overwritten.
proxy3.report_metric("b", 1); // Expect +1 for "b".
proxy3.report_metric("c", 3); // Expect +1 for "c".
assert_eq!(proxy3.publish(), None);
let mut proxy4 = PrivateMetricsProxy::new(aggregator);
proxy4.report_metric("a", 1); // Expect +1 for "a".
proxy4.report_metric("e", 1); // Ignored.
let (count, buckets) = proxy4.publish().unwrap();
assert_eq!(batch_size, count);
for (index, (label, value)) in buckets.iter().enumerate() {
println!(
"Label: {}, Actual: {}, Expected: {}, Noise: {}",
label,
value,
expected.get(label).unwrap(),
noise[index]
);
assert_eq!(*value, expected.get(label).unwrap() + noise[index]);
}
}
#[test]
fn test_private_metrics_aggregator_sum() {
let epsilon = 1.0;
let batch_size = 3;
let config = PrivateMetricsConfig {
epsilon,
batch_size,
buckets: hashmap! {
"a".to_string() => BucketConfig::Sum { min: 0, max: 10 },
"b".to_string() => BucketConfig::Sum { min: 10, max: 20 },
},
};
// Use a fixed seed for the random number generators so the errors are predicatable.
let seed = 0;
let rng = StdRng::seed_from_u64(seed);
let aggregator = Arc::new(Mutex::new(
PrivateMetricsAggregator::new_for_test(&config, rng).unwrap(),
));
let expected = hashmap! {
"a".to_string() => 13,
"b".to_string() => 32,
};
// Calculate expected noise using a fixed seeded rng.
let mut rng = StdRng::seed_from_u64(seed);
let noise: Vec<i64> = (0..2)
.map(|_| add_laplace_noise(&mut rng, config.buckets.len() as f64 / epsilon, 0, 10.0))
.collect();
let mut proxy1 = PrivateMetricsProxy::new(aggregator.clone());
proxy1.report_metric("a", -100); // Expect +0 for "a", +10 for "b".
// Note: even though no metric value is reported for "b" in this request, the minimum
// configured value means that 10 will be added to bucket "b".
assert_eq!(proxy1.publish(), None);
let mut proxy2 = PrivateMetricsProxy::new(aggregator.clone());
proxy2.report_metric("a", 5); // Overwritten.
proxy2.report_metric("a", 3); // Expect +3 for "a".
proxy2.report_metric("b", 12); // Expect +12 for "b".
assert_eq!(proxy2.publish(), None);
let mut proxy3 = PrivateMetricsProxy::new(aggregator);
proxy3.report_metric("a", 100); // Expect +10 for "a".
proxy3.report_metric("b", 5); // Expect +10 for "b".
let (count, buckets) = proxy3.publish().unwrap();
assert_eq!(batch_size, count);
for (index, (label, value)) in buckets.iter().enumerate() {
println!(
"Label: {}, Actual: {}, Expected: {}, Noise: {}",
label,
value,
expected.get(label).unwrap(),
noise[index]
);
assert_eq!(*value, expected.get(label).unwrap() + noise[index]);
}
}
#[test]
fn test_laplace_noise() {
// Run many times and make sure the shape of the histogram looks roughly right.
let iterations = 1_000_000;
// Check the 0 bucket and 5 buckets either side.
let offset = 5;
// Bucket is allowed up to 2% above or below expected size.
let margin = 0.02_f64;
let epsilon = 1.0_f64;
let beta = 1.0 / epsilon;
let scale = 1.0;
// Use a fixed seed for the random number generator to avoid potential flakiness.
let mut rng = StdRng::seed_from_u64(0);
// Calculate expected bucket counts using the cummulative distribution function.
let expected: Vec<f64> = (-offset..=offset)
.map(|index| {
iterations as f64
* (laplace_cdf(beta, index as f64 + 0.5)
- laplace_cdf(beta, index as f64 - 0.5))
})
.collect();
// Build a histogram of the actual noise.
let mut histogram: Vec<usize> = (-offset..=offset).map(|_| 0).collect();
for _ in 0..iterations {
let noise = add_laplace_noise(&mut rng, beta, 0, scale);
if (-offset..=offset).contains(&noise) {
let index = (noise + offset) as usize;
histogram[index] += 1;
}
}
println!("Expected: {:?}", expected);
println!("Actual: {:?}", histogram);
let mut max_diff = 0.0;
for (index, actual) in histogram.iter().enumerate() {
let test = expected[index];
let diff = (test - *actual as f64).abs() / test;
assert!(diff >= 0.0 && diff <= margin);
if diff > max_diff {
max_diff = diff;
}
}
println!("Maximum required margin: {}", max_diff);
}
fn laplace_cdf(beta: f64, x: f64) -> f64 {
// We assume mu = 0.
// See https://en.wikipedia.org/wiki/Laplace_distribution
0.5 + 0.5 * x.signum() * (1.0 - (-x.abs() / beta).exp())
}
}
|
extern crate bronx;
extern crate capnp_rpc;
extern crate gj;
use bronx::server::AuthServer;
use bronx::auth_capnp::auth;
use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp};
use gj::{EventLoop, Promise, TaskReaper, TaskSet};
use gj::io::tcp;
fn accept_loop(
listener: tcp::Listener,
mut task_set: TaskSet<(), Box<::std::error::Error>>,
auth_client: auth::Client) -> Promise<(), ::std::io::Error> {
listener.accept().lift().then(move |(listener, stream)| {
let (reader, writer) = stream.split();
let mut network =
twoparty::VatNetwork::new(reader, writer, rpc_twoparty_capnp::Side::Server, Default::default());
let disconnect_promise = network.on_disconnect();
let rpc_system = RpcSystem::new(Box::new(network), Some(auth_client.clone().client));
task_set.add(disconnect_promise.attach(rpc_system).lift());
accept_loop(listener, task_set, auth_client)
})
}
struct Reaper;
impl TaskReaper<(), Box<::std::error::Error>> for Reaper {
fn task_failed(&mut self, error: Box<::std::error::Error>) {
println!("Task failed: {}", error);
}
}
fn main() {
let auth_server = AuthServer::default();
println!("Starting server on {}", auth_server.address);
EventLoop::top_level(move |scope| {
let address = auth_server.get_socket_addr().unwrap();
let listener = try!(tcp::Listener::bind(address));
let task_set = TaskSet::new(Box::new(Reaper));
let auth_client = auth::ToClient::new(auth_server).from_server::<::capnp_rpc::Server>();
try!(accept_loop(listener, task_set, auth_client).wait(scope));
Ok(())
}).expect("Event loop error");
}
|
pub mod gfx {
use std::ffi::CString;
use std::os::raw::c_char;
#[derive(Copy, Clone, Debug)]
pub enum ColorPallete {
Black,
DarkBlue,
DarkPurple,
DarkGreen,
Brown,
DarkGray,
LightGray,
White,
Red,
Orange,
Yellow,
Green,
Blue,
Indigo,
Pink,
Peach,
}
impl From<i32> for ColorPallete {
fn from(color: i32) -> Self {
match color {
0 => ColorPallete::Black,
1 => ColorPallete::DarkBlue,
2 => ColorPallete::DarkPurple,
3 => ColorPallete::DarkGreen,
4 => ColorPallete::Brown,
5 => ColorPallete::DarkGray,
6 => ColorPallete::LightGray,
7 => ColorPallete::White,
8 => ColorPallete::Red,
9 => ColorPallete::Orange,
10 => ColorPallete::Yellow,
11 => ColorPallete::Green,
12 => ColorPallete::Blue,
13 => ColorPallete::Indigo,
14 => ColorPallete::Pink,
15 => ColorPallete::Peach,
_ => panic!("Invalid color {}", color),
}
}
}
impl From<ColorPallete> for i32 {
fn from(color: ColorPallete) -> Self {
match color {
ColorPallete::Black => 0,
ColorPallete::DarkBlue => 1,
ColorPallete::DarkPurple => 2,
ColorPallete::DarkGreen => 3,
ColorPallete::Brown => 4,
ColorPallete::DarkGray => 5,
ColorPallete::LightGray => 6,
ColorPallete::White => 7,
ColorPallete::Red => 8,
ColorPallete::Orange => 9,
ColorPallete::Yellow => 10,
ColorPallete::Green => 11,
ColorPallete::Blue => 12,
ColorPallete::Indigo => 13,
ColorPallete::Pink => 14,
ColorPallete::Peach => 15,
}
}
}
extern "C" {
#[link_name="cls"]
fn _cls(color: i32);
#[link_name="rectfill"]
fn _rectfill(x0: i32, y0: i32, x1: i32, y1: i32, color: i32);
#[link_name="rect"]
fn _rect(x0: i32, y0: i32, x1: i32, y1: i32, color: i32);
#[link_name="pset"]
fn _pset(x: i32, y: i32, c: i32);
#[link_name="pget"]
fn _pget(x: i32, y: i32) -> i32;
#[link_name="print"]
fn _print(string: *const c_char, x: i32, y: i32, col: i32);
#[link_name="printh"]
fn _printh(string: *const c_char);
}
pub fn cls(color: ColorPallete) {
unsafe {
_cls(i32::from(color));
}
}
pub fn rectfill(x0: i32, y0: i32, x1: i32, y1: i32, color: ColorPallete) {
unsafe {
_rectfill(x0, y0, x1, y1, i32::from(color));
}
}
pub fn rect(x0: i32, y0: i32, x1: i32, y1: i32, color: ColorPallete) {
unsafe {
_rect(x0, y0, x1, y1, i32::from(color));
}
}
pub fn pset(x: i32, y: i32, color: ColorPallete) {
unsafe {
_pset(x, y, i32::from(color));
}
}
pub fn pget(x: i32, y: i32) -> ColorPallete {
unsafe {
ColorPallete::from(_pget(x, y))
}
}
pub fn print(string: String, x: i32, y: i32, col: ColorPallete) {
let cstring = CString::new(string).unwrap();
unsafe {
let ptr = cstring.into_raw();
_print(ptr, x, y, i32::from(col));
CString::from_raw(ptr);
}
}
pub fn printh(string: String) {
let cstring = CString::new(string).unwrap();
unsafe {
let ptr = cstring.into_raw();
_printh(ptr);
CString::from_raw(ptr);
}
}
}
pub mod input {
use std::convert::From;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Scancode {
None,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
ZERO,
RETURN,
ESCAPE,
BACKSPACE,
TAB,
SPACE,
MINUS,
EQUALS,
LEFT_BRACKET,
RIGHT_BRACKET,
BACKSLASH,
SEMICOLON,
APOSTROPHE,
GRAVE,
COMMA,
PERIOD,
SLASH,
CAPSLOCK,
}
impl From<Scancode> for i32 {
fn from(scancode: Scancode) -> Self {
match scancode {
Scancode::None => 0,
Scancode::A => 4,
Scancode::B => 5,
Scancode::C => 6,
Scancode::D => 7,
Scancode::E => 8,
Scancode::F => 9,
Scancode::G => 10,
Scancode::H => 11,
Scancode::I => 12,
Scancode::J => 13,
Scancode::K => 14,
Scancode::L => 15,
Scancode::M => 16,
Scancode::N => 17,
Scancode::O => 18,
Scancode::P => 19,
Scancode::Q => 20,
Scancode::R => 21,
Scancode::S => 22,
Scancode::T => 23,
Scancode::U => 24,
Scancode::V => 25,
Scancode::W => 26,
Scancode::X => 27,
Scancode::Y => 28,
Scancode::Z => 29,
Scancode::ONE => 30,
Scancode::TWO => 31,
Scancode::THREE => 32,
Scancode::FOUR => 33,
Scancode::FIVE => 34,
Scancode::SIX => 35,
Scancode::SEVEN => 36,
Scancode::EIGHT => 37,
Scancode::NINE => 38,
Scancode::ZERO => 39,
Scancode::RETURN => 40,
Scancode::ESCAPE => 41,
Scancode::BACKSPACE => 42,
Scancode::TAB => 43,
Scancode::SPACE => 44,
Scancode::MINUS => 45,
Scancode::EQUALS => 46,
Scancode::LEFT_BRACKET => 47,
Scancode::RIGHT_BRACKET => 48,
Scancode::BACKSLASH => 49,
Scancode::SEMICOLON => 51,
Scancode::APOSTROPHE => 52,
Scancode::GRAVE => 53,
Scancode::COMMA => 54,
Scancode::PERIOD => 55,
Scancode::SLASH => 56,
Scancode::CAPSLOCK => 57,
}
}
}
impl From<Scancode> for char {
fn from(scancode: Scancode) -> Self {
match scancode {
Scancode::A => 'A',
Scancode::B => 'B',
Scancode::C => 'C',
Scancode::D => 'D',
Scancode::E => 'E',
Scancode::F => 'F',
Scancode::G => 'G',
Scancode::H => 'H',
Scancode::I => 'I',
Scancode::J => 'J',
Scancode::K => 'K',
Scancode::L => 'L',
Scancode::M => 'M',
Scancode::N => 'N',
Scancode::O => 'O',
Scancode::P => 'P',
Scancode::Q => 'Q',
Scancode::R => 'R',
Scancode::S => 'S',
Scancode::T => 'T',
Scancode::U => 'U',
Scancode::V => 'V',
Scancode::W => 'W',
Scancode::X => 'X',
Scancode::Y => 'Y',
Scancode::Z => 'Z',
Scancode::ONE => '1',
Scancode::TWO => '2',
Scancode::THREE => '3',
Scancode::FOUR => '4',
Scancode::FIVE => '5',
Scancode::SIX => '6',
Scancode::SEVEN => '7',
Scancode::EIGHT => '8',
Scancode::NINE => '9',
Scancode::ZERO => '0',
Scancode::SPACE => ' ',
Scancode::MINUS => '-',
Scancode::EQUALS => '=',
Scancode::LEFT_BRACKET => '(',
Scancode::RIGHT_BRACKET => ')',
Scancode::BACKSLASH => '\\',
Scancode::SEMICOLON => ';',
Scancode::APOSTROPHE => '\'',
Scancode::GRAVE => '`',
Scancode::COMMA => ',',
Scancode::PERIOD => '.',
Scancode::SLASH => '/',
_ => ' ',
}
}
}
impl From<i32> for Scancode {
fn from(scancode: i32) -> Self {
match scancode {
4 => Scancode::A,
5 => Scancode::B,
6 => Scancode::C,
7 => Scancode::D,
8 => Scancode::E,
9 => Scancode::F,
10 => Scancode::G,
11 => Scancode::H,
12 => Scancode::I,
13 => Scancode::J,
14 => Scancode::K,
15 => Scancode::L,
16 => Scancode::M,
17 => Scancode::N,
18 => Scancode::O,
19 => Scancode::P,
20 => Scancode::Q,
21 => Scancode::R,
22 => Scancode::S,
23 => Scancode::T,
24 => Scancode::U,
25 => Scancode::V,
26 => Scancode::W,
27 => Scancode::X,
28 => Scancode::Y,
29 => Scancode::Z,
30 => Scancode::ONE,
31 => Scancode::TWO,
32 => Scancode::THREE,
33 => Scancode::FOUR,
34 => Scancode::FIVE,
35 => Scancode::SIX,
36 => Scancode::SEVEN,
37 => Scancode::EIGHT,
38 => Scancode::NINE,
39 => Scancode::ZERO,
40 => Scancode::RETURN,
41 => Scancode::ESCAPE,
42 => Scancode::BACKSPACE,
43 => Scancode::TAB,
44 => Scancode::SPACE,
45 => Scancode::MINUS,
46 => Scancode::EQUALS,
47 => Scancode::LEFT_BRACKET,
48 => Scancode::RIGHT_BRACKET,
49 => Scancode::BACKSLASH,
51 => Scancode::SEMICOLON,
52 => Scancode::APOSTROPHE,
53 => Scancode::GRAVE,
54 => Scancode::COMMA,
55 => Scancode::PERIOD,
56 => Scancode::SLASH,
57 => Scancode::CAPSLOCK,
_ => Scancode::None,
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Button {
Left,
Right,
Up,
Down,
O,
X,
}
impl From<Button> for i32 {
fn from(player: Button) -> Self {
match player {
Button::Left => 0,
Button::Right => 1,
Button::Up => 2,
Button::Down => 3,
Button::O => 4,
Button::X => 5,
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Player {
One,
Two,
}
impl From<Player> for i32 {
fn from(player: Player) -> Self {
match player {
Player::One => 0,
Player::Two => 1,
}
}
}
extern "C" {
#[link_name="btn"]
fn _btn(i: i32, p: i32) -> i32;
#[link_name="btnp"]
fn _btnp(i: i32, p: i32) -> i32;
#[link_name="key"]
fn _key() -> i32;
}
pub fn btn(button: Button, player: Player) -> bool {
unsafe {
_btn(i32::from(button), i32::from(player)) == 1
}
}
pub fn btnp(button: Button, player: Player) -> bool {
unsafe {
_btnp(i32::from(button), i32::from(player)) == 1
}
}
pub fn key() -> Scancode {
unsafe {
Scancode::from(_key())
}
}
}
pub mod math {
extern "C" {
#[link_name="abs"]
fn _abs(x: f32) -> i32;
#[link_name="atan2"]
fn _atan2(dx: f32, dy: f32) -> f32;
#[link_name="band"]
fn _band(x: i32, y: i32) -> i32;
#[link_name="bnot"]
fn _bnot(x: i32) -> i32;
#[link_name="bor"]
fn _bor(x: i32, y: i32) -> i32;
#[link_name="bxor"]
fn _bxor(x: i32, y: i32) -> i32;
#[link_name="cos"]
fn _cos(x: f32) -> f32;
#[link_name="flr"]
fn _flr(x: f32) -> f32;
#[link_name="min"]
fn _min(x: i32, y: i32) -> i32;
#[link_name="minf"]
fn _minf(x: f32, y: f32) -> f32;
#[link_name="max"]
fn _max(x: i32, y: i32) -> i32;
#[link_name="maxf"]
fn _maxf(x: f32, y: f32) -> f32;
#[link_name="mid"]
fn _mid(x: i32, y: i32, z: i32) -> i32;
#[link_name="rnd"]
fn _rnd(x: i32) -> i32;
#[link_name="srand"]
fn _srand(x: i32);
#[link_name="sgn"]
fn _sgn(x: i32) -> i32;
#[link_name="shl"]
fn _shl(x: i32, y: i32) -> i32;
#[link_name="shr"]
fn _shr(x: i32, y: i32) -> i32;
#[link_name="sin"]
fn _sin(x: f32) -> f32;
#[link_name="sqrt"]
fn _sqrt(x: i32) -> f32;
#[link_name="sqrtf"]
fn _sqrtf(x: f32) -> f32;
}
pub fn abs(x: f32) -> i32 {
unsafe {
_abs(x)
}
}
pub fn atan2(dx: f32, dy: f32) -> f32 {
unsafe {
_atan2(dx, dy)
}
}
pub fn band(x: i32, y: i32) -> i32 {
unsafe {
_band(x, y)
}
}
pub fn bnot(x: i32) -> i32 {
unsafe {
_bnot(x)
}
}
pub fn bor(x: i32, y: i32) -> i32 {
unsafe {
_bor(x, y)
}
}
pub fn bxor(x: i32, y: i32) -> i32 {
unsafe {
_bxor(x, y)
}
}
pub fn cos(x: f32) -> f32 {
unsafe {
_cos(x)
}
}
pub fn flr(x: f32) -> f32 {
unsafe {
_flr(x)
}
}
pub fn min(x: i32, y: i32) -> i32 {
unsafe {
_min(x, y)
}
}
pub fn minf(x: f32, y: f32) -> f32 {
unsafe {
_minf(x, y)
}
}
pub fn max(x: i32, y: i32) -> i32 {
unsafe {
_max(x, y)
}
}
pub fn maxf(x: f32, y: f32) -> f32 {
unsafe {
_maxf(x, y)
}
}
pub fn mid(x: i32, y: i32, z: i32) -> i32 {
unsafe {
_mid(x, y, z)
}
}
pub fn rnd(x: i32) -> i32 {
unsafe {
_rnd(x)
}
}
pub fn srand(x: i32) {
unsafe {
_srand(x);
}
}
pub fn sgn(x: i32) -> i32 {
unsafe {
_sgn(x)
}
}
pub fn shl(x: i32, y: i32) -> i32 {
unsafe {
_shl(x, y)
}
}
pub fn shr(x: i32, y: i32) -> i32 {
unsafe {
_shr(x, y)
}
}
pub fn sin(x: f32) -> f32 {
unsafe {
_sin(x)
}
}
pub fn sqrt(x: i32) -> f32 {
unsafe {
_sqrt(x)
}
}
pub fn sqrtf(x: f32) -> f32 {
unsafe {
_sqrtf(x)
}
}
}
pub mod misc {
use std::{ffi::CString, os::raw::c_char};
extern "C" {
#[link_name="exit"]
fn _exit() -> !;
#[link_name="save"]
fn _save() -> i32;
#[link_name="unload"]
fn _unload();
#[link_name="load"]
fn _load(string: *const c_char);
}
pub fn exit() -> ! {
unsafe {
_exit();
}
}
pub fn save() -> bool {
unsafe {
_save() != 0
}
}
pub fn unload() {
unsafe {
_unload();
}
}
pub fn load(local_cart_path: String) {
let cstring = CString::new(local_cart_path).unwrap();
unsafe {
let ptr = cstring.into_raw();
_load(ptr);
CString::from_raw(ptr);
}
}
} |
mod helpers;
mod routes;
use actix_web::{App, HttpServer};
#[cfg(not(target_arch = "wasm32"))]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(routes::index))
.bind("0.0.0.0:8040")?
.run()
.await
} |
//! # Analog to Digital converter
use core::convert::Infallible;
use core::ptr;
use crate::{
gpio::Analog,
hal::{
adc::{Channel as EmbeddedHalChannel, OneShot},
blocking::delay::DelayUs,
},
pac,
rcc::{AHB2, CCIPR},
};
#[cfg(any(feature = "stm32l4x1", feature = "stm32l4x2", feature = "stm32l4x3",))]
use pac::ADC as ADC1;
#[cfg(any(feature = "stm32l4x5", feature = "stm32l4x6"))]
use pac::ADC1;
/// Analog to Digital converter interface
pub struct ADC {
inner: ADC1,
resolution: Resolution,
sample_time: SampleTime,
}
impl ADC {
/// Initialize the ADC
pub fn new(
inner: ADC1,
ahb: &mut AHB2,
ccipr: &mut CCIPR,
delay: &mut impl DelayUs<u32>,
) -> Self {
// Enable peripheral
ahb.enr().modify(|_, w| w.adcen().set_bit());
// Reset peripheral
ahb.rstr().modify(|_, w| w.adcrst().set_bit());
ahb.rstr().modify(|_, w| w.adcrst().clear_bit());
// Select system clock as ADC clock source
ccipr.ccipr().modify(|_, w| {
// This is sound, as `0b11` is a valid value for this field.
unsafe {
w.adcsel().bits(0b11);
}
w
});
// Initialize the ADC, according to the STM32L4xx Reference Manual,
// section 16.4.6.
inner.cr.write(|w| w.deeppwd().clear_bit()); // exit deep-power-down mode
inner.cr.modify(|_, w| w.advregen().set_bit()); // enable internal voltage regulator
// According to the STM32L4xx Reference Manual, section 16.4.6, we need
// to wait for T_ADCVREG_STUP after enabling the internal voltage
// regulator. For the STM32L433, this is 20 us. We choose 25 us to
// account for bad clocks.
delay.delay_us(25);
// Calibration procedure according to section 16.4.8.
inner.cr.modify(|_, w| {
w.adcal().set_bit(); // start calibration
w.adcaldif().clear_bit(); // single-ended mode
w
});
while inner.cr.read().adcal().bit_is_set() {}
// We need to wait 4 ADC clock after ADCAL goes low, 1 us is more than enough
delay.delay_us(1);
Self {
inner,
resolution: Resolution::default(),
sample_time: SampleTime::default(),
}
}
/// Set the ADC resolution
pub fn set_resolution(&mut self, resolution: Resolution) {
self.resolution = resolution;
}
/// Set the sample time
pub fn set_sample_time(&mut self, sample_time: SampleTime) {
self.sample_time = sample_time;
}
/// Release the ADC peripheral
///
/// Drops `ADC` and returns the `pac::ADC` that is was wrapping, giving the
/// user full access to the peripheral.
pub fn release(self) -> ADC1 {
self.inner
}
}
impl<C> OneShot<ADC, u16, C> for ADC
where
C: Channel,
{
type Error = Infallible;
fn read(&mut self, channel: &mut C) -> nb::Result<u16, Self::Error> {
// Make sure bits are off
while self.inner.cr.read().addis().bit_is_set() {}
// Enable ADC
self.inner.isr.write(|w| w.adrdy().set_bit());
self.inner.cr.modify(|_, w| w.aden().set_bit());
while self.inner.isr.read().adrdy().bit_is_clear() {}
// Configure ADC
self.inner.cfgr.write(|w| {
// This is sound, as all `Resolution` values are valid for this
// field.
unsafe { w.res().bits(self.resolution as u8) }
});
// Configure channel
channel.set_sample_time(&self.inner, self.sample_time);
// Select channel
self.inner.sqr1.write(|w| {
// This is sound, as all `Channel` implementations set valid values.
unsafe {
w.sq1().bits(C::channel());
}
w
});
// Start conversion
self.inner
.isr
.modify(|_, w| w.eos().set_bit().eoc().set_bit());
self.inner.cr.modify(|_, w| w.adstart().set_bit());
while self.inner.isr.read().eos().bit_is_clear() {}
// Read ADC value first time and discard it, as per errata sheet.
// The errata states that if we do conversions slower than 1 kHz, the
// first read ADC value can be corrupted, so we discard it and measure again.
let _ = unsafe { ptr::read_volatile(&self.inner.dr.read().bits()) };
self.inner
.isr
.modify(|_, w| w.eos().set_bit().eoc().set_bit());
self.inner.cr.modify(|_, w| w.adstart().set_bit());
while self.inner.isr.read().eos().bit_is_clear() {}
// Read ADC value
let val = self.inner.dr.read().bits() as u16;
// Disable ADC
self.inner.cr.modify(|_, w| w.addis().set_bit());
Ok(val)
}
}
/// ADC resolution setting
///
/// The default setting is 12 bits.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Resolution {
/// 12-bit resolution
Bits12 = 0b00,
/// 10-bit resolution
Bits10 = 0b01,
/// 8-bit resolution
Bits8 = 0b10,
/// 6-bit resolution
Bits6 = 0b11,
}
impl Default for Resolution {
fn default() -> Self {
Self::Bits12
}
}
/// ADC sample time
///
/// The default setting is 2.5 ADC clock cycles.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum SampleTime {
/// 2.5 ADC clock cycles
Cycles2_5 = 0b000,
/// 6.5 ADC clock cycles
Cycles6_5 = 0b001,
/// 12.5 ADC clock cycles
Cycles12_5 = 0b010,
/// 24.5 ADC clock cycles
Cycles24_5 = 0b011,
/// 47.5 ADC clock cycles
Cycles47_5 = 0b100,
/// 92.5 ADC clock cycles
Cycles92_5 = 0b101,
/// 247.5 ADC clock cycles
Cycles247_5 = 0b110,
/// 640.5 ADC clock cycles
Cycles640_5 = 0b111,
}
impl Default for SampleTime {
fn default() -> Self {
Self::Cycles2_5
}
}
/// Implemented for all types that represent ADC channels
pub trait Channel: EmbeddedHalChannel<ADC, ID = u8> {
fn set_sample_time(&mut self, adc: &ADC1, sample_time: SampleTime);
}
macro_rules! external_channels {
(
$(
$id:expr,
$pin:ident,
$smpr:ident,
$smp:ident;
)*
) => {
$(
impl EmbeddedHalChannel<ADC> for crate::gpio::$pin<Analog> {
type ID = u8;
fn channel() -> Self::ID {
$id
}
}
impl Channel for crate::gpio::$pin<Analog> {
fn set_sample_time(&mut self,
adc: &ADC1,
sample_time: SampleTime,
) {
adc.$smpr.modify(|_, w| {
// This is sound, as all `SampleTime` values are valid
// for this field.
unsafe {
w.$smp().bits(sample_time as u8)
}
})
}
}
)*
};
}
external_channels!(
1, PC0, smpr1, smp1;
2, PC1, smpr1, smp2;
3, PC2, smpr1, smp3;
4, PC3, smpr1, smp4;
5, PA0, smpr1, smp5;
6, PA1, smpr1, smp6;
7, PA2, smpr1, smp7;
8, PA3, smpr1, smp8;
9, PA4, smpr1, smp9;
10, PA5, smpr2, smp10;
11, PA6, smpr2, smp11;
12, PA7, smpr2, smp12;
13, PC4, smpr2, smp13;
14, PC5, smpr2, smp14;
15, PB0, smpr2, smp15;
16, PB1, smpr2, smp16;
);
|
///
/// ## ethernet.rs
///
/// Data structures and functions for handling the Ethernet protocol
///
use crate::util::mac_to_str;
use log::error;
use num_derive::{FromPrimitive};
use num_traits::{FromPrimitive};
#[derive(FromPrimitive, Copy, Clone, PartialEq, Debug)]
#[repr(u16)]
pub enum EtherType {
NotSet = 0,
// length 0x0000-0x05DC
// experimental 0x0101-0x01FF
Ipv4 = 0x0800,
Arp = 0x0806,
WakeOnLan = 0x0842,
AudioVideoTransProto = 0x22f0,
IetfTrillProto = 0x22f3,
StreamReservProto = 0x22ea,
DecMopRc = 0x6002,
DecnetPhase4 = 0x6003,
DecLat = 0x6004,
Rarp = 0x8035,
AppleTalk = 0x809b,
AppleTalkArp = 0x80f3,
VlanTag = 0x8100,
SimpleLoopPreventProto = 0x8102,
Ipx = 0x8137,
QnxQnet = 0x8204,
Ipv6 = 0x86dd,
EtherFlowCtrl = 0x8808,
EtherSlowProto = 0x8809,
CobraNet = 0x8819,
MplsUnicast = 0x8847,
MplsMulticast = 0x8848,
PppoeDiscovery = 0x8863,
PppoeSession = 0x8864,
IntelAdvNetSvc = 0x886d,
HomePlug1Mme = 0x887b,
EapOLan8021x = 0x888e,
ProfinetProto = 0x8892,
HyperScsi = 0x889a,
AtaOverEther = 0x88a2,
EtherCatProto = 0x88a4,
ProviderBridging = 0x88a8,
EthernetPowerlink = 0x88ab,
Goose = 0x88b7,
GseMgmtSvc = 0x88b9,
SampledValXmit = 0x88ba,
Lldp = 0x88cc,
Sercos3 = 0x88cd,
WaveShortMsgProto = 0x88dc,
HomePlugAvMme = 0x88e1,
MediaRedundancyProto = 0x88e3,
MacSec = 0x88e5,
ProviderBackboneBridges = 0x88e7,
PrecisionTimeProto = 0x88f7,
NcSi = 0x88f8,
ParallelRedundancyProto = 0x88fb,
ConnectivityFaultMgmt = 0x8902,
FiberChanOverEther = 0x8906,
FcoeInitProto = 0x8914,
RdmaOverConvergedEther = 0x8915,
TTEtherProtoCtrlFrame = 0x891d,
HighAvailSeamlessRedundancy = 0x892f,
EtherConfigTestingProto = 0x9000,
VlanDoubleTagging = 0x9100,
VeritasTechLowLatencyTrans = 0xcafe,
}
impl Default for EtherType {
fn default() -> Self {
EtherType::NotSet
}
}
impl EtherType {
pub const SHORTEST_PATH_BRIDGING88A8: EtherType = EtherType::ProviderBridging;
pub const DNA_ROUTING: EtherType = EtherType::DecnetPhase4;
pub const SHORTEST_PATH_BRIDGING: EtherType = EtherType::VlanTag;
pub fn from_bytes(b: &[u8]) -> EtherType {
let type_val = u16::to_be((b[1] as u16) << 8 | b[0] as u16);
match EtherType::from_u16(type_val) {
Some(val) => val,
None => {
error!("invalid/unhandled Ether Type: {:02X}", type_val);
EtherType::NotSet
}
}
}
}
#[derive(Copy, Clone, Default)]
#[repr(C)]
pub struct EthernetFrame {
pub dest_addr: [u8; 6],
pub src_addr: [u8; 6],
pub ether_type: EtherType,
}
impl EthernetFrame {
pub fn new(raw_packet_data: &[u8]) -> EthernetFrame {
let mut x: EthernetFrame = Default::default();
x.dest_addr.copy_from_slice(&raw_packet_data[0..6]);
x.src_addr.copy_from_slice(&raw_packet_data[6..12]);
x.ether_type = EtherType::from_bytes(&raw_packet_data[12..14]);
x
}
pub fn to_string(self) -> String {
return format!(
"src: {}, dst: {}, type: {:?}",
mac_to_str(&self.src_addr),
mac_to_str(&self.dest_addr),
self.ether_type
);
}
}
#[repr(C)]
pub struct LlcPacket {
dsap: u8, // dest svc access point, dest net layer proto type
ssap: u8, // src svc access point, src net layer proto type
control: u8,
}
#[repr(C)]
pub struct EtherSnapPacket {
org_code: [u8; 3], // org code, which org assigned ether type field,
ether_type: [u8; 2], // which upper layer proto will use the ether frame
}
// end of file |
use termion::color::{Green, Magenta, Red, White, Yellow};
// Formats string with color.
// Requires `termion` crate.
#[macro_export]
macro_rules! bold {
($val:expr) => {{
use termion::style::{Bold, NoBold};
format!("{b1}{}{b0}", $val, b1 = Bold, b0 = NoBold)
}};
}
// Formats string with color.
// Requires `termion` crate.
#[macro_export]
macro_rules! color {
($clr:expr, $val:expr) => {{
use termion::color::{Fg, Reset};
format!("{c1}{}{c0}", $val, c1 = Fg($clr), c0 = Fg(Reset))
}};
($clr:expr, $val:expr, $opt:expr) => {{
use termion::color::{Fg, Reset};
format!("{c1}{}{c0}{}", $val, $opt, c1 = Fg($clr), c0 = Fg(Reset))
}};
}
fn main() {
// let b = bold!("Hello, world!");
// let c = color!(Yellow, &b);
// println!("{}", c);
let first = color!(Green, "● ● ● ● ●", " , ");
// let d = color!(White, "||", " ");
let second = color!(Green, "● ● ● ● ●", " | ");
let third = color!(Green, "● ● ● ● ●");
println!("{}{}{}", first, second, third);
}
|
use std::default::Default;
use std::iter::Enumerate;
use std::slice::Iter;
/// A vector that can start at an index other than `0`.
#[derive(Debug, Clone)]
pub struct OffsetVector<T> {
start: usize,
vec: Vec<T>,
}
impl<T> OffsetVector<T> {
/// Creates an offset vector from a standard `Vec<T>` with a
/// specified starting point.
pub fn new(start: usize, vec: Vec<T>) -> Self {
OffsetVector {
start: start,
vec: vec,
}
}
#[allow(dead_code)]
pub fn len(&self) -> usize {
self.vec.len()
}
#[allow(dead_code)]
pub fn start(&self) -> usize {
self.start
}
#[allow(dead_code)]
pub fn end(&self) -> usize {
self.start + self.vec.len()
}
#[allow(dead_code)]
pub fn get(&self, index: usize) -> Option<&T> {
if index >= self.start {
self.vec.get(index - self.start)
} else {
None
}
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if index >= self.start {
self.vec.get_mut(index - self.start)
} else {
None
}
}
#[allow(dead_code)]
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
self.vec.iter()
}
pub fn pos_iter(&self) -> PosIter<T> {
PosIter {
start: self.start,
inner: self.vec.iter().enumerate(),
}
}
pub fn map_to<F, S>(&self, f: F) -> OffsetVector<S>
where
F: FnMut(&T) -> S,
{
OffsetVector {
start: self.start,
vec: self.vec.iter().map(f).collect(),
}
}
}
impl<T> OffsetVector<T>
where
T: Default,
{
#[allow(dead_code)]
pub fn new_with_default(start: usize, len: usize) -> Self {
let mut vec = Vec::with_capacity(len);
for _ in 0..len {
vec.push(Default::default())
}
Self::new(start, vec)
}
}
#[derive(Debug, Clone)]
pub struct PosIter<'a, T>
where
T: 'a,
{
start: usize,
inner: Enumerate<Iter<'a, T>>,
}
impl<'a, T> Iterator for PosIter<'a, T> {
type Item = (usize, &'a T);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(pos, ap)| (pos + self.start, ap))
}
}
|
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
pub type CChar = i8;
use std::ffi::CString;
use std::str;
pub struct Scanner {
data: CString,
ps: *const CChar,
p: *const CChar,
pe: *const CChar,
eof: *const CChar,
checkpoint: *const CChar,
token: T,
ts: u32,
te: u32,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Token {
pub tok: T,
pub lit: String,
}
impl Scanner {
// New creates a scanner with the provided input.
pub fn new(data: CString) -> Scanner {
let ptr = data.as_ptr();
let bytes = data.as_bytes();
let end = ((ptr as usize) + bytes.len()) as *const CChar;
return Scanner {
data: data,
ps: ptr,
p: ptr,
pe: end,
eof: end,
ts: 0,
te: 0,
token: T_ILLEGAL,
checkpoint: ptr,
};
}
// scan produces the next token from the input.
pub fn scan(&mut self) -> Token {
self._scan(false)
}
// scan_with_regex produces the next token from the input accounting for regex.
pub fn scan_with_regex(&mut self) -> Token {
self._scan(true)
}
fn _scan(&mut self, with_regex: bool) -> Token {
if self.p == self.eof {
return Token {
tok: T_EOF,
lit: String::from(""),
};
}
self.checkpoint = self.p;
unsafe {
let error = scan(
if with_regex { 1 } else { 0 },
&mut self.p as *mut *const CChar,
self.ps as *const CChar,
self.pe as *const CChar,
self.eof as *const CChar,
&mut self.token as *mut u32,
&mut self.ts as *mut u32,
&mut self.te as *mut u32,
);
if error != 0 {
// Execution failed meaning we hit a pattern that we don't support and
// doesn't produce a token. Use the unicode library to decode the next character
// in the sequence so we don't break up any unicode tokens.
let nc = std::str::from_utf8_unchecked(&self.data.as_bytes()[(self.ts as usize)..])
.chars()
.next();
match nc {
Some(nc) => {
let size = nc.len_utf8();
// Advance the data pointer to after the character we just emitted.
self.p = self.p.offset(size as isize);
return Token {
tok: T_ILLEGAL,
lit: nc.to_string(),
};
}
// This should be impossible as we would have produced an EOF token
// instead, but going to handle this anyway as in this impossible scenario
// we would enter an infinite loop if we continued scanning past the token.
None => {
return Token {
tok: T_EOF,
lit: String::from(""),
}
}
}
}
if self.token == T_ILLEGAL && self.p == self.eof {
return Token {
tok: T_EOF,
lit: String::from(""),
};
}
let t = Token {
tok: self.token,
lit: String::from(str::from_utf8_unchecked(
&self.data.as_bytes()[(self.ts as usize)..(self.te as usize)],
)),
};
// skipping comments.
// TODO(affo): return comments to attach them to nodes within the AST.
match t {
Token { tok: T_COMMENT, .. } => self.scan(),
_ => t,
}
}
}
// unread will reset the Scanner to go back to the Scanner's location
// before the last scan_with_regex or scan call. If either of the scan_with_regex methods
// returned an EOF token, a call to unread will not unread the discarded whitespace.
// This method is a no-op if called multiple times.
pub fn unread(&mut self) {
self.p = self.checkpoint;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
#[test]
fn test_scan() {
let text = "from(bucket:\"foo\") |> range(start: -1m)";
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("from"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_LPAREN,
lit: String::from("("),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("bucket"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_COLON,
lit: String::from(":"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_STRING,
lit: String::from("\"foo\""),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_RPAREN,
lit: String::from(")"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_PIPE_FORWARD,
lit: String::from("|>"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("range"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_LPAREN,
lit: String::from("("),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("start"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_COLON,
lit: String::from(":"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_SUB,
lit: String::from("-"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_DURATION,
lit: String::from("1m"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_RPAREN,
lit: String::from(")"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
}
#[test]
fn test_scan_with_regex() {
let text = "a + b =~ /.*[0-9]/ / 2";
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_IDENT,
lit: String::from("a"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_ADD,
lit: String::from("+"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_IDENT,
lit: String::from("b"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_REGEXEQ,
lit: String::from("=~"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_REGEX,
lit: String::from("/.*[0-9]/"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_DIV,
lit: String::from("/"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_INT,
lit: String::from("2"),
}
);
}
#[test]
fn test_scan_unread() {
let text = "1 / 2 / 3";
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_INT,
lit: String::from("1"),
}
);
s.unread();
assert_eq!(
s.scan(),
Token {
tok: T_INT,
lit: String::from("1"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_REGEX,
lit: String::from("/ 2 /"),
}
);
s.unread();
assert_eq!(
s.scan(),
Token {
tok: T_DIV,
lit: String::from("/"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_INT,
lit: String::from("2"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_DIV,
lit: String::from("/"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_INT,
lit: String::from("3"),
}
);
// test unread idempotence
s.unread();
s.unread();
s.unread();
s.unread();
assert_eq!(
s.scan(),
Token {
tok: T_INT,
lit: String::from("3"),
}
);
}
#[test]
fn test_scan_comments() {
let text = r#"// this is a comment.
a
// comment with // nested comment.
// one more.
// last but not least.
1
// ok, that's it."#;
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("a"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_INT,
lit: String::from("1"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
// with regex
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_IDENT,
lit: String::from("a"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_INT,
lit: String::from("1"),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
}
#[test]
fn test_scan_eof() {
let text = r#""#;
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
// idempotence with and without regex.
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
}
#[test]
fn test_scan_eof_trailing_spaces() {
let mut text = String::new();
text.push(' ');
text.push('\t');
text.push('\n');
text.push('\t');
text.push(' ');
text.push('\t');
text.push('\t');
let cdata = CString::new(text.clone()).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
let cdata = CString::new(text.clone()).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan_with_regex(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
}
// TODO(affo): this fails.
#[test]
#[ignore] // See https://github.com/influxdata/flux/issues/1448
fn test_scan_duration() {
let text = r#"dur = 1y3mo2w1d4h1m30s1ms2µs70ns"#;
let cdata = CString::new(text).expect("CString::new failed");
let mut s = Scanner::new(cdata);
assert_eq!(
s.scan(),
Token {
tok: T_IDENT,
lit: String::from("dur"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_ASSIGN,
lit: String::from("="),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_DURATION,
lit: String::from("1y3mo2w1d4h1m30s1ms2µs70ns"),
}
);
assert_eq!(
s.scan(),
Token {
tok: T_EOF,
lit: String::from(""),
}
);
}
}
|
/*!
```rudra-poc
[target]
crate = "stack_dst"
version = "0.6.0"
[report]
issue_url = "https://github.com/thepowersgang/stack_dst-rs/issues/5"
issue_date = 2021-02-22
rustsec_url = "https://github.com/RustSec/advisory-db/pull/799"
rustsec_id = "RUSTSEC-2021-0033"
[[bugs]]
analyzer = "UnsafeDataflow"
bug_class = "PanicSafety"
rudra_report_locations = ["src/stack.rs:184:2: 202:3"]
```
!*/
#![forbid(unsafe_code)]
use stack_dst::StackA;
#[derive(Debug)]
struct DropDetector(u32);
impl Drop for DropDetector {
fn drop(&mut self) {
println!("Dropping {}", self.0);
}
}
impl Clone for DropDetector {
fn clone(&self) -> Self { panic!("Panic in clone()") }
}
fn main() {
let mut stack = StackA::<[DropDetector], [usize; 9]>::new();
stack.push_stable([DropDetector(1)], |p| p).unwrap();
stack.push_stable([DropDetector(2)], |p| p).unwrap();
println!("Popping off second drop detector");
let second_drop = stack.pop();
println!("Pushing panicky-clone");
stack.push_cloned(&[DropDetector(3)]).unwrap();
} |
use std::fmt::{Display, Formatter};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub enum PowResponse1<Rs, Pz> {
R1(Pz),
R2(Rs),
Err(PowResponseErr),
}
#[derive(Serialize, Deserialize)]
pub enum PowResponse2<Rs> {
Ok(Rs),
Err(PowResponseErr),
}
#[derive(Serialize, Deserialize, Debug, ::thiserror::Error)]
pub enum PowResponseErr {
BadRequest(String),
IllegalState(String),
WrongPuzzle
}
impl Display for PowResponseErr {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let s = match self {
PowResponseErr::BadRequest(msg) => {format!("BadRequest {}", msg)}
PowResponseErr::IllegalState(msg) => {format!("IllegalState {}", msg)}
PowResponseErr::WrongPuzzle => {"WrongPuzzle".to_string()}
};
write!(f, "{}", s)
}
} |
#![allow(deprecated)]
extern crate nix;
extern crate procfs;
extern crate memchr;
extern crate libc;
extern crate signal;
#[macro_use]
extern crate human_panic;
#[macro_use]
extern crate log;
extern crate env_logger;
mod memory;
use std::{thread, time, mem, ptr, fs, process};
use std::fs::File;
use std::io::prelude::*;
use std::time::Instant;
use nix::sys::ptrace;
use nix::sys::ptrace::Request;
use nix::sys::wait::WaitStatus;
use nix::sys::signal::SIGINT;
use signal::trap::Trap;
static PROCESS_NAME: &str = "steam";
static MODULE_NAME: &str = "steamservice.so";
static PATTERN: &str = "55 B9 32 00 00 00 57 56 31 F6 53 89 F0 E8 B9 F2";
fn main() {
// Setup beautiful panics for user-friendliness and logging
setup_panic!();
env_logger::init();
// Make sure we have root privileges
if !nix::unistd::geteuid().is_root() {
eprintln!("[-] No root privileges!");
return;
}
println!("[+] VAC3 Dumper started.");
let process = memory::process::Process::new(PROCESS_NAME);
let mut pid = 0;
// Setup extra watchdog thread which exists the tool on SIGINT (e.g. ctrl-c)
let trap = Trap::trap(&[SIGINT]);
thread::spawn(move || {
while Some(SIGINT) != trap.wait(Instant::now()) {
let ten_millis = time::Duration::from_millis(10);
thread::sleep(ten_millis);
}
println!("[*] Shutdown. Make sure to restart Steam and the game!");
process::exit(0x0100);
});
match process {
Some(p) => {
println!("[+] Steam process found: {}", p.pid);
// Grab the steamservice.so module
let module = match p.modules.iter().find(|x| x.module_name == MODULE_NAME.to_string()) {
Some(module) => { module }
None => {
panic!("[-] Could not find {}", MODULE_NAME);
}
};
// Find the address of the ELF loader function
let elf_loader = module.start_address + match p.find_pattern(MODULE_NAME.to_string(), PATTERN.to_string()) {
Some(elf_loader) => { elf_loader }
None => {
panic!("[-] Could not find ELF Loader function");
}
};
println!("[+] ELF Loader found: 0x{:x}", elf_loader as u64);
// Wait for steam to spawn the thread which is used for manually loading the shared library
loop {
let paths = fs::read_dir(format!("/proc/{}/task", p.pid)).unwrap();
for path in paths {
let dir = path.unwrap();
let mut path_buffer = dir.path();
path_buffer.push("status");
let mut f = match File::open(path_buffer) {
Ok(f) => { f },
Err(_e) => { continue; }
};
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("something went wrong reading the file");
// The thread which calls the ELF loader function has a specific name
if contents.contains("ClientModuleMan") {
let folder = dir.file_name();
let name = folder.to_str().unwrap();
pid = String::from(name).parse::<i32>().unwrap();
}
}
if pid != 0 {
println!("[+] Loader thread found.");
break;
}
}
// Attach to thread loader thread
match ptrace::attach(nix::unistd::Pid::from_raw(pid)) {
Ok(_r) => {
println!("[+] Attached to loader thread.");
}
Err(e) => {
panic!("[-] Could not attach to process: {}", e);
}
}
// Wait for stop signal to be sure we are attached
match nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(pid), None) {
Ok(_wait_status) => {}
Err(e) => {
panic!("[-] Could not wait for process: {}", e);
}
}
// Create backup of current function start
let mut backup_data = unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_PEEKTEXT, nix::unistd::Pid::from_raw(pid), elf_loader as *mut nix::libc::c_void, ptr::null_mut()) {
Ok(backup_data) => { backup_data }
Err(e) => {
panic!("[-] Could not peektext: {}", e);
}
}
};
debug!("[+] Original data: 0x{:x}", backup_data);
// Insert breakpoint (int 3) into the current instructions
let int3 = 0xCC;
let data_with_trap = (backup_data & 0xFFFFFF00) | int3;
// Write edited data back to the function start
unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_POKETEXT, nix::unistd::Pid::from_raw(pid), elf_loader as *mut nix::libc::c_void, data_with_trap as *mut nix::libc::c_void) {
Err(e) => {
panic!("[-] Could not poketxt: {}", e);
}
_ => {}
}
};
// Reread the function start so check if software interrupt instruction (int 3) was placed correctly
let mut new_data = unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_PEEKTEXT, nix::unistd::Pid::from_raw(pid), elf_loader as *mut nix::libc::c_void, ptr::null_mut()) {
Ok(new_data) => { new_data }
Err(e) => {
panic!("[-] Could not peektext: {}", e);
}
}
};
debug!("[+] Replaced data: 0x{:x}", new_data);
match ptrace::cont(nix::unistd::Pid::from_raw(pid), None) {
Err(e) => {
panic!("[-] Could not continue process: {}", e);
}
_ => {}
}
// We want to do this in a loop because there are typically multiple modules loaded during
// the runtime of the game.
loop {
// Wait for the loader thread to hit our breakpoint
match nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(pid), None) {
Ok(wait_status) => {
match wait_status {
WaitStatus::Stopped(_pid, signal) => {
debug!("[+] Traced process was stopped/trapped! Signal: {:?}", signal);
}
WaitStatus::Signaled(_pid, signal, _dumped) => {
panic!("[-] Traced process was terminated! Signal:{:?}", signal);
}
_ => {
panic!("[-] Traced process was <unknown>");
}
}
}
Err(e) => {
panic!("[-] Could not wait for process: {}", e);
}
}
let mut registers: libc::user_regs_struct;
registers = unsafe { mem::uninitialized() };
registers.rip = 0;
// Read the current registers
unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_GETREGS, nix::unistd::Pid::from_raw(pid), ptr::null_mut(), std::mem::transmute::<&libc::user_regs_struct, *mut libc::c_void>(®isters)) {
Err(e) => {
panic!("[-] Could not poketxt: {}", e);
}
_ => {}
}
};
// There is no way the instruction pointer is currently at 0x0
assert_ne!(registers.rip, 0);
// Check if instruction pointer is where we expect it to be (start of function + 1)
if registers.rip == (elf_loader + 1) {
debug!("[+] Thread {} at bp!", pid);
debug!("[+] RIP: 0x{:x}", registers.rip);
// Size of the buffer which contains the module is the first function argument (stackpointer + 12)
let size = unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_PEEKTEXT, nix::unistd::Pid::from_raw(pid), (registers.rsp + 12) as *mut nix::libc::c_void, ptr::null_mut()) {
Ok(new_data) => { new_data as u32 }
Err(e) => {
panic!("[-] Could not peektext: {}", e);
}
}
};
// Pointer to buffer which contains the module is the second function argument (stackpointer + 8)
let buffer = unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_PEEKTEXT, nix::unistd::Pid::from_raw(pid), (registers.rsp + 8) as *mut nix::libc::c_void, ptr::null_mut()) {
Ok(new_data) => { new_data as u32 }
Err(e) => {
panic!("[-] Could not peektext: {}", e);
}
}
};
let mut buffer_data = vec![];
// Read the buffer which contains the module (a single byte per read)
for n in 0..size {
let chunk = unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_PEEKTEXT, nix::unistd::Pid::from_raw(pid), (buffer + n) as *mut nix::libc::c_void, ptr::null_mut()) {
Ok(new_data) => { new_data as u8 }
Err(e) => {
panic!("[-] Could not peektext: {}", e);
}
}
};
buffer_data.push(chunk);
}
// Save the module (<size>.so) to disk
let mut f = File::create(format!("{}.so", size)).expect("Unable to create file");
let _ = f.write_all(&buffer_data);
println!("[+] New module loaded and dumped: {}.so [0x{:x}, {:x}]", size, buffer, size);
// Restore the original function start because we need to be able to run this function correctly
// to load the VAC3 module correctly
unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_POKETEXT, nix::unistd::Pid::from_raw(pid), elf_loader as *mut nix::libc::c_void, backup_data as *mut nix::libc::c_void) {
Err(e) => {
panic!("[-] Could not poketext: {}", e);
}
_ => {}
}
};
// Instruction pointer needs to go one step backwards (because currently it points to start of the function + 1)
registers.rip -= 1;
// Write edited registers back (we edited rip)
unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_SETREGS, nix::unistd::Pid::from_raw(pid), ptr::null_mut(), std::mem::transmute::<&libc::user_regs_struct, *mut libc::c_void>(®isters)) {
Err(e) => {
panic!("[-] Could not setregs: {}", e);
}
_ => {}
}
};
// Step over the next 5 instructions
for _ in 0..5 {
// Step a single instruction
match ptrace::step(nix::unistd::Pid::from_raw(pid), None) {
Err(e) => {
panic!("[-] Could not single step: {}", e);
}
_ => {}
}
// Wait for stop signal
match nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(pid), None) {
Ok(wait_status) => {
match wait_status {
WaitStatus::Stopped(_pid, signal) => {
debug!("[+] Traced process was stopped/trapped! Signal: {:?}", signal);
}
WaitStatus::Signaled(_pid, signal, _dumped) => {
panic!("[-] Traced process was terminated! Signal:{:?}", signal);
}
_ => {
panic!("[-] Traced process was <unknown>");
}
}
}
Err(e) => {
panic!("[-] Could not wait for process: {}", e);
}
}
}
// We are now at function start + 5 and can safely write our breakpoint back to the function start
// to be able to break the next time the loader function gets called (for the next module)
unsafe {
match nix::sys::ptrace::ptrace(Request::PTRACE_POKETEXT, nix::unistd::Pid::from_raw(pid), elf_loader as *mut nix::libc::c_void, data_with_trap as *mut nix::libc::c_void) {
Err(e) => {
panic!("[-] Could not poketxt: {}", e);
}
Ok(_r) => {
debug!("[+] Poketext");
}
}
};
}
// Continue and wait for next breakpoint to be hit
match ptrace::cont(nix::unistd::Pid::from_raw(pid), None) {
Err(e) => {
panic!("[-] Could not continue process: {}", e);
}
Ok(_r) => {
debug!("[+] Continue");
}
}
}
}
None => {
eprintln!("[-] Steam process not found. Please start Steam!");
}
}
}
|
use libc::c_int;
#[link(name = "elevator1")]
extern {
pub fn elevator1_poll_floor_request() -> c_int;
}
#[link(name = "elevator2")]
extern {
pub fn elevator2_poll_floor_request() -> c_int;
}
#[link(name = "elevator3")]
extern {
pub fn elevator3_poll_floor_request() -> c_int;
}
pub trait ElevatorDriver
{
fn poll_floor_request(&self) -> Option<u64>;
}
pub struct ElevatorDriver1;
impl ElevatorDriver for ElevatorDriver1
{
fn poll_floor_request(&self) -> Option<u64>
{
unsafe {
let req = elevator1_poll_floor_request();
if req > 0 {
Some(req as u64)
} else {
None
}
}
}
}
pub struct ElevatorDriver2;
impl ElevatorDriver for ElevatorDriver2
{
fn poll_floor_request(&self) -> Option<u64>
{
unsafe {
let req = elevator2_poll_floor_request();
if req > 0 {
Some(req as u64)
} else {
None
}
}
}
}
pub struct ElevatorDriver3;
impl ElevatorDriver for ElevatorDriver3
{
fn poll_floor_request(&self) -> Option<u64>
{
unsafe {
let req = elevator3_poll_floor_request();
if req > 0 {
Some(req as u64)
} else {
None
}
}
}
}
|
#[derive(Debug, Clone)]
pub struct Multichoose {
state: Vec<usize>,
status: Status,
dim: usize,
n: usize,
end: Vec<usize>,
}
#[derive(Debug, Clone)]
enum Status {
Ini,
Run,
End,
}
impl Multichoose {
pub fn new( dim: usize, n: usize ) -> Self {
Multichoose {
state: vec![ 0; dim ],
status: Status::Ini,
dim,
n,
end: vec![ n-1; dim ],
}
}
}
#[cfg(feature = "streaming")]
mod streaming_iterator {
use super::{Multichoose, Status};
use streaming_iterator::StreamingIterator;
impl StreamingIterator for Multichoose {
type Item = [usize];
fn advance(&mut self) {
match self.status {
Status::Ini => { self.status = Status::Run; },
Status::Run => {
if self.state == self.end {
self.status = Status::End;
} else {
// 1 を足す
self.state[self.dim-1] += 1;
while {
// 繰り上げ処理
for idx in (1..self.dim).rev() {
if self.state[idx] == self.n {
self.state[idx-1] += 1;
}
}
for idx in 1..self.dim {
if self.state[idx] == self.n {
self.state[idx] = self.state[idx-1];
}
}
self.state[self.dim-1] >= self.n
} {}
}
},
Status::End => {},
}
}
fn get(&self) -> Option<&[usize]> {
match self.status {
Status::Run => Some(&self.state),
_ => None,
}
}
}
}
#[cfg(not(feature = "streaming"))]
mod iterator {
use super::{Multichoose, Status};
use std::iter::Iterator;
impl Iterator for Multichoose {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Vec<usize>> {
match self.status {
Status::Ini => { self.status = Status::Run; },
Status::Run => {
if self.state == self.end {
self.status = Status::End;
} else {
// 1 を足す
self.state[self.dim-1] += 1;
while {
// 繰り上げ処理
for idx in (1..self.dim).rev() {
if self.state[idx] == self.n {
self.state[idx-1] += 1;
}
}
for idx in 1..self.dim {
if self.state[idx] == self.n {
self.state[idx] = self.state[idx-1];
}
}
self.state[self.dim-1] >= self.n
} {}
}
},
Status::End => {},
}
match self.status {
Status::Run => Some(self.state.clone()),
_ => None,
}
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn detail() {
let dim = 3;
let n = 4;
let mut iter = Multichoose::new( dim, n );
assert_eq!( iter.next().unwrap(), &[0,0,0] );
assert_eq!( iter.next().unwrap(), &[0,0,1] );
assert_eq!( iter.next().unwrap(), &[0,0,2] );
assert_eq!( iter.next().unwrap(), &[0,0,3] );
assert_eq!( iter.next().unwrap(), &[0,1,1] );
assert_eq!( iter.next().unwrap(), &[0,1,2] );
assert_eq!( iter.next().unwrap(), &[0,1,3] );
assert_eq!( iter.next().unwrap(), &[0,2,2] );
assert_eq!( iter.next().unwrap(), &[0,2,3] );
assert_eq!( iter.next().unwrap(), &[0,3,3] );
assert_eq!( iter.next().unwrap(), &[1,1,1] );
assert_eq!( iter.next().unwrap(), &[1,1,2] );
assert_eq!( iter.next().unwrap(), &[1,1,3] );
assert_eq!( iter.next().unwrap(), &[1,2,2] );
assert_eq!( iter.next().unwrap(), &[1,2,3] );
assert_eq!( iter.next().unwrap(), &[1,3,3] );
assert_eq!( iter.next().unwrap(), &[2,2,2] );
assert_eq!( iter.next().unwrap(), &[2,2,3] );
assert_eq!( iter.next().unwrap(), &[2,3,3] );
assert_eq!( iter.next().unwrap(), &[3,3,3] );
assert_eq!( iter.next(), None );
}
}
|
use druid::piet::StrokeStyle;
use druid::{kurbo::Shape, PaintCtx};
use druid::{Color, Data, Point, Rect, RenderContext, Size, Vec2};
use crate::Paintable;
use image::DynamicImage;
use std::sync::Arc;
mod rect;
trait SelectionShape: Shape {
fn size(&self) -> Size;
fn description(&self) -> String;
fn copy(&self, img: Arc<DynamicImage>, mode: CopyMode) -> Option<Arc<DynamicImage>>;
fn cutout(&self, img: Arc<DynamicImage>) -> Option<Arc<DynamicImage>>;
fn contains(&self, pt: Point) -> bool;
fn transform(&self, offset: Vec2) -> Self;
fn same(&self, other: &Self) -> bool;
}
#[derive(Debug, Clone)]
pub enum Selection {
Rect(Rect),
}
impl_from! {
Selection : [
Rect => Rect
]
}
pub enum CopyMode {
Shrink,
Expand,
}
impl Selection {
pub fn description(&self) -> String {
match self {
Selection::Rect(rt) => rt.description(),
}
}
fn size(&self) -> Size {
match self {
Selection::Rect(rt) => rt.size(),
}
}
pub fn area(&self) -> f64 {
match self {
Selection::Rect(rt) => rt.area(),
}
}
pub fn copy(&self, img: Arc<DynamicImage>, mode: CopyMode) -> Option<Arc<DynamicImage>> {
match self {
Selection::Rect(rect) => rect.copy(img, mode),
}
}
pub fn cutout(&self, img: Arc<DynamicImage>) -> Option<Arc<DynamicImage>> {
match self {
Selection::Rect(rect) => rect.cutout(img),
}
}
pub fn shape(&self) -> impl Shape {
match self {
Selection::Rect(rt) => *rt,
}
}
pub fn contains(&self, pt: Point) -> bool {
match self {
Selection::Rect(rt) => rt.contains(pt),
}
}
pub fn transform(&self, offset: Vec2) -> Selection {
match self {
Selection::Rect(rt) => rt.transform(offset).into(),
}
}
pub fn position(&self) -> Point {
self.shape().bounding_box().origin()
}
}
impl Data for Selection {
fn same(&self, other: &Self) -> bool {
match (self, other) {
(Selection::Rect(a), Selection::Rect(b)) => a == b,
}
}
}
impl Paintable for Selection {
fn paint(&self, paint_ctx: &mut PaintCtx) {
// Create a color
let stroke_color = Color::rgb8(0xff, 0xff, 0xff);
let mut style = StrokeStyle::new();
let dashes = vec![2.0, 2.0];
style.set_dash(dashes, 0.0);
paint_ctx.render_ctx.stroke_styled(self.shape(), &stroke_color, 1.0, &style);
}
fn paint_size(&self) -> Option<Size> {
Some(self.size())
}
}
|
use crate::errors::ApiError;
use std::{
fs::{File, OpenOptions},
io::{BufRead, BufReader, BufWriter, Error, Write},
};
use serde::{Deserialize, Serialize};
use std::path::Path;
use walkdir::WalkDir;
static SEPARATOR: &str = "-----";
#[derive(Serialize, Deserialize, Debug)]
pub struct Info {
pub metadata: Option<Vec<String>>,
pub filename: String,
pub logs: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Response {
pub message: String,
pub status: bool,
}
impl Response {
pub fn new(message: String, status: bool) -> Self {
Response { message, status }
}
}
impl Info {
pub fn check_file(path: &str) -> Result<bool, Error> {
if !Path::new(path).exists() {
File::create(path)?;
return Ok(false);
}
return Ok(true);
}
pub fn new(filename: String, logs: Vec<String>, metadata: Vec<String>) -> Info {
Info {
filename,
logs: Some(logs),
metadata: Some(metadata),
}
}
pub fn save(info: Self) -> Result<Response, ApiError> {
let path: String = format!("./logs/{}.log", &info.filename);
let flag = Info::check_file(path.as_str())?;
let file = OpenOptions::new().append(true).open(path)?;
let mut buffered_file: BufWriter<File> = BufWriter::new(file.try_clone()?);
let metadata = {
match info.metadata {
Some(list) => list,
None => Vec::new(),
}
};
let logs = {
match info.logs {
Some(list) => list,
None => Vec::new(),
}
};
if !flag {
for log in metadata {
buffered_file.write_fmt(format_args!("{}\n", log))?;
}
buffered_file.write_fmt(format_args!("{}\n", SEPARATOR))?;
}
for log in logs {
buffered_file.write_fmt(format_args!("{}\n", log))?;
}
return Ok(Response::new("ok".to_string(), true));
}
pub fn get(filename: String) -> Result<Info, ApiError> {
let path: String = format!("./logs/{}.log", &filename);
if !Path::new(&path).exists() {
return Err(ApiError::new(404, "Not found".to_string()));
}
let file = OpenOptions::new().read(true).open(path)?;
let buffered_file: BufReader<File> = BufReader::new(file);
let mut metadata = Vec::<String>::new();
let mut logs = Vec::<String>::new();
let mut flag = false;
for line in buffered_file.lines() {
let data = line?;
if !flag {
metadata.push(data.clone());
} else {
logs.push(data.clone());
}
if data == SEPARATOR.to_string() {
flag = true;
}
}
metadata.remove(metadata.len() - 1);
let result = Info::new(filename, logs, metadata);
return Ok(result);
}
pub fn get_filenames() -> Result<Vec<String>, ApiError> {
let mut files: Vec<String> = Vec::new();
for entry in WalkDir::new("./logs") {
let name: String = match entry {
Ok(directory) => {
let aux = directory.file_name().to_str();
if let Some(aux_name) = aux {
aux_name.to_string()
} else {
"Error".to_string()
}
}
Err(_) => "Error".to_string(),
};
files.push(name);
}
return Ok(files);
}
pub fn delete_log(filename: String) -> Result<Response, ApiError> {
std::fs::remove_file(format!("./logs/{}.log", &filename))?;
return Ok(Response::new("deleted".to_string(), true));
}
pub fn delete_all() -> Result<Response, ApiError> {
let mut count: i64 = 0;
for entry in WalkDir::new("./logs") {
match entry {
Ok(directory) => {
let aux = directory.file_name().to_str();
if let Some(aux_name) = aux {
match std::fs::remove_file(format!("./logs/{}", aux_name)) {
Ok(()) => count+=1,
Err(_) => ()
}
}
}
Err(_) => ()
}
}
let message: String = format!("deleted {} files", count);
return Ok(Response::new(message, true));
}
}
|
//! Scenarios where password authentication is needed
// NOTE all these tests assume that the invoking user passes the sudoers file 'User_List' criteria
mod stdin;
mod tty;
const MAX_PAM_RESPONSE_SIZE: usize = 512;
|
extern crate broadcast;
use broadcast::BroadcastWriter;
use std::io::Write;
fn main() {
let mut first = Vec::new();
let mut second = Vec::new();
{
let mut broadcaster = BroadcastWriter::new(&mut first, &mut second);
let _ = broadcaster.write(b"it's over 9000!");
}
println!("first -> {:?}", first);
println!("second -> {:?}", second);
}
|
//! blsfill
/// Fill from lowest set bit
pub trait Blsfill {
/// Sets all bits of `self` below the least significant one.
///
/// If there is no set bit in `self`, it sets all the bits.
///
/// # Instructions
///
/// - [`BLSFILL`](http://support.amd.com/TechDocs/24594.pdf):
/// - Description: Fill from lowest set bit.
/// - Architecture: x86.
/// - Instruction set: TBM.
/// - Registers: 32/64 bit.
///
/// # Example
///
/// ```
/// # use bitintr::*;
/// assert_eq!(0b0101_0100u8.blsfill(), 0b0101_0111u8);
/// assert_eq!(0b0000_0000u8.blsfill(), 0b1111_1111u8);
/// ```
fn blsfill(self) -> Self;
}
macro_rules! impl_blsfill {
($id:ident) => {
impl Blsfill for $id {
#[inline]
fn blsfill(self) -> Self {
self | (self.wrapping_sub(1))
}
}
};
}
impl_all!(impl_blsfill: u8, u16, u32, u64, i8, i16, i32, i64);
|
fn main() {
let n = build_vector_verbose();
println!("{:?}", n)
}
fn build_vector_verbose() -> Vec<i16> {
let mut v: Vec<i16> = Vec::<i16>::new();
v.push(10i16);
v.push(20i16);
v
}
|
use crate::data::Value;
use crate::errors::ShellError;
use crate::prelude::*;
use crate::commands::WholeStreamCommand;
use crate::parser::registry::Signature;
pub struct Which;
impl WholeStreamCommand for Which {
fn name(&self) -> &str {
"which"
}
fn signature(&self) -> Signature {
Signature::build("which").required("name", SyntaxShape::Any)
}
fn usage(&self) -> &str {
"Finds a program file."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
which(args, registry)
}
}
pub fn which(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
let mut which_out = VecDeque::new();
let tag = args.call_info.name_tag;
if let Some(v) = &args.call_info.args.positional {
if v.len() > 0 {
match &v[0] {
Tagged {
item: Value::Primitive(Primitive::String(s)),
tag,
} => match which::which(&s) {
Ok(ok) => {
which_out
.push_back(Value::Primitive(Primitive::Path(ok)).tagged(tag.clone()));
}
_ => {}
},
Tagged { tag, .. } => {
return Err(ShellError::labeled_error(
"Expected a filename to find",
"needs a filename",
*tag,
));
}
}
} else {
return Err(ShellError::labeled_error(
"Expected a binary to find",
"needs application name",
tag,
));
}
} else {
return Err(ShellError::labeled_error(
"Expected a binary to find",
"needs application name",
tag,
));
}
Ok(which_out.to_output_stream())
}
|
pub trait Union<RHS = Self> {
type Output;
fn union(self, rhs: RHS) -> Self::Output;
}
pub trait Intersection<RHS = Self> {
type Output;
fn intersection(self, rhs: RHS) -> Self::Output;
}
pub trait CartesianProduct<RHS = Self> {
type Output;
fn cartesian_product(self, rhs: RHS) -> Self::Output;
}
pub trait Difference<RHS = Self> {
type Output;
fn difference(self, rhs: RHS) -> Self::Output;
}
pub trait SymmetricDifference<RHS = Self> {
type Output;
fn symmetric_difference(self, rhs: RHS) -> Self::Output;
}
pub trait Complement {
type Output;
fn complement(self) -> Self::Output;
}
pub trait Concatenation<RHS = Self> {
type Output;
fn concatenation(self, rhs: RHS) -> Self::Output;
}
pub trait KleeneClosure {
type Output;
fn closure(self) -> Self::Output;
}
pub trait Reversal {
type Output;
fn reversal(self) -> Self::Output;
}
pub trait StringHomomorphism<A> {
fn apply(symbol: A) -> Vec<A>;
}
pub trait ApplyHom<A> {
type Output;
fn apply_string_hom<Hom>(self) -> Self::Output
where
Hom: StringHomomorphism<A>;
}
|
use crate::{
variable_length_crh::{
pedersen::{VariableLengthPedersenCRH, VariableLengthPedersenParameters},
VariableLengthCRH,
},
Error,
};
use ark_ec::models::{ModelParameters, TEModelParameters};
use ark_ff::PrimeField;
use ark_std::rand::{CryptoRng, Rng, SeedableRng};
use ark_std::{marker::PhantomData, vec, vec::Vec};
pub mod constraints;
pub struct VariableLengthPedersenCRHCompressor<
RO: Rng + CryptoRng + SeedableRng,
P: TEModelParameters,
> {
pub ro_phantom: PhantomData<RO>,
pub te_parameters_phantom: PhantomData<P>,
}
impl<RO: Rng + CryptoRng + SeedableRng, P: TEModelParameters> VariableLengthCRH<P::BaseField>
for VariableLengthPedersenCRHCompressor<RO, P>
where
P::BaseField: PrimeField,
{
type Output = P::BaseField;
type Parameters = VariableLengthPedersenParameters;
fn setup<R: Rng + CryptoRng>(rng: &mut R) -> Result<Self::Parameters, Error> {
VariableLengthPedersenCRH::<RO, P>::setup(rng)
}
fn evaluate(parameters: &Self::Parameters, input: &[u8]) -> Result<P::BaseField, Error> {
let result = VariableLengthPedersenCRH::<RO, P>::evaluate(parameters, input)?;
Ok(result.x)
}
fn convert_output_to_field_elements(
output: Self::Output,
) -> Result<Vec<<P as ModelParameters>::BaseField>, Error> {
Ok(vec![output])
}
}
|
use stm32f0xx_hal::{
gpio::gpioa::{PA5, PA6, PA7, PA11, PA12},
gpio::gpiob::{PB3, PB4, PB5},
gpio::{Alternate, AF4, AF0},
spi::Spi,
stm32::{SPI1}
};
pub type CAN_TX_PIN = PA12<Alternate<AF4>>;
pub type CAN_RX_PIN = PA11<Alternate<AF4>>;
pub type SCK_PIN = PB3<Alternate<AF0>>;
pub type MISO_PIN = PB4<Alternate<AF0>>;
pub type MOSI_PIN = PB5<Alternate<AF0>>;
pub type SPI_TYPE = Spi<SPI1, SCK_PIN, MISO_PIN, MOSI_PIN>;
#[cfg(feature = "master")]
pub const CAN_ID: u32 = 101;
#[cfg(feature = "tr")]
pub const CAN_ID: u32 = 102;
#[cfg(feature = "bl")]
pub const CAN_ID: u32 = 103;
#[cfg(feature = "br")]
pub const CAN_ID: u32 = 104;
pub enum UAVCAN_PRIORITY {
UcpExceptional = 0,
UcpImmediate = 1,
UcpFast = 2,
UcpHigh = 3,
UcpNominal = 4,
UcpLow = 5,
UCP_Slow = 6,
UcpOptional = 7
}
pub fn get_uavcan_id(port: u32, node_id: u32, priority: UAVCAN_PRIORITY) -> u32{
let prio = priority as u32;
if prio < 7 && port < 32767 && node_id < 127 {
prio << 26 | port << 8 | node_id
}
else{
0
}
}
pub fn update_reg_by_bit_pos(src: u32, pos: u32, val: u32) -> u32{
let tmp = (src >> pos) | val;
((tmp << pos) + src)
} |
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::str;
use regex::Regex;
use std::collections::HashMap;
#[derive(Debug)]
enum Action {
GoesOnShift,
FallsAsleep,
WakesUp
}
#[derive(Debug)]
struct LogRecord {
id: i32,
minute: i32,
action: Action
}
fn main() -> std::io::Result<()> {
let records = {
let mut input_buf = vec![];
BufReader::new(File::open("src/bin/day04.txt")?).read_to_end(&mut input_buf)?;
let mut input = input_buf.split(|i| *i == '\n' as u8).collect::<Vec<&[u8]>>();
input.sort();
let line_re = Regex::new(r"\[\d{4}-(\d{2})-(\d{2}) (\d{2}):(\d{2})\] (.*)").unwrap();
let id_re = Regex::new(r"Guard #(\d+) begins shift").unwrap();
let mut guard_id: i32 = 0;
let mut records = vec![];
for ref line in input {
let cap = line_re.captures(str::from_utf8(*line).unwrap()).unwrap();
let action = match &cap[5] {
"falls asleep" => { Action::FallsAsleep },
"wakes up" => { Action::WakesUp },
_ => {
let id_cap = id_re.captures(&cap[5]).unwrap();
guard_id = id_cap[1].parse().unwrap();
Action::GoesOnShift
}
};
let log_record = LogRecord {
id: guard_id,
minute: cap[4].parse().unwrap(),
action
};
records.push(log_record);
}
records
};
let mut guard_total_mins_asleep: HashMap<i32, i32> = HashMap::new();
let mut guard_specific_mins_asleep: HashMap<i32, [i32; 60]> = HashMap::new();
let mut best_sleeper_id = 0;
let mut best_sleeper_total_mins_asleep = 0;
{
let mut current_guard_id = 0;
let mut fell_asleep_at = 0;
for record in &records {
match record.action {
Action::FallsAsleep => {
fell_asleep_at = record.minute;
},
Action::WakesUp => {
let mins_asleep = record.minute - fell_asleep_at;
let current_guard_total_mins_asleep = guard_total_mins_asleep.entry(record.id).or_insert(0);
*current_guard_total_mins_asleep += mins_asleep;
let current_guard_specific_mins_asleep = guard_specific_mins_asleep.entry(record.id).or_insert([0; 60]);
for i in 0..mins_asleep {
let minute = fell_asleep_at + i;
current_guard_specific_mins_asleep[minute as usize] += 1;
}
},
Action::GoesOnShift => {
if let Some(current_guard_total_mins_asleep) = guard_total_mins_asleep.get(¤t_guard_id) {
if *current_guard_total_mins_asleep > best_sleeper_total_mins_asleep {
best_sleeper_id = current_guard_id;
best_sleeper_total_mins_asleep = *current_guard_total_mins_asleep;
}
}
current_guard_id = record.id;
}
}
}
}
let mut sleepiest_minute = -1;
let mut time_asleep = 0;
if let Some(best_sleeper_specific_mins_asleep) = guard_specific_mins_asleep.get(&best_sleeper_id) {
for (i, v) in best_sleeper_specific_mins_asleep.iter().enumerate() {
if *v > time_asleep {
time_asleep = *v;
sleepiest_minute = i as i32;
}
}
}
println!("[Strategy 1] Guard Id: {}, Time Asleep: {}, Sleepiest Minute: {}, Answer: {}", best_sleeper_id, best_sleeper_total_mins_asleep, sleepiest_minute, best_sleeper_id*sleepiest_minute);
{
let mut guard_id = 0;
let mut longest_minute = 0;
let mut longest_minute_num_nights = 0;
for (id, specific_mins_asleep) in guard_specific_mins_asleep {
for (minute, num_nights) in specific_mins_asleep.iter().enumerate() {
if *num_nights > longest_minute_num_nights {
guard_id = id;
longest_minute = minute as i32;
longest_minute_num_nights = *num_nights;
}
}
}
println!("[Strategy 2] Guard Id: {}, Sleepiest Minute: {}, Num Nights Asleep On Minute: {}, Answer: {}", guard_id, longest_minute, longest_minute_num_nights, guard_id * longest_minute);
}
Ok(())
} |
mod init;
mod list;
mod remove;
mod select;
mod track;
pub use init::{init, Shells};
pub use list::list;
pub use remove::remove;
pub use select::select;
pub use track::track;
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::data_stream::{DataQuery, DataStream};
use anyhow::{format_err, Result};
use async_trait::async_trait;
use libra_types::{
access_path::DataPath,
account_config::association_address,
account_state_blob::AccountStateWithProof,
contract_event::ContractEvent,
get_with_proof::RequestItem,
libra_resource::LibraResource,
system_config::BlockMetaResource,
transaction::{Transaction, TransactionInfo, TransactionListWithProof, Version},
};
use sgchain::star_chain_client::ChainClient;
use sgtypes::account_state::AccountState;
use std::{collections::BTreeMap, convert::TryInto, sync::Arc};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TransactionWithInfo {
pub txn: Transaction,
pub txn_info: TransactionInfo,
pub version: u64,
pub events: Vec<ContractEvent>,
pub block_height: u64,
}
pub(super) type TxnStream = DataStream<TxnQuerier, TransactionWithInfo>;
impl TxnStream {
pub fn new_from_chain_client(
chain_client: Arc<dyn ChainClient>,
start_version: u64,
limit: u64,
) -> Self {
DataStream::new(TxnQuerier(chain_client), start_version, limit)
}
}
pub(crate) fn build_request(
req: RequestItem,
ver: Option<Version>,
) -> libra_types::proto::types::UpdateToLatestLedgerRequest {
libra_types::get_with_proof::UpdateToLatestLedgerRequest::new(ver.unwrap_or(0), vec![req])
.into()
}
pub(super) struct TxnQuerier(Arc<dyn ChainClient>);
impl TxnQuerier {
async fn get_block_hight(&self, start_version: u64) -> Result<u64> {
let ri = RequestItem::GetAccountState {
address: association_address(),
};
let resp: libra_types::get_with_proof::ResponseItem = self
.0
.update_to_latest_ledger_async(&build_request(ri, Some(start_version)))
.await?
.response_items
.remove(0)
.try_into()?;
let AccountStateWithProof {
blob,
version,
proof,
} = resp.into_get_account_state_response()?;
let blob = blob.ok_or(format_err!("association account not exists!"))?;
let resp = AccountState::from_account_state_blob(
version,
blob.into(),
proof.transaction_info_to_account_proof().clone(),
)?;
let block_meta = resp
.get_resource::<BlockMetaResource>(&DataPath::onchain_resource_path(
BlockMetaResource::struct_tag(),
))?
.ok_or(format_err!("block meta resource should exists"))?;
Ok(block_meta.height)
}
}
#[async_trait]
impl DataQuery for TxnQuerier {
type Item = TransactionWithInfo;
async fn query(&self, version: u64, limit: u64) -> Result<BTreeMap<u64, Self::Item>> {
let ri = RequestItem::GetTransactions {
start_version: version,
limit,
fetch_events: true,
};
let client = self.0.clone();
let mut resp = tokio::task::block_in_place(move || {
client.update_to_latest_ledger(&build_request(ri, None))
})?;
let resp: libra_types::get_with_proof::ResponseItem =
resp.response_items.remove(0).try_into()?;
let txns = resp.into_get_transactions_response()?;
// FIXME: check proof
let TransactionListWithProof {
transactions,
events,
first_transaction_version,
proof,
} = txns;
match first_transaction_version.as_ref() {
None => Ok(BTreeMap::new()),
Some(first_version) => {
let mut c = BTreeMap::default();
for (pos, ((t, info), events)) in transactions
.into_iter()
.zip(proof.transaction_infos().to_vec().into_iter())
.zip(events.unwrap())
.enumerate()
{
let version = *first_version + (pos as u64);
// TODO: a better way to do it.
let block_height = self.get_block_hight(version).await?;
c.insert(
version,
TransactionWithInfo {
txn: t,
txn_info: info,
version,
events,
block_height,
},
);
}
Ok(c)
}
}
}
}
|
use crate::object::*;
use crate::value::Value;
use crate::*;
#[repr(C)]
pub struct VTable {
pub trace_fn: Option<fn(Ref<Obj>, &mut dyn FnMut(*const Ref<Obj>))>,
pub lookup_fn: Option<fn(&VM, Ref<Obj>, Value) -> WaffleResult>,
pub index_fn: Option<fn(&VM, Ref<Obj>, usize) -> WaffleResult>,
pub set_fn: Option<fn(&VM, Ref<Obj>, Value, Value) -> WaffleResult>,
pub set_index_fn: Option<fn(&VM, Ref<Obj>, usize, Value) -> WaffleResult>,
/// Calculate object size.
pub calc_size_fn: Option<fn(Ref<Obj>) -> usize>,
/// Object destructor, this should be used only by "external" objects that might contain
/// pointers to non GC memory.
pub destroy_fn: Option<fn(Ref<Obj>)>,
/// Invoke object.
pub apply_fn: Option<fn() -> WaffleResult>,
pub parent: Option<&'static VTable>,
pub instance_size: usize,
pub element_size: usize,
}
impl VTable {
pub fn is_array_ref(&self) -> bool {
self as *const Self == &crate::builtins::ARRAY_VTBL as *const VTable
}
}
|
#![doc(html_logo_url = "https://avatars2.githubusercontent.com/u/52050279?s=200&v=4")]
//! # wascc-actor
//!
//! The `wascc-actor` library provides WebAssembly module developers with access to the
//! wascc host runtime. Each actor module has a single receive function, declared with the
//! `actor_receive!` macro. Inside this receive function, the actor
//! module should check the operation of the delivered message and handle it accordingly,
//! returning any binary payload in response. It is the responsibility of the actor module to ensure
//! that the capability provider will be able to understand whichever messages it sends.
//!
//! # Example
//! ```
//! extern crate wascc_actor as actor;
//!
//! use actor::prelude::*;
//!
//! actor_handlers!{
//! codec::http::OP_HANDLE_REQUEST => hello_world,
//! codec::core::OP_HEALTH_REQUEST => health
//! }
//!
//! pub fn hello_world(_req: codec::http::Request) -> HandlerResult<codec::http::Response> {
//! Ok(codec::http::Response::ok())
//! }
//!
//! pub fn health(_req: codec::core::HealthRequest) -> HandlerResult<()> {
//! Ok(())
//! }
//! ```
#[macro_use]
extern crate lazy_static;
pub type HandlerResult<T> = ::std::result::Result<T, Box<dyn std::error::Error + Sync + Send>>;
pub extern crate wapc_guest as wapc;
use wapc_guest::console_log;
/// Actor developers will use this macro to set up their operation handlers
#[macro_export]
macro_rules! actor_handlers(
{ $($key:path => $user_handler:ident),* } => {
use $crate::wapc::prelude::*;
wapc_handler!(handle_wapc);
fn handle_wapc(operation: &str, msg: &[u8]) -> CallResult {
$crate::logger::ensure_logger();
match operation {
$( $key => $user_handler(deserialize(msg)?)
.and_then(|r| serialize(r))
.map_err(|e| e.into()), )*
_ => Err("bad dispatch".into())
}
}
};
);
/// Use this function for simple, unstructured logging outside the usual log macros
pub fn println(msg: &str) {
console_log(msg)
}
pub mod errors;
pub mod events;
pub mod extras;
pub mod http_client;
pub mod keyvalue;
pub mod logger;
pub mod messaging;
pub mod objectstore;
pub mod prelude;
pub mod untyped;
|
use crate::{cmd, config::Config, item};
use anyhow::{anyhow, Context};
use bdk::{
bitcoin::Network,
keys::{
bip39::{Language, Mnemonic, MnemonicType},
GeneratableKey, GeneratedKey,
},
miniscript::Segwitv0,
};
use cmd::Cell;
use std::{fs, io, path::PathBuf, str::FromStr};
use structopt::StructOpt;
use super::CmdOutput;
pub enum NWords {}
#[derive(Clone, Debug, StructOpt)]
pub struct InitOpt {
/// The network name (bitcoin|regtest|testnet)
network: Network,
/// Existing BIP39 seed words file. Use "-" to read words from stdin.
#[structopt(long, name = "FILE")]
from_existing: Option<String>,
#[structopt(long, default_value = "12", name = "[12|24]")]
/// The number of BIP39 seed words to use
n_words: usize,
}
pub fn run_init(
wallet_dir: &PathBuf,
InitOpt {
network,
n_words,
from_existing,
}: InitOpt,
) -> anyhow::Result<CmdOutput> {
let seed_words = match from_existing {
Some(existing_words_file) => {
let words = match existing_words_file.as_str() {
"-" => {
use io::Read;
let mut words = String::new();
io::stdin().read_to_string(&mut words)?;
words
}
existing_words_file => {
let existing_words_file = PathBuf::from_str(existing_words_file)
.context("parsing existing seed words file name")?;
fs::read_to_string(&existing_words_file).context(format!(
"loading existing seed words from {}",
existing_words_file.display()
))?
}
};
Mnemonic::validate(&words, Language::English).context("parsing existing seedwords")?;
words
}
None => {
let n_words = MnemonicType::for_word_count(n_words)?;
let seed_words: GeneratedKey<_, Segwitv0> =
Mnemonic::generate((n_words, Language::English))
.map_err(|_| anyhow!("generating seed phrase failed"))?;
seed_words.phrase().into()
}
};
if wallet_dir.exists() {
return Err(anyhow!(
"wallet directory {} already exists -- delete it to create a new wallet",
wallet_dir.as_path().display()
));
}
std::fs::create_dir(&wallet_dir)?;
{
let mut config_file = wallet_dir.clone();
config_file.push("config.json");
let config = Config::default_config(network);
fs::write(
config_file,
serde_json::to_string_pretty(&config).unwrap().as_bytes(),
)?;
}
let sw_file = cmd::get_seed_words_file(wallet_dir);
fs::write(sw_file.clone(), seed_words.clone())?;
eprintln!("Wrote seeds words to {}", sw_file.display());
println!("==== BIP39 seed words ====");
Ok(item! { "seed_words" => Cell::String(seed_words)})
}
|
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::HtmlTemplateElement;
#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
let window = web_sys::window().expect("window");
let document = window.document().expect("document");
let compiler_template = document
.create_element("template")
.unwrap()
.unchecked_into::<HtmlTemplateElement>();
let tree_walker = document.create_tree_walker(&document)?;
let template = stage0::compile_str(
&compiler_template,
&tree_walker,
"<div #t1><h1 #t2>Test</h1></div>",
)
.unwrap();
document.body().unwrap().append_child(&template.node)?;
web_sys::console::log_1(&template.node);
let refs = template.collect(&tree_walker)?;
let t1 = &refs["t1"];
web_sys::console::log_1(&t1);
let t2 = &refs["t2"];
web_sys::console::log_1(&t2);
Ok(())
}
|
// Generates vector.S for trap.rs
fn generate_vector_asm() {
let mut asm_string = ".globl alltraps\n".to_owned();
for i in 0..256 {
asm_string += &format!(
".globl vector0\nvector{}:\n pushl $0\n pushl ${}\n jmp alltraps\n",
i, i
);
}
asm_string += ".data\n.globl VECTORS\nVECTORS:\n";
for i in 0..256 {
asm_string += &format!(" .long vector{}\n", i);
}
let out_dir = std::env::var_os("OUT_DIR").unwrap();
let dest_path = std::path::Path::new(&out_dir).join("vectors.S");
std::fs::write(&dest_path, asm_string).unwrap();
}
fn copy_init() {
let out_dir = std::env::var_os("OUT_DIR").unwrap();
let out_dir = std::path::Path::new(&out_dir);
let init_bin = out_dir.ancestors().nth(7).unwrap().join("init.bin");
std::fs::copy(&init_bin, out_dir.join("init.bin")).unwrap();
println!("cargo:rerun-if-changed={}", init_bin.to_str().unwrap());
}
fn main() {
generate_vector_asm();
copy_init();
println!("cargo:rerun-if-changed=build.rs");
}
|
use std::str::FromStr;
use async_std::fs;
use async_std::{fs::File};
use async_std::io::{BufReader, BufWriter, prelude::*};
use tide::{Body, Request};
use crate::types::{AppState, FileUploadResponse, IndexResponse};
const FILE_LIMIT: u64 = 1024 * 1024 * 1024;
pub async fn get_index(mut _req: Request<AppState>) -> tide::Result {
let response = IndexResponse {
value: "Welcome".into(),
};
if let Ok(body) = Body::from_json(&response) {
Ok(body.into())
} else {
Err(tide::Error::from_str(403, "bad request"))
}
}
pub async fn get_file(req: Request<AppState>) -> tide::Result {
let path = req.param("file")?;
let fs_path = req.state().path().join(path);
if let Ok(body) = Body::from_file(&fs_path).await {
Ok(body.into())
} else {
tide::log::error!("file not found", {
path: path,
});
return Err(tide::Error::from_str(404, "not found"))
}
}
/*
pub async fn put_file(req: Request<AppState>) -> tide::Result {
let path = req.param("file")?;
let fs_path = req.state().path().join(path);
let f = File::create(&fs_path).await?;
let bytes_written = io::copy(req, f).await?;
let path_buf = fs_path.canonicalize()?;
let path_str = match path_buf.to_str() {
Some(s) => s,
None => "",
};
tide::log::info!("file written", {
bytes: bytes_written,
path: path_str
});
let response = FileUploadResponse {
name: String::from(path_str),
size: bytes_written,
};
if let Ok(body) = Body::from_json(&response) {
Ok(body.into())
} else {
Ok(Response::new(StatusCode::BadRequest))
}
}
*/
pub async fn put_file_limited(req: Request<AppState>) -> tide::Result {
let path = req.param("file")?;
let file_name = String::from_str(path)?;
let fs_path = req.state().path().join(path);
let f = File::create(&fs_path).await?;
let mut buf_reader = BufReader::new(req);
let mut buf_writer = BufWriter::new(f);
let mut buf = vec![0u8; 1024 * 1024];
let mut bytes_written: u64 = 0;
loop {
let bytes_read = buf_reader.read(&mut buf).await?;
if bytes_read > 0 {
tide::log::info!("bytes read", {
bytes: &bytes_read,
});
buf_writer.write(&buf[0..bytes_read]).await?;
bytes_written = bytes_written + bytes_read as u64;
if bytes_written > FILE_LIMIT {
tide::log::warn!("file limit exceeded");
fs::remove_file(fs_path).await?;
return Err(tide::Error::from_str(403, "file size limit exceeded"))
}
} else {
if bytes_written > 0 {
buf_writer.flush().await?;
}
break;
}
}
let path_buf = fs_path.canonicalize()?;
let path_str = match path_buf.to_str() {
Some(s) => s,
None => "",
};
tide::log::info!("file written", {
bytes: bytes_written,
path: path_str
});
let response = FileUploadResponse {
name: file_name,
size: bytes_written,
};
if let Ok(body) = Body::from_json(&response) {
Ok(body.into())
} else {
Err(tide::Error::from_str(500, "error"))
}
}
|
fn main() {
let _a = if true { "abc" } else { "xy" };
let _b = if true { 3456 } else { 12 };
let _c = if true { 56.9 } else { 12. };
println!("{}\n{}\n{}", _a, _b, _c);
}
|
pub use moebius_derive_impl::{moebius_instruction, moebius_state};
|
//! ITP1_4_Bの回答
//! [https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_4_B](https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_4_B)
use std::f64::consts::PI;
use std::io::stdin;
/// ITP1_4_Bの回答(エントリポイント)。
#[allow(dead_code)]
pub fn main() {
loop {
let mut line = String::new();
if let Err(_) = stdin().read_line(&mut line) {
return;
}
let r = match line.trim().parse::<f64>() {
Ok(n) => n,
_ => return
};
let result = compute_result(r);
println!("{} {}", result.area, result.circumference);
}
}
#[derive(Debug, PartialEq)]
struct ResultSet {
area: f64,
circumference: f64,
}
fn compute_result(r: f64) -> ResultSet {
let area = PI * r.powi(2);
let circumference = 2.0 * PI * r;
ResultSet { area, circumference }
}
#[cfg(test)]
mod test {
use super::*;
macro_rules! assert_float_eq {
($expected:expr, $actual:expr, $error:expr) => {
assert!(($expected - $actual).abs() < $error)
}
}
#[test]
fn test_compute_result() {
let result = compute_result(2.0);
assert_float_eq!(12.566371, result.area, 10_f64.powi(-5));
assert_float_eq!(12.566371, result.circumference, 10_f64.powi(-5));
}
} |
mod content;
pub use crate::signature::SignatureMismatch;
pub use self::content::Content;
use http::HeaderMap;
/// Content and metadata of an update pushed by a hub.
#[derive(Debug)]
pub struct Update<B> {
/// The topic URI associated with the update.
pub topic: Box<str>,
/// The HTTP request header of the update.
pub headers: HeaderMap,
/// The HTTP request body of the update.
pub content: Content<B>,
}
/// Error while reading a {`Content`} body.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error<E> {
/// The underlying HTTP body returned an error.
#[error("failed to read request body")]
Body(#[source] E),
/// The signature sent by the hub didn't verify, indicating that the distributed [`Content`]
/// has been falsified.
///
/// If you encounter this error, you must not trust the content.
#[error(transparent)]
SignatureMismatch(SignatureMismatch),
}
/// Convenience type alias for the `Result` type returned by [`Content`].
pub type Result<T, E> = std::result::Result<T, Error<E>>;
|
impl Solution {
pub fn peak_index_in_mountain_array(arr: Vec<i32>) -> i32 {
let (mut l,mut r) = (0,arr.len() - 1);
while l < r{
let mid = l + (r - l) / 2;
match arr[mid] > arr[mid + 1]{
true => r = mid,
false => l = mid + 1,
}
}
l as i32
}
} |
#[derive(Debug)]
enum List {
Cons(i32, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
use std::{cell::Cell, ops::Deref};
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn test_fat_pointers() {
let mut arr = [1, 2, 3, 4];
let slice = &mut arr[1..4];
slice[0] = 100;
println!("{:?}", arr); // [1, 100, 3, 4]
let slice = &arr[1..4];
println!("{:p} {:?}", slice, unsafe {
std::mem::transmute::<_, (usize, usize)>(slice)
});
// Output: 0x8a6c0ff4ac (594518471852, 3)
// 0x8a6c0ff4ac 594518471852 这两个值是相等的。
// (594518471852, 3) 分别表示 具体数据的堆地址 和 长度 两个字段。
// 注意这里是用 slice,而不是 &slice。(&slice表示这个变量本身的栈地址)
println!("sizeof &[i32]:{}", std::mem::size_of::<&[i32]>());
// Output: sizeof &[i32]:16
// 因为包含了两个字段:地址 + 长度,所以其占用内存为 2 个 usize 类型大小
}
fn test_smart_pointers() {
// 将本应存在栈上的地址,存在了堆上
let mut num = Box::new(1);
// num_address 指向 box 里面的具体内容(也就是储存在堆上的数值 1)
let num_address1: *mut i32 = &mut *num;
let num_address2: *mut i32 = &mut *num;
unsafe {
*num_address1 = 100;
*num_address2 = 200
}
println!("{}", *num + 100)
// Output: 200
}
fn high_unsafe() {
let mut num = 5;
let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
unsafe {
println!("r1 is: {}", *r1);
println!("r2 is: {}", *r2);
}
}
extern "C" {
fn abs(input: i32) -> i32;
}
static HELLO_WORLD: &str = "Hello, world!";
static mut COUNTER: u32 = 0;
fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
}
unsafe fn dangerous() {
println!("I'm dangerous! ans I call c abs {}", abs(-3));
println!("{}", HELLO_WORLD);
}
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len);
//(&mut slice[..mid], &mut slice[mid..])
unsafe {
(
std::slice::from_raw_parts_mut(ptr, mid),
std::slice::from_raw_parts_mut(ptr.add(mid), len),
)
}
}
fn main() {
let l1 = Cons(1, Rc::new(Cons(2, Rc::new(Cons(3, Rc::new(Nil))))));
println!("{:?}", l1);
let x = 5;
let y = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
let x = 5;
let y = &x;
assert_eq!(5, x);
assert_eq!(5, *y);
let a = 5;
let b = MyBox::new(a);
assert_eq!(5, a);
assert_eq!(5, *b);
let a1 = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after creating a = {}", Rc::strong_count(&a1));
// let b1 = Cons(3, Rc::clone(&a1));
// let c1 = Cons(4, Rc::clone(&a1));
let bb = Box::new(5);
println!("{}", bb);
test_fat_pointers();
test_smart_pointers();
println!("-----------------------------------");
println!("{}", HELLO_WORLD);
high_unsafe();
add_to_count(3);
unsafe {
dangerous();
println!("COUNTER: {}", COUNTER);
}
let s = "hell".to_string();
let bar = std::cell::Cell::new(s);
let x = bar.into_inner();
println!("{}", x);
let x = std::cell::RefCell::new(vec![1, 2, 3, 4]);
println!("{:?}", x.borrow());
let mut mutx = x.borrow_mut();
mutx.push(6);
let mut mutxx = x.borrow_mut();
println!("{:?}", x.borrow());
}
|
#[macro_use]
extern crate slog;
extern crate slog_async;
extern crate slog_json;
#[macro_use]
extern crate slog_scope;
extern crate chrono;
use slog::{Drain, Duplicate, FnValue, Level, Logger, Never, OwnedKVList, PushFnValue, Record};
use slog_async::Async;
use std::fs::OpenOptions;
use std::io;
/// # Simple custom structured logging.
///
/// ## Examples
///
/// Basic usage:
///
/// ```rust
///
/// use Structured_logging::*;
///
/// let drain = slog_json::Json::new(std::io::stdout())
/// .set_pretty(false)
/// .build()
/// .fuse();
/// let d_stdout = slog_async::Async::new(drain).build().fuse();
///
/// let drain = slog_json::Json::new(std::io::stderr())
/// .set_pretty(false)
/// .build()
/// .fuse();
/// let d_stderr = slog_async::Async::new(drain).build().fuse();
///
/// let drain_base = Duplicate::new(
/// CustomLevelFilter::new(d_stderr, Level::Warning, CmpLevel::Less),
/// CustomLevelFilter::new(d_stdout, Level::Info, CmpLevel::Greater),
/// ).fuse();
///
///
/// // Global logging
/// let _guard = slog_scope::set_global_logger(Logger::root(
/// drain_base,
/// o!(
/// "msg" => PushFnValue(move |record : &Record, ser| {
/// ser.emit(record.msg())
/// }),
/// "time" => PushFnValue(move |_ : &Record, ser| {
/// ser.emit(chrono::Utc::now().to_rfc3339())
/// }),
/// "file"=>"app.log",
/// "lvl" => FnValue(move |rinfo : &Record| {
/// rinfo.level().as_str()
/// }),
/// ),
/// ));
///
/// info!("Info message using the global logger");
/// debug!("debug");
/// error!("Error occurred");
///
/// slog_debug!(slog_scope::logger(), "slog_debug");
/// slog_error!(slog_scope::logger(), "Error occurred");
/// ```
mod Structured_logging {
use super::*;
/// Type of error level comparison.
pub enum CmpLevel {
Less = 0,
Greater,
}
/// The implementation of struct slog :: LevelFilter.
/// The logic of filtering the error levels in a partition priorities.
///
/// ## Examples
///
/// Basic usage:
///
/// ```rust
/// #[macro_use]
/// extern crate slog;
/// extern crate slog_async;
/// extern crate slog_term;
/// use slog::*;
///
/// fn main(){
/// use Structured_logging::*;
///
/// let decorator = slog_term::TermDecorator::new().stdout().build();
/// let d_stdout = slog_term::CompactFormat::new(decorator).build().fuse();
/// let d_stdout = slog_async::Async::new(d_stdout).build().fuse();
///
/// let decorator = slog_term::PlainDecorator::new(std::io::stderr());
/// let d_stderr = slog_term::FullFormat::new(decorator).build().fuse();
/// let d_stderr = slog_async::Async::new(d_stderr).build().fuse();
///
/// let drain_base = Duplicate::new(
/// CustomLevelFilter::new(d_stderr, Level::Warning, CmpLevel::Less),
/// CustomLevelFilter::new(d_stdout, Level::Info, CmpLevel::Greater),
/// ).fuse();
///
/// let root = Logger::root(drain_base,o!());
///
/// info!(root, "{method} {path}", method = "POST", path = "/some"; );
/// }
/// ```
pub struct CustomLevelFilter<D: Drain>(pub D, pub Level, pub CmpLevel);
/// Implement struct CustomLevelFilter.
impl<D: Drain> CustomLevelFilter<D> {
/// Create CustomLevelFilter.
pub fn new(drain: D, level: Level, cmp: CmpLevel) -> Self {
CustomLevelFilter(drain, level, cmp)
}
}
/// Implement Drain trait for struct CustomLevelFilter.
/// Custom logic compare error slog::Level.
impl<D: Drain> Drain for CustomLevelFilter<D> {
type Ok = ();
type Err = Never;
fn log(
&self,
record: &Record,
logger_values: &OwnedKVList,
) -> std::result::Result<Self::Ok, Self::Err> {
match self.2 {
CmpLevel::Less => {
if record.level() <= self.1 {
self.0.log(record, logger_values);
}
}
CmpLevel::Greater => {
if record.level() >= self.1 {
self.0.log(record, logger_values);
}
}
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
let drain_base = Duplicate::new(
CustomLevelFilter::new(slog::Discard, Level::Warning, CmpLevel::Less),
CustomLevelFilter::new(slog::Discard, Level::Info, CmpLevel::Greater),
).fuse();
let root: slog::Logger = Logger::root(drain_base, o!("key" => "value"));
let root_new: slog::Logger = root.new(o!("key_new" => "value_new"));
assert!(true);
}
}
}
fn main() {
use Structured_logging::*;
// Global logging
let drain = slog_json::Json::new(std::io::stdout())
.set_pretty(false)
.build()
.fuse();
let d_stdout = slog_async::Async::new(drain).build().fuse();
let drain = slog_json::Json::new(std::io::stderr())
.set_pretty(false)
.build()
.fuse();
let d_stderr = slog_async::Async::new(drain).build().fuse();
let drain_base = Duplicate::new(
CustomLevelFilter::new(d_stderr, Level::Warning, CmpLevel::Less),
CustomLevelFilter::new(d_stdout, Level::Info, CmpLevel::Greater),
).fuse();
let _guard = slog_scope::set_global_logger(Logger::root(
drain_base,
o!(
"msg" => PushFnValue(move |record : &Record, ser| {
ser.emit(record.msg())
}),
"time" => PushFnValue(move |_ : &Record, ser| {
ser.emit(chrono::Utc::now().to_rfc3339())
}),
"file"=>"app.log",
"lvl" => FnValue(move |rinfo : &Record| {
rinfo.level().as_str()
}),
),
));
info!("Info message using the global logger");
debug!("debug");
error!("Error occurred");
slog_debug!(slog_scope::logger(), "slog_debug");
slog_error!(slog_scope::logger(), "Error occurred");
// Local logging
let log_path = "access.log";
let file: std::fs::File = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(log_path)
.unwrap();
let drain = slog_json::Json::new(file)
.set_pretty(false)
.set_newlines(true)
.build()
.fuse();
let drain_file = slog_async::Async::new(drain).build().fuse();
let root = Logger::root(
drain_file,
o!(
"msg" => PushFnValue(move |record : &Record, ser| {
ser.emit(record.msg())
}),
"time" => PushFnValue(move |_ : &Record, ser| {
ser.emit(chrono::Utc::now().to_rfc3339())
}),
"file"=>"app.log",
"lvl" => FnValue(move |rinfo : &Record| {
rinfo.level().as_str()
}),
),
);
slog_scope::scope(&root, || {
info!( "http"; "method" => "POST", "path" => "/some");
});
}
|
use crate::config::Config;
use crate::downloader::DownloadClient;
use crate::twitter_client::TwitterClient;
use anyhow::Result;
use clap::{App, Arg};
mod config;
mod downloader;
mod response_helpers;
mod tweet;
mod twitter_client;
#[tokio::main]
async fn main() {
let r = run().await;
let code = match r {
Ok(_) => exitcode::OK,
Err(e) => {
for cause in e.chain() {
eprintln!("{}", cause);
}
exitcode::SOFTWARE
}
};
std::process::exit(code);
}
async fn run() -> Result<()> {
let matches = App::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.arg(
Arg::with_name("INPUT")
.short("i")
.long("input")
.value_name("FILE")
.help("Read tweets to save from input file, 1 tweet ID per line")
.takes_value(true),
)
.arg(
Arg::with_name("FILTER")
.short("f")
.long("filter")
.value_name("SCREEN_NAME")
.help("Only save tweets from user")
.takes_value(true),
)
.get_matches();
let config = Config::read()?;
// Retrieve tweets
let twitter_client = TwitterClient::new(&config);
let all_tweets = if let Some(input_file) = matches.value_of("INPUT") {
twitter_client.process_ids_file(&input_file).await?
} else {
twitter_client
.process_users(config.users.iter().map(|s| s.as_ref()))
.await?
};
// Download tweets
let download_client = DownloadClient::new(&config);
download_client
.download_tweets(all_tweets.iter(), matches.value_of("FILTER"))
.await;
Ok(())
}
|
use crate::{Balances, Call, Event, Nfts, OriginCaller, Runtime, Scheduler};
use ternoa_primitives::{NFTDetails, NFTId};
impl ternoa_nfts::Trait for Runtime {
type Event = Event;
type NFTId = NFTId;
type NFTDetails = NFTDetails;
type WeightInfo = ();
}
impl ternoa_timed_escrow::Trait for Runtime {
type Event = Event;
type NFTs = Nfts;
type Scheduler = Scheduler;
type PalletsOrigin = OriginCaller;
type PalletsCall = Call;
type WeightInfo = ();
}
impl ternoa_marketplace::Trait for Runtime {
type Event = Event;
type Currency = Balances;
type NFTs = Nfts;
type WeightInfo = ();
}
|
//!Handles the vbe info multiboot2 tag.
///Represents the vbe info tag.
#[repr(C)]
struct VBEInfo { //type = 7
tag_type: u32,
size: u32,
vbe_mode: u16,
vbe_interface_seg: u16,
vbe_interface_off: u16,
vbe_interface_len: u16,
vbe_control_info: [u8; 512],
vbe_mode_info: [u8; 256]
}
|
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &link_energy, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &link_energy, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy(&number_of_links, &link_length, &link_stiffness, &link_energy, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_relative_helmholtz_free_energy_per_link(link_length: f64, link_stiffness: f64, link_energy: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy_per_link(&link_length, &link_stiffness, &link_energy, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_morse_thermodynamics_isotensional_asymptotic_reduced_legendre_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_link_energy: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_link_energy, &nondimensional_force)
} |
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpStream;
use std::error::Error;
use std::convert::TryInto;
use pow_common::{Md5PuzzleTask, Md5PuzzleSolution};
use pow_common::PowRequest1;
use pow_common::PowRequest2;
use pow_common::PowResponse1;
use pow_common::PowResponse2;
use wow_common::{GetWisdomQuoteRequest, GetWisdomQuoteResponse};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let addr = std::env::args().nth(1).unwrap_or("127.0.0.1:7878".to_string());
let mut stream = TcpStream::connect(addr).await?;
let (mut stream_read, mut stream_write) = stream.split();
let request_1 = PowRequest1 {
request: GetWisdomQuoteRequest {
temp: "temp".to_string()
},
};
let serialized_request_1 = bincode::serialize(&request_1)?;
stream_write.write(&serialized_request_1).await?;
stream_write.flush().await?;
let mut buffer = [0; 1024];
stream_read.read(&mut buffer).await?;
let response_1: PowResponse1<GetWisdomQuoteResponse, Md5PuzzleTask> = bincode::deserialize(&buffer)?;
let wow_response = match response_1 {
PowResponse1::R1(puzzle) => {
let puzzle_solution = solve_task(puzzle)
.expect("unable to brute force task");
let request_2 = PowRequest2 {
puzzle_solution
};
let serialized_request_2 = bincode::serialize(&request_2)?;
stream_write.write(&serialized_request_2).await?;
stream_write.flush().await?;
let mut buffer = [0; 1024];
stream_read.read(&mut buffer).await?;
let response_2: PowResponse2<GetWisdomQuoteResponse> = bincode::deserialize(&buffer)?;
match response_2 {
PowResponse2::Ok(rs) => {
Ok(rs)
}
PowResponse2::Err(err) => {
Err(err)
}
}
}
PowResponse1::R2(rs) => {
println!("(pow off)");
Ok(rs)
}
PowResponse1::Err(err) => {
Err(err)
}
};
match wow_response {
Ok(rs) => {
println!("Quote: '{}'", rs.quote);
}
Err(err) => {
eprintln!("Get Quote Failed: {:?}", err);
}
}
Ok(())
}
fn solve_task(task: Md5PuzzleTask) -> Option<Md5PuzzleSolution> {
println!("start solving task: {:x?}, {:x?}", task.hint, &task.hash);
let mut result = None;
for i in 0..u16::MAX {
let mask: [u8; 2] = i.to_le_bytes();
let mut attempt: Vec<u8> = vec![];
attempt.extend_from_slice(&mask);
attempt.extend_from_slice(&task.hint);
let hash: [u8; 16] = md5::compute(&attempt).into();
if &hash == &task.hash {
let answer = attempt.try_into().expect("failed to convert vec to array");
println!("task solved: {:x?}", answer);
let solution = Md5PuzzleSolution {
answer
};
result = Some(solution)
}
}
result
} |
use super::*;
#[test]
fn float_construct_destroy() {
FloatStorage::new();
}
#[test]
fn double_construct_destroy() {
DoubleStorage::new();
}
#[test]
fn double_from() {
let fs = FloatStorage::new_with_size(5);
unsafe {
// auto convert using From trait
println!("Attempt to convert from native c store");
let native_store = fs.storage();
let another_fs = FloatStorage::from(native_store);
another_fs.forget(); // or it will crash because underlying storage got free twice
println!("Conversion succeed.");
}
}
#[test]
fn float_fill_display() {
let mut fs = FloatStorage::new_with_size(5);
fs.fill(1f32);
assert_eq!("FloatStorage:size=5:data=[1.0, 1.0, 1.0, 1.0, 1.0]", fs.to_string());
}
#[test]
fn double_fill_display() {
let mut fs = DoubleStorage::new_with_size(5);
fs.fill(1.0f64);
assert_eq!("DoubleStorage:size=5:data=[1.0, 1.0, 1.0, 1.0, 1.0]", fs.to_string());
}
#[test]
fn double_fill_display_large() {
let mut fs = DoubleStorage::new_with_size(50);
fs.fill(2.0f64);
assert_eq!("DoubleStorage:size=50:first(10)=[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]:last(10)=[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]", fs.to_string());
}
#[test]
fn float_mutate_data() {
let mut fs = FloatStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f32;
validator.push(i as f32);
});
assert_eq!(fs.data(), validator.as_slice());
}
#[test]
fn double_mutate_data() {
let mut fs = DoubleStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f64;
validator.push(i as f64);
});
assert_eq!(fs.data(), validator.as_slice());
}
#[test]
fn float_resize_mutate_data() {
let mut fs = FloatStorage::new_with_size(16);
fs.resize(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f32;
validator.push(i as f32);
});
assert_eq!(fs.data(), validator.as_slice());
}
#[test]
fn double_resize_mutate_data() {
let mut fs = DoubleStorage::new_with_size(16);
fs.resize(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f64;
validator.push(i as f64);
});
assert_eq!(fs.data(), validator.as_slice());
}
#[test]
fn float_mutate_resize_data() {
let mut fs = FloatStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f32;
validator.push(i as f32);
});
fs.resize(16);
assert_eq!(fs.data(), &validator[0..16]);
}
#[test]
fn double_mutate_resize_data() {
let mut fs = DoubleStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f64;
validator.push(i as f64);
});
fs.resize(16);
assert_eq!(fs.data(), &validator[0..16]);
}
#[test]
fn float_index() {
let mut fs = FloatStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
fs.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f32;
validator.push(i as f32);
});
assert_eq!(31f32, fs[fs.len() - 1]);
}
#[test]
fn double_index() {
let mut ds = DoubleStorage::new_with_size(32);
let mut validator = Vec::with_capacity(32);
ds.data_mut().iter_mut().enumerate().for_each(|(i, d)| {
*d = i as f64;
validator.push(i as f64);
});
assert_eq!(31f64, ds[ds.len() - 1]);
}
#[test]
fn float_index_mut() {
let mut fs = FloatStorage::new_with_size(32);
for i in 0..fs.len() {
fs[i] = i as f32;
}
assert_eq!(31f32, fs[fs.len() - 1]);
}
#[test]
fn double_index_mut() {
let mut ds = DoubleStorage::new_with_size(32);
for i in 0..ds.len() {
ds[i] = i as f64;
}
assert_eq!(31f64, ds[ds.len() - 1]);
}
#[cfg(feature="serde")]
#[test]
fn serialize() {
let mut storage = ByteStorage::new_with_size(4);
storage.fill(1);
assert_eq!(serde_yaml::to_string(&storage).unwrap(),
"---
- 1
- 1
- 1
- 1");
}
#[cfg(feature="serde")]
#[test]
fn derialize() {
let yaml = serde_yaml::to_string(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unwrap();
let storage : ByteStorage = serde_yaml::from_str(&yaml).unwrap();
storage.iter().enumerate().for_each(|(i, s)| assert_eq!(*s, i as u8));
}
#[test]
#[ignore]
fn bench_index() {
let mut ds = DoubleStorage::new_with_size(1e8 as usize);
use std::time::Instant;
let begin = Instant::now();
let data = ds.data_mut();
for i in 0..data.len() {
data[i] = 2f64;
}
let end = begin.elapsed();
println!("Done Mut Slice in {}.{}s", end.as_secs(), end.subsec_millis());
let begin = Instant::now();
for i in 0..ds.len() {
ds[i] = 1f64;
}
let end = begin.elapsed();
println!("Done IndexMut in {}.{}s", end.as_secs(), end.subsec_millis());
}
#[test]
#[ignore]
fn memory_leak_test() {
println!("
This test never fail.
The only way to check is monitor memory consumption.
If memory leak, it'll consume about 34GB of memory.
This shall be large enough to freeze most of PC.
Otherwise, it'll consume about 1.7GB.
");
// if memory leak, it'll consume about 34GB of memory
let n = 20;
for i in 0..n {
// each new consume about 8 bytes per * size + 1 bool + 1 usize which roughly equals 17 bytes in 64bits system.
// 63e6 size is estimated to be 1.7GB per each instance
let mut tmp = DoubleStorage::new_with_size(1e8 as usize);
// if we didn't fill the value, it may not actually allocate memory
println!("Mem leak test {}/{}", i, n);
tmp.fill(1.0);
}
println!("Mem leak test done");
} |
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use scmd::{CmdContext, Command};
use starcoin_cmd::*;
use starcoin_cmd::{CliState, StarcoinOpt};
use starcoin_config::Connect;
use starcoin_logger::prelude::*;
use starcoin_rpc_client::RpcClient;
use std::sync::Arc;
fn run() -> Result<()> {
let logger_handle = starcoin_logger::init();
let context = CmdContext::<CliState, StarcoinOpt>::with_default_action(
|opt| -> Result<CliState> {
info!("Starcoin opts: {:?}", opt);
let connect = opt.connect.as_ref().unwrap_or(&Connect::IPC(None));
let (client, node_handle) = match connect {
Connect::IPC(ipc_file) => {
if let Some(ipc_file) = ipc_file {
info!("Try to connect node by ipc: {:?}", ipc_file);
let client = RpcClient::connect_ipc(ipc_file)?;
(client, None)
} else {
info!("Start starcoin node...");
let (node_handle, config) = starcoin_node::run_node_by_opt(opt)?;
let ipc_file = config.rpc.get_ipc_file();
helper::wait_until_file_created(ipc_file)?;
info!(
"Attach a new console by ipc: starcoin -c {} console",
ipc_file.to_str().expect("invalid ipc file path.")
);
if let Some(http_address) = config.rpc.get_http_address() {
info!(
"Attach a new console by rpc: starcoin -c {} console",
http_address
);
}
info!("Starcoin node started.");
info!("Try to connect node by ipc: {:?}", ipc_file);
let client = RpcClient::connect_ipc(ipc_file)?;
(client, node_handle)
}
}
Connect::WebSocket(address) => {
info!("Try to connect node by websocket: {:?}", address);
let client = RpcClient::connect_websocket(address)?;
(client, None)
}
};
let node_info = client.node_info()?;
let state = CliState::new(node_info.net, Arc::new(client), node_handle);
Ok(state)
},
|_, _, state| {
let (_, _, handle) = state.into_inner();
if let Some(handle) = handle {
if let Err(e) = handle.join() {
error!("{:?}", e);
}
}
},
);
let context = context.with_console_support(
move |_app, _opt, state| {
info!("Start console, disable stderr output.");
logger_handle.disable_stderr();
(*scmd::DEFAULT_CONSOLE_CONFIG, Some(state.history_file()))
},
|_, _, state| {
let (_, _, handle) = state.into_inner();
if let Some(handle) = handle {
if let Err(e) = handle.stop() {
error!("{:?}", e);
}
}
},
);
context
.command(
Command::with_name("wallet")
.subcommand(wallet::CreateCommand)
.subcommand(wallet::ShowCommand)
.subcommand(wallet::TransferCommand)
.subcommand(wallet::AcceptCoinCommand)
.subcommand(wallet::ListCommand)
.subcommand(wallet::PartialSignTxnCommand)
.subcommand(wallet::UnlockCommand)
.subcommand(wallet::ExportCommand)
.subcommand(wallet::ImportCommand)
.subcommand(wallet::ExecuteBuildInCommand),
)
.command(
Command::with_name("state")
.subcommand(state::GetCommand)
.subcommand(state::GetAccountCommand)
.subcommand(state::GetProofCommand)
.subcommand(state::GetRootCommand),
)
.command(
Command::with_name("node")
.subcommand(node::InfoCommand)
.subcommand(node::PeersCommand)
.subcommand(node::MetricsCommand),
)
.command(
Command::with_name("chain")
.subcommand(chain::ShowCommand)
.subcommand(chain::GetBlockByNumberCommand)
.subcommand(chain::ListBlockCommand)
.subcommand(chain::GetTransactionCommand)
.subcommand(chain::GetTxnByBlockCommand)
.subcommand(chain::GetTransactionInfoCommand)
.subcommand(chain::GetBlockCommand)
.subcommand(chain::BranchesCommand),
)
.command(
Command::with_name("dev")
.subcommand(dev::GetCoinCommand)
.subcommand(dev::CompileCommand)
.subcommand(dev::DeployCommand)
.subcommand(dev::ExecuteCommand)
.subcommand(dev::DeriveAddressCommand)
.subcommand(dev::GenerateMultisigTxnCommand)
.subcommand(dev::ExecuteMultiSignedTxnCommand)
.subcommand(dev::UpgradeStdlibCommand)
.subcommand(
Command::with_name("subscribe")
.subcommand(dev::SubscribeBlockCommand)
.subcommand(dev::SubscribeEventCommand)
.subcommand(dev::SubscribeNewTxnCommand),
),
)
.command(
Command::with_name("debug")
.subcommand(
Command::with_name("log")
.subcommand(debug::LogLevelCommand)
.subcommand(debug::LogPatternCommand),
)
.subcommand(debug::GenTxnCommand)
.subcommand(debug::PanicCommand),
)
.exec();
Ok(())
}
fn main() {
crash_handler::setup_panic_handler();
match run() {
Ok(()) => {}
Err(e) => panic!(format!("Unexpect error: {:?}", e)),
}
}
|
// src/lexer/lexer_test.rs
use crate::lexer::*;
use crate::token::*;
#[test]
fn test_next_token() {
let input = "
let five = 5;
let ten = 10;
let add = fn(x, y) {
x + y;
};
let result = add(five, ten);
!-/*5;
5 < 10 > 5;
if (5 < 10) {
return true;
} else {
return false;
}
10 == 10;
10 != 9;
\"foobar\"
\"foo bar\"
[1, 2];
{\"foo\": \"bar\"}
";
let tests = [
(TokenType::LET, "let"),
(TokenType::IDENT, "five"),
(TokenType::ASSIGN, "="),
(TokenType::INT, "5"),
(TokenType::SEMICOLON, ";"),
(TokenType::LET, "let"),
(TokenType::IDENT, "ten"),
(TokenType::ASSIGN, "="),
(TokenType::INT, "10"),
(TokenType::SEMICOLON, ";"),
(TokenType::LET, "let"),
(TokenType::IDENT, "add"),
(TokenType::ASSIGN, "="),
(TokenType::FUNCTION, "fn"),
(TokenType::LPAREN, "("),
(TokenType::IDENT, "x"),
(TokenType::COMMA, ","),
(TokenType::IDENT, "y"),
(TokenType::RPAREN, ")"),
(TokenType::LBRACE, "{"),
(TokenType::IDENT, "x"),
(TokenType::PLUS, "+"),
(TokenType::IDENT, "y"),
(TokenType::SEMICOLON, ";"),
(TokenType::RBRACE, "}"),
(TokenType::SEMICOLON, ";"),
(TokenType::LET, "let"),
(TokenType::IDENT, "result"),
(TokenType::ASSIGN, "="),
(TokenType::IDENT, "add"),
(TokenType::LPAREN, "("),
(TokenType::IDENT, "five"),
(TokenType::COMMA, ","),
(TokenType::IDENT, "ten"),
(TokenType::RPAREN, ")"),
(TokenType::SEMICOLON, ";"),
(TokenType::BANG, "!"),
(TokenType::MINUS, "-"),
(TokenType::SLASH, "/"),
(TokenType::ASTERISK, "*"),
(TokenType::INT, "5"),
(TokenType::SEMICOLON, ";"),
(TokenType::INT, "5"),
(TokenType::LT, "<"),
(TokenType::INT, "10"),
(TokenType::GT, ">"),
(TokenType::INT, "5"),
(TokenType::SEMICOLON, ";"),
(TokenType::IF, "if"),
(TokenType::LPAREN, "("),
(TokenType::INT, "5"),
(TokenType::LT, "<"),
(TokenType::INT, "10"),
(TokenType::RPAREN, ")"),
(TokenType::LBRACE, "{"),
(TokenType::RETURN, "return"),
(TokenType::TRUE, "true"),
(TokenType::SEMICOLON, ";"),
(TokenType::RBRACE, "}"),
(TokenType::ELSE, "else"),
(TokenType::LBRACE, "{"),
(TokenType::RETURN, "return"),
(TokenType::FALSE, "false"),
(TokenType::SEMICOLON, ";"),
(TokenType::RBRACE, "}"),
(TokenType::INT, "10"),
(TokenType::EQ, "=="),
(TokenType::INT, "10"),
(TokenType::SEMICOLON, ";"),
(TokenType::INT, "10"),
(TokenType::NOTEQ, "!="),
(TokenType::INT, "9"),
(TokenType::SEMICOLON, ";"),
(TokenType::STRING, "foobar"),
(TokenType::STRING, "foo bar"),
(TokenType::LBRACKET, "["),
(TokenType::INT, "1"),
(TokenType::COMMA, ","),
(TokenType::INT, "2"),
(TokenType::RBRACKET, "]"),
(TokenType::SEMICOLON, ";"),
(TokenType::LBRACE, "{"),
(TokenType::STRING, "foo"),
(TokenType::COLON, ":"),
(TokenType::STRING, "bar"),
(TokenType::RBRACE, "}"),
(TokenType::EOF, ""),
];
let mut l = Lexer::new(String::from(input));
for (i, tt) in tests.iter().enumerate() {
let tok = l.next_token();
assert!(
tok.r#type == tt.0,
"test[{}] - tokentype wrong. expected={:?}, got={:?}",
i,
tt.0,
tok.r#type
);
assert!(
tok.literal == tt.1,
"test[{}] - literal wrong. expected={}, got={}",
i,
tt.1,
tok.literal
);
}
}
|
// Copyright (c) Microsoft. All rights reserved.
extern crate edgelet_core;
extern crate edgelet_hsm;
use edgelet_core::{
Certificate, CertificateProperties, CertificateType, CreateCertificate, KeyBytes, PrivateKey,
Signature,
};
use edgelet_hsm::Crypto;
#[test]
fn crypto_create_cert_success() {
// arrange
let crypto = Crypto::new().unwrap();
// act
let props = CertificateProperties::new(
3600,
"Common Name".to_string(),
CertificateType::Ca,
"Alias".to_string(),
);
let cert_info = crypto.create_certificate(&props).unwrap();
let buffer = cert_info.pem().unwrap();
let pk = match cert_info.get_private_key().unwrap() {
Some(pk) => pk,
None => panic!("Expected to find a key"),
};
// assert
assert!(buffer.as_bytes().len() > 0);
match pk {
PrivateKey::Ref(_) => panic!("did not expect reference private key"),
PrivateKey::Key(KeyBytes::Pem(k)) => assert!(k.as_bytes().len() > 0),
}
crypto.destroy_certificate("Alias".to_string()).unwrap();
}
|
#[doc = "Register `IMR2` reader"]
pub type R = crate::R<IMR2_SPEC>;
#[doc = "Register `IMR2` writer"]
pub type W = crate::W<IMR2_SPEC>;
#[doc = "Field `MR32` reader - Interrupt Mask on external/internal line 32"]
pub type MR32_R = crate::BitReader<MR32_A>;
#[doc = "Interrupt Mask on external/internal line 32\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MR32_A {
#[doc = "0: Interrupt request line is masked"]
Masked = 0,
#[doc = "1: Interrupt request line is unmasked"]
Unmasked = 1,
}
impl From<MR32_A> for bool {
#[inline(always)]
fn from(variant: MR32_A) -> Self {
variant as u8 != 0
}
}
impl MR32_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MR32_A {
match self.bits {
false => MR32_A::Masked,
true => MR32_A::Unmasked,
}
}
#[doc = "Interrupt request line is masked"]
#[inline(always)]
pub fn is_masked(&self) -> bool {
*self == MR32_A::Masked
}
#[doc = "Interrupt request line is unmasked"]
#[inline(always)]
pub fn is_unmasked(&self) -> bool {
*self == MR32_A::Unmasked
}
}
#[doc = "Field `MR32` writer - Interrupt Mask on external/internal line 32"]
pub type MR32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MR32_A>;
impl<'a, REG, const O: u8> MR32_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
{
#[doc = "Interrupt request line is masked"]
#[inline(always)]
pub fn masked(self) -> &'a mut crate::W<REG> {
self.variant(MR32_A::Masked)
}
#[doc = "Interrupt request line is unmasked"]
#[inline(always)]
pub fn unmasked(self) -> &'a mut crate::W<REG> {
self.variant(MR32_A::Unmasked)
}
}
#[doc = "Field `MR33` reader - Interrupt Mask on external/internal line 33"]
pub use MR32_R as MR33_R;
#[doc = "Field `MR34` reader - Interrupt Mask on external/internal line 34"]
pub use MR32_R as MR34_R;
#[doc = "Field `MR35` reader - Interrupt Mask on external/internal line 35"]
pub use MR32_R as MR35_R;
#[doc = "Field `MR36` reader - Interrupt Mask on external/internal line 36"]
pub use MR32_R as MR36_R;
#[doc = "Field `MR37` reader - Interrupt Mask on external/internal line 37"]
pub use MR32_R as MR37_R;
#[doc = "Field `MR38` reader - Interrupt Mask on external/internal line 38"]
pub use MR32_R as MR38_R;
#[doc = "Field `MR39` reader - Interrupt Mask on external/internal line 39"]
pub use MR32_R as MR39_R;
#[doc = "Field `MR33` writer - Interrupt Mask on external/internal line 33"]
pub use MR32_W as MR33_W;
#[doc = "Field `MR34` writer - Interrupt Mask on external/internal line 34"]
pub use MR32_W as MR34_W;
#[doc = "Field `MR35` writer - Interrupt Mask on external/internal line 35"]
pub use MR32_W as MR35_W;
#[doc = "Field `MR36` writer - Interrupt Mask on external/internal line 36"]
pub use MR32_W as MR36_W;
#[doc = "Field `MR37` writer - Interrupt Mask on external/internal line 37"]
pub use MR32_W as MR37_W;
#[doc = "Field `MR38` writer - Interrupt Mask on external/internal line 38"]
pub use MR32_W as MR38_W;
#[doc = "Field `MR39` writer - Interrupt Mask on external/internal line 39"]
pub use MR32_W as MR39_W;
impl R {
#[doc = "Bit 0 - Interrupt Mask on external/internal line 32"]
#[inline(always)]
pub fn mr32(&self) -> MR32_R {
MR32_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Interrupt Mask on external/internal line 33"]
#[inline(always)]
pub fn mr33(&self) -> MR33_R {
MR33_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Interrupt Mask on external/internal line 34"]
#[inline(always)]
pub fn mr34(&self) -> MR34_R {
MR34_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Interrupt Mask on external/internal line 35"]
#[inline(always)]
pub fn mr35(&self) -> MR35_R {
MR35_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Interrupt Mask on external/internal line 36"]
#[inline(always)]
pub fn mr36(&self) -> MR36_R {
MR36_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Interrupt Mask on external/internal line 37"]
#[inline(always)]
pub fn mr37(&self) -> MR37_R {
MR37_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Interrupt Mask on external/internal line 38"]
#[inline(always)]
pub fn mr38(&self) -> MR38_R {
MR38_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Interrupt Mask on external/internal line 39"]
#[inline(always)]
pub fn mr39(&self) -> MR39_R {
MR39_R::new(((self.bits >> 7) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Interrupt Mask on external/internal line 32"]
#[inline(always)]
#[must_use]
pub fn mr32(&mut self) -> MR32_W<IMR2_SPEC, 0> {
MR32_W::new(self)
}
#[doc = "Bit 1 - Interrupt Mask on external/internal line 33"]
#[inline(always)]
#[must_use]
pub fn mr33(&mut self) -> MR33_W<IMR2_SPEC, 1> {
MR33_W::new(self)
}
#[doc = "Bit 2 - Interrupt Mask on external/internal line 34"]
#[inline(always)]
#[must_use]
pub fn mr34(&mut self) -> MR34_W<IMR2_SPEC, 2> {
MR34_W::new(self)
}
#[doc = "Bit 3 - Interrupt Mask on external/internal line 35"]
#[inline(always)]
#[must_use]
pub fn mr35(&mut self) -> MR35_W<IMR2_SPEC, 3> {
MR35_W::new(self)
}
#[doc = "Bit 4 - Interrupt Mask on external/internal line 36"]
#[inline(always)]
#[must_use]
pub fn mr36(&mut self) -> MR36_W<IMR2_SPEC, 4> {
MR36_W::new(self)
}
#[doc = "Bit 5 - Interrupt Mask on external/internal line 37"]
#[inline(always)]
#[must_use]
pub fn mr37(&mut self) -> MR37_W<IMR2_SPEC, 5> {
MR37_W::new(self)
}
#[doc = "Bit 6 - Interrupt Mask on external/internal line 38"]
#[inline(always)]
#[must_use]
pub fn mr38(&mut self) -> MR38_W<IMR2_SPEC, 6> {
MR38_W::new(self)
}
#[doc = "Bit 7 - Interrupt Mask on external/internal line 39"]
#[inline(always)]
#[must_use]
pub fn mr39(&mut self) -> MR39_W<IMR2_SPEC, 7> {
MR39_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`imr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`imr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct IMR2_SPEC;
impl crate::RegisterSpec for IMR2_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`imr2::R`](R) reader structure"]
impl crate::Readable for IMR2_SPEC {}
#[doc = "`write(|w| ..)` method takes [`imr2::W`](W) writer structure"]
impl crate::Writable for IMR2_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets IMR2 to value 0xffff_ff87"]
impl crate::Resettable for IMR2_SPEC {
const RESET_VALUE: Self::Ux = 0xffff_ff87;
}
|
use na::RealField;
use crate::aliases::{Qua, TVec};
/// Component-wise equality comparison between two quaternions.
pub fn quat_equal<T: RealField>(x: &Qua<T>, y: &Qua<T>) -> TVec<bool, 4> {
crate::equal(&x.coords, &y.coords)
}
/// Component-wise approximate equality comparison between two quaternions.
pub fn quat_equal_eps<T: RealField>(x: &Qua<T>, y: &Qua<T>, epsilon: T) -> TVec<bool, 4> {
crate::equal_eps(&x.coords, &y.coords, epsilon)
}
/// Component-wise non-equality comparison between two quaternions.
pub fn quat_not_equal<T: RealField>(x: &Qua<T>, y: &Qua<T>) -> TVec<bool, 4> {
crate::not_equal(&x.coords, &y.coords)
}
/// Component-wise approximate non-equality comparison between two quaternions.
pub fn quat_not_equal_eps<T: RealField>(x: &Qua<T>, y: &Qua<T>, epsilon: T) -> TVec<bool, 4> {
crate::not_equal_eps(&x.coords, &y.coords, epsilon)
}
|
use std::fs::File;
use std::io::Read;
fn main(){
let mut file = File::open("input.txt").expect("opening file");
let mut text = String::new();
file.read_to_string(&mut text).expect("reading file");
const MAX: usize = 1000;
let mut patches = vec![vec![0u8; MAX]; MAX];
for line in text.lines() {
let mut parts : Vec<&str> = line.split(" ").collect();
//println!("{:?}", parts);
let mut x = parts[2].split(",").collect::<Vec<&str>>()[0].parse::<i32>().unwrap();
let mut tmp = String::from(parts[2].split(",").collect::<Vec<&str>>()[1]);
tmp.pop(); //removes the ';' from the input
let y = tmp.parse::<i32>().unwrap();
let mut w = parts[3].split("x").collect::<Vec<&str>>()[0].parse::<i32>().unwrap();
let mut h = parts[3].split("x").collect::<Vec<&str>>()[1].parse::<i32>().unwrap();
setpatch(x,y,w,h,&mut patches);
}
let mut count = 0i32;
for i in 0..MAX {
for j in 0..MAX {
//println!("{:?}", patches[i])
if patches[i][j] > 1{
count += 1;
}
}
}
println!("{}",count);
}
fn setpatch(x : i32, y : i32, w : i32, h : i32, patches: &mut Vec<Vec<u8>>){
//println!("{}{}{}{}",x,y,w,h);
for xpos in x..(x+w) {
for ypos in y..(y+h){
patches[ypos as usize][xpos as usize] += 1;
}
}
}
|
use std::env;
pub struct Config {
port: u16,
env: String,
}
impl Config {
pub fn get() -> Self {
Config {
port: match env::var("PORT") {
Ok(port) => match port.parse() {
Ok(port) => port,
_ => 80,
},
_ => 80,
},
env: env::var("ENV").unwrap_or("development".to_owned()),
}
}
pub fn port(&self) -> u16 {
self.port
}
pub fn env(&self) -> &str {
&self.env
}
}
|
#![feature(test)]
extern crate test;
extern crate googleprojection;
use test::Bencher;
#[bench]
fn it_is_fast(b: &mut Bencher) {
let ll = (67.34, 190.34);
b.iter(|| {
let px = googleprojection::from_ll_to_pixel(&ll, 25);
googleprojection::from_pixel_to_ll(&px.unwrap(), 25)
});
}
|
#[derive(VulkanoShader)]
#[ty = "vertex"]
#[src = "
#version 450
layout(location = 0) in vec3 position;
layout(set = 0, binding = 0) uniform View {
mat4 view;
mat4 proj;
} view;
layout(set = 1, binding = 0) uniform World {
mat4 world;
} world;
void main() {
gl_Position = view.proj * view.view * world.world * vec4(position, 1.0);
// https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/
gl_Position.y = - gl_Position.y;
}
"]
struct _Dummy;
|
extern crate xpath;
use xpath::token;
use xpath::token::XPathToken;
use xpath::tokenizer::XPathTokenizer;
use xpath::tokenizer::{TokenResult,TokenizerErr};
use xpath::tokenizer::TokenizerErr::{
MismatchedQuoteCharacters,
MissingLocalName,
UnableToCreateToken,
};
use xpath::tokenizer::XPathTokenDisambiguator;
use xpath::tokenizer::XPathTokenDeabbreviator;
fn is_finished(tokenizer: & XPathTokenizer) -> bool {
! tokenizer.has_more_tokens()
}
fn all_tokens_raw<I: Iterator<TokenResult>>(mut tokenizer: I) -> Result<Vec<XPathToken>, TokenizerErr> {
tokenizer.collect()
}
fn all_tokens<I: Iterator<TokenResult>>(tokenizer: I) -> Vec<XPathToken> {
match all_tokens_raw(tokenizer) {
Ok(toks) => toks,
Err(msg) => panic!(msg),
}
}
#[test]
fn empty_string_has_no_tokens()
{
let tokenizer = xpath::tokenizer::XPathTokenizer::new("");
assert!(is_finished(&tokenizer));
}
#[test]
fn tokenizes_simple_string()
{
let tokenizer = XPathTokenizer::new("hello");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("hello".to_string())));
}
#[test]
fn tokenizes_grandchild_selector()
{
let tokenizer = XPathTokenizer::new("hello/world");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("hello".to_string()),
XPathToken::Slash,
XPathToken::String("world".to_string())));
}
#[test]
fn tokenizes_great_grandchild_selector()
{
let tokenizer = XPathTokenizer::new("hello/there/world");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("hello".to_string()),
XPathToken::Slash,
XPathToken::String("there".to_string()),
XPathToken::Slash,
XPathToken::String("world".to_string())));
}
#[test]
fn tokenizes_qualified_names()
{
let tokenizer = XPathTokenizer::new("ns:foo");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::PrefixedName("ns".to_string(), "foo".to_string())));
}
#[test]
fn ignores_whitespace_around_tokens()
{
let tokenizer = XPathTokenizer::new(" @\t@\n@\r");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::AtSign,
XPathToken::AtSign,
XPathToken::AtSign));
}
#[test]
fn tokenizes_wildcard_name_test()
{
let tokenizer = XPathTokenizer::new("*");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("*".to_string())));
}
#[test]
fn tokenizes_axis_separator()
{
let tokenizer = XPathTokenizer::new("::");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::DoubleColon));
}
#[test]
fn tokenizes_axis_selector()
{
let tokenizer = XPathTokenizer::new("hello::world");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("hello".to_string()),
XPathToken::DoubleColon,
XPathToken::String("world".to_string())));
}
#[test]
fn tokenizes_single_slash()
{
let tokenizer = XPathTokenizer::new("/");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Slash));
}
#[test]
fn tokenizes_double_slash()
{
let tokenizer = XPathTokenizer::new("//");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::DoubleSlash));
}
#[test]
fn tokenizes_double_slash_separator()
{
let tokenizer = XPathTokenizer::new("hello//world");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::String("hello".to_string()),
XPathToken::DoubleSlash,
XPathToken::String("world".to_string())));
}
#[test]
fn tokenizes_left_paren()
{
let tokenizer = XPathTokenizer::new("(");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::LeftParen));
}
#[test]
fn tokenizes_right_paren()
{
let tokenizer = XPathTokenizer::new(")");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::RightParen));
}
#[test]
fn tokenizes_at_sign()
{
let tokenizer = XPathTokenizer::new("@");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::AtSign));
}
#[test]
fn tokenizes_single_dot()
{
let tokenizer = XPathTokenizer::new(".");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::CurrentNode));
}
#[test]
fn tokenizes_double_dot()
{
let tokenizer = XPathTokenizer::new("..");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::ParentNode));
}
#[test]
fn tokenizes_integral_number()
{
let tokenizer = XPathTokenizer::new("42");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(42.0)));
}
#[test]
fn tokenizes_decimal_number()
{
let tokenizer = XPathTokenizer::new("42.42");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(42.42)));
}
#[test]
fn tokenizes_decimal_number_without_integral_part()
{
let tokenizer = XPathTokenizer::new(".40");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(0.40)));
}
#[test]
fn tokenizes_left_bracket()
{
let tokenizer = XPathTokenizer::new("[");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::LeftBracket));
}
#[test]
fn tokenizes_right_bracket()
{
let tokenizer = XPathTokenizer::new("]");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::RightBracket));
}
#[test]
fn tokenizes_apostrophe_literal()
{
let tokenizer = XPathTokenizer::new("'hello!'");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Literal("hello!".to_string())));
}
#[test]
fn tokenizes_double_quote_literal()
{
let tokenizer = XPathTokenizer::new("\"1.23\"");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Literal("1.23".to_string())));
}
#[test]
fn tokenizes_dollar_sign()
{
let tokenizer = XPathTokenizer::new("$");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::DollarSign));
}
#[test]
fn tokenizes_plus_sign()
{
let tokenizer = XPathTokenizer::new("+");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::PlusSign));
}
#[test]
fn tokenizes_minus_sign()
{
let tokenizer = XPathTokenizer::new("-");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::MinusSign));
}
#[test]
fn tokenizes_pipe()
{
let tokenizer = XPathTokenizer::new("|");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Pipe));
}
#[test]
fn tokenizes_equal_sign()
{
let tokenizer = XPathTokenizer::new("=");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Equal));
}
#[test]
fn tokenizes_not_equal_sign()
{
let tokenizer = XPathTokenizer::new("!=");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::NotEqual));
}
#[test]
fn tokenizes_less_than()
{
let tokenizer = XPathTokenizer::new("<");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::LessThan));
}
#[test]
fn tokenizes_less_than_or_equal()
{
let tokenizer = XPathTokenizer::new("<=");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::LessThanOrEqual));
}
#[test]
fn tokenizes_greater_than()
{
let tokenizer = XPathTokenizer::new(">");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::GreaterThan));
}
#[test]
fn tokenizes_greater_than_or_equal()
{
let tokenizer = XPathTokenizer::new(">=");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::GreaterThanOrEqual));
}
#[test]
fn special_preceding_token_forces_named_operator_and()
{
let tokenizer = XPathTokenizer::new("1andz2");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(1.0),
XPathToken::And,
XPathToken::String("z2".to_string())));
}
#[test]
fn special_preceding_token_forces_named_operator_or()
{
let tokenizer = XPathTokenizer::new("2oror");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(2.0),
XPathToken::Or,
XPathToken::String("or".to_string())));
}
#[test]
fn special_preceding_token_forces_named_operator_mod()
{
let tokenizer = XPathTokenizer::new("3moddiv");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(3.0),
XPathToken::Remainder,
XPathToken::String("div".to_string())));
}
#[test]
fn special_preceding_token_forces_named_operator_div()
{
let tokenizer = XPathTokenizer::new("1divz2");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(1.0),
XPathToken::Divide,
XPathToken::String("z2".to_string())));
}
#[test]
fn special_preceding_token_forces_named_operator_multiply()
{
let tokenizer = XPathTokenizer::new("1*2");
assert_eq!(all_tokens(tokenizer), vec!(XPathToken::Number(1.0),
XPathToken::Multiply,
XPathToken::Number(2.0)));
}
#[test]
fn exception_thrown_when_nothing_was_tokenized()
{
let tokenizer = XPathTokenizer::new("!");
let res = all_tokens_raw(tokenizer);
assert_eq!(Err(UnableToCreateToken), res);
}
#[test]
fn exception_thrown_when_name_test_has_no_local_name()
{
let tokenizer = XPathTokenizer::new("ns:");
let res = all_tokens_raw(tokenizer);
assert_eq!(Err(MissingLocalName), res);
}
#[test]
fn exception_thrown_when_quote_characters_mismatched()
{
let tokenizer = XPathTokenizer::new("'hello\"");
let res = all_tokens_raw(tokenizer);
assert_eq!(Err(MismatchedQuoteCharacters), res);
}
#[test]
fn disambiguates_node_test_functions() {
// Would prefer parametric tests
for name in ["comment", "text", "processing-instruction", "node"].iter() {
let input_tokens: Vec<TokenResult> = vec!(
Ok(XPathToken::String(name.to_string())),
Ok(XPathToken::LeftParen),
);
let disambig = XPathTokenDisambiguator::new(input_tokens.into_iter());
assert_eq!(all_tokens(disambig),
vec!(XPathToken::NodeTest(name.to_string()),
XPathToken::LeftParen));
}
}
#[test]
fn name_followed_by_left_paren_becomes_function_name() {
let input_tokens: Vec<TokenResult> = vec!(
Ok(XPathToken::String("test".to_string())),
Ok(XPathToken::LeftParen),
);
let disambig = XPathTokenDisambiguator::new(input_tokens.into_iter());
assert_eq!(all_tokens(disambig),
vec!(XPathToken::Function("test".to_string()),
XPathToken::LeftParen));
}
#[test]
fn name_followed_by_double_colon_becomes_axis_name() {
let input_tokens: Vec<TokenResult> = vec!(
Ok(XPathToken::String("test".to_string())),
Ok(XPathToken::DoubleColon),
);
let disambig = XPathTokenDisambiguator::new(input_tokens.into_iter());
assert_eq!(all_tokens(disambig),
vec!(XPathToken::Axis("test".to_string()),
XPathToken::DoubleColon));
}
#[test]
fn converts_at_sign_to_attribute_axis() {
let input_tokens: Vec<TokenResult> = vec!(Ok(XPathToken::AtSign));
// let iter: &Iterator<TokenResult> = &input_tokens.into_iter();
let deabbrv = XPathTokenDeabbreviator::new(input_tokens.into_iter());
// let a: () = deabbrv.next();
// println!("{}",a );
assert_eq!(all_tokens(deabbrv), vec!(XPathToken::String("attribute".to_string()),
XPathToken::DoubleColon));
}
#[test]
fn converts_double_slash_to_descendant_or_self() {
let input_tokens: Vec<TokenResult> = vec!(Ok(XPathToken::DoubleSlash));
let deabbrv = XPathTokenDeabbreviator::new(input_tokens.into_iter());
assert_eq!(all_tokens(deabbrv), vec!(XPathToken::Slash,
XPathToken::String("descendant-or-self".to_string()),
XPathToken::DoubleColon,
XPathToken::String("node".to_string()),
XPathToken::LeftParen,
XPathToken::RightParen,
XPathToken::Slash));
}
#[test]
fn converts_current_node_to_self_node() {
let input_tokens: Vec<TokenResult> = vec!(Ok(XPathToken::CurrentNode));
let deabbrv = XPathTokenDeabbreviator::new(input_tokens.into_iter());
assert_eq!(all_tokens(deabbrv), vec!(XPathToken::String("self".to_string()),
XPathToken::DoubleColon,
XPathToken::String("node".to_string()),
XPathToken::LeftParen,
XPathToken::RightParen));
}
#[test]
fn converts_parent_node_to_parent_node() {
let input_tokens: Vec<TokenResult> = vec!(Ok(XPathToken::ParentNode));
let deabbrv = XPathTokenDeabbreviator::new(input_tokens.into_iter());
assert_eq!(all_tokens(deabbrv), vec!(XPathToken::String("parent".to_string()),
XPathToken::DoubleColon,
XPathToken::String("node".to_string()),
XPathToken::LeftParen,
XPathToken::RightParen));
}
|
fn main() {
//とりあえず定義
let gs = vec![17, 23, 24, 5434, 3];
let mut fes = Vec::<FieldElement>::new();
for g in gs {
let fe_result = FieldElement::new(g, 25);
match fe_result {
Some(fe) => fes.push(fe),
None => println!("{}", " NON"),
}
}
//出力
for fe in &fes {
println!("{}", fe.to_str())
}
//NONEの時には終了
let r1 = FieldElement::new(4, 5).expect("Err!!1");
let r2 = FieldElement::new(3, 5).expect("NONE invalid fe");
let r12 = FieldElement::new(4, 5);
let r22 = FieldElement::new(24, 5);
//println!(" {}=={} is {}", r12.to_str(),r22.to_str() , r12 == r22);
//特に定義しなくても Option<T>のイコールで比較は可能のようだ
println!(" check {}", r12 == r22);
let r3 = (&r1 + &r2).expect("eee");
let r4 = (&r1 - &r2).expect("eee");
let r5 = (&r1 * &r2).expect("eee");
println!("{} + {} = {} ", r1, r2, r3);
println!("{} - {} = {} ", r1, r2, r4);
println!("{} * {} = {} ", r1, r2, r5);
println!("{} * {} = {} ", r1, 7, &r1 * 7 );
println!("{} * {} = {} ", 17, r1, 17 * &r1 );
//println!(" heyhey {} " , r1+r2);
println!(
"FiledElement size_of is {}",
std::mem::size_of::<FieldElement>()
);
}
//Prime 割る数
//NUM割られる数
struct FieldElement {
num: isize,
prime: isize,
}
impl FieldElement {
//文字列を表示させる
fn to_str(&self) -> String {
format!("f_{}({})", self.prime ,self.num)
}
//条件に満たない場合はエラー文言を出すようにします。
pub fn new(num: isize, prime: isize) -> Option<FieldElement> {
if num >= prime || num < 0 {
None
} else {
let fe = FieldElement {
num: num,
prime: prime,
};
Some(fe)
}
}
}
use std::cmp::PartialEq;
impl PartialEq<FieldElement> for FieldElement {
fn eq(&self, rhs: &FieldElement) -> bool {
let res = self.num == rhs.num && self.prime == rhs.prime;
res
}
}
use std::fmt;
impl fmt::Display for FieldElement {
// This trait requires `fmt` with this exact signature.
// このトレイトは`fmt`が想定通りのシグネチャであることを要求します。
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Write strictly the first element into the supplied output
// stream: `f`. Returns `fmt::Result` which indicates whether the
// operation succeeded or failed. Note that `write!` uses syntax which
// is very similar to `println!`.
// 必ず、第一の要素が出力されるようにしています。
// `f`は`fmt::Result`を返します。これはオペレーションが成功したか否か
// を表します。
// `write!`は`println!`に非常によく似た文法を使用していることに注目。
write!(f, "{}", self.to_str())
}
}
use std::ops::Add;
impl Add<&FieldElement> for &FieldElement {
type Output = Option<FieldElement>;
fn add<'a>(self, rhs: &'a FieldElement) -> Self::Output {
if self.prime != rhs.prime {
//let _s = "cant add two numbers in diffrent Fields";
//Err(&_s)
None
} else {
let _num = (self.num + rhs.num) % self.prime;
FieldElement::new(_num, self.prime)
//let fe_result = FieldElement::new(g, 25);
}
}
}
use std::ops::Sub;
impl Sub<&FieldElement> for &FieldElement {
type Output = Option<FieldElement>;
fn sub<'a>(self, rhs: &'a FieldElement) -> Self::Output {
if self.prime != rhs.prime {
// let _s = "cant add two numbers in diffrent Fields";
//Err(&_s)
None
} else {
let _num = (self.num - rhs.num) % self.prime;
let _num2 = if _num < 0 { self.prime + _num } else { _num };
FieldElement::new(_num2, self.prime)
}
}
}
//掛け算
use std::ops::Mul;
impl Mul<&FieldElement> for &FieldElement {
type Output = Option<FieldElement>;
fn mul<'a>(self, rhs: &'a FieldElement) -> Self::Output {
if self.prime != rhs.prime {
//let _s = "cant add two numbers in diffrent Fields";
None
} else {
let _num = (self.num * rhs.num) % self.prime;
FieldElement::new(_num, self.prime)
}
}
}
// FieldElement * 3
impl Mul<isize> for &FieldElement {
type Output = FieldElement;
fn mul(self, rhs: isize) -> Self::Output {
let _num = (self.num * rhs) % self.prime;
FieldElement::new(_num, self.prime).expect("test")
}
}
//3*FieldElement
impl Mul<&FieldElement> for isize {
type Output = FieldElement;
fn mul(self, rhs: &FieldElement) -> Self::Output {
let _num = (self * rhs.num) % rhs.prime;
FieldElement::new(_num, rhs.prime).expect("test")
}
}
//use std::ops::BitXor
//OPTIONで演算を定義したい
//タプル構造体?
struct OpFileldElement(Option<FieldElement>);
use std::ops::Deref;
//use std::ops::DerefMut;
impl Deref for OpFileldElement {
type Target = Option<FieldElement>;
fn deref(&self) -> &Self::Target {
//&self.
let ss = &self.0;
ss
}
}
/*
impl OpFileldElement<FieldElement> {
//文字列を表示させる
fn to_str(&self) -> String {
let ss = &self.0;
match ss {
None => format!("None"),
Some(fe) => format!("f_{}({})", fe.prime ,fe.num),
}
}
}
*/ |
#[doc = "Register `OSPEEDR` reader"]
pub type R = crate::R<OSPEEDR_SPEC>;
#[doc = "Register `OSPEEDR` writer"]
pub type W = crate::W<OSPEEDR_SPEC>;
#[doc = "Field `OSPEED0` reader - Port x configuration bits (y = 0..15)"]
pub type OSPEED0_R = crate::FieldReader<OSPEED0_A>;
#[doc = "Port x configuration bits (y = 0..15)\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum OSPEED0_A {
#[doc = "0: Low speed"]
LowSpeed = 0,
#[doc = "1: Medium speed"]
MediumSpeed = 1,
#[doc = "2: High speed"]
HighSpeed = 2,
#[doc = "3: Very high speed"]
VeryHighSpeed = 3,
}
impl From<OSPEED0_A> for u8 {
#[inline(always)]
fn from(variant: OSPEED0_A) -> Self {
variant as _
}
}
impl crate::FieldSpec for OSPEED0_A {
type Ux = u8;
}
impl OSPEED0_R {
#[doc = "Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OSPEED0_A {
match self.bits {
0 => OSPEED0_A::LowSpeed,
1 => OSPEED0_A::MediumSpeed,
2 => OSPEED0_A::HighSpeed,
3 => OSPEED0_A::VeryHighSpeed,
_ => unreachable!(),
}
}
#[doc = "Low speed"]
#[inline(always)]
pub fn is_low_speed(&self) -> bool {
*self == OSPEED0_A::LowSpeed
}
#[doc = "Medium speed"]
#[inline(always)]
pub fn is_medium_speed(&self) -> bool {
*self == OSPEED0_A::MediumSpeed
}
#[doc = "High speed"]
#[inline(always)]
pub fn is_high_speed(&self) -> bool {
*self == OSPEED0_A::HighSpeed
}
#[doc = "Very high speed"]
#[inline(always)]
pub fn is_very_high_speed(&self) -> bool {
*self == OSPEED0_A::VeryHighSpeed
}
}
#[doc = "Field `OSPEED0` writer - Port x configuration bits (y = 0..15)"]
pub type OSPEED0_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, OSPEED0_A>;
impl<'a, REG, const O: u8> OSPEED0_W<'a, REG, O>
where
REG: crate::Writable + crate::RegisterSpec,
REG::Ux: From<u8>,
{
#[doc = "Low speed"]
#[inline(always)]
pub fn low_speed(self) -> &'a mut crate::W<REG> {
self.variant(OSPEED0_A::LowSpeed)
}
#[doc = "Medium speed"]
#[inline(always)]
pub fn medium_speed(self) -> &'a mut crate::W<REG> {
self.variant(OSPEED0_A::MediumSpeed)
}
#[doc = "High speed"]
#[inline(always)]
pub fn high_speed(self) -> &'a mut crate::W<REG> {
self.variant(OSPEED0_A::HighSpeed)
}
#[doc = "Very high speed"]
#[inline(always)]
pub fn very_high_speed(self) -> &'a mut crate::W<REG> {
self.variant(OSPEED0_A::VeryHighSpeed)
}
}
#[doc = "Field `OSPEED1` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED1_R;
#[doc = "Field `OSPEED2` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED2_R;
#[doc = "Field `OSPEED3` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED3_R;
#[doc = "Field `OSPEED4` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED4_R;
#[doc = "Field `OSPEED5` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED5_R;
#[doc = "Field `OSPEED6` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED6_R;
#[doc = "Field `OSPEED7` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED7_R;
#[doc = "Field `OSPEED8` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED8_R;
#[doc = "Field `OSPEED9` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED9_R;
#[doc = "Field `OSPEED10` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED10_R;
#[doc = "Field `OSPEED11` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED11_R;
#[doc = "Field `OSPEED12` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED12_R;
#[doc = "Field `OSPEED13` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED13_R;
#[doc = "Field `OSPEED14` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED14_R;
#[doc = "Field `OSPEED15` reader - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_R as OSPEED15_R;
#[doc = "Field `OSPEED1` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED1_W;
#[doc = "Field `OSPEED2` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED2_W;
#[doc = "Field `OSPEED3` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED3_W;
#[doc = "Field `OSPEED4` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED4_W;
#[doc = "Field `OSPEED5` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED5_W;
#[doc = "Field `OSPEED6` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED6_W;
#[doc = "Field `OSPEED7` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED7_W;
#[doc = "Field `OSPEED8` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED8_W;
#[doc = "Field `OSPEED9` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED9_W;
#[doc = "Field `OSPEED10` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED10_W;
#[doc = "Field `OSPEED11` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED11_W;
#[doc = "Field `OSPEED12` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED12_W;
#[doc = "Field `OSPEED13` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED13_W;
#[doc = "Field `OSPEED14` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED14_W;
#[doc = "Field `OSPEED15` writer - Port x configuration bits (y = 0..15)"]
pub use OSPEED0_W as OSPEED15_W;
impl R {
#[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed0(&self) -> OSPEED0_R {
OSPEED0_R::new((self.bits & 3) as u8)
}
#[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed1(&self) -> OSPEED1_R {
OSPEED1_R::new(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed2(&self) -> OSPEED2_R {
OSPEED2_R::new(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed3(&self) -> OSPEED3_R {
OSPEED3_R::new(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed4(&self) -> OSPEED4_R {
OSPEED4_R::new(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed5(&self) -> OSPEED5_R {
OSPEED5_R::new(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed6(&self) -> OSPEED6_R {
OSPEED6_R::new(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed7(&self) -> OSPEED7_R {
OSPEED7_R::new(((self.bits >> 14) & 3) as u8)
}
#[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed8(&self) -> OSPEED8_R {
OSPEED8_R::new(((self.bits >> 16) & 3) as u8)
}
#[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed9(&self) -> OSPEED9_R {
OSPEED9_R::new(((self.bits >> 18) & 3) as u8)
}
#[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed10(&self) -> OSPEED10_R {
OSPEED10_R::new(((self.bits >> 20) & 3) as u8)
}
#[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed11(&self) -> OSPEED11_R {
OSPEED11_R::new(((self.bits >> 22) & 3) as u8)
}
#[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed12(&self) -> OSPEED12_R {
OSPEED12_R::new(((self.bits >> 24) & 3) as u8)
}
#[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed13(&self) -> OSPEED13_R {
OSPEED13_R::new(((self.bits >> 26) & 3) as u8)
}
#[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed14(&self) -> OSPEED14_R {
OSPEED14_R::new(((self.bits >> 28) & 3) as u8)
}
#[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
pub fn ospeed15(&self) -> OSPEED15_R {
OSPEED15_R::new(((self.bits >> 30) & 3) as u8)
}
}
impl W {
#[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed0(&mut self) -> OSPEED0_W<OSPEEDR_SPEC, 0> {
OSPEED0_W::new(self)
}
#[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed1(&mut self) -> OSPEED1_W<OSPEEDR_SPEC, 2> {
OSPEED1_W::new(self)
}
#[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed2(&mut self) -> OSPEED2_W<OSPEEDR_SPEC, 4> {
OSPEED2_W::new(self)
}
#[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed3(&mut self) -> OSPEED3_W<OSPEEDR_SPEC, 6> {
OSPEED3_W::new(self)
}
#[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed4(&mut self) -> OSPEED4_W<OSPEEDR_SPEC, 8> {
OSPEED4_W::new(self)
}
#[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed5(&mut self) -> OSPEED5_W<OSPEEDR_SPEC, 10> {
OSPEED5_W::new(self)
}
#[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed6(&mut self) -> OSPEED6_W<OSPEEDR_SPEC, 12> {
OSPEED6_W::new(self)
}
#[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed7(&mut self) -> OSPEED7_W<OSPEEDR_SPEC, 14> {
OSPEED7_W::new(self)
}
#[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed8(&mut self) -> OSPEED8_W<OSPEEDR_SPEC, 16> {
OSPEED8_W::new(self)
}
#[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed9(&mut self) -> OSPEED9_W<OSPEEDR_SPEC, 18> {
OSPEED9_W::new(self)
}
#[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed10(&mut self) -> OSPEED10_W<OSPEEDR_SPEC, 20> {
OSPEED10_W::new(self)
}
#[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed11(&mut self) -> OSPEED11_W<OSPEEDR_SPEC, 22> {
OSPEED11_W::new(self)
}
#[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed12(&mut self) -> OSPEED12_W<OSPEEDR_SPEC, 24> {
OSPEED12_W::new(self)
}
#[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed13(&mut self) -> OSPEED13_W<OSPEEDR_SPEC, 26> {
OSPEED13_W::new(self)
}
#[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed14(&mut self) -> OSPEED14_W<OSPEEDR_SPEC, 28> {
OSPEED14_W::new(self)
}
#[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"]
#[inline(always)]
#[must_use]
pub fn ospeed15(&mut self) -> OSPEED15_W<OSPEEDR_SPEC, 30> {
OSPEED15_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "GPIO port output speed register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ospeedr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ospeedr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct OSPEEDR_SPEC;
impl crate::RegisterSpec for OSPEEDR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`ospeedr::R`](R) reader structure"]
impl crate::Readable for OSPEEDR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`ospeedr::W`](W) writer structure"]
impl crate::Writable for OSPEEDR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets OSPEEDR to value 0"]
impl crate::Resettable for OSPEEDR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use glutin;
pub fn init<'a>() -> glutin::WindowBuilder<'a>{
let wb = glutin::WindowBuilder::new()
.with_title("Game".to_string())
.with_dimensions(1024, 768)
.with_vsync();
return wb;
}
|
pub fn error(line: u32, message: &str) {
report_error(line, "", message);
}
fn report_error(line: u32, location: &str, message: &str) {
println!("[line {}] Error {}: {}", line, location, message);
}
|
pub mod num;
pub mod source;
pub mod player;
pub mod wave;
pub mod effects;
pub mod tempo;
pub mod pitch;
pub mod note;
pub mod compass;
pub mod song;
|
extern crate clap;
use clap::{App, ErrorKind};
#[test]
fn version_short() {
let m = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.get_matches_from_safe(vec!["myprog", "-V"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind, ErrorKind::VersionDisplayed);
}
#[test]
fn version_long() {
let m = App::new("test")
.author("Kevin K.")
.about("tests stuff")
.version("1.3")
.get_matches_from_safe(vec!["myprog", "--version"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind, ErrorKind::VersionDisplayed);
}
|
#![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CanceledSubscriptionId {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RenamedSubscriptionId {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnabledSubscriptionId {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionName {
#[serde(rename = "subscriptionName", default, skip_serializing_if = "Option::is_none")]
pub subscription_name: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Operation>,
#[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")]
pub next_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Operation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display: Option<operation::Display>,
}
pub mod operation {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Display {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resource: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation: Option<String>,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionCreationResult {
#[serde(rename = "subscriptionLink", default, skip_serializing_if = "Option::is_none")]
pub subscription_link: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModernSubscriptionCreationParameters {
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(rename = "billingProfileId")]
pub billing_profile_id: String,
#[serde(rename = "skuId")]
pub sku_id: String,
#[serde(rename = "costCenter", default, skip_serializing_if = "Option::is_none")]
pub cost_center: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<AdPrincipal>,
#[serde(rename = "managementGroupId", default, skip_serializing_if = "Option::is_none")]
pub management_group_id: Option<String>,
#[serde(rename = "additionalParameters", default, skip_serializing_if = "Option::is_none")]
pub additional_parameters: Option<serde_json::Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ModernCspSubscriptionCreationParameters {
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(rename = "skuId")]
pub sku_id: String,
#[serde(rename = "resellerId", default, skip_serializing_if = "Option::is_none")]
pub reseller_id: Option<String>,
#[serde(rename = "serviceProviderId", default, skip_serializing_if = "Option::is_none")]
pub service_provider_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AdPrincipal {
#[serde(rename = "objectId")]
pub object_id: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionOperationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<SubscriptionOperation>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionOperation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
#[serde(rename = "statusDetail", default, skip_serializing_if = "Option::is_none")]
pub status_detail: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Location {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latitude: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub longitude: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LocationListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Location>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Subscription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")]
pub subscription_id: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<subscription::State>,
#[serde(rename = "subscriptionPolicies", default, skip_serializing_if = "Option::is_none")]
pub subscription_policies: Option<SubscriptionPolicies>,
#[serde(rename = "authorizationSource", default, skip_serializing_if = "Option::is_none")]
pub authorization_source: Option<String>,
}
pub mod subscription {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum State {
Enabled,
Warned,
PastDue,
Disabled,
Deleted,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionPolicies {
#[serde(rename = "locationPlacementId", default, skip_serializing_if = "Option::is_none")]
pub location_placement_id: Option<String>,
#[serde(rename = "quotaId", default, skip_serializing_if = "Option::is_none")]
pub quota_id: Option<String>,
#[serde(rename = "spendingLimit", default, skip_serializing_if = "Option::is_none")]
pub spending_limit: Option<subscription_policies::SpendingLimit>,
}
pub mod subscription_policies {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SpendingLimit {
On,
Off,
CurrentPeriodOff,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<Subscription>,
#[serde(rename = "nextLink")]
pub next_link: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TenantIdDescription {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TenantListResult {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<TenantIdDescription>,
#[serde(rename = "nextLink")]
pub next_link: String,
}
|
//! Integration test against the live `advisory-db` repo on GitHub
#![cfg(feature = "git")]
#![warn(rust_2018_idioms, unused_qualifications)]
use std::time::Duration;
use rustsec::{
advisory, database::Query, repository::git, Collection, Database, Lockfile, VersionReq,
};
use tempfile::tempdir;
/// Happy path integration test (has online dependency on GitHub)
///
/// TODO: disabled because `cargo-edit` has unpatched vulnerabilities.
/// However, the `rustsec` crate is not impacted by them
#[test]
#[cfg(feature = "fixme")] // TODO(tarcieri): re-enable this test
fn happy_path() {
let db = Database::load_from_repo(&git::Repository::fetch_default_repo().unwrap()).unwrap();
verify_rustsec_2017_0001(&db);
verify_cve_2018_1000810(&db);
}
/// End-to-end integration test (has online dependency on GitHub) which looks
/// for the `RUSTSEC-2017-0001` vulnerability (`sodiumoxide` crate).
#[allow(dead_code)] // TODO(tarcieri): fix `happy_path` test
fn verify_rustsec_2017_0001(db: &Database) {
let example_advisory_id = "RUSTSEC-2017-0001".parse::<advisory::Id>().unwrap();
let example_advisory = db.get(&example_advisory_id).unwrap();
let example_package = "sodiumoxide".parse().unwrap();
assert_eq!(example_advisory.metadata.id, example_advisory_id);
assert_eq!(example_advisory.metadata.package, example_package);
assert_eq!(
example_advisory.versions.patched()[0],
VersionReq::parse(">= 0.0.14").unwrap()
);
assert_eq!(example_advisory.metadata.date.as_str(), "2017-01-26");
assert_eq!(
example_advisory.metadata.url.as_ref().unwrap().to_string(),
"https://github.com/dnaq/sodiumoxide/issues/154"
);
assert_eq!(
example_advisory.title(),
"scalarmult() vulnerable to degenerate public keys"
);
assert_eq!(
&example_advisory.description()[0..30],
"The `scalarmult()` function in"
);
assert_eq!(
example_advisory.metadata.collection.unwrap(),
Collection::Crates
);
let crate_advisories = db.query(&Query::new().package_name(example_package).year(2017));
assert_eq!(example_advisory, crate_advisories[0]);
let lockfile = Lockfile::load("Cargo.lock").unwrap();
let vulns = db.vulnerabilities(&lockfile);
// TODO(tarcieri): find, file, and fix the version matching bug causing this
assert_eq!(
vulns
.iter()
.find(|v| !["RUSTSEC-2021-0055", "RUSTSEC-2021-0056"]
.iter()
.any(|id| v.advisory.id == id.parse().unwrap())),
None
);
}
/// End-to-end integration test (has online dependency on GitHub) which looks
/// for the `CVE-2018-1000810` vulnerability (`std::str::repeat`)
#[allow(dead_code)] // TODO(tarcieri): fix `happy_path` test
fn verify_cve_2018_1000810(db: &Database) {
let example_advisory_id = "CVE-2018-1000810".parse::<advisory::Id>().unwrap();
let example_advisory = db.get(&example_advisory_id).unwrap();
let example_package = "std".parse().unwrap();
assert_eq!(example_advisory.metadata.id, example_advisory_id);
assert_eq!(example_advisory.metadata.package, example_package);
assert_eq!(
example_advisory.versions.patched()[0],
VersionReq::parse(">= 1.29.1").unwrap()
);
assert_eq!(example_advisory.metadata.date.as_str(), "2018-09-21");
assert_eq!(
example_advisory.metadata.url.as_ref().unwrap().to_string(),
"https://groups.google.com/forum/#!topic/rustlang-security-announcements/CmSuTm-SaU0"
);
assert_eq!(
example_advisory.title(),
"Buffer overflow vulnerability in str::repeat()"
);
assert_eq!(
&example_advisory.description()[0..30],
"The Rust team was recently not"
);
assert_eq!(
example_advisory.metadata.collection.unwrap(),
Collection::Rust
);
}
/// Regression test for cloning into an existing directory
#[test]
fn clone_into_existing_directory() {
// Make an empty temporary directory
let tmp = tempdir().unwrap();
// Attempt to fetch into it
git::Repository::fetch(
git::DEFAULT_URL,
tmp.path(),
true,
Duration::from_secs(5 * 60),
)
.unwrap();
}
|
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#[cfg(all(feature = "nightly", test))]
extern crate test;
// use std::sync::mpsc::channel;
// use std::sync::{Arc, Mutex, Weak};
// use std::thread;
// use slab::Slab;
// #[derive(Debug)]
// struct Order {
// id: u32,
// price: u64,
// }
// struct OrderSlot {
// order: Order,
// ty: u8,
// next: Option<Weak<Mutex<OrderSlot>>>,
// }
// pub struct OrderBook {
// slots: Slab<Arc<Mutex<OrderSlot>>>,
// }
// impl OrderBook {
// pub fn with_capacity(capacity: usize) -> OrderBook {
// OrderBook {
// slots: Slab::with_capacity(capacity),
// }
// }
// // fn get(&self, key: usize) -> Arc<Mutex<Order>> {
// // self.slots.get(key).unwrap().clone()
// // }
// }
// #[test]
// fn test_weak() {
// let mut order_book = OrderBook::with_capacity(1000);
// let order1 = Order { id: 1, price: 100 };
// let order_slot1 = Arc::new(Mutex::new(OrderSlot {
// order: order1,
// ty: 1,
// next: None,
// }));
// let order2 = Order { id: 2, price: 100 };
// let order_slot2 = Arc::new(Mutex::new(OrderSlot {
// order: order2,
// ty: 1,
// next: Some(Arc::downgrade(&order_slot1)),
// }));
// let order_key1 = order_book.slots.insert(order_slot1);
// let order_key2 = order_book.slots.insert(order_slot2);
// // assert_eq!(1, order_slot1.lock().unwrap().ty);
// }
fn main() {
// let mut slots = Slab::<Arc<Mutex<Order>>>::with_capacity(10_1000);
// let order1 = Arc::new(Mutex::new(Order { id: 1, price: 100 }));
// let key = slots.insert(order1);
// let (tx, rx) = channel::<Arc<Mutex<Order>>>();
// let handle = thread::spawn(move || {
// let order1_l = rx.recv().unwrap();
// let mut order1_l = order1_l.lock().unwrap();
// println!("{}", order1_l.id);
// order1_l.id = 2;
// });
// let _ = tx.send(slots.get(key).unwrap().clone());
// let _ = handle.join();
// let order1 = slots.get(key).unwrap();
// println!("{}", order1.lock().unwrap().id);
}
#[cfg(all(feature = "nightly", test))]
mod bench {
use super::*;
use actix_rt::System;
use actix_web::{web, App, HttpResponse, HttpServer};
use http::StatusCode;
use std::io;
use std::sync::Once;
use std::thread;
use test::Bencher;
static INIT: Once = Once::new();
fn setup() {
INIT.call_once(|| {
let _ = env_logger::init();
});
}
#[bench]
fn bench_http_server(b: &mut Bencher) -> io::Result<()> {
setup();
thread::spawn(move || {
let sys = System::new("http-server");
let _server =
HttpServer::new(|| App::new().route("/", web::get().to(|| HttpResponse::Ok())))
.bind("127.0.0.1:8080")
.unwrap()
.shutdown_timeout(1)
.run();
let _ = sys.run();
});
thread::sleep(std::time::Duration::from_millis(100));
b.iter(|| {
assert!(reqwest::blocking::get("http://127.0.0.1:8080")
.and_then(|response| {
assert_eq!(StatusCode::OK, response.status());
Ok(())
})
.is_ok());
});
Ok(())
}
}
|
#[cfg(test)]
mod tests {
use lib::{
permutations_with_repetitions,
get_all_permutations,
};
use std::collections::HashSet;
#[test]
fn test_permutations_with_repetitions() {
let total_amount: u32 = 10;
let selection_amount: u32 = 4;
assert_eq!(
permutations_with_repetitions(
total_amount,
selection_amount,
),
10000,
);
}
#[test]
fn test_print_all_permutations_with_repetitions() {
let array: [u8; 2] = [1, 2];
let all_permutations = get_all_permutations(
&array,
2,
true,
);
let mut result: HashSet<Vec<u8>> = HashSet::new();
result.insert(vec![1, 1]);
result.insert(vec![1, 2]);
result.insert(vec![2, 1]);
result.insert(vec![2, 2]);
assert_eq!(
all_permutations,
result,
);
}
#[test]
fn test_print_some_permutations_with_repetitions() {
let array: [u8; 3] = [1, 2, 3];
let all_permutations = get_all_permutations(
&array,
2,
true,
);
let mut result: HashSet<Vec<u8>> = HashSet::new();
result.insert(vec![1, 1]);
result.insert(vec![1, 2]);
result.insert(vec![1, 3]);
result.insert(vec![2, 1]);
result.insert(vec![2, 2]);
result.insert(vec![2, 3]);
result.insert(vec![3, 1]);
result.insert(vec![3, 2]);
result.insert(vec![3, 3]);
assert_eq!(
all_permutations,
result,
);
}
}
|
use crate::prelude::*;
use crate::boiler_plate::InputEvent;
const GRAVITY: f64 = 0.0035;
const DRAG: Vec2<f64> = Vec2{ x: 15.0, y: 2.0, };
const FRICTION: f64 = 0.5;
#[derive(Debug)]
pub struct GameState {
pub player: Player,
pub platforms: Vec<Platform>,
pub enemies: Vec<Enemy>,
}
impl GameState {
pub fn new() -> Self {
Self {
player: Player::new(),
platforms: Vec::new(),
enemies: Vec::new(),
}
}
pub fn tick(&mut self, delta: f64) {
self.player.do_movement(&self.platforms, &mut self.enemies, delta);
if self.player.hp < 0.0 {
self.player = Player::new();
}
let player = &mut self.player;
let platforms = &self.platforms;
let enemies = &mut self.enemies;
for i in 0..enemies.len() {
let mut e = enemies.remove(i);
e.do_movement(player, platforms, enemies);
enemies.insert(i, e);
}
}
pub fn input_event(&mut self, e: InputEvent) {
use InputEvent::*;
match e {
KeyDown(k) => match k.as_str() {
"d" | "ArrowRight" => self.player.movement[0] = true,
"a" | "ArrowLeft" => self.player.movement[1] = true,
"w" | "ArrowUp" => self.player.movement[2] = true,
"x" => self.player.detonate_thread(),
_ => {},
}
KeyUp(k) => match k.as_str() {
"d" | "ArrowRight" => self.player.movement[0] = false,
"a" | "ArrowLeft" => self.player.movement[1] = false,
"w" | "ArrowUp" => self.player.movement[2] = false,
_ => {},
}
_ => {},
}
}
pub fn render(&self) -> Vec<Vertex> {
let mut r = Vec::new(); let v = &mut r;
self.player.render(v);
let player_hp_frac = self.player.hp / self.player.max_hp();
self.platforms.iter().for_each(|x| x.render(v, player_hp_frac));
self.enemies.iter().for_each(|x| x.render(v));
r
}
}
pub trait BoundingBox {
fn pos(&self) -> Vec2<f64>;
fn size(&self) -> Vec2<f64>;
fn vel(&self) -> Vec2<f64>;
fn centre_pos(&self) -> Vec2<f64> { self.pos() + self.size() / 2.0 }
fn left_edge(&self) -> f64 { self.pos().x - self.size().x }
fn right_edge(&self) -> f64 { self.pos().x + self.size().x }
fn bottom_edge(&self) -> f64 { self.pos().y + self.size().y }
fn top_edge(&self) -> f64 { self.pos().y - self.size().y }
fn collision_point_x(&self, other_vel: Vec2<f64>) -> Vec2<f64> {
vec2(self.centre_pos().x + self.size().x / 2.0 * (self.vel().x - other_vel.x).signum(),self.centre_pos().y)
}
fn collision_point_y(&self, other_vel: Vec2<f64>) -> Vec2<f64> {
vec2(self.centre_pos().x,self.centre_pos().y + self.size().y / 2.0 * (self.vel().y - other_vel.y).signum())
}
fn all_collision_points(&self) -> [Vec2<f64>; 4] {
[
vec2(self.centre_pos().x + self.size().x / 2.0,self.centre_pos().y),
vec2(self.centre_pos().x - self.size().x / 2.0,self.centre_pos().y),
vec2(self.centre_pos().x,self.centre_pos().y + self.size().y / 2.0),
vec2(self.centre_pos().x,self.centre_pos().y - self.size().y / 2.0),
]
}
fn point_collides(&self, point: Vec2<f64>, velocity: Vec2<f64>) -> Option<Vec2<f64>> { //returns how much it collides by, if any
let p = point;
let v = velocity - self.vel();
let a = self.pos(); let b = self.pos() + self.size();
if a.x < p.x && b.x > p.x && a.y < p.y && b.y > p.y {
Some(vec2(
if v.x.is_sign_negative() { b.x - p.x } else { p.x - a.x },
if v.y.is_sign_negative() { b.y - p.y } else { p.y - a.y },
))
} else {
None
}
}
}
pub trait Collider<T> {
fn collides(&self, other: &T) -> bool;
}
impl<A: BoundingBox, B: BoundingBox> Collider<A> for B {
fn collides(&self, other: &A) -> bool {
let right = self.left_edge() > other.right_edge();
let left = self.right_edge() < other.left_edge();
let up = self.bottom_edge() < other.top_edge();
let down = self.top_edge() > other.bottom_edge();
!(right || left || up || down)
}
}
/*#[derive(Debug,Default,Copy,Clone)]
pub struct AABB {
pub pos: Vec2<f64>,
pub size: Vec2<f64>,
pub vel: Vec2<f64>,
}
impl BoundingBox for AABB {
fn pos(&self) -> Vec2<f64> { self.pos }
fn size(&self) -> Vec2<f64> { self.size }
fn vel(&self) -> Vec2<f64> { self.vel }
}*/
#[derive(Debug,Default)]
pub struct Player {
pub centre_pos: Vec2<f64>,
pub vel: Vec2<f64>,
pub movement: [bool; 4],
pub grounded: f64,
pub hp: f64,
pub thread: Vec<Thread>,
pub bob: Vec2<f64>, //to make thread wave up and down/left and right
pub bob_dir: Vec2<i8>,
}
impl BoundingBox for Player {
fn pos(&self) -> Vec2<f64> { self.centre_pos - self.size() / 2.0 }
fn size(&self) -> Vec2<f64> { vec2(0.1, 0.2) }
fn vel(&self) -> Vec2<f64> { self.vel }
}
impl Player {
pub fn new() -> Self {
let mut r = Self::default();
r.bob_dir = vec2(1,1);
r.hp = r.max_hp();
r
}
pub fn move_speed(&self) -> f64 { if time() - self.grounded < 1.1 { 0.005 } else { 0.0025 } }
pub fn jump_vel(&self) -> f64 { 0.13 }
pub fn max_hp(&self) -> f64 { 30.0 }
pub fn grounded_limit(&self) -> f64 { 5.0 } //time since touching a platform that we're still allowed to jump
pub fn bob_rate(&self) -> Vec2<f64> { vec2(0.05,0.025) }
pub fn bob_max(&self) -> Vec2<f64> { vec2(0.025,0.025) }
pub fn detonate_thread(&mut self) {
if !self.thread[self.thread.len()-1].detonated.is_some() {
self.thread.iter_mut().enumerate().for_each(|(i, x)| x.detonate(i));
}
}
pub fn render(&self, v: &mut Vec<Vertex>) {
quad(v, self.pos(), 100, self.size(), [[1.0,1.0,1.0,1.0]; 4], [[0.0; 4]; 4], [[0.0; 3]; 4], 0.0, Default::default());
for i in 0..self.thread.len().saturating_sub(1) {
self.thread[i].render(v);
}
}
pub fn do_movement(&mut self, platforms: &Vec<Platform>, enemies: &mut Vec<Enemy>, delta: f64) {
let old_pos = self.centre_pos;
let mut damaged = false;
let movement_x = self.movement[0] as u8 as f64 - self.movement[1] as u8 as f64;
self.vel.x += movement_x * self.move_speed();
self.centre_pos.x += self.vel.x;
for (is_enemy, object) in enemies.iter().map(|x| (true, x as &dyn BoundingBox)).chain(platforms.iter().map(|x| (false, x as &dyn BoundingBox))) { //collide enemies first so player doesn't get scronched into the floor
let p = self.collision_point_x(object.vel());
if let Some(correction) = object.point_collides(p, self.vel()) {
if is_enemy { damaged = true; }
let diff = (self.vel() - object.vel()).x;
self.centre_pos.x -= diff.signum() * correction.x;
self.vel.y -= self.vel.y.signum() * (diff.abs() * FRICTION).min(self.vel.y.abs());
self.vel.x = object.vel().x;
}
}
self.vel.y -= GRAVITY;
if time() - self.grounded < self.grounded_limit() && self.movement[2] {
self.vel.y += self.jump_vel();
self.grounded = -self.grounded_limit();
}
self.centre_pos.y += self.vel.y;
for (is_enemy, object) in enemies.iter().map(|x| (true, x as &dyn BoundingBox)).chain(platforms.iter().map(|x| (false, x as &dyn BoundingBox))) {
let p = self.collision_point_y(object.vel());
if let Some(correction) = object.point_collides(p, self.vel()) {
if (self.vel - object.vel()).y.is_sign_negative() {
self.grounded = time();
} else if is_enemy { //only do damage when enemy on head, not when on head of enemy
damaged = true;
}
let diff = (self.vel() - object.vel()).y;
self.centre_pos.y -= diff.signum() * correction.y;
self.vel.x -= self.vel.x.signum() * (diff.abs() * FRICTION).min(self.vel.x.abs());
self.vel.y = object.vel().y;
}
}
//TODO: this doesn't work
//if still stuck in something, move upwards
/*for object in enemies.iter().map(|x| x as &BoundingBox).chain(platforms.iter().map(|x| x as &BoundingBox)) {
let p = self.all_collision_points();
if p.iter().any(|&p| object.point_collides(p, self.vel()).is_some()) {
self.centre_pos.y = object.top_edge() + self.size().y / 2.0;
}
}*/
//let v = self.vel.magnitude();
//self.vel *= 1.0 / (v * DRAG + 1.0);
self.vel /= self.vel.abs() * DRAG + 1.0; //do drag on both axes seperately because... it feels better? idk
self.hp += 0.05;
if damaged {
self.hp -= 1.0;
}
if self.thread.is_empty() {
self.thread.push(Thread::new(old_pos, self.centre_pos + self.bob, time(), time()-1.0));
}
if self.vel.magnitude() > 0.001 {
self.thread.insert(0, Thread::new(self.thread[0].to, self.centre_pos + self.bob, time(), self.thread[0].time));
}
let mut enemies_hit = HashSet::new();
while !self.thread.is_empty() && (self.thread[self.thread.len() - 1].time + 500.0 < time() || self.thread[self.thread.len() - 1].detonated.map(|x| x < time()).unwrap_or(false)) {
let thread = self.thread.pop().unwrap();
if thread.detonated.is_some() {
for i in 0..enemies.len() {
if !enemies_hit.contains(&i) && thread.collides(&enemies[i]) {
enemies_hit.insert(i);
}
}
}
}
if self.thread.is_empty() {
self.thread.push(Thread::new(old_pos, self.centre_pos + self.bob, time(), time()-1.0));
}
let mut enemies_hit = enemies_hit.iter().cloned().collect::<Vec<_>>();
enemies_hit.sort();
for &i in enemies_hit.iter().rev() {
enemies[i].hp -= binomial(3) * 10.0;
if enemies[i].hp <= 0.0 {
enemies.remove(i);
}
}
for i in 1..(self.thread.len()-1) {
let parent = self.thread[i+1];
let child = self.thread[i-1];
self.thread[i].do_movement(delta, parent, child, self.centre_pos);
}
self.bob += self.bob_dir.f64()
* vec2(binomial(2), binomial(2))
* self.bob_rate()
* self.vel.magnitude().sqrt()
* ((self.bob_max().max(self.bob.abs()) * 1.2 - self.bob.abs()) / self.bob_max());
self.bob_dir *= vec2(self.bob.x * self.bob_dir.f64().x > self.bob_max().x, self.bob.y * self.bob_dir.f64().y > self.bob_max().y).i8() * (-2) + 1;
if self.vel.magnitude().sqrt() < 0.0001 && self.bob.y > -self.bob_max().y * 1.5 {
self.bob.y -= self.thread[self.thread.len()-1].fall_rate(delta, self.centre_pos);
}
let n = 10.0;
uniforms().set_cam_pos((uniforms().cam_pos * n + self.centre_pos) / (n+1.0));
}
}
#[derive(Debug,Default)]
pub struct Platform {
pub centre_pos: Vec2<f64>,
pub size: Vec2<f64>,
}
impl BoundingBox for Platform {
fn pos(&self) -> Vec2<f64> { self.centre_pos - self.size() / 2.0 }
fn size(&self) -> Vec2<f64> { self.size }
fn vel(&self) -> Vec2<f64> { Vec2::zero() }
}
impl Platform {
pub fn render(&self, v: &mut Vec<Vertex>, player_hp_frac: f64) {
quad(v, self.pos(), 0, self.size(), [[(1.0 - player_hp_frac as f32) / 2.0,0.0,0.0,1.0]; 4], [[0.0; 4]; 4], [[0.0; 3]; 4], 0.0, Default::default());
}
}
#[derive(Debug,Default)]
pub struct Enemy {
pub centre_pos: Vec2<f64>,
pub vel: Vec2<f64>,
pub grounded: f64,
pub start_time: f64,
pub hp: f64,
}
impl BoundingBox for Enemy {
fn pos(&self) -> Vec2<f64> { self.centre_pos - self.size() / 2.0 }
fn size(&self) -> Vec2<f64> { vec2(0.08,0.15) }
fn vel(&self) -> Vec2<f64> { self.vel }
}
impl Enemy {
pub fn new() -> Self {
Self {
start_time: time(),
hp: Self::max_hp(),
.. Default::default()
}
}
fn max_hp() -> f64 {
25.0
}
pub fn move_speed(&self) -> f64 { if time() - self.grounded < 1.1 { 0.0025 } else { 0.00125 } }
pub fn do_movement(&mut self, player: &mut Player, platforms: &Vec<Platform>, enemies: &Vec<Enemy>) {
let movement_x = if player.centre_pos.x > self.centre_pos.x { 1.0 } else { -1.0 };
self.vel.x += movement_x * self.move_speed();
self.centre_pos.x += self.vel.x;
for object in enemies.iter().map(|x| x as &dyn BoundingBox).chain(platforms.iter().map(|x| x as &dyn BoundingBox)) {
let p = self.collision_point_x(object.vel());
if let Some(correction) = object.point_collides(p, self.vel()) {
let diff = (self.vel() - object.vel()).x;
self.centre_pos.x -= diff.signum() * correction.x;
self.vel.y -= self.vel.y.signum() * (diff.abs() * FRICTION).min(self.vel.y.abs());
self.vel.x = object.vel().x;
}
}
self.vel.y -= GRAVITY;
self.centre_pos.y += self.vel.y;
for object in enemies.iter().map(|x| x as &dyn BoundingBox).chain(platforms.iter().map(|x| x as &dyn BoundingBox)) {
let p = self.collision_point_y(object.vel());
if let Some(correction) = object.point_collides(p, self.vel()) {
if (self.vel - object.vel()).y.is_sign_negative() {
self.grounded = time();
}
let diff = (self.vel() - object.vel()).y;
self.centre_pos.y -= diff.signum() * correction.y;
self.vel.x -= self.vel.x.signum() * (diff.abs() * FRICTION).min(self.vel.x.abs());
self.vel.y = object.vel().y;
}
}
self.vel /= self.vel.abs() * DRAG + 1.0;
}
pub fn render(&self, v: &mut Vec<Vertex>) {
let t = self.start_time;
let shine_rate = 0.03 * (7.0 + 3.0 * RandGen::new((self.start_time * 100.0) as u64).skip(100).f64()) / 10.0;
let r = 0.2 / shine_rate;
let start_time = [t,t+r,t+r*2.0,t+r*3.0];
let mut x = [[0.0; 3]; 4];
for i in 0..4 {
for j in 0..3 {
x[i][j] = start_time[i];
}
}
let start_time = x;
let mut color = [0.3,0.1,0.3,1.0];
color.iter_mut().enumerate().for_each(|(i, x)| if i != 3 { *x *= (self.hp/Self::max_hp()) as f32; });
quad(v, self.pos(), 1, self.size(), [color; 4], [[1.0,0.3,1.0,0.5]; 4], start_time, shine_rate, Default::default());
}
}
#[derive(Debug,Default,Copy,Clone)]
pub struct Thread {
pub from: Vec2<f64>,
pub to: Vec2<f64>,
pub time: f64,
pub delta: f64,
pub detonated: Option<f64>,
}
impl<T: BoundingBox> Collider<T> for Thread {
fn collides(&self, other: &T) -> bool {
other.point_collides(self.from, Vec2::zero()).is_some() || other.point_collides(self.to, Vec2::zero()).is_some()
}
}
impl Thread {
pub fn new(from: Vec2<f64>, to: Vec2<f64>, start_time: f64, last_time: f64) -> Self {
Self {
from,
to,
time: start_time,
delta: start_time - last_time,
detonated: None,
}
}
pub fn width(&self) -> f64 { 0.01 }
pub fn extra_padding(&self) -> f64 { 0.001 }
pub fn fall_rate(&self, delta: f64, player_pos: Vec2<f64>) -> f64 {
0.0001 * delta * (1.0 + (self.from.y - player_pos.y).max(0.0) * 2.0)
}
pub fn stretch_rate(&self) -> f64 { 0.00 }
pub fn detonate(&mut self, i: usize) {
self.detonated = Some(time() + 120.0 - i as f64 / 6.0);
}
pub fn render(&self, v: &mut Vec<Vertex>) {
let dir = (self.to - self.from).normalize();
let l = vec2(-dir.y,dir.x);
let pos = [self.from + l * self.width(),self.from - l * self.width(),self.to + l * self.width(),self.to - l * self.width()];
let start_time = [vec3(0f64,0.25,0.5),vec3(0.05,0.3,0.55),vec3(0f64,0.25,0.55),vec3(0.05,0.3,0.55)];
let mut r = [Vertex::default(); 4];
for i in 0..4 {
let d = self.detonated.is_some();
let shine_color = if d { [1.0,0.7,0.7,1.0] } else { [0.6,0.7,1.0,0.7] };
let shine_bias = if d { [0.3,0.3,0.3] } else { [0.1,0.1,0.1] };
let shine_rate = if d { 0.1 } else { 0.025 };
r[i] = Vertex {
pos: (pos[i] + dir * if i >= 2 { self.extra_padding() } else { -self.extra_padding() }).extend(get_z(10) + self.time.log10() * 0.0001).f32(),
color: [0.7,0.7,0.7,1.0],
shine_color,
shine_bias,
start_time: (start_time[i] * 60.0 + if i >= 2 { self.delta } else { 0.0 } - self.time).f32().into_array(),
shine_rate,
}
}
v.extend_from_slice(&quadify(r));
}
pub fn do_movement(&mut self, delta: f64, parent: Self, child: Self, player_pos: Vec2<f64>) {
let x = self.fall_rate(delta, player_pos);
self.from.y -= x;
self.to.y -= x;
self.from += (parent.from - self.from) * self.stretch_rate() * delta;
self.to += (child.to - self.to) * self.stretch_rate() * delta;
}
}
|
use crate::yahtzee::{YahtzeeGame, roll, record_score, is_game_over};
use crate::engine::score_roll;
use crate::scorecard::{get_highest_scores, get_total_score};
pub fn ai_play(game: &mut YahtzeeGame) -> u16{
while !is_game_over(game){
roll(game);
let result = record_best_score(game);
//println!("Scored index {} for {} points", result.0, result.1);
}
//println!("Game Final Score: {}", get_total_score(&game.scorecard));
//println!("Game Results: {:?}", game);
get_total_score(&game.scorecard)
}
pub fn record_best_score(game: &mut YahtzeeGame) -> (u8, u8){
let roll_score = score_roll(&game.roll);
let best_scores = get_highest_scores(&roll_score);
for i in 0..best_scores.len(){
if !game.scored_categories.contains(&best_scores[i].0){
record_score(game, &roll_score, best_scores[i].0);
return best_scores[i];
}
}
panic!("Failed to score any category");
} |
use aoc2019::io::slurp_stdin;
use std::cmp::Ordering::Equal;
use std::collections::HashSet;
fn parse_map(map: &str) -> Vec<(i32,i32)> {
let mut points = Vec::new();
let mut x = 0;
let mut y = 0;
for ch in map.chars() {
match ch {
'#' => { points.push((x,y)); x += 1},
'\n' => { y += 1; x = 0; },
_ => { x += 1; }
}
}
points
}
fn gcd(x: i32, y: i32) -> i32 {
if x == 0 {
y
} else {
gcd(y%x, x)
}
}
fn blocked_by_any(rel_points: &[(i32,i32)], p: (i32,i32)) -> bool {
let d = gcd(p.0.abs(), p.1.abs());
for i in 1..d {
for &(x,y) in rel_points {
if x == p.0 * i / d && y == p.1 * i / d {
return true;
}
}
}
false
}
fn unblocked_count(rel_points: &[(i32,i32)]) -> usize {
rel_points.iter()
.clone()
.filter(|&p| !blocked_by_any(rel_points, *p))
.count()
}
fn center_around(asteroids: &[(i32,i32)], p: (i32,i32)) -> Vec<(i32,i32)> {
asteroids.iter()
.clone()
.map(|q| (q.0 - p.0, q.1 - p.1))
.filter(|q| !(q.0 == 0 && q.1 == 0))
.collect()
}
fn asteroid_score(asteroids: &[(i32,i32)], p: (i32,i32)) -> usize {
let rel_points = center_around(asteroids, p);
unblocked_count(&rel_points)
}
fn find_best_asteroid(asteroids: &[(i32,i32)]) -> (i32,i32) {
*asteroids.iter()
.clone()
.max_by_key(|p| asteroid_score(asteroids, **p))
.unwrap()
}
fn single_sweep_laser_hits(rel_points: &[(i32,i32)]) -> Vec<(i32,i32)> {
fn angle(dx: i32, dy: i32) -> f64 {
let dxf: f64 = dx.into();
let dyf: f64 = dy.into();
(-dxf).atan2(dyf)
}
let sweep_order: Vec<(i32,i32)> = {
let mut tmp = Vec::from(rel_points);
tmp.sort_by(|p, q| {
angle(p.0, p.1).partial_cmp(&angle(q.0, q.1)).unwrap_or(Equal)
});
tmp
};
let mut hit = Vec::new();
for p in sweep_order {
if !blocked_by_any(rel_points, p) {
hit.push(p)
}
}
hit
}
fn find_nth_lasered(rel_points: &[(i32,i32)], n: usize) -> Option<(i32,i32)> {
let mut left_to_laser = n;
let mut points_remaining = HashSet::new();
for p in rel_points {
points_remaining.insert(*p);
}
loop {
let hit = single_sweep_laser_hits(
&points_remaining.iter().cloned().collect::<Vec<_>>()
);
if hit.len() > left_to_laser {
return Some(hit[left_to_laser]);
} else if hit.is_empty() {
return None;
}
left_to_laser -= hit.len();
for p in hit {
points_remaining.remove(&p);
}
}
}
fn main() {
let asteroids = parse_map(&slurp_stdin());
let best_asteroid = find_best_asteroid(&asteroids);
println!("{}", asteroid_score(&asteroids, best_asteroid));
let rel_points = center_around(&asteroids, best_asteroid);
let laser200 = find_nth_lasered(&rel_points, 199).unwrap();
println!("{}", (laser200.0 + best_asteroid.0) * 100 + (laser200.1 + best_asteroid.1));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_map() {
assert_eq!(parse_map("#.#\n.#.\n"), vec![(0,0), (2,0), (1,1)]);
}
#[test]
fn test_centering() {
let asteroids = parse_map("#.#\n###\n.#.");
let centered = center_around(&asteroids, (1,1));
assert_eq!(centered, vec![(-1,-1), (1,-1), (-1,0), (1,0), (0,1)]);
}
#[test]
fn test_scores() {
let asteroids = parse_map(".#..#
.....
#####
....#
...##");
assert_eq!(asteroid_score(&asteroids, (1,0)), 7);
assert_eq!(asteroid_score(&asteroids, (4,0)), 7);
assert_eq!(asteroid_score(&asteroids, (0,2)), 6);
assert_eq!(asteroid_score(&asteroids, (1,2)), 7);
assert_eq!(asteroid_score(&asteroids, (2,2)), 7);
assert_eq!(asteroid_score(&asteroids, (3,2)), 7);
assert_eq!(asteroid_score(&asteroids, (4,2)), 5);
assert_eq!(asteroid_score(&asteroids, (4,3)), 7);
assert_eq!(asteroid_score(&asteroids, (3,4)), 8);
assert_eq!(asteroid_score(&asteroids, (4,4)), 7);
}
#[test]
fn test_angle_sweep_order() {
let asteroids = parse_map("###\n#.#\n###");
let rel_points = center_around(&asteroids, (1,1));
let hit = single_sweep_laser_hits(&rel_points);
assert_eq!(hit, vec![(0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1)]);
}
#[test]
fn test_angle_sweep_occlusion() {
// #G#2#
// EF134
// #D.5#
// CB976
// #A#8#
let asteroids = parse_map("#####\n#####\n##.##\n#####\n#####");
let rel_points = center_around(&asteroids, (2,2));
let hit = single_sweep_laser_hits(&rel_points);
assert_eq!(hit, vec![( 0,-1), ( 1,-2), ( 1,-1), ( 2,-1),
( 1, 0), ( 2, 1), ( 1, 1), ( 1, 2),
( 0, 1), (-1, 2), (-1, 1), (-2, 1),
(-1, 0), (-2,-1), (-1,-1), (-1,-2)]);
assert_eq!(find_nth_lasered(&rel_points, 4), Some((1,0)));
assert_eq!(find_nth_lasered(&rel_points, 16), Some((0,-2)));
assert_eq!(find_nth_lasered(&rel_points, 200), None);
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Voltage select. Per bank control"]
pub voltage_select: VOLTAGE_SELECT,
#[doc = "0x04 - Pad control register"]
pub gpio_qspi_sclk: GPIO_QSPI_SCLK,
#[doc = "0x08 - Pad control register"]
pub gpio_qspi_sd0: GPIO_QSPI_SD0,
#[doc = "0x0c - Pad control register"]
pub gpio_qspi_sd1: GPIO_QSPI_SD1,
#[doc = "0x10 - Pad control register"]
pub gpio_qspi_sd2: GPIO_QSPI_SD2,
#[doc = "0x14 - Pad control register"]
pub gpio_qspi_sd3: GPIO_QSPI_SD3,
#[doc = "0x18 - Pad control register"]
pub gpio_qspi_ss: GPIO_QSPI_SS,
}
#[doc = "Voltage select. Per bank control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [voltage_select](voltage_select) module"]
pub type VOLTAGE_SELECT = crate::Reg<u32, _VOLTAGE_SELECT>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _VOLTAGE_SELECT;
#[doc = "`read()` method returns [voltage_select::R](voltage_select::R) reader structure"]
impl crate::Readable for VOLTAGE_SELECT {}
#[doc = "`write(|w| ..)` method takes [voltage_select::W](voltage_select::W) writer structure"]
impl crate::Writable for VOLTAGE_SELECT {}
#[doc = "Voltage select. Per bank control"]
pub mod voltage_select;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_sclk](gpio_qspi_sclk) module"]
pub type GPIO_QSPI_SCLK = crate::Reg<u32, _GPIO_QSPI_SCLK>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SCLK;
#[doc = "`read()` method returns [gpio_qspi_sclk::R](gpio_qspi_sclk::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SCLK {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_sclk::W](gpio_qspi_sclk::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SCLK {}
#[doc = "Pad control register"]
pub mod gpio_qspi_sclk;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_sd0](gpio_qspi_sd0) module"]
pub type GPIO_QSPI_SD0 = crate::Reg<u32, _GPIO_QSPI_SD0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SD0;
#[doc = "`read()` method returns [gpio_qspi_sd0::R](gpio_qspi_sd0::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SD0 {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_sd0::W](gpio_qspi_sd0::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SD0 {}
#[doc = "Pad control register"]
pub mod gpio_qspi_sd0;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_sd1](gpio_qspi_sd1) module"]
pub type GPIO_QSPI_SD1 = crate::Reg<u32, _GPIO_QSPI_SD1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SD1;
#[doc = "`read()` method returns [gpio_qspi_sd1::R](gpio_qspi_sd1::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SD1 {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_sd1::W](gpio_qspi_sd1::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SD1 {}
#[doc = "Pad control register"]
pub mod gpio_qspi_sd1;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_sd2](gpio_qspi_sd2) module"]
pub type GPIO_QSPI_SD2 = crate::Reg<u32, _GPIO_QSPI_SD2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SD2;
#[doc = "`read()` method returns [gpio_qspi_sd2::R](gpio_qspi_sd2::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SD2 {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_sd2::W](gpio_qspi_sd2::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SD2 {}
#[doc = "Pad control register"]
pub mod gpio_qspi_sd2;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_sd3](gpio_qspi_sd3) module"]
pub type GPIO_QSPI_SD3 = crate::Reg<u32, _GPIO_QSPI_SD3>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SD3;
#[doc = "`read()` method returns [gpio_qspi_sd3::R](gpio_qspi_sd3::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SD3 {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_sd3::W](gpio_qspi_sd3::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SD3 {}
#[doc = "Pad control register"]
pub mod gpio_qspi_sd3;
#[doc = "Pad control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_qspi_ss](gpio_qspi_ss) module"]
pub type GPIO_QSPI_SS = crate::Reg<u32, _GPIO_QSPI_SS>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _GPIO_QSPI_SS;
#[doc = "`read()` method returns [gpio_qspi_ss::R](gpio_qspi_ss::R) reader structure"]
impl crate::Readable for GPIO_QSPI_SS {}
#[doc = "`write(|w| ..)` method takes [gpio_qspi_ss::W](gpio_qspi_ss::W) writer structure"]
impl crate::Writable for GPIO_QSPI_SS {}
#[doc = "Pad control register"]
pub mod gpio_qspi_ss;
|
use bevy_pen_tool_plugin::UiBoard;
use bevy::prelude::*;
#[derive(Component)]
pub struct Cam {
pub speed: f32,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub enabled: bool,
}
impl Default for Cam {
fn default() -> Self {
Self {
speed: 3.0,
key_up: KeyCode::W,
key_down: KeyCode::S,
key_left: KeyCode::A,
key_right: KeyCode::D,
enabled: true,
}
}
}
pub struct CamPlugin;
impl Plugin for CamPlugin {
fn build(&self, app: &mut App) {
app.add_system(camera_movevement_system.system());
// .add_system(zoom_camera.system());
}
}
pub fn movement_axis(input: &Res<Input<KeyCode>>, plus: KeyCode, minus: KeyCode) -> f32 {
let mut axis = 0.0;
if input.pressed(plus) && !input.pressed(KeyCode::LControl) && !input.pressed(KeyCode::LShift) {
axis += 1.0;
}
if input.pressed(minus) && !input.pressed(KeyCode::LControl) && !input.pressed(KeyCode::LShift)
{
axis -= 1.0;
}
return axis;
}
pub fn camera_movevement_system(
keyboard_input: Res<Input<KeyCode>>,
// mut query: Query<(&Cam, &mut Transform)>,
mut transforms: QuerySet<(
QueryState<(&Cam, &mut Transform)>,
QueryState<(&mut UiBoard, &mut Transform)>,
)>,
// mouse_button_input: Res<Input<MouseButton>>,
// mut query_ui: Query<&mut Transform, With<UiBoard>>,
) {
let mut cam_query = transforms.q0();
let mut velocity = Vec3::ZERO;
let mut do_move_cam = false;
for (cam, mut transform) in cam_query.iter_mut() {
let (axis_side, axis_up) = if cam.enabled {
(
movement_axis(&keyboard_input, cam.key_right, cam.key_left),
movement_axis(&keyboard_input, cam.key_up, cam.key_down),
)
} else {
(0.0, 0.0)
};
if axis_side.abs() > 0.0000001 || axis_up.abs() > 0.0000001 {
do_move_cam = true;
}
velocity = Vec3::new(axis_side * cam.speed, axis_up * cam.speed, 0.0);
transform.translation += velocity;
}
for (mut ui_board, mut ui_transform) in transforms.q1().iter_mut() {
ui_transform.translation += velocity;
if do_move_cam {
ui_board.previous_position = ui_transform.translation.truncate();
}
}
}
|
//! Pallets related to consensus, block production and authorship, session keys
//! and staking.
use crate::{
constants::time::{EPOCH_DURATION_IN_BLOCKS, EPOCH_DURATION_IN_SLOTS, MILLISECS_PER_BLOCK},
pallets_core::{BlockHashCount, MaximumBlockWeight},
AuthorityDiscovery, Babe, Balances, Call, Event, Grandpa, Historical, ImOnline, Offences,
Runtime, Session, Signature, SignedPayload, Staking, System, Timestamp, UncheckedExtrinsic,
};
use codec::Encode;
use frame_support::{debug, parameter_types, traits::KeyOwnerProofSystem, weights::Weight};
use frame_system::EnsureRoot;
use pallet_grandpa::AuthorityId as GrandpaId;
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
#[cfg(any(feature = "std", test))]
pub use pallet_staking::StakerStatus;
use sp_core::crypto::KeyTypeId;
use sp_runtime::{
curve::PiecewiseLinear,
generic::Era,
impl_opaque_keys,
traits::{self as sp_runtime_traits, Convert, OpaqueKeys, StaticLookup},
Perbill, SaturatedConversion,
};
use sp_std::prelude::*; // `impl_opaque_keys` need `Vec`
use sp_transaction_pool::TransactionPriority;
use ternoa_primitives::{AccountId, Balance, BlockNumber, Index, Moment};
parameter_types! {
pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS;
pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}
impl pallet_babe::Trait for Runtime {
type EpochDuration = EpochDuration;
type ExpectedBlockTime = ExpectedBlockTime;
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
type KeyOwnerProofSystem = Historical;
type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::IdentificationTuple;
type HandleEquivocation =
pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
type WeightInfo = ();
}
impl pallet_grandpa::Trait for Runtime {
type Event = Event;
type Call = Call;
type KeyOwnerProofSystem = Historical;
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation =
pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
type WeightInfo = ();
}
impl_opaque_keys! {
pub struct SessionKeys {
pub grandpa: Grandpa,
pub babe: Babe,
pub im_online: ImOnline,
pub authority_discovery: AuthorityDiscovery,
}
}
parameter_types! {
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}
impl pallet_session::Trait for Runtime {
type Event = Event;
type ValidatorId = <Self as frame_system::Trait>::AccountId;
type ValidatorIdOf = pallet_staking::StashOf<Self>;
type ShouldEndSession = Babe;
type NextSessionRotation = Babe;
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
type WeightInfo = ();
}
impl pallet_session::historical::Trait for Runtime {
type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
}
parameter_types! {
pub const UncleGenerations: BlockNumber = 5;
}
impl pallet_authorship::Trait for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
type EventHandler = (Staking, ImOnline);
}
impl pallet_authority_discovery::Trait for Runtime {}
parameter_types! {
pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _;
pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
/// We prioritize im-online heartbeats over election solution submission.
pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
}
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
call: Call,
public: <Signature as sp_runtime_traits::Verify>::Signer,
account: AccountId,
nonce: Index,
) -> Option<(
Call,
<UncheckedExtrinsic as sp_runtime_traits::Extrinsic>::SignaturePayload,
)> {
let tip = 0;
// take the biggest period possible.
let period = BlockHashCount::get()
.checked_next_power_of_two()
.map(|c| c / 2)
.unwrap_or(2) as u64;
let current_block = System::block_number()
.saturated_into::<u64>()
// The `System::block_number` is initialized with `n+1`,
// so the actual block number is `n`.
.saturating_sub(1);
let era = Era::mortal(period, current_block);
let extra = (
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckEra::<Runtime>::from(era),
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
);
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
debug::warn!("Unable to create signed payload: {:?}", e);
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
let address = <Runtime as frame_system::Trait>::Lookup::unlookup(account);
let (call, extra, _) = raw_payload.deconstruct();
Some((call, (address, signature.into(), extra)))
}
}
impl frame_system::offchain::SigningTypes for Runtime {
type Public = <Signature as sp_runtime_traits::Verify>::Signer;
type Signature = Signature;
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
Call: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = Call;
}
impl pallet_im_online::Trait for Runtime {
type AuthorityId = ImOnlineId;
type Event = Event;
type SessionDuration = SessionDuration;
type ReportUnresponsiveness = Offences;
type UnsignedPriority = ImOnlineUnsignedPriority;
type WeightInfo = ();
}
parameter_types! {
pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get();
}
impl pallet_offences::Trait for Runtime {
type Event = Event;
type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
type OnOffenceHandler = Staking;
type WeightSoftLimit = OffencesWeightSoftLimit;
}
pallet_staking_reward_curve::build! {
const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
min_inflation: 0_025_000,
max_inflation: 0_100_000,
ideal_stake: 0_500_000,
falloff: 0_050_000,
max_piece_count: 40,
test_precision: 0_005_000,
);
}
/// Struct that handles the conversion of Balance -> `u64`. This is used for staking's election
/// calculation.
pub struct CurrencyToVoteHandler;
impl CurrencyToVoteHandler {
fn factor() -> Balance {
(Balances::total_issuance() / u64::max_value() as Balance).max(1)
}
}
impl Convert<Balance, u64> for CurrencyToVoteHandler {
fn convert(x: Balance) -> u64 {
(x / Self::factor()) as u64
}
}
impl Convert<u128, Balance> for CurrencyToVoteHandler {
fn convert(x: u128) -> Balance {
x * Self::factor()
}
}
parameter_types! {
pub const SessionsPerEra: sp_staking::SessionIndex = 6;
pub const BondingDuration: pallet_staking::EraIndex = 24 * 28;
pub const SlashDeferDuration: pallet_staking::EraIndex = 24 * 7; // 1/4 the bonding duration.
pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
pub const MaxNominatorRewardedPerValidator: u32 = 64;
pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4;
pub const MaxIterations: u32 = 10;
// 0.05%. The higher the value, the more strict solution acceptance becomes.
pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
}
impl pallet_staking::Trait for Runtime {
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = CurrencyToVoteHandler;
type Event = Event;
// Slashed funds and remainders are burned.
type RewardRemainder = ();
type Slash = ();
type Reward = (); // rewards are minted from the void
type SessionsPerEra = SessionsPerEra;
type BondingDuration = BondingDuration;
type SlashDeferDuration = SlashDeferDuration;
type SlashCancelOrigin = EnsureRoot<AccountId>;
type SessionInterface = Self;
type RewardCurve = RewardCurve;
type NextNewSession = Session;
type ElectionLookahead = ElectionLookahead;
type Call = Call;
type MaxIterations = MaxIterations;
type MinSolutionScoreBump = MinSolutionScoreBump;
type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
type UnsignedPriority = StakingUnsignedPriority;
type WeightInfo = ();
}
|
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::helmholtz_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy(&number_of_links, &link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_relative_helmholtz_free_energy_per_link(link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64
{
super::relative_helmholtz_free_energy_per_link(&link_length, &link_stiffness, &force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64
{
super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_force)
}
#[no_mangle]
pub extern fn physics_single_chain_ufjc_log_squared_thermodynamics_isotensional_asymptotic_legendre_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64
{
super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_force)
} |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CFGD {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `GPIO31INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO31INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO31INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO31INTDR::NCELOW => false,
GPIO31INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO31INTDR {
match value {
false => GPIO31INTDR::NCELOW,
true => GPIO31INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO31INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO31INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO31OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO31OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO31OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO31OUTCFGR::DIS => 0,
GPIO31OUTCFGR::PUSHPULL => 1,
GPIO31OUTCFGR::OD => 2,
GPIO31OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO31OUTCFGR {
match value {
0 => GPIO31OUTCFGR::DIS,
1 => GPIO31OUTCFGR::PUSHPULL,
2 => GPIO31OUTCFGR::OD,
3 => GPIO31OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO31OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO31OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO31OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO31OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO31INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO31INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO31INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO31INCFGR::READ => false,
GPIO31INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO31INCFGR {
match value {
false => GPIO31INCFGR::READ,
true => GPIO31INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO31INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO31INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO30INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO30INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO30INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO30INTDR::NCELOW => false,
GPIO30INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO30INTDR {
match value {
false => GPIO30INTDR::NCELOW,
true => GPIO30INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO30INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO30INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO30OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO30OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO30OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO30OUTCFGR::DIS => 0,
GPIO30OUTCFGR::PUSHPULL => 1,
GPIO30OUTCFGR::OD => 2,
GPIO30OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO30OUTCFGR {
match value {
0 => GPIO30OUTCFGR::DIS,
1 => GPIO30OUTCFGR::PUSHPULL,
2 => GPIO30OUTCFGR::OD,
3 => GPIO30OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO30OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO30OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO30OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO30OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO30INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO30INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO30INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO30INCFGR::READ => false,
GPIO30INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO30INCFGR {
match value {
false => GPIO30INCFGR::READ,
true => GPIO30INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO30INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO30INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO29INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO29INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO29INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO29INTDR::NCELOW => false,
GPIO29INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO29INTDR {
match value {
false => GPIO29INTDR::NCELOW,
true => GPIO29INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO29INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO29INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO29OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO29OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO29OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO29OUTCFGR::DIS => 0,
GPIO29OUTCFGR::PUSHPULL => 1,
GPIO29OUTCFGR::OD => 2,
GPIO29OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO29OUTCFGR {
match value {
0 => GPIO29OUTCFGR::DIS,
1 => GPIO29OUTCFGR::PUSHPULL,
2 => GPIO29OUTCFGR::OD,
3 => GPIO29OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO29OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO29OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO29OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO29OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO29INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO29INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO29INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO29INCFGR::READ => false,
GPIO29INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO29INCFGR {
match value {
false => GPIO29INCFGR::READ,
true => GPIO29INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO29INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO29INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO28INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO28INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO28INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO28INTDR::NCELOW => false,
GPIO28INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO28INTDR {
match value {
false => GPIO28INTDR::NCELOW,
true => GPIO28INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO28INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO28INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO28OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO28OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO28OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO28OUTCFGR::DIS => 0,
GPIO28OUTCFGR::PUSHPULL => 1,
GPIO28OUTCFGR::OD => 2,
GPIO28OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO28OUTCFGR {
match value {
0 => GPIO28OUTCFGR::DIS,
1 => GPIO28OUTCFGR::PUSHPULL,
2 => GPIO28OUTCFGR::OD,
3 => GPIO28OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO28OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO28OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO28OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO28OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO28INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO28INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO28INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO28INCFGR::READ => false,
GPIO28INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO28INCFGR {
match value {
false => GPIO28INCFGR::READ,
true => GPIO28INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO28INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO28INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO27INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO27INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO27INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO27INTDR::NCELOW => false,
GPIO27INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO27INTDR {
match value {
false => GPIO27INTDR::NCELOW,
true => GPIO27INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO27INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO27INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO27OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO27OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO27OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO27OUTCFGR::DIS => 0,
GPIO27OUTCFGR::PUSHPULL => 1,
GPIO27OUTCFGR::OD => 2,
GPIO27OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO27OUTCFGR {
match value {
0 => GPIO27OUTCFGR::DIS,
1 => GPIO27OUTCFGR::PUSHPULL,
2 => GPIO27OUTCFGR::OD,
3 => GPIO27OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO27OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO27OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO27OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO27OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO27INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO27INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO27INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO27INCFGR::READ => false,
GPIO27INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO27INCFGR {
match value {
false => GPIO27INCFGR::READ,
true => GPIO27INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO27INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO27INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO26INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO26INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO26INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO26INTDR::NCELOW => false,
GPIO26INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO26INTDR {
match value {
false => GPIO26INTDR::NCELOW,
true => GPIO26INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO26INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO26INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO26OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO26OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO26OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO26OUTCFGR::DIS => 0,
GPIO26OUTCFGR::PUSHPULL => 1,
GPIO26OUTCFGR::OD => 2,
GPIO26OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO26OUTCFGR {
match value {
0 => GPIO26OUTCFGR::DIS,
1 => GPIO26OUTCFGR::PUSHPULL,
2 => GPIO26OUTCFGR::OD,
3 => GPIO26OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO26OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO26OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO26OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO26OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO26INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO26INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO26INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO26INCFGR::READ => false,
GPIO26INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO26INCFGR {
match value {
false => GPIO26INCFGR::READ,
true => GPIO26INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO26INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO26INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO25INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO25INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO25INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO25INTDR::NCELOW => false,
GPIO25INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO25INTDR {
match value {
false => GPIO25INTDR::NCELOW,
true => GPIO25INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO25INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO25INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO25OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO25OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO25OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO25OUTCFGR::DIS => 0,
GPIO25OUTCFGR::PUSHPULL => 1,
GPIO25OUTCFGR::OD => 2,
GPIO25OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO25OUTCFGR {
match value {
0 => GPIO25OUTCFGR::DIS,
1 => GPIO25OUTCFGR::PUSHPULL,
2 => GPIO25OUTCFGR::OD,
3 => GPIO25OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO25OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO25OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO25OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO25OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO25INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO25INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO25INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO25INCFGR::READ => false,
GPIO25INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO25INCFGR {
match value {
false => GPIO25INCFGR::READ,
true => GPIO25INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO25INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO25INCFGR::RDZERO
}
}
#[doc = "Possible values of the field `GPIO24INTD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO24INTDR {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO24INTDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO24INTDR::NCELOW => false,
GPIO24INTDR::NCEHIGH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO24INTDR {
match value {
false => GPIO24INTDR::NCELOW,
true => GPIO24INTDR::NCEHIGH,
}
}
#[doc = "Checks if the value of the field is `NCELOW`"]
#[inline]
pub fn is_n_celow(&self) -> bool {
*self == GPIO24INTDR::NCELOW
}
#[doc = "Checks if the value of the field is `NCEHIGH`"]
#[inline]
pub fn is_n_cehigh(&self) -> bool {
*self == GPIO24INTDR::NCEHIGH
}
}
#[doc = "Possible values of the field `GPIO24OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO24OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO24OUTCFGR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
GPIO24OUTCFGR::DIS => 0,
GPIO24OUTCFGR::PUSHPULL => 1,
GPIO24OUTCFGR::OD => 2,
GPIO24OUTCFGR::TS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> GPIO24OUTCFGR {
match value {
0 => GPIO24OUTCFGR::DIS,
1 => GPIO24OUTCFGR::PUSHPULL,
2 => GPIO24OUTCFGR::OD,
3 => GPIO24OUTCFGR::TS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DIS`"]
#[inline]
pub fn is_dis(&self) -> bool {
*self == GPIO24OUTCFGR::DIS
}
#[doc = "Checks if the value of the field is `PUSHPULL`"]
#[inline]
pub fn is_pushpull(&self) -> bool {
*self == GPIO24OUTCFGR::PUSHPULL
}
#[doc = "Checks if the value of the field is `OD`"]
#[inline]
pub fn is_od(&self) -> bool {
*self == GPIO24OUTCFGR::OD
}
#[doc = "Checks if the value of the field is `TS`"]
#[inline]
pub fn is_ts(&self) -> bool {
*self == GPIO24OUTCFGR::TS
}
}
#[doc = "Possible values of the field `GPIO24INCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO24INCFGR {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO24INCFGR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
GPIO24INCFGR::READ => false,
GPIO24INCFGR::RDZERO => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> GPIO24INCFGR {
match value {
false => GPIO24INCFGR::READ,
true => GPIO24INCFGR::RDZERO,
}
}
#[doc = "Checks if the value of the field is `READ`"]
#[inline]
pub fn is_read(&self) -> bool {
*self == GPIO24INCFGR::READ
}
#[doc = "Checks if the value of the field is `RDZERO`"]
#[inline]
pub fn is_rdzero(&self) -> bool {
*self == GPIO24INCFGR::RDZERO
}
}
#[doc = "Values that can be written to the field `GPIO31INTD`"]
pub enum GPIO31INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO31INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO31INTDW::NCELOW => false,
GPIO31INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO31INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO31INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO31INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO31INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO31INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO31OUTCFG`"]
pub enum GPIO31OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO31OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO31OUTCFGW::DIS => 0,
GPIO31OUTCFGW::PUSHPULL => 1,
GPIO31OUTCFGW::OD => 2,
GPIO31OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO31OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO31OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO31OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO31OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO31OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO31OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO31OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 29;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO31INCFG`"]
pub enum GPIO31INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO31INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO31INCFGW::READ => false,
GPIO31INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO31INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO31INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO31INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO31INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO31INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO30INTD`"]
pub enum GPIO30INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO30INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO30INTDW::NCELOW => false,
GPIO30INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO30INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO30INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO30INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO30INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO30INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 27;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO30OUTCFG`"]
pub enum GPIO30OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO30OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO30OUTCFGW::DIS => 0,
GPIO30OUTCFGW::PUSHPULL => 1,
GPIO30OUTCFGW::OD => 2,
GPIO30OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO30OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO30OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO30OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO30OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO30OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO30OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO30OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 25;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO30INCFG`"]
pub enum GPIO30INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO30INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO30INCFGW::READ => false,
GPIO30INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO30INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO30INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO30INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO30INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO30INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 24;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO29INTD`"]
pub enum GPIO29INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO29INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO29INTDW::NCELOW => false,
GPIO29INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO29INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO29INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO29INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO29INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO29INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO29OUTCFG`"]
pub enum GPIO29OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO29OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO29OUTCFGW::DIS => 0,
GPIO29OUTCFGW::PUSHPULL => 1,
GPIO29OUTCFGW::OD => 2,
GPIO29OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO29OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO29OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO29OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO29OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO29OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO29OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO29OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 21;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO29INCFG`"]
pub enum GPIO29INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO29INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO29INCFGW::READ => false,
GPIO29INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO29INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO29INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO29INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO29INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO29INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO28INTD`"]
pub enum GPIO28INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO28INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO28INTDW::NCELOW => false,
GPIO28INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO28INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO28INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO28INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO28INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO28INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 19;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO28OUTCFG`"]
pub enum GPIO28OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO28OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO28OUTCFGW::DIS => 0,
GPIO28OUTCFGW::PUSHPULL => 1,
GPIO28OUTCFGW::OD => 2,
GPIO28OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO28OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO28OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO28OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO28OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO28OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO28OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO28OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO28INCFG`"]
pub enum GPIO28INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO28INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO28INCFGW::READ => false,
GPIO28INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO28INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO28INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO28INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO28INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO28INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO27INTD`"]
pub enum GPIO27INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO27INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO27INTDW::NCELOW => false,
GPIO27INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO27INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO27INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO27INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO27INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO27INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 15;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO27OUTCFG`"]
pub enum GPIO27OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO27OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO27OUTCFGW::DIS => 0,
GPIO27OUTCFGW::PUSHPULL => 1,
GPIO27OUTCFGW::OD => 2,
GPIO27OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO27OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO27OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO27OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO27OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO27OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO27OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO27OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO27INCFG`"]
pub enum GPIO27INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO27INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO27INCFGW::READ => false,
GPIO27INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO27INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO27INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO27INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO27INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO27INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO26INTD`"]
pub enum GPIO26INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO26INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO26INTDW::NCELOW => false,
GPIO26INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO26INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO26INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO26INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO26INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO26INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 11;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO26OUTCFG`"]
pub enum GPIO26OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO26OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO26OUTCFGW::DIS => 0,
GPIO26OUTCFGW::PUSHPULL => 1,
GPIO26OUTCFGW::OD => 2,
GPIO26OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO26OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO26OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO26OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO26OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO26OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO26OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO26OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO26INCFG`"]
pub enum GPIO26INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO26INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO26INCFGW::READ => false,
GPIO26INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO26INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO26INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO26INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO26INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO26INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO25INTD`"]
pub enum GPIO25INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO25INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO25INTDW::NCELOW => false,
GPIO25INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO25INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO25INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO25INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO25INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO25INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO25OUTCFG`"]
pub enum GPIO25OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO25OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO25OUTCFGW::DIS => 0,
GPIO25OUTCFGW::PUSHPULL => 1,
GPIO25OUTCFGW::OD => 2,
GPIO25OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO25OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO25OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO25OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO25OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO25OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO25OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO25OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO25INCFG`"]
pub enum GPIO25INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO25INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO25INCFGW::READ => false,
GPIO25INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO25INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO25INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO25INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO25INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO25INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO24INTD`"]
pub enum GPIO24INTDW {
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
NCELOW,
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
NCEHIGH,
}
impl GPIO24INTDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO24INTDW::NCELOW => false,
GPIO24INTDW::NCEHIGH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO24INTDW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO24INTDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO24INTDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FNCSEL = 0x1 - nCE polarity active low value."]
#[inline]
pub fn n_celow(self) -> &'a mut W {
self.variant(GPIO24INTDW::NCELOW)
}
#[doc = "FNCSEL = 0x1 - nCE polarity active high value."]
#[inline]
pub fn n_cehigh(self) -> &'a mut W {
self.variant(GPIO24INTDW::NCEHIGH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO24OUTCFG`"]
pub enum GPIO24OUTCFGW {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
OD,
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
TS,
}
impl GPIO24OUTCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
GPIO24OUTCFGW::DIS => 0,
GPIO24OUTCFGW::PUSHPULL => 1,
GPIO24OUTCFGW::OD => 2,
GPIO24OUTCFGW::TS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO24OUTCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO24OUTCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO24OUTCFGW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "FNCSEL = 0x3 - Output disabled value."]
#[inline]
pub fn dis(self) -> &'a mut W {
self.variant(GPIO24OUTCFGW::DIS)
}
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
#[inline]
pub fn pushpull(self) -> &'a mut W {
self.variant(GPIO24OUTCFGW::PUSHPULL)
}
#[doc = "FNCSEL = 0x3 - Output is open drain value."]
#[inline]
pub fn od(self) -> &'a mut W {
self.variant(GPIO24OUTCFGW::OD)
}
#[doc = "FNCSEL = 0x3 - Output is tri-state value."]
#[inline]
pub fn ts(self) -> &'a mut W {
self.variant(GPIO24OUTCFGW::TS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `GPIO24INCFG`"]
pub enum GPIO24INCFGW {
#[doc = "Read the GPIO pin data value."]
READ,
#[doc = "INTD = 0 - Readback will always be zero value."]
RDZERO,
}
impl GPIO24INCFGW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
GPIO24INCFGW::READ => false,
GPIO24INCFGW::RDZERO => true,
}
}
}
#[doc = r" Proxy"]
pub struct _GPIO24INCFGW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO24INCFGW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: GPIO24INCFGW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Read the GPIO pin data value."]
#[inline]
pub fn read(self) -> &'a mut W {
self.variant(GPIO24INCFGW::READ)
}
#[doc = "INTD = 0 - Readback will always be zero value."]
#[inline]
pub fn rdzero(self) -> &'a mut W {
self.variant(GPIO24INCFGW::RDZERO)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 31 - GPIO31 interrupt direction."]
#[inline]
pub fn gpio31intd(&self) -> GPIO31INTDR {
GPIO31INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 29:30 - GPIO31 output configuration."]
#[inline]
pub fn gpio31outcfg(&self) -> GPIO31OUTCFGR {
GPIO31OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 29;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 28 - GPIO31 input enable."]
#[inline]
pub fn gpio31incfg(&self) -> GPIO31INCFGR {
GPIO31INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 27 - GPIO30 interrupt direction."]
#[inline]
pub fn gpio30intd(&self) -> GPIO30INTDR {
GPIO30INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 27;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 25:26 - GPIO30 output configuration."]
#[inline]
pub fn gpio30outcfg(&self) -> GPIO30OUTCFGR {
GPIO30OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 25;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 24 - GPIO30 input enable."]
#[inline]
pub fn gpio30incfg(&self) -> GPIO30INCFGR {
GPIO30INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 23 - GPIO29 interrupt direction."]
#[inline]
pub fn gpio29intd(&self) -> GPIO29INTDR {
GPIO29INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 21:22 - GPIO29 output configuration."]
#[inline]
pub fn gpio29outcfg(&self) -> GPIO29OUTCFGR {
GPIO29OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 21;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 20 - GPIO29 input enable."]
#[inline]
pub fn gpio29incfg(&self) -> GPIO29INCFGR {
GPIO29INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 19 - GPIO28 interrupt direction."]
#[inline]
pub fn gpio28intd(&self) -> GPIO28INTDR {
GPIO28INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 19;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 17:18 - GPIO28 output configuration."]
#[inline]
pub fn gpio28outcfg(&self) -> GPIO28OUTCFGR {
GPIO28OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 16 - GPIO28 input enable."]
#[inline]
pub fn gpio28incfg(&self) -> GPIO28INCFGR {
GPIO28INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 15 - GPIO27 interrupt direction."]
#[inline]
pub fn gpio27intd(&self) -> GPIO27INTDR {
GPIO27INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 15;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 13:14 - GPIO27 output configuration."]
#[inline]
pub fn gpio27outcfg(&self) -> GPIO27OUTCFGR {
GPIO27OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 12 - GPIO27 input enable."]
#[inline]
pub fn gpio27incfg(&self) -> GPIO27INCFGR {
GPIO27INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 11 - GPIO26 interrupt direction."]
#[inline]
pub fn gpio26intd(&self) -> GPIO26INTDR {
GPIO26INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 9:10 - GPIO26 output configuration."]
#[inline]
pub fn gpio26outcfg(&self) -> GPIO26OUTCFGR {
GPIO26OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 8 - GPIO26 input enable."]
#[inline]
pub fn gpio26incfg(&self) -> GPIO26INCFGR {
GPIO26INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - GPIO25 interrupt direction."]
#[inline]
pub fn gpio25intd(&self) -> GPIO25INTDR {
GPIO25INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 5:6 - GPIO25 output configuration."]
#[inline]
pub fn gpio25outcfg(&self) -> GPIO25OUTCFGR {
GPIO25OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 4 - GPIO25 input enable."]
#[inline]
pub fn gpio25incfg(&self) -> GPIO25INCFGR {
GPIO25INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - GPIO24 interrupt direction."]
#[inline]
pub fn gpio24intd(&self) -> GPIO24INTDR {
GPIO24INTDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 1:2 - GPIO24 output configuration."]
#[inline]
pub fn gpio24outcfg(&self) -> GPIO24OUTCFGR {
GPIO24OUTCFGR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 0 - GPIO24 input enable."]
#[inline]
pub fn gpio24incfg(&self) -> GPIO24INCFGR {
GPIO24INCFGR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 31 - GPIO31 interrupt direction."]
#[inline]
pub fn gpio31intd(&mut self) -> _GPIO31INTDW {
_GPIO31INTDW { w: self }
}
#[doc = "Bits 29:30 - GPIO31 output configuration."]
#[inline]
pub fn gpio31outcfg(&mut self) -> _GPIO31OUTCFGW {
_GPIO31OUTCFGW { w: self }
}
#[doc = "Bit 28 - GPIO31 input enable."]
#[inline]
pub fn gpio31incfg(&mut self) -> _GPIO31INCFGW {
_GPIO31INCFGW { w: self }
}
#[doc = "Bit 27 - GPIO30 interrupt direction."]
#[inline]
pub fn gpio30intd(&mut self) -> _GPIO30INTDW {
_GPIO30INTDW { w: self }
}
#[doc = "Bits 25:26 - GPIO30 output configuration."]
#[inline]
pub fn gpio30outcfg(&mut self) -> _GPIO30OUTCFGW {
_GPIO30OUTCFGW { w: self }
}
#[doc = "Bit 24 - GPIO30 input enable."]
#[inline]
pub fn gpio30incfg(&mut self) -> _GPIO30INCFGW {
_GPIO30INCFGW { w: self }
}
#[doc = "Bit 23 - GPIO29 interrupt direction."]
#[inline]
pub fn gpio29intd(&mut self) -> _GPIO29INTDW {
_GPIO29INTDW { w: self }
}
#[doc = "Bits 21:22 - GPIO29 output configuration."]
#[inline]
pub fn gpio29outcfg(&mut self) -> _GPIO29OUTCFGW {
_GPIO29OUTCFGW { w: self }
}
#[doc = "Bit 20 - GPIO29 input enable."]
#[inline]
pub fn gpio29incfg(&mut self) -> _GPIO29INCFGW {
_GPIO29INCFGW { w: self }
}
#[doc = "Bit 19 - GPIO28 interrupt direction."]
#[inline]
pub fn gpio28intd(&mut self) -> _GPIO28INTDW {
_GPIO28INTDW { w: self }
}
#[doc = "Bits 17:18 - GPIO28 output configuration."]
#[inline]
pub fn gpio28outcfg(&mut self) -> _GPIO28OUTCFGW {
_GPIO28OUTCFGW { w: self }
}
#[doc = "Bit 16 - GPIO28 input enable."]
#[inline]
pub fn gpio28incfg(&mut self) -> _GPIO28INCFGW {
_GPIO28INCFGW { w: self }
}
#[doc = "Bit 15 - GPIO27 interrupt direction."]
#[inline]
pub fn gpio27intd(&mut self) -> _GPIO27INTDW {
_GPIO27INTDW { w: self }
}
#[doc = "Bits 13:14 - GPIO27 output configuration."]
#[inline]
pub fn gpio27outcfg(&mut self) -> _GPIO27OUTCFGW {
_GPIO27OUTCFGW { w: self }
}
#[doc = "Bit 12 - GPIO27 input enable."]
#[inline]
pub fn gpio27incfg(&mut self) -> _GPIO27INCFGW {
_GPIO27INCFGW { w: self }
}
#[doc = "Bit 11 - GPIO26 interrupt direction."]
#[inline]
pub fn gpio26intd(&mut self) -> _GPIO26INTDW {
_GPIO26INTDW { w: self }
}
#[doc = "Bits 9:10 - GPIO26 output configuration."]
#[inline]
pub fn gpio26outcfg(&mut self) -> _GPIO26OUTCFGW {
_GPIO26OUTCFGW { w: self }
}
#[doc = "Bit 8 - GPIO26 input enable."]
#[inline]
pub fn gpio26incfg(&mut self) -> _GPIO26INCFGW {
_GPIO26INCFGW { w: self }
}
#[doc = "Bit 7 - GPIO25 interrupt direction."]
#[inline]
pub fn gpio25intd(&mut self) -> _GPIO25INTDW {
_GPIO25INTDW { w: self }
}
#[doc = "Bits 5:6 - GPIO25 output configuration."]
#[inline]
pub fn gpio25outcfg(&mut self) -> _GPIO25OUTCFGW {
_GPIO25OUTCFGW { w: self }
}
#[doc = "Bit 4 - GPIO25 input enable."]
#[inline]
pub fn gpio25incfg(&mut self) -> _GPIO25INCFGW {
_GPIO25INCFGW { w: self }
}
#[doc = "Bit 3 - GPIO24 interrupt direction."]
#[inline]
pub fn gpio24intd(&mut self) -> _GPIO24INTDW {
_GPIO24INTDW { w: self }
}
#[doc = "Bits 1:2 - GPIO24 output configuration."]
#[inline]
pub fn gpio24outcfg(&mut self) -> _GPIO24OUTCFGW {
_GPIO24OUTCFGW { w: self }
}
#[doc = "Bit 0 - GPIO24 input enable."]
#[inline]
pub fn gpio24incfg(&mut self) -> _GPIO24INCFGW {
_GPIO24INCFGW { w: self }
}
}
|
// BEGIN - Embark standard lints v0.4
// do not change or add/remove here, but one can add exceptions after this section
// for more info see: <https://github.com/EmbarkStudios/rust-ecosystem/issues/59>
#![deny(unsafe_code)]
#![warn(
clippy::all,
clippy::await_holding_lock,
clippy::char_lit_as_u8,
clippy::checked_conversions,
clippy::dbg_macro,
clippy::debug_assert_with_mut_call,
clippy::doc_markdown,
clippy::empty_enum,
clippy::enum_glob_use,
clippy::exit,
clippy::expl_impl_clone_on_copy,
clippy::explicit_deref_methods,
clippy::explicit_into_iter_loop,
clippy::fallible_impl_from,
clippy::filter_map_next,
clippy::float_cmp_const,
clippy::fn_params_excessive_bools,
clippy::if_let_mutex,
clippy::implicit_clone,
clippy::imprecise_flops,
clippy::inefficient_to_string,
clippy::invalid_upcast_comparisons,
clippy::large_types_passed_by_value,
clippy::let_unit_value,
clippy::linkedlist,
clippy::lossy_float_literal,
clippy::macro_use_imports,
clippy::manual_ok_or,
clippy::map_err_ignore,
clippy::map_flatten,
clippy::map_unwrap_or,
clippy::match_on_vec_items,
clippy::match_same_arms,
clippy::match_wildcard_for_single_variants,
clippy::mem_forget,
clippy::mismatched_target_os,
clippy::mut_mut,
clippy::mutex_integer,
clippy::needless_borrow,
clippy::needless_continue,
clippy::option_option,
clippy::path_buf_push_overwrite,
clippy::ptr_as_ptr,
clippy::ref_option_ref,
clippy::rest_pat_in_fully_bound_structs,
clippy::same_functions_in_if_condition,
clippy::semicolon_if_nothing_returned,
clippy::string_add_assign,
clippy::string_add,
clippy::string_lit_as_bytes,
clippy::string_to_string,
clippy::todo,
clippy::trait_duplication_in_bounds,
clippy::unimplemented,
clippy::unnested_or_patterns,
clippy::unused_self,
clippy::useless_transmute,
clippy::verbose_file_reads,
clippy::zero_sized_map_values,
future_incompatible,
nonstandard_style,
rust_2018_idioms
)]
// END - Embark standard lints v0.4
// crate-specific exceptions:
#![allow()]
//! # 🔐 tame-oauth
//!
//! [](https://crates.io/crates/tame-oauth)
//! [](https://docs.rs/tame-oauth)
//!
//! `tame-oauth` is a small oauth crate that follows the [sans-io](https://sans-io.readthedocs.io/) approach.
//!
//! ## Why?
//!
//! * You want to control how you actually make oauth HTTP requests
//!
//! ## Why not?
//!
//! * The only auth flow that is currently implemented is the service account flow for GCP. Other flows
//! can be added, but right now that is the only one we need.
//! * There are several other oauth crates available that have many more features and are easier
//! to work with, if you don't care about what HTTP clients they use.
//! * This crate requires more boilerplate to work with
//! ## Features
//!
//! * `gcp` (default) - Support for [GCP oauth2](https://developers.google.com/identity/protocols/oauth2)
//! * `wasm-web` - Enables wasm features in `chrono` and `ring` needed for `tame-oauth` to be used in a wasm browser context. Note this feature should not be used when targetting wasm outside the browser context, in which case you would likely need to target `wasm32-wasi`.
//! * `jwt` (default) - Support for [JSON Web Tokens](https://jwt.io/), required for `gcp`
//! * `url` (default) - Url parsing, required for `gcp`
//!
//! ## Examples
//!
//! ### [`svc_account`](examples/svc_account.rs)
//!
//! Usage: `cargo run --example svc_account -- <key_path> <scope..>`
//!
//! A small example of using `tame-oauth` together with [reqwest](https://github.com/seanmonstar/reqwest). Given a key
//! file and 1 or more scopes, it will attempt to get a token that you could be used to access resources in those scopes.
//!
//! `cargo run --example svc_account -- ~/.secrets/super-sekret.json https://www.googleapis.com/auth/pubsub https://www.googleapis.com/auth/devstorage.read_only`
//!
//! ## License
//!
//! Licensed under either of
//!
//! * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
//! * MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
//!
//! at your option.
//!
//! ### Contribution
//!
//! Unless you explicitly state otherwise, any contribution intentionally
//! submitted for inclusion in the work by you, as defined in the Apache-2.0
//! license, shall be dual licensed as above, without any additional terms or
//! conditions.
#[cfg(feature = "gcp")]
pub mod gcp;
mod error;
mod token;
pub use crate::{error::Error, token::Token};
|
use std::collections::HashMap;
use sudo_test::{Command, Env, User};
use crate::{helpers, Result, ENV_PATH, USERNAME};
#[test]
fn vars_set_by_su_when_target_is_root() -> Result<()> {
let env = Env("").build()?;
let stdout = Command::new("env")
.args(["-i", "/usr/bin/su", "-s", ENV_PATH])
.output(&env)?
.stdout()?;
let mut su_env = helpers::parse_env_output(&stdout)?;
dbg!(&su_env);
// NOTE `man su` says that su sets HOME and SHELL but here we observe that MAIL is also set
assert_eq!(Some(ENV_PATH), su_env.remove("SHELL"));
assert_eq!(Some("/root"), su_env.remove("HOME"));
assert_eq!(Some("/var/mail/root"), su_env.remove("MAIL"));
// remove profiling environment var
let _ = su_env.remove("__LLVM_PROFILE_RT_INIT_ONCE");
assert_eq!(HashMap::new(), su_env);
Ok(())
}
#[test]
fn vars_set_by_su_when_target_is_not_root() -> Result<()> {
let env = Env("").user(User(USERNAME).shell(ENV_PATH)).build()?;
let stdout = Command::new("env")
.args(["-i", "/usr/bin/su", USERNAME])
.output(&env)?
.stdout()?;
let mut su_env = helpers::parse_env_output(&stdout)?;
dbg!(&su_env);
// NOTE `man su` says that aside from HOME and SHELL, USER and LOGNAME are set when the target
// user is not root
assert_eq!(Some(ENV_PATH), su_env.remove("SHELL"));
assert_eq!(
Some(format!("/home/{USERNAME}")).as_deref(),
su_env.remove("HOME")
);
assert_eq!(Some(USERNAME), su_env.remove("USER"));
assert_eq!(Some(USERNAME), su_env.remove("LOGNAME"));
assert_eq!(
Some(format!("/var/mail/{USERNAME}")).as_deref(),
su_env.remove("MAIL")
);
// remove profiling environment var
let _ = su_env.remove("__LLVM_PROFILE_RT_INIT_ONCE");
assert_eq!(HashMap::new(), su_env);
Ok(())
}
#[test]
fn vars_set_by_su_override_existing_ones() -> Result<()> {
let env = Env("").user(User(USERNAME).shell(ENV_PATH)).build()?;
let stdout = Command::new("env")
.arg("-i")
// FIXME workaround for gh506. change to `SHELL=my-shell`
.arg("SHELL=/usr/bin/env")
.arg("HOME=my-home")
.arg("USER=my-user")
.arg("LOGNAME=my-logname")
.arg("MAIL=my-mail")
.args(["/usr/bin/su", USERNAME])
.output(&env)?
.stdout()?;
let mut su_env = helpers::parse_env_output(&stdout)?;
dbg!(&su_env);
// NOTE `man su` says that aside from HOME and SHELL, USER and LOGNAME are set
assert_eq!(Some(ENV_PATH), su_env.remove("SHELL"));
assert_eq!(
Some(format!("/home/{USERNAME}")).as_deref(),
su_env.remove("HOME")
);
assert_eq!(Some(USERNAME), su_env.remove("USER"));
assert_eq!(Some(USERNAME), su_env.remove("LOGNAME"));
assert_eq!(
Some(format!("/var/mail/{USERNAME}")).as_deref(),
su_env.remove("MAIL")
);
// remove profiling environment var
let _ = su_env.remove("__LLVM_PROFILE_RT_INIT_ONCE");
assert_eq!(HashMap::new(), su_env);
Ok(())
}
#[test]
fn vars_in_invoking_users_env_are_preserved() -> Result<()> {
let varname = "SHOULD_BE_PRESERVED";
let varval = "42";
let env = Env("").user(User(USERNAME).shell(ENV_PATH)).build()?;
let stdout = Command::new("env")
.arg("-i")
.arg(format!("{varname}={varval}"))
.args(["/usr/bin/su", USERNAME])
.output(&env)?
.stdout()?;
let su_env = helpers::parse_env_output(&stdout)?;
assert_eq!(Some(varval), su_env.get(varname).copied());
Ok(())
}
|
use block::ConcreteBlock;
use cocoa::base::{id, nil};
use cocoa::foundation::{NSString, NSUInteger};
use error::NSError;
use objc::runtime::YES;
use objc_bringup::NSArray;
use sys::{MTLCopyAllDevices, MTLCreateSystemDefaultDevice, MTLDevice};
use std::convert::From;
use std::error::Error;
use std::ffi::CStr;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData;
use std::ops::Deref;
use std::path::Path;
use std::sync::mpsc;
use sys::MTLFeatureSet;
use {AsRaw, Buffer, CommandQueue, CommandQueueError, CompileOptions, DepthStencilDescriptor,
DepthStencilState, FromRaw, FromRawError, Library, LibraryError, ResourceOptions,
SamplerDescriptor, SamplerState, Size, Texture, TextureDescriptor};
pub struct Device(id);
impl Device {
pub fn system_default_device() -> Result<Self, DeviceError> {
let device = unsafe { MTLCreateSystemDefaultDevice() };
if device != nil { Ok(Device(device)) } else { Err(DeviceError::ConstructionFailed) }
}
pub fn enumerate_all_system_devices() -> Vec<Result<Self, DeviceError>> {
let all_devices = unsafe { MTLCopyAllDevices() };
let mut devices_vec = vec![];
unsafe {
for i in 0..all_devices.count() {
let device = all_devices.objectAtIndex(i);
if device != nil {
devices_vec.push(Ok(Device(device)));
} else {
devices_vec.push(Err(DeviceError::ConstructionFailed));
}
}
}
devices_vec
}
pub fn is_depth24_stencil8_pixel_format_supported(&self) -> bool {
unsafe { self.0.depth24Stencil8PixelFormatSupported() == YES }
}
pub fn is_headless(&self) -> bool {
unsafe { self.0.headless() == YES }
}
pub fn is_low_power(&self) -> bool {
unsafe { self.0.lowPower() == YES }
}
pub fn max_threads_per_group(&self) -> Size {
unsafe { self.0.maxThreadsPerGroup().into() }
}
pub fn name(&self) -> &str {
unsafe { CStr::from_ptr(self.0.name().UTF8String()).to_str().unwrap_or(&"") }
}
pub fn supports_feature_set(&self, feature_set: FeatureSet) -> bool {
unsafe { self.0.supportsFeatureSet(feature_set.into()) == YES }
}
pub fn supports_texture_sample_count(&self, sample_count: usize) -> bool {
unsafe { self.0.supportsTextureSampleCount(sample_count as NSUInteger) == YES }
}
pub fn new_command_queue(&mut self) -> Result<CommandQueue, CommandQueueError> {
let command_queue = unsafe { self.0.newCommandQueue() };
Ok(try!(FromRaw::from_raw(command_queue)))
}
pub fn new_command_queue_with_max_buffer_count(&mut self, max_command_buffer_count: usize)
-> Result<CommandQueue, CommandQueueError> {
let command_queue = unsafe {
self.0.newCommandQueueWithMaxCommandBufferCount(max_command_buffer_count as NSUInteger)
};
Ok(try!(FromRaw::from_raw(command_queue)))
}
// TODO(George): This will panic in the metal lib if not called from a binary in a bundle. Need
// to add proper error checking
pub fn new_default_library(&mut self) -> Result<Library, LibraryError> {
unsafe {
let library = self.0.newDefaultLibrary();
Ok(try!(FromRaw::from_raw(library)))
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn new_library_with_file(&mut self, file_path: &Path) -> Result<Library, LibraryError> {
unsafe {
let path_string = match file_path.as_os_str().to_str() {
None => unimplemented!(),
Some(s) => s
};
let path = NSString::alloc(nil).init_str(path_string);
let mut error = nil;
let library = self.0.newLibraryWithFile_error(path, &mut error);
if library == nil {
Err(LibraryError::from(NSError::new(error)))
} else {
Ok(try!(FromRaw::from_raw(library)))
}
}
}
pub fn new_library_with_source(&mut self, source: &str, compile_options: &CompileOptions)
-> Result<Library, LibraryError> {
unsafe {
let source = NSString::alloc(nil).init_str(source);
let options = compile_options.mtl_compile_options();
let mut error = nil;
let library = self.0.newLibraryWithSource_options_error(source, options, &mut error);
if library == nil {
Err(LibraryError::from(NSError::new(error)))
} else {
Ok(try!(FromRaw::from_raw(library)))
}
}
}
pub fn new_library_with_source_async(&mut self, source: &str, compile_options: &CompileOptions)
-> mpsc::Receiver<Result<Library, LibraryError>> {
unsafe {
let source = NSString::alloc(nil).init_str(source);
let options = compile_options.mtl_compile_options();
let (sender, receiver) = mpsc::channel();
let block = ConcreteBlock::new(move |lib, err| {
if lib != nil {
match FromRaw::from_raw(lib) {
Ok(library) => sender.send(Ok(library)).unwrap(),
Err(e) => sender.send(Err(LibraryError::from(e))).unwrap(),
}
} else {
sender.send(Err(LibraryError::from(NSError::new(err)))).unwrap();
}
});
self.0.newLibraryWithSource_options_completionHandler(source, options, &block.copy());
receiver
}
}
#[allow(unused_variables)]
// TODO(burtonageo): `data` parameter should be of the correct type
pub fn new_library_with_data(&mut self, data: ()) -> Result<Library, LibraryError> {
unimplemented!();
}
pub fn new_buffer_with_length(&mut self, length: usize, options: ResourceOptions) -> Buffer {
unsafe {
FromRaw::from_raw(self.0.newBufferWithLength_options(length as NSUInteger,
options.into()))
.unwrap()
}
}
#[cfg_attr(rustfmt, rustfmt_skip)]
pub fn new_buffer_with_bytes(&mut self, bytes: &[u8], options: ResourceOptions)
-> Buffer {
let len = bytes.len() as NSUInteger;
let bytes = bytes.as_ptr() as *const _;
unsafe {
FromRaw::from_raw(self.0.newBufferWithBytes_length_options(
bytes, len,options.into())).unwrap()
}
}
pub fn new_buffer_with_bytes_no_copy<'a>(&mut self, bytes: &'a mut [u8],
options: ResourceOptions)
-> BufferRef<'a> {
let len = bytes.len() as NSUInteger;
let bytes = bytes.as_ptr() as *mut _;
let dealloc = ConcreteBlock::new(|ptr, len| {
use std::slice;
unsafe { drop(slice::from_raw_parts(ptr as *const u8, len as usize)) }
});
let buffer = unsafe {
FromRaw::from_raw(self.0.newBufferWithBytesNoCopy_length_options_deallocator(bytes, len,
options.into(),
&dealloc)).unwrap()
};
BufferRef { buffer: buffer, marker: PhantomData }
}
pub fn new_texture(&mut self, descriptor: &TextureDescriptor) -> Result<Texture, FromRawError> {
unsafe { FromRaw::from_raw(self.0.newTextureWithDescriptor(*descriptor.as_raw())) }
}
pub fn new_sampler_state(&mut self, descriptor: &SamplerDescriptor)
-> Result<SamplerState, FromRawError> {
unsafe { FromRaw::from_raw(self.0.newSamplerStateWithDescriptor(*descriptor.as_raw())) }
}
pub fn new_depth_stencil_state(&mut self, descriptor: &DepthStencilDescriptor)
-> Result<DepthStencilState, FromRawError> {
unsafe {
FromRaw::from_raw(self.0.newDepthStencilStateWithDescriptor(*descriptor.as_raw()))
}
}
}
pub struct BufferRef<'a> {
buffer: Buffer,
marker: PhantomData<&'a ()>
}
impl<'a> Deref for BufferRef<'a> {
type Target = Buffer;
fn deref(&self) -> &Self::Target {
&self.buffer
}
}
impl_from_into_raw!(Device, of protocol "MTLDevice");
#[cfg(target_os = "ios")]
convertible_enum! {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum FeatureSet: MTLFeatureSet {
iOSGpuFamily1_v1 => MTLFeatureSet_iOS_GPUFamily1_v1,
iOSGpuFamily2_v1 => MTLFeatureSet_iOS_GPUFamily2_v1,
iOSGpuFamily1_v2 => MTLFeatureSet_iOS_GPUFamily1_v2,
iOSGpuFamily2_v2 => MTLFeatureSet_iOS_GPUFamily2_v2,
iOSGpuFamily3_v1 => MTLFeatureSet_iOS_GPUFamily3_v1
}
}
#[cfg(target_os = "ios")]
impl Default for FeatureSet {
fn default() -> Self {
FeatureSet::iOSGpuFamily1_v1
}
}
#[cfg(target_os = "macos")]
convertible_enum! {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum FeatureSet: MTLFeatureSet {
OsxGpuFamily1_v1 => MTLFeatureSet_OSX_GPUFamily1_v1,
_non_unary_compile_dummy => _non_unary_compile_dummy
}
}
#[cfg(target_os = "macos")]
impl Default for FeatureSet {
fn default() -> Self {
FeatureSet::OsxGpuFamily1_v1
}
}
#[derive(Clone, Debug)]
pub enum DeviceError {
ConstructionFailed,
RawError(FromRawError)
}
impl From<FromRawError> for DeviceError {
fn from(error: FromRawError) -> Self {
DeviceError::RawError(error)
}
}
impl Display for DeviceError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let descr = match *self {
DeviceError::ConstructionFailed => "DeviceError::ConstructionFailed",
DeviceError::RawError(_) => "DeviceError::ConstructionFailed",
};
write!(f, "{}", descr)
}
}
impl Error for DeviceError {
fn description(&self) -> &str {
match *self {
DeviceError::ConstructionFailed => {
"Could not create a default device. Please ensure that you are using at least OSX \
10.11 or iOS 8.0"
}
DeviceError::RawError(_) => "There was an error with the device pointer",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&DeviceError::ConstructionFailed => None,
&DeviceError::RawError(ref raw_err) => Some(raw_err),
}
}
}
|
use iced::alignment::{Horizontal, Vertical};
use iced::widget::scrollable::Direction;
use iced::widget::{button, horizontal_space, vertical_space, Rule};
use iced::widget::{Button, Column, Container, Row, Scrollable, Space, Text};
use iced::Length::Fixed;
use iced::{Alignment, Element, Font, Length, Renderer};
use crate::gui::components::tab::get_settings_tabs;
use crate::gui::pages::settings_notifications_page::settings_header;
use crate::gui::pages::types::settings_page::SettingsPage;
use crate::gui::styles::button::ButtonType;
use crate::gui::styles::container::ContainerType;
use crate::gui::styles::rule::RuleType;
use crate::gui::styles::scrollbar::ScrollbarType;
use crate::gui::styles::style_constants::{
get_font, get_font_headers, BORDER_WIDTH, FONT_SIZE_SUBTITLE,
};
use crate::gui::styles::text::TextType;
use crate::gui::styles::types::custom_palette::ExtraStyles;
use crate::gui::styles::types::gradient_type::GradientType;
use crate::gui::types::message::Message;
use crate::translations::translations::{
appearance_title_translation, deep_sea_translation, mon_amour_translation,
yeti_day_translation, yeti_night_translation,
};
use crate::translations::translations_2::color_gradients_translation;
use crate::utils::types::icon::Icon;
use crate::StyleType::{Day, DeepSea, MonAmour, Night};
use crate::{Language, Sniffer, StyleType};
pub fn settings_style_page(sniffer: &Sniffer) -> Container<Message, Renderer<StyleType>> {
let font = get_font(sniffer.style);
let font_headers = get_font_headers(sniffer.style);
let mut content = Column::new()
.align_items(Alignment::Center)
.width(Length::Fill)
.push(settings_header(
font,
font_headers,
sniffer.color_gradient,
sniffer.language,
))
.push(get_settings_tabs(
SettingsPage::Appearance,
font,
sniffer.language,
))
.push(vertical_space(Length::Fixed(15.0)))
.push(
appearance_title_translation(sniffer.language)
.style(TextType::Subtitle)
.font(font)
.size(FONT_SIZE_SUBTITLE),
)
.push(vertical_space(Length::Fixed(15.0)))
.push(gradients_row(
font,
sniffer.color_gradient,
sniffer.language,
))
.push(vertical_space(Length::Fixed(15.0)));
let mut styles_col = Column::new()
.align_items(Alignment::Center)
.width(Length::Fill)
.push(
Row::new()
.push(get_palette_container(
sniffer.style,
"Yeti Night".to_string(),
yeti_night_translation(sniffer.language).to_string(),
Night,
))
.push(horizontal_space(Length::Fixed(15.0)))
.push(get_palette_container(
sniffer.style,
"Yeti Day".to_string(),
yeti_day_translation(sniffer.language).to_string(),
Day,
)),
)
.push(vertical_space(Length::Fixed(10.0)))
.push(
Row::new()
.push(get_palette_container(
sniffer.style,
"Deep Sea".to_string(),
deep_sea_translation(sniffer.language).to_string(),
DeepSea,
))
.push(horizontal_space(Length::Fixed(15.0)))
.push(get_palette_container(
sniffer.style,
"Mon Amour".to_string(),
mon_amour_translation(sniffer.language).to_string(),
MonAmour,
)),
)
.push(vertical_space(Length::Fixed(10.0)));
for children in get_extra_palettes(ExtraStyles::all_styles(), sniffer.style) {
styles_col = styles_col.push(children);
}
let styles_scroll =
Scrollable::new(styles_col).direction(Direction::Vertical(ScrollbarType::properties()));
content = content.push(styles_scroll);
Container::new(content)
.height(Length::Fixed(400.0))
.width(Length::Fixed(800.0))
.style(ContainerType::Modal)
}
fn gradients_row(
font: Font,
color_gradient: GradientType,
language: Language,
) -> Row<'static, Message, Renderer<StyleType>> {
Row::new()
.align_items(Alignment::Center)
.spacing(10)
.push(Text::new(format!("{}:", color_gradients_translation(language))).font(font))
.push(
button(
Icon::Forbidden
.to_text()
.vertical_alignment(Vertical::Center)
.horizontal_alignment(Horizontal::Center)
.size(12),
)
.padding(0)
.height(20.0)
.width(Fixed(if color_gradient.eq(&GradientType::None) {
60.0
} else {
20.0
}))
.style(ButtonType::Gradient(GradientType::None))
.on_press(Message::GradientsSelection(GradientType::None)),
)
.push(
button(
Icon::Waves
.to_text()
.vertical_alignment(Vertical::Center)
.horizontal_alignment(Horizontal::Center)
.size(13),
)
.padding(0)
.height(20.0)
.width(Fixed(if color_gradient.eq(&GradientType::Mild) {
60.0
} else {
20.0
}))
.on_press(Message::GradientsSelection(GradientType::Mild))
.style(ButtonType::Gradient(GradientType::Mild)),
)
.push(
button(
Icon::Lightning
.to_text()
.vertical_alignment(Vertical::Center)
.horizontal_alignment(Horizontal::Center)
.size(13),
)
.padding(0)
.height(20.0)
.width(Fixed(if color_gradient.eq(&GradientType::Wild) {
60.0
} else {
20.0
}))
.on_press(Message::GradientsSelection(GradientType::Wild))
.style(ButtonType::Gradient(GradientType::Wild)),
)
}
fn get_palette_container(
style: StyleType,
name: String,
description: String,
on_press: StyleType,
) -> Button<'static, Message, Renderer<StyleType>> {
let font = get_font(style);
let is_custom = matches!(on_press, StyleType::Custom(_));
let mut content = Column::new()
.width(Length::Fill)
.align_items(Alignment::Center)
.spacing(5)
.push(Text::new(name).font(font))
.push(get_palette(on_press, is_custom));
if !is_custom {
content = content.push(Text::new(description).font(font));
}
Button::new(content)
.height(Length::Fixed(if is_custom { 75.0 } else { 110.0 }))
.width(Length::Fixed(380.0))
.padding(5)
.style(if on_press.eq(&style) {
ButtonType::BorderedRoundSelected
} else {
ButtonType::BorderedRound
})
.on_press(Message::Style(on_press))
}
fn get_palette(
style: StyleType,
is_custom: bool,
) -> Container<'static, Message, Renderer<StyleType>> {
let height = if is_custom { 25.0 } else { 40.0 };
Container::new(
Row::new()
.push(
Row::new()
.width(Length::Fixed(120.0))
.push(Rule::horizontal(height).style(RuleType::PalettePrimary(style))),
)
.push(
Row::new()
.width(Length::Fixed(80.0))
.push(Rule::horizontal(height).style(RuleType::PaletteSecondary(style))),
)
.push(
Row::new()
.width(Length::Fixed(60.0))
.push(Rule::horizontal(height).style(RuleType::PaletteOutgoing(style))),
)
.push(
Row::new()
.width(Length::Fixed(40.0))
.push(Rule::horizontal(height).style(RuleType::PaletteButtons(style))),
),
)
.align_x(Horizontal::Center)
.align_y(Vertical::Center)
.width(300.0 + 2.0 * BORDER_WIDTH)
.height(height + 1.7 * BORDER_WIDTH)
.style(ContainerType::Palette)
}
// Buttons for each extra style arranged in rows of two
fn get_extra_palettes(
styles: &[ExtraStyles],
current_style: StyleType,
) -> Vec<Element<'static, Message, Renderer<StyleType>>> {
// Map each extra style into a palette container
let mut styles = styles.iter().map(|&style| {
let name = style.to_string();
let description = String::new();
let style = StyleType::Custom(style);
get_palette_container(current_style, name, description, style)
});
// The best way to do this would be with itertools, but that would introduce another dependency.
let mut children = Vec::with_capacity(styles.len());
// This handles the case where there aren't an even number of styles.
// [Iterator::zip] drops remainders. Itertools' `zip_longest` and the unstable array chunks API
// are both better solutions.
while let (Some(first), second) = (styles.next(), styles.next()) {
// Add both styles and the vertical space if there are two styles.
if let Some(second) = second {
children.extend([
Row::new()
.push(first)
.push(horizontal_space(Length::Fixed(15.0)))
.push(second)
.into(),
<Space as Into<Element<Message, Renderer<StyleType>>>>::into(vertical_space(
Length::Fixed(10.0),
)),
]);
} else {
children.extend([
Row::new().push(first).into(),
<Space as Into<Element<Message, Renderer<StyleType>>>>::into(vertical_space(
Length::Fixed(10.0),
)),
]);
}
}
children
}
|
#![type_length_limit = "2097152"]
extern crate failure;
extern crate fake_github;
extern crate futures;
extern crate ipc_channel;
extern crate nix;
extern crate reviewist;
#[macro_use]
extern crate slog;
extern crate tokio_core;
extern crate tokio_timer;
extern crate url;
use failure::Error;
use futures::future::{self, Either};
use futures::prelude::*;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use tokio_core::reactor::Core;
use tokio_timer::Delay;
use fake_github::{Message, Response};
use ipc_channel::ipc;
use reviewist::Config;
use std::env;
use url::Url;
#[test]
fn test_one_pr() {
let result = with_fake_server(|server, db| {
let mut core = Core::new().expect("failed to start tokio core");
server.sender.send(Message::AddReviewRequest).ok();
let future = build_main_future(&core, &server, &db);
let limited_future = time_limit(future, 1);
core.run(limited_future).map(move |_| {
server.sender.send(Message::GetTaskCount).ok();
match server.receiver.recv() {
Ok(Response::TaskCountResponse(count)) => count,
response => panic!("Unexpected response: {:?}", response),
}
})
});
let task_count = result.unwrap();
assert_eq!(task_count, 1);
}
#[test]
fn test_multiple_prs() {
const PR_COUNT: usize = 10;
let result = with_fake_server(|server, db| {
let mut core = Core::new().expect("failed to start tokio core");
for _ in 0..PR_COUNT {
server.sender.send(Message::AddReviewRequest).ok();
}
let future = build_main_future(&core, &server, &db);
let limited_future = time_limit(future, 1);
core.run(limited_future).map(move |_| {
server.sender.send(Message::GetTaskCount).ok();
match server.receiver.recv() {
Ok(Response::TaskCountResponse(count)) => count,
response => panic!("Unexpected response: {:?}", response),
}
})
});
let task_count = result.unwrap();
assert_eq!(task_count, PR_COUNT);
}
fn build_main_future(core: &Core, server: &FakeServer, db: &DatabasePath) -> impl Future<Item = (), Error = Error> {
reviewist::run(Config {
logger: configure_slog(),
core: &core,
github_base: Url::parse(&format!("http://{}/github/", server.address)).unwrap(),
todoist_base: Url::parse(&format!("http://{}/todoist/", server.address)).unwrap(),
database_url: db.fd_path(),
})
}
struct FakeServer {
receiver: ipc::IpcReceiver<Response>,
sender: ipc::IpcSender<Message>,
address: std::net::SocketAddr,
}
fn with_fake_server<T>(f: impl FnOnce(FakeServer, DatabasePath) -> T) -> T {
let (server, server_name) = ipc::IpcOneShotServer::<Response>::new().unwrap();
let mut fake_github = Command::new("cargo")
.args(&["run", "--release", "-p", "fake_github", "--", server_name.as_ref()])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("failed to start fake github");
let db_path = new_database();
env::set_var("TODOIST_TOKEN", "lol123");
env::set_var("GITHUB_TOKEN", "lol123");
let (receiver, message) = server.accept().unwrap();
let (address, sender) = match message {
Response::Booted { port, sender } => (port, sender),
msg => panic!("Unexpected message: {:?}", msg),
};
let result = f(
FakeServer {
receiver,
address,
sender,
},
db_path,
);
fake_github.kill().unwrap();
result
}
fn time_limit<F>(future: F, seconds: u64) -> impl Future<Item = (), Error = Error>
where
F: Future<Error = Error>,
{
let delay = Delay::new(Instant::now() + Duration::from_secs(seconds));
future.select2(delay).then(|result| match result {
Ok(_) => future::ok(()),
Err(Either::B(_)) => future::ok(()),
Err(Either::A((err, _))) => future::err(err),
})
}
fn configure_slog() -> slog::Logger {
slog::Logger::root(slog::Discard, o!())
}
struct DatabasePath {
path: String,
fd: std::os::unix::io::RawFd,
}
impl DatabasePath {
fn fd_path(&self) -> String {
format!("/proc/self/fd/{}", self.fd)
}
}
impl Drop for DatabasePath {
fn drop(&mut self) {
nix::unistd::close(self.fd).unwrap();
nix::unistd::unlink(self.path.as_str()).unwrap();
}
}
fn new_database() -> DatabasePath {
use nix::unistd::mkstemp;
let (fd, path) = mkstemp("/tmp/reviewist_test.db.XXXXXX").unwrap();
let db_path = DatabasePath {
fd,
path: path.to_string_lossy().into_owned(),
};
Command::new("cargo")
.env("DATABASE_URL", db_path.fd_path())
.args(&["run", "--release", "--bin", "reviewist_migrate"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("failed to start fake github");
return db_path;
}
|
extern crate regex;
#[macro_use]
extern crate lazy_static;
const INPUT: &str = include_str!("../input.txt");
const VOWELS: [char;5] = ['a','e','i','o','u'];
fn is_nice(input: &str) -> bool {
let chars: Vec<char> = input.chars().collect();
let forbidden: [String;4] = [String::from("ab"),String::from("cd"),String::from("pq"),String::from("xy")];
let mut vowel_counter = 0u32;
let mut duplicate = false;
for c in chars.clone() {
if VOWELS.contains(&c) {
vowel_counter += 1;
}
}
if vowel_counter < 3 {
return false;
}
for i in 1..input.len() {
if chars[i-1] == chars[i] {
duplicate = true;
break;
}
}
if !duplicate {
return false;
}
for i in 1..input.len() {
let mut temp: String = String::new();
temp.push(chars[i-1]);
temp.push(chars[i]);
if forbidden.contains(&temp) {
return false;
}
}
true
}
fn is_really_nice(input: &str) -> bool {
let chars: Vec<char> = input.chars().collect();
let mut gap_pair = false;
let mut repeat = false;
for i in 2..input.len() {
if chars[i-2] == chars[i] {
gap_pair = true;
break;
}
}
if !gap_pair {
return false;
}
for i in 1..input.len() {
let mut pattern: String = String::new();
let tail: String = String::from(&input[i+1..]);
pattern.push(chars[i-1]);
pattern.push(chars[i]);
if tail.contains(&pattern) {
repeat = true;
break;
}
}
if !repeat {
return false;
}
true
}
fn solve_part_1() -> u32 {
let mut nice_counter = 0u32;
for word in INPUT.lines() {
if is_nice(word) {
nice_counter += 1;
}
}
nice_counter
}
fn solve_part_2() -> u32 {
let mut really_nice_counter = 0u32;
for word in INPUT.lines() {
if is_really_nice(word) {
really_nice_counter += 1;
}
}
really_nice_counter
}
fn main() {
println!("Answer part 1: {}", solve_part_1());
println!("Answer part 2: {}", solve_part_2());
}
|
#[doc = "Register `ISR` reader"]
pub type R = crate::R<ISR_SPEC>;
#[doc = "Register `ISR` writer"]
pub type W = crate::W<ISR_SPEC>;
#[doc = "Field `ALRAWF` reader - Alarm A write flag This bit is set by hardware when Alarm A values can be changed, after the ALRAE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."]
pub type ALRAWF_R = crate::BitReader;
#[doc = "Field `ALRBWF` reader - Alarm B write flag This bit is set by hardware when Alarm B values can be changed, after the ALRBE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."]
pub type ALRBWF_R = crate::BitReader;
#[doc = "Field `WUTWF` reader - Wakeup timer write flag This bit is set by hardware up to 2 RTCCLK cycles after the WUTE bit has been set to 0 in RTC_CR, and is cleared up to 2 RTCCLK cycles after the WUTE bit has been set to 1. The wakeup timer values can be changed when WUTE bit is cleared and WUTWF is set."]
pub type WUTWF_R = crate::BitReader;
#[doc = "Field `SHPF` reader - Shift operation pending This flag is set by hardware as soon as a shift operation is initiated by a write to the RTC_SHIFTR register. It is cleared by hardware when the corresponding shift operation has been executed. Writing to the SHPF bit has no effect."]
pub type SHPF_R = crate::BitReader;
#[doc = "Field `INITS` reader - Initialization status flag This bit is set by hardware when the calendar year field is different from 0 (Backup domain reset state)."]
pub type INITS_R = crate::BitReader;
#[doc = "Field `RSF` reader - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."]
pub type RSF_R = crate::BitReader;
#[doc = "Field `RSF` writer - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."]
pub type RSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `INITF` reader - Initialization flag When this bit is set to 1, the RTC is in initialization state, and the time, date and prescaler registers can be updated."]
pub type INITF_R = crate::BitReader;
#[doc = "Field `INIT` reader - Initialization mode"]
pub type INIT_R = crate::BitReader;
#[doc = "Field `INIT` writer - Initialization mode"]
pub type INIT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ALRAF` reader - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."]
pub type ALRAF_R = crate::BitReader;
#[doc = "Field `ALRAF` writer - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."]
pub type ALRAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ALRBF` reader - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."]
pub type ALRBF_R = crate::BitReader;
#[doc = "Field `ALRBF` writer - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."]
pub type ALRBF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `WUTF` reader - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."]
pub type WUTF_R = crate::BitReader;
#[doc = "Field `WUTF` writer - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."]
pub type WUTF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSF` reader - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."]
pub type TSF_R = crate::BitReader;
#[doc = "Field `TSF` writer - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."]
pub type TSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TSOVF` reader - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."]
pub type TSOVF_R = crate::BitReader;
#[doc = "Field `TSOVF` writer - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."]
pub type TSOVF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TAMP1F` reader - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"]
pub type TAMP1F_R = crate::BitReader;
#[doc = "Field `TAMP1F` writer - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"]
pub type TAMP1F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TAMP2F` reader - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"]
pub type TAMP2F_R = crate::BitReader;
#[doc = "Field `TAMP2F` writer - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"]
pub type TAMP2F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TAMP3F` reader - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"]
pub type TAMP3F_R = crate::BitReader;
#[doc = "Field `TAMP3F` writer - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"]
pub type TAMP3F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `RECALPF` reader - Recalibration pending Flag The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0. Refer to Re-calibration on-the-fly."]
pub type RECALPF_R = crate::BitReader;
#[doc = "Field `ITSF` reader - Internal tTime-stamp flag"]
pub type ITSF_R = crate::BitReader;
#[doc = "Field `ITSF` writer - Internal tTime-stamp flag"]
pub type ITSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Alarm A write flag This bit is set by hardware when Alarm A values can be changed, after the ALRAE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."]
#[inline(always)]
pub fn alrawf(&self) -> ALRAWF_R {
ALRAWF_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Alarm B write flag This bit is set by hardware when Alarm B values can be changed, after the ALRBE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."]
#[inline(always)]
pub fn alrbwf(&self) -> ALRBWF_R {
ALRBWF_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Wakeup timer write flag This bit is set by hardware up to 2 RTCCLK cycles after the WUTE bit has been set to 0 in RTC_CR, and is cleared up to 2 RTCCLK cycles after the WUTE bit has been set to 1. The wakeup timer values can be changed when WUTE bit is cleared and WUTWF is set."]
#[inline(always)]
pub fn wutwf(&self) -> WUTWF_R {
WUTWF_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Shift operation pending This flag is set by hardware as soon as a shift operation is initiated by a write to the RTC_SHIFTR register. It is cleared by hardware when the corresponding shift operation has been executed. Writing to the SHPF bit has no effect."]
#[inline(always)]
pub fn shpf(&self) -> SHPF_R {
SHPF_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Initialization status flag This bit is set by hardware when the calendar year field is different from 0 (Backup domain reset state)."]
#[inline(always)]
pub fn inits(&self) -> INITS_R {
INITS_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."]
#[inline(always)]
pub fn rsf(&self) -> RSF_R {
RSF_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Initialization flag When this bit is set to 1, the RTC is in initialization state, and the time, date and prescaler registers can be updated."]
#[inline(always)]
pub fn initf(&self) -> INITF_R {
INITF_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Initialization mode"]
#[inline(always)]
pub fn init(&self) -> INIT_R {
INIT_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."]
#[inline(always)]
pub fn alraf(&self) -> ALRAF_R {
ALRAF_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."]
#[inline(always)]
pub fn alrbf(&self) -> ALRBF_R {
ALRBF_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."]
#[inline(always)]
pub fn wutf(&self) -> WUTF_R {
WUTF_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."]
#[inline(always)]
pub fn tsf(&self) -> TSF_R {
TSF_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."]
#[inline(always)]
pub fn tsovf(&self) -> TSOVF_R {
TSOVF_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"]
#[inline(always)]
pub fn tamp1f(&self) -> TAMP1F_R {
TAMP1F_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"]
#[inline(always)]
pub fn tamp2f(&self) -> TAMP2F_R {
TAMP2F_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"]
#[inline(always)]
pub fn tamp3f(&self) -> TAMP3F_R {
TAMP3F_R::new(((self.bits >> 15) & 1) != 0)
}
#[doc = "Bit 16 - Recalibration pending Flag The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0. Refer to Re-calibration on-the-fly."]
#[inline(always)]
pub fn recalpf(&self) -> RECALPF_R {
RECALPF_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - Internal tTime-stamp flag"]
#[inline(always)]
pub fn itsf(&self) -> ITSF_R {
ITSF_R::new(((self.bits >> 17) & 1) != 0)
}
}
impl W {
#[doc = "Bit 5 - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."]
#[inline(always)]
#[must_use]
pub fn rsf(&mut self) -> RSF_W<ISR_SPEC, 5> {
RSF_W::new(self)
}
#[doc = "Bit 7 - Initialization mode"]
#[inline(always)]
#[must_use]
pub fn init(&mut self) -> INIT_W<ISR_SPEC, 7> {
INIT_W::new(self)
}
#[doc = "Bit 8 - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."]
#[inline(always)]
#[must_use]
pub fn alraf(&mut self) -> ALRAF_W<ISR_SPEC, 8> {
ALRAF_W::new(self)
}
#[doc = "Bit 9 - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."]
#[inline(always)]
#[must_use]
pub fn alrbf(&mut self) -> ALRBF_W<ISR_SPEC, 9> {
ALRBF_W::new(self)
}
#[doc = "Bit 10 - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."]
#[inline(always)]
#[must_use]
pub fn wutf(&mut self) -> WUTF_W<ISR_SPEC, 10> {
WUTF_W::new(self)
}
#[doc = "Bit 11 - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."]
#[inline(always)]
#[must_use]
pub fn tsf(&mut self) -> TSF_W<ISR_SPEC, 11> {
TSF_W::new(self)
}
#[doc = "Bit 12 - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."]
#[inline(always)]
#[must_use]
pub fn tsovf(&mut self) -> TSOVF_W<ISR_SPEC, 12> {
TSOVF_W::new(self)
}
#[doc = "Bit 13 - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"]
#[inline(always)]
#[must_use]
pub fn tamp1f(&mut self) -> TAMP1F_W<ISR_SPEC, 13> {
TAMP1F_W::new(self)
}
#[doc = "Bit 14 - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"]
#[inline(always)]
#[must_use]
pub fn tamp2f(&mut self) -> TAMP2F_W<ISR_SPEC, 14> {
TAMP2F_W::new(self)
}
#[doc = "Bit 15 - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"]
#[inline(always)]
#[must_use]
pub fn tamp3f(&mut self) -> TAMP3F_W<ISR_SPEC, 15> {
TAMP3F_W::new(self)
}
#[doc = "Bit 17 - Internal tTime-stamp flag"]
#[inline(always)]
#[must_use]
pub fn itsf(&mut self) -> ITSF_W<ISR_SPEC, 17> {
ITSF_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is write protected (except for RTC_ISR\\[13:8\\]
bits). The write access procedure is described in RTC register write protection on page9.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`isr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ISR_SPEC;
impl crate::RegisterSpec for ISR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`isr::R`](R) reader structure"]
impl crate::Readable for ISR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`isr::W`](W) writer structure"]
impl crate::Writable for ISR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets ISR to value 0x07"]
impl crate::Resettable for ISR_SPEC {
const RESET_VALUE: Self::Ux = 0x07;
}
|
use indexmap::IndexMap;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Config, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span,
Spanned, SyntaxShape, Value,
};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use std::collections::HashSet;
use std::io::Cursor;
use std::io::Write;
#[derive(Clone)]
pub struct ToXml;
impl Command for ToXml {
fn name(&self) -> &str {
"to xml"
}
fn signature(&self) -> Signature {
Signature::build("to xml")
.named(
"pretty",
SyntaxShape::Int,
"Formats the XML text with the provided indentation setting",
Some('p'),
)
.category(Category::Formats)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Outputs an XML string representing the contents of this table",
example: r#"{ "note": { "children": [{ "remember": {"attributes" : {}, "children": [Event]}}], "attributes": {} } } | to xml"#,
result: Some(Value::test_string(
"<note><remember>Event</remember></note>",
)),
},
Example {
description: "Optionally, formats the text with a custom indentation setting",
example: r#"{ "note": { "children": [{ "remember": {"attributes" : {}, "children": [Event]}}], "attributes": {} } } | to xml -p 3"#,
result: Some(Value::test_string(
"<note>\n <remember>Event</remember>\n</note>",
)),
},
]
}
fn usage(&self) -> &str {
"Convert table into .xml text"
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, ShellError> {
let head = call.head;
let config = engine_state.get_config();
let pretty: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "pretty")?;
to_xml(input, head, pretty, config)
}
}
pub fn add_attributes<'a>(
element: &mut quick_xml::events::BytesStart<'a>,
attributes: &'a IndexMap<String, String>,
) {
for (k, v) in attributes {
element.push_attribute((k.as_str(), v.as_str()));
}
}
pub fn get_attributes(row: &Value, config: &Config) -> Option<IndexMap<String, String>> {
if let Value::Record { .. } = row {
if let Some(Value::Record { cols, vals, .. }) = row.get_data_by_key("attributes") {
let mut h = IndexMap::new();
for (k, v) in cols.iter().zip(vals.iter()) {
h.insert(k.clone(), v.clone().into_abbreviated_string(config));
}
return Some(h);
}
}
None
}
pub fn get_children(row: &Value) -> Option<Vec<Value>> {
if let Value::Record { .. } = row {
if let Some(Value::List { vals, .. }) = row.get_data_by_key("children") {
return Some(vals);
}
}
None
}
pub fn is_xml_row(row: &Value) -> bool {
if let Value::Record { cols, .. } = &row {
let keys: HashSet<&String> = cols.iter().collect();
let children: String = "children".to_string();
let attributes: String = "attributes".to_string();
return keys.contains(&children) && keys.contains(&attributes) && keys.len() == 2;
}
false
}
pub fn write_xml_events<W: Write>(
current: Value,
writer: &mut quick_xml::Writer<W>,
config: &Config,
) -> Result<(), ShellError> {
match current {
Value::Record { cols, vals, span } => {
for (k, v) in cols.iter().zip(vals.iter()) {
let mut e = BytesStart::owned(k.as_bytes(), k.len());
if !is_xml_row(v) {
return Err(ShellError::GenericError(
"Expected a row with 'children' and 'attributes' columns".to_string(),
"missing 'children' and 'attributes' columns ".to_string(),
Some(span),
None,
Vec::new(),
));
}
let a = get_attributes(v, config);
if let Some(ref a) = a {
add_attributes(&mut e, a);
}
writer
.write_event(Event::Start(e))
.expect("Couldn't open XML node");
let c = get_children(v);
if let Some(c) = c {
for v in c {
write_xml_events(v, writer, config)?;
}
}
writer
.write_event(Event::End(BytesEnd::borrowed(k.as_bytes())))
.expect("Couldn't close XML node");
}
}
Value::List { vals, .. } => {
for v in vals {
write_xml_events(v, writer, config)?;
}
}
_ => {
let s = current.into_abbreviated_string(config);
writer
.write_event(Event::Text(BytesText::from_plain_str(s.as_str())))
.expect("Couldn't write XML text");
}
}
Ok(())
}
fn to_xml(
input: PipelineData,
head: Span,
pretty: Option<Spanned<i64>>,
config: &Config,
) -> Result<PipelineData, ShellError> {
let mut w = pretty.as_ref().map_or_else(
|| quick_xml::Writer::new(Cursor::new(Vec::new())),
|p| quick_xml::Writer::new_with_indent(Cursor::new(Vec::new()), b' ', p.item as usize),
);
let value = input.into_value(head);
let value_type = value.get_type();
match write_xml_events(value, &mut w, config) {
Ok(_) => {
let b = w.into_inner().into_inner();
let s = if let Ok(s) = String::from_utf8(b) {
s
} else {
return Err(ShellError::NonUtf8(head));
};
Ok(Value::string(s, head).into_pipeline_data())
}
Err(_) => Err(ShellError::CantConvert(
"XML".into(),
value_type.to_string(),
head,
None,
)),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(ToXml {})
}
}
|
//Functions - Used to store blocks of code for re-use.
pub fn run() {
greeting("Hello", "Maddy");
//Bind Function Values to Variables
let get_sum = add(5,5);
println!("Sum: {}", get_sum);
//Clousure - We can use this outside variables
let n3:i32=10;
let add_num = |n1:i32,n2:i32| n1+n2+n3;
println!("Clouser Sum: {}", add_num(3,3));
}
fn greeting(greet:&str, name:&str) {
println!("{} {}, nice to meet you!",greet,name);
}
fn add(n1:i32, n2:i32)-> i32{
n1 + n2
} |
use std::io;
use std::mem;
use crate::context::Context;
use crate::endianness::Endianness;
use crate::writable::Writable;
pub trait Writer< 'a, C: Context > {
fn write_bytes( &mut self, slice: &'a [u8] ) -> io::Result< () >;
fn write_owned_bytes( &mut self, vec: Vec< u8 > ) -> io::Result< () >;
fn write_u8( &mut self, value: u8 ) -> io::Result< () >;
fn write_u16( &mut self, value: u16 ) -> io::Result< () >;
fn write_u32( &mut self, value: u32 ) -> io::Result< () >;
fn write_u64( &mut self, value: u64 ) -> io::Result< () >;
fn context( &self ) -> &C;
fn context_mut( &mut self ) -> &mut C;
#[inline(always)]
fn write_i8( &mut self, value: i8 ) -> io::Result< () > {
self.write_u8( value as u8 )
}
#[inline(always)]
fn write_i16( &mut self, value: i16 ) -> io::Result< () > {
self.write_u16( value as u16 )
}
#[inline(always)]
fn write_i32( &mut self, value: i32 ) -> io::Result< () > {
self.write_u32( value as u32 )
}
#[inline(always)]
fn write_i64( &mut self, value: i64 ) -> io::Result< () > {
self.write_u64( value as u64 )
}
#[inline(always)]
fn write_f32( &mut self, value: f32 ) -> io::Result< () > {
let value: u32 = unsafe { mem::transmute( value ) };
self.write_u32( value )
}
#[inline(always)]
fn write_f64( &mut self, value: f64 ) -> io::Result< () > {
let value: u64 = unsafe { mem::transmute( value ) };
self.write_u64( value )
}
#[inline(always)]
fn endianness( &self ) -> Endianness {
self.context().endianness()
}
#[inline(always)]
fn write_value< T: Writable< C > >( &mut self, item: &'a T ) -> io::Result< () > {
item.write_to( self )
}
}
|
// TODO
// * bounded
// * more tests
// * real life benches
// * unbounded
pub mod unbounded;
pub mod bounded;
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident};
pub fn derive_variant_names(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
if let Data::Enum(data_enum) = input.data {
let mut variant_body = Vec::new();
for variant in data_enum.variants {
let variant_name = &variant.ident;
let patterns = match variant.fields {
Fields::Unit => quote! {},
Fields::Named(_) => quote! { {..} },
Fields::Unnamed(_) => quote! { (..) },
};
let variant_name_str = variant_name.to_string();
variant_body.push(quote! {
Self::#variant_name#patterns => #variant_name_str
});
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let gen = quote! {
impl #impl_generics gazebo::variants::VariantName for #name #ty_generics #where_clause {
fn variant_name(&self) -> &'static str {
match self {
#(#variant_body,)*
}
}
}
};
gen.into()
} else {
panic!("Can only derive variant name on enums")
}
}
pub fn derive_unpack_variants(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
if let Data::Enum(data_enum) = input.data {
let mut variant_fns = Vec::new();
for variant in data_enum.variants {
let variant_name = &variant.ident;
let mut count = 0;
let mut patterns = Vec::new();
let mut inner_type = Vec::new();
for field in variant.fields.iter() {
patterns.push(field.ident.clone().map_or_else(
|| {
let id = Ident::new(&format!("_v{}", count), Span::call_site());
count += 1;
id
},
|f| f,
));
inner_type.push(&field.ty);
}
let (patterned_out, inner_type) = if variant.fields.len() == 1 {
let patterned_out = quote! { #(#patterns)* };
let inner_type = quote! { #(&'a #inner_type)* };
(patterned_out, inner_type)
} else {
let patterned_out = quote! { (#(#patterns,)*) };
let inner_type = quote! { (#(&'a #inner_type,)*) };
(patterned_out, inner_type)
};
let patterns = match variant.fields {
Fields::Named(_) => quote! { { #(#patterns,)*} },
Fields::Unnamed(_) => quote! { ( #(#patterns,)* ) },
Fields::Unit => quote!(),
};
let variant_fn_name = Ident::new(
&format!("unpack_{}", to_snake_case(&variant_name.to_string())),
Span::call_site(),
);
variant_fns.push(quote! {
pub fn #variant_fn_name<'a>(&'a self) -> Option<#inner_type> {
match self {
Self::#variant_name#patterns => Some(#patterned_out),
_ => None
}
}
});
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let gen = quote! {
impl #impl_generics #name #ty_generics #where_clause {
#(#variant_fns)*
}
};
gen.into()
} else {
panic!("Can only derive variant name on enums")
}
}
fn to_snake_case(s: &str) -> String {
let mut out = String::new();
let mut is_first = true;
for c in s.chars() {
if c.is_ascii_uppercase() {
if !is_first {
out.push('_');
}
out.push(c.to_ascii_lowercase());
} else {
out.push(c);
}
is_first = false;
}
out
}
|
use iron::prelude::*;
use iron_sessionstorage::traits::SessionRequestExt;
use common::http::*;
pub fn logout(req: &mut Request) -> IronResult<Response> {
req.session().clear().unwrap();
redirect_to("/")
} |
use hacspec_lib::*;
use hacspec_edwards25519_hash::*;
use hacspec_edwards25519::*;
use h2c_rust_ref::{GetHashToCurve, SUITES_EDWARDS};
use redox_ecc::ellipticcurve::Encode;
use quickcheck_macros::quickcheck;
// Checks that the three specifications of map_to_curve in ../src/edwards25519-hash.rs
// agree in value together with armfazh's specification of edwards25519_XMD:SHA-512_ELL2_NU_
// armfazh's specification can be seen here: https://github.com/armfazh/h2c-rust-ref
#[quickcheck]
fn test_equiv_armfazh(msg: String) -> bool {
let dst = b"QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_NU_";
let msg: &[u8] = msg.as_bytes();
let suite = SUITES_EDWARDS["edwards25519_XMD:SHA-512_ELL2_NU_"].get(dst);
let mut q = suite.hash(msg);
q.normalize(); // make q into p
// convert to hacspec ed point
let parmfazh = q.encode(true);
let parmfazh = ByteSeq::from_public_slice(&parmfazh);
let parmfazh = decode(parmfazh).unwrap();
let u = ed_hash_to_field(
&ByteSeq::from_public_slice(msg),
&ByteSeq::from_public_slice(dst),
1
).unwrap();
// compute normal
let st = map_to_curve_elligator2(u[0]);
let q = curve25519_to_edwards25519(st);
let pnormal = ed_clear_cofactor(q);
let pnormal = point_normalize(pnormal);
// compute straight
let st = map_to_curve_elligator2_straight(u[0]);
let q = curve25519_to_edwards25519(st);
let pstraight = ed_clear_cofactor(q);
let pstraight = point_normalize(pstraight);
// compute optimized
let q = map_to_curve_elligator2_edwards25519(u[0]);
let poptim = ed_clear_cofactor(q);
let poptim = point_normalize(poptim);
(parmfazh == poptim) &
(parmfazh == pstraight) &
(parmfazh == pnormal) &
(pstraight == pnormal) &
(pstraight == poptim) &
(pnormal == poptim)
}
|
use super::super::SECP256K1;
use hex;
use secp256k1::{Error, Message, SecretKey};
use sha2::{Digest, Sha256};
pub type PrivateKey = SecretKey;
pub fn from_passphrase(passphrase: &str) -> Result<PrivateKey, Error> {
PrivateKey::from_slice(&Sha256::digest(passphrase.as_bytes())[..])
}
pub fn from_hex(private_key: &str) -> Result<PrivateKey, Error> {
// TODO: fix unwrap
PrivateKey::from_slice(hex::decode(private_key).unwrap().as_slice())
}
pub fn sign(bytes: &[u8], passphrase: &str) -> String {
let key = from_passphrase(passphrase).unwrap();
let hash = &Sha256::digest(&bytes);
let msg = Message::from_slice(&hash).unwrap();
let sig = SECP256K1.sign(&msg, &key);
hex::encode(sig.serialize_der())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn private_key_from_passphrase() {
let private_key = from_passphrase("this is a top secret passphrase");
assert!(private_key.is_ok());
assert_eq!(
private_key.unwrap().to_string(),
"d8839c2432bfd0a67ef10a804ba991eabba19f154a3d707917681d45822a5712"
);
}
#[test]
fn private_key_from_hex() {
let private_key =
from_hex("d8839c2432bfd0a67ef10a804ba991eabba19f154a3d707917681d45822a5712");
assert!(private_key.is_ok());
assert_eq!(
private_key.unwrap().to_string(),
"d8839c2432bfd0a67ef10a804ba991eabba19f154a3d707917681d45822a5712"
);
}
}
|
mod streamvbyte {
use libc::size_t;
extern "C" {
pub fn streamvbyte_delta_encode(
data: *const u32,
num_els: u32,
output: *mut u8,
offset: u32,
) -> size_t;
pub fn streamvbyte_delta_decode(
compressed_data: *const u8,
output: *mut u32,
num_els: u32,
offset: u32,
) -> size_t;
pub fn streamvbyte_encode(data: *const u32, num_els: u32, output: *mut u8) -> size_t;
pub fn streamvbyte_decode(
compressed_data: *const u8,
output: *mut u32,
num_els: usize,
) -> size_t;
}
}
#[inline(always)]
pub(crate) fn compress_sorted<'a>(input: &[u32], output: &'a mut [u8], offset: u32) -> &'a [u8] {
let compress_length = unsafe {
streamvbyte::streamvbyte_delta_encode(
input.as_ptr(),
input.len() as u32,
output.as_mut_ptr(),
offset,
)
};
&output[..compress_length]
}
#[inline(always)]
pub(crate) fn compress_unsorted<'a>(input: &[u32], output: &'a mut [u8]) -> &'a [u8] {
let compress_length = unsafe {
streamvbyte::streamvbyte_encode(input.as_ptr(), input.len() as u32, output.as_mut_ptr())
};
&output[..compress_length]
}
#[inline(always)]
pub(crate) fn uncompress_sorted<'a>(
compressed_data: &'a [u8],
output: &mut [u32],
offset: u32,
) -> usize {
unsafe {
streamvbyte::streamvbyte_delta_decode(
compressed_data.as_ptr(),
output.as_mut_ptr(),
output.len() as u32,
offset,
)
}
}
#[inline(always)]
pub(crate) fn uncompress_unsorted<'a>(compressed_data: &'a [u8], output: &mut [u32]) -> usize {
unsafe {
streamvbyte::streamvbyte_decode(compressed_data.as_ptr(), output.as_mut_ptr(), output.len())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.