text
stringlengths
8
4.13M
pub const BGP_PORT: u16 = 179; pub const BGP_HEADER_LEN: usize = 19; pub use capability::*; pub use client::Bgp; pub use client::Client; pub use client::Event; pub use client::Message; pub use communities::Communities; pub use message::MessageHeader; pub use neighbor::Neighbor; pub use neighbor::NeighborVec; pub use neighbor_map::NeighborMap; pub use packet::*; mod capability; pub mod client; mod communities; mod message; mod neighbor; mod neighbor_map; mod packet;
extern crate rand; pub use rand::Rng; pub trait Vector<I32> { fn new_sorted(number: usize, min_dist: i32, max_dist:i32) -> Self where Self: Sized; fn new(number: usize, min_value: i32, max_value: i32) -> Self where Self: Sized; fn len(&self) -> isize; fn display(&self); fn sequential_search(&self, search_num: i32) -> Option<i32>; fn binary_search(&self, search_num: i32, l: i32, r: i32) -> Option<i32>; fn interpolation_search(&self, search: i32, l: i32, r: i32) -> Option<i32>; } impl Vector<i32> for Vec<i32> { fn new_sorted(number: usize, min_dist: i32, max_dist:i32) -> Self where Self: Sized { let mut rng = rand::thread_rng(); let mut ret: Vec<i32> = Vec::with_capacity(number); ret.push(rng.gen_range(min_dist, max_dist)); for i in 1..ret.capacity() { ret.push(ret[i - 1] + rng.gen_range(min_dist, max_dist)); } ret } fn new(number: usize, min_value: i32, max_value: i32) -> Self where Self: Sized { let mut rng = rand::thread_rng(); let mut ret: Vec<i32> = Vec::with_capacity(number); for _ in 0..ret.capacity() { ret.push(rng.gen_range(min_value, max_value)); } ret } fn len(&self) -> isize { self.len() as isize } fn display(&self) { println!("{:?}", self); } fn sequential_search(&self, search_num: i32) -> Option<i32> { for i in 0..self.len() { if self[i as usize] == search_num { return Some(i as i32); } } return None; } fn binary_search(&self, search_num: i32, mut l: i32, mut r: i32) -> Option<i32> { while l <= r { println!("l = {}, r = {}", l, r); let mid:i32 = (l + r) / 2; if self[mid as usize] == search_num { return Some(mid); } else if self[mid as usize] > search_num { r = mid - 1; } else { l = mid + 1; } } return None; } fn interpolation_search(&self, search_num: i32, mut l: i32, mut r: i32) -> Option<i32> { while self[r as usize] != self[l as usize] && l <= r { let mid:i32 = l + (search_num - self[l as usize]) / (self[r as usize] - self[l as usize]) * (r - l); if self[mid as usize] == search_num { return Some(mid); } else if self[mid as usize] > search_num { r = mid - 1; } else { l = mid + 1; } } if search_num == self[l as usize] { return Some(l as i32); } else { return None; } } }
//! Process HTTP connections on the client. use async_std::io::{self, Read, Write}; use http_types::{Request, Response}; mod decode; mod encode; pub use decode::decode; pub use encode::Encoder; /// Opens an HTTP/1.1 connection to a remote host. pub async fn connect<RW>(mut stream: RW, req: Request) -> http_types::Result<Response> where RW: Read + Write + Send + Sync + Unpin + 'static, { let mut req = Encoder::new(req); log::trace!("> {:?}", &req); io::copy(&mut req, &mut stream).await?; let res = decode(stream).await?; log::trace!("< {:?}", &res); Ok(res) }
use serde::{Deserialize, Serialize}; use sqlx::postgres::PgPool; use sqlx::sqlx_macros::Type; use sqlx::types::Uuid; use strum_macros::{Display, EnumString}; use thiserror::Error; pub mod drives; pub mod hosts; pub mod kernels; pub mod storage; pub mod vms;
use service::SamotopService; use tokio::net::TcpStream; #[derive(Clone)] struct DeadService; impl SamotopService for DeadService { fn handle(self, _socket: TcpStream) {} }
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Details of the atom representation that need to be shared between //! the macros crate and the run-time library, in order to guarantee //! consistency. #![cfg_attr(test, deny(warnings))] #[macro_use] extern crate debug_unreachable; extern crate phf_shared; use std::ptr; use std::slice; pub use self::UnpackedAtom::{Dynamic, Inline, Static}; include!(concat!(env!("OUT_DIR"), "/static_atom_set.rs")); // FIXME(rust-lang/rust#18153): generate these from an enum pub const DYNAMIC_TAG: u8 = 0b_00; pub const INLINE_TAG: u8 = 0b_01; // len in upper nybble pub const STATIC_TAG: u8 = 0b_10; pub const TAG_MASK: u64 = 0b_11; pub const ENTRY_ALIGNMENT: usize = 4; // Multiples have TAG_MASK bits unset, available for tagging. pub const MAX_INLINE_LEN: usize = 7; pub struct StaticAtomSet { key: u64, disps: &'static [(u32, u32)], atoms: &'static [&'static str], } impl StaticAtomSet { #[inline] pub fn get_index_or_hash(&self, s: &str) -> Result<u32, u64> { let hash = phf_shared::hash(s, self.key); let index = phf_shared::get_index(hash, self.disps, self.atoms.len()); if self.atoms[index as usize] == s { Ok(index) } else { Err(hash) } } #[inline] pub fn index(&self, i: u32) -> Option<&'static str> { self.atoms.get(i as usize).map(|&s| s) } #[inline] pub fn iter(&self) -> slice::Iter<&'static str> { self.atoms.iter() } } // Atoms use a compact representation which fits this enum in a single u64. // Inlining avoids actually constructing the unpacked representation in memory. #[allow(missing_copy_implementations)] pub enum UnpackedAtom { /// Pointer to a dynamic table entry. Must be 16-byte aligned! Dynamic(*mut ()), /// Length + bytes of string. Inline(u8, [u8; 7]), /// Index in static interning table. Static(u32), } const STATIC_SHIFT_BITS: usize = 32; pub static ALL_NS: &'static [(&'static str, &'static str)] = &[ ("", ""), ("html", "http://www.w3.org/1999/xhtml"), ("xml", "http://www.w3.org/XML/1998/namespace"), ("xmlns", "http://www.w3.org/2000/xmlns/"), ("xlink", "http://www.w3.org/1999/xlink"), ("svg", "http://www.w3.org/2000/svg"), ("mathml", "http://www.w3.org/1998/Math/MathML"), ]; struct RawSlice { data: *const u8, len: usize, } #[cfg(target_endian = "little")] // Not implemented yet for big-endian #[inline(always)] unsafe fn inline_atom_slice(x: &u64) -> RawSlice { let x: *const u64 = x; RawSlice { data: (x as *const u8).offset(1), len: 7, } } pub fn pack_static(n: u32) -> u64 { (STATIC_TAG as u64) | ((n as u64) << STATIC_SHIFT_BITS) } impl UnpackedAtom { #[inline(always)] pub unsafe fn pack(self) -> u64 { match self { Static(n) => pack_static(n), Dynamic(p) => { let n = p as u64; debug_assert!(0 == n & TAG_MASK); n } Inline(len, buf) => { debug_assert!((len as usize) <= MAX_INLINE_LEN); let mut data: u64 = (INLINE_TAG as u64) | ((len as u64) << 4); { let raw_slice = inline_atom_slice(&mut data); let dest: &mut [u8] = slice::from_raw_parts_mut( raw_slice.data as *mut u8, raw_slice.len); copy_memory(&buf[..], dest); } data } } } #[inline(always)] pub unsafe fn from_packed(data: u64) -> UnpackedAtom { debug_assert!(DYNAMIC_TAG == 0); // Dynamic is untagged match (data & TAG_MASK) as u8 { DYNAMIC_TAG => Dynamic(data as *mut ()), STATIC_TAG => Static((data >> STATIC_SHIFT_BITS) as u32), INLINE_TAG => { let len = ((data & 0xf0) >> 4) as usize; debug_assert!(len <= MAX_INLINE_LEN); let mut buf: [u8; 7] = [0; 7]; let raw_slice = inline_atom_slice(&data); let src: &[u8] = slice::from_raw_parts(raw_slice.data, raw_slice.len); copy_memory(src, &mut buf[..]); Inline(len as u8, buf) }, _ => debug_unreachable!(), } } } /// Used for a fast path in Clone and Drop. #[inline(always)] pub unsafe fn from_packed_dynamic(data: u64) -> Option<*mut ()> { if (DYNAMIC_TAG as u64) == (data & TAG_MASK) { Some(data as *mut ()) } else { None } } /// For as_slice on inline atoms, we need a pointer into the original /// string contents. /// /// It's undefined behavior to call this on a non-inline atom!! #[inline(always)] pub unsafe fn inline_orig_bytes<'a>(data: &'a u64) -> &'a [u8] { match UnpackedAtom::from_packed(*data) { Inline(len, _) => { let raw_slice = inline_atom_slice(&data); let src: &[u8] = slice::from_raw_parts(raw_slice.data, raw_slice.len); &src[..(len as usize)] } _ => debug_unreachable!(), } } /// Copy of std::slice::bytes::copy_memory, which is unstable. #[inline] pub fn copy_memory(src: &[u8], dst: &mut [u8]) { let len_src = src.len(); assert!(dst.len() >= len_src); // `dst` is unaliasable, so we know statically it doesn't overlap // with `src`. unsafe { ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len_src); } }
#[doc = "Reader of register RSTB2R"] pub type R = crate::R<u32, super::RSTB2R>; #[doc = "Writer for register RSTB2R"] pub type W = crate::W<u32, super::RSTB2R>; #[doc = "Register RSTB2R `reset()`'s with value 0"] impl crate::ResetValue for super::RSTB2R { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "UPDATE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UPDATE_A { #[doc = "0: Register update event has no effect"] NOEFFECT = 0, #[doc = "1: Register update event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<UPDATE_A> for bool { #[inline(always)] fn from(variant: UPDATE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UPDATE`"] pub type UPDATE_R = crate::R<bool, UPDATE_A>; impl UPDATE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UPDATE_A { match self.bits { false => UPDATE_A::NOEFFECT, true => UPDATE_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == UPDATE_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == UPDATE_A::SETINACTIVE } } #[doc = "Write proxy for field `UPDATE`"] pub struct UPDATE_W<'a> { w: &'a mut W, } impl<'a> UPDATE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UPDATE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Register update event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(UPDATE_A::NOEFFECT) } #[doc = "Register update event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(UPDATE_A::SETINACTIVE) } #[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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "EXTEVNT10\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EXTEVNT10_A { #[doc = "0: External event has no effect"] NOEFFECT = 0, #[doc = "1: External event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<EXTEVNT10_A> for bool { #[inline(always)] fn from(variant: EXTEVNT10_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EXTEVNT10`"] pub type EXTEVNT10_R = crate::R<bool, EXTEVNT10_A>; impl EXTEVNT10_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EXTEVNT10_A { match self.bits { false => EXTEVNT10_A::NOEFFECT, true => EXTEVNT10_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == EXTEVNT10_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == EXTEVNT10_A::SETINACTIVE } } #[doc = "Write proxy for field `EXTEVNT10`"] pub struct EXTEVNT10_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT10_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT10_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "EXTEVNT9"] pub type EXTEVNT9_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT9`"] pub type EXTEVNT9_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT9`"] pub struct EXTEVNT9_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT9_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "EXTEVNT8"] pub type EXTEVNT8_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT8`"] pub type EXTEVNT8_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT8`"] pub struct EXTEVNT8_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT8_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "EXTEVNT7"] pub type EXTEVNT7_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT7`"] pub type EXTEVNT7_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT7`"] pub struct EXTEVNT7_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT7_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "EXTEVNT6"] pub type EXTEVNT6_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT6`"] pub type EXTEVNT6_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT6`"] pub struct EXTEVNT6_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT6_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "EXTEVNT5"] pub type EXTEVNT5_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT5`"] pub type EXTEVNT5_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT5`"] pub struct EXTEVNT5_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT5_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "EXTEVNT4"] pub type EXTEVNT4_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT4`"] pub type EXTEVNT4_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT4`"] pub struct EXTEVNT4_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT4_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 } } #[doc = "EXTEVNT3"] pub type EXTEVNT3_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT3`"] pub type EXTEVNT3_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT3`"] pub struct EXTEVNT3_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT3_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "EXTEVNT2"] pub type EXTEVNT2_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT2`"] pub type EXTEVNT2_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT2`"] pub struct EXTEVNT2_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "EXTEVNT1"] pub type EXTEVNT1_A = EXTEVNT10_A; #[doc = "Reader of field `EXTEVNT1`"] pub type EXTEVNT1_R = crate::R<bool, EXTEVNT10_A>; #[doc = "Write proxy for field `EXTEVNT1`"] pub struct EXTEVNT1_W<'a> { w: &'a mut W, } impl<'a> EXTEVNT1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EXTEVNT1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "External event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(EXTEVNT10_A::NOEFFECT) } #[doc = "External event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(EXTEVNT10_A::SETINACTIVE) } #[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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "TIMEVNT9\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIMEVNT9_A { #[doc = "0: Timer event has no effect"] NOEFFECT = 0, #[doc = "1: Timer event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<TIMEVNT9_A> for bool { #[inline(always)] fn from(variant: TIMEVNT9_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIMEVNT9`"] pub type TIMEVNT9_R = crate::R<bool, TIMEVNT9_A>; impl TIMEVNT9_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIMEVNT9_A { match self.bits { false => TIMEVNT9_A::NOEFFECT, true => TIMEVNT9_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == TIMEVNT9_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == TIMEVNT9_A::SETINACTIVE } } #[doc = "Write proxy for field `TIMEVNT9`"] pub struct TIMEVNT9_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT9_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "TIMEVNT8"] pub type TIMEVNT8_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT8`"] pub type TIMEVNT8_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT8`"] pub struct TIMEVNT8_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT8_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "TIMEVNT7"] pub type TIMEVNT7_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT7`"] pub type TIMEVNT7_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT7`"] pub struct TIMEVNT7_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT7_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "TIMEVNT6"] pub type TIMEVNT6_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT6`"] pub type TIMEVNT6_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT6`"] pub struct TIMEVNT6_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT6_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "TIMEVNT5"] pub type TIMEVNT5_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT5`"] pub type TIMEVNT5_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT5`"] pub struct TIMEVNT5_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT5_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "TIMEVNT4"] pub type TIMEVNT4_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT4`"] pub type TIMEVNT4_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT4`"] pub struct TIMEVNT4_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT4_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "TIMEVNT3"] pub type TIMEVNT3_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT3`"] pub type TIMEVNT3_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT3`"] pub struct TIMEVNT3_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT3_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "TIMEVNT2"] pub type TIMEVNT2_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT2`"] pub type TIMEVNT2_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT2`"] pub struct TIMEVNT2_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "TIMEVNT1"] pub type TIMEVNT1_A = TIMEVNT9_A; #[doc = "Reader of field `TIMEVNT1`"] pub type TIMEVNT1_R = crate::R<bool, TIMEVNT9_A>; #[doc = "Write proxy for field `TIMEVNT1`"] pub struct TIMEVNT1_W<'a> { w: &'a mut W, } impl<'a> TIMEVNT1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIMEVNT1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(TIMEVNT9_A::NOEFFECT) } #[doc = "Timer event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(TIMEVNT9_A::SETINACTIVE) } #[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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "MSTCMP4\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTCMP4_A { #[doc = "0: Master timer compare event has no effect"] NOEFFECT = 0, #[doc = "1: Master timer compare event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<MSTCMP4_A> for bool { #[inline(always)] fn from(variant: MSTCMP4_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MSTCMP4`"] pub type MSTCMP4_R = crate::R<bool, MSTCMP4_A>; impl MSTCMP4_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSTCMP4_A { match self.bits { false => MSTCMP4_A::NOEFFECT, true => MSTCMP4_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == MSTCMP4_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == MSTCMP4_A::SETINACTIVE } } #[doc = "Write proxy for field `MSTCMP4`"] pub struct MSTCMP4_W<'a> { w: &'a mut W, } impl<'a> MSTCMP4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTCMP4_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Master timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(MSTCMP4_A::NOEFFECT) } #[doc = "Master timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(MSTCMP4_A::SETINACTIVE) } #[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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "MSTCMP3"] pub type MSTCMP3_A = MSTCMP4_A; #[doc = "Reader of field `MSTCMP3`"] pub type MSTCMP3_R = crate::R<bool, MSTCMP4_A>; #[doc = "Write proxy for field `MSTCMP3`"] pub struct MSTCMP3_W<'a> { w: &'a mut W, } impl<'a> MSTCMP3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTCMP3_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Master timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(MSTCMP4_A::NOEFFECT) } #[doc = "Master timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(MSTCMP4_A::SETINACTIVE) } #[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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "MSTCMP2"] pub type MSTCMP2_A = MSTCMP4_A; #[doc = "Reader of field `MSTCMP2`"] pub type MSTCMP2_R = crate::R<bool, MSTCMP4_A>; #[doc = "Write proxy for field `MSTCMP2`"] pub struct MSTCMP2_W<'a> { w: &'a mut W, } impl<'a> MSTCMP2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTCMP2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Master timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(MSTCMP4_A::NOEFFECT) } #[doc = "Master timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(MSTCMP4_A::SETINACTIVE) } #[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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "MSTCMP1"] pub type MSTCMP1_A = MSTCMP4_A; #[doc = "Reader of field `MSTCMP1`"] pub type MSTCMP1_R = crate::R<bool, MSTCMP4_A>; #[doc = "Write proxy for field `MSTCMP1`"] pub struct MSTCMP1_W<'a> { w: &'a mut W, } impl<'a> MSTCMP1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTCMP1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Master timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(MSTCMP4_A::NOEFFECT) } #[doc = "Master timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(MSTCMP4_A::SETINACTIVE) } #[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 = "MSTPER\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSTPER_A { #[doc = "0: Master timer counter roll-over/reset has no effect"] NOEFFECT = 0, #[doc = "1: Master timer counter roll-over/reset forces the output to its inactive state"] SETINACTIVE = 1, } impl From<MSTPER_A> for bool { #[inline(always)] fn from(variant: MSTPER_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MSTPER`"] pub type MSTPER_R = crate::R<bool, MSTPER_A>; impl MSTPER_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSTPER_A { match self.bits { false => MSTPER_A::NOEFFECT, true => MSTPER_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == MSTPER_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == MSTPER_A::SETINACTIVE } } #[doc = "Write proxy for field `MSTPER`"] pub struct MSTPER_W<'a> { w: &'a mut W, } impl<'a> MSTPER_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTPER_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Master timer counter roll-over/reset has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(MSTPER_A::NOEFFECT) } #[doc = "Master timer counter roll-over/reset forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(MSTPER_A::SETINACTIVE) } #[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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "CMP4\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CMP4_A { #[doc = "0: Timer compare event has no effect"] NOEFFECT = 0, #[doc = "1: Timer compare event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<CMP4_A> for bool { #[inline(always)] fn from(variant: CMP4_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CMP4`"] pub type CMP4_R = crate::R<bool, CMP4_A>; impl CMP4_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CMP4_A { match self.bits { false => CMP4_A::NOEFFECT, true => CMP4_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == CMP4_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == CMP4_A::SETINACTIVE } } #[doc = "Write proxy for field `CMP4`"] pub struct CMP4_W<'a> { w: &'a mut W, } impl<'a> CMP4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP4_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(CMP4_A::NOEFFECT) } #[doc = "Timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(CMP4_A::SETINACTIVE) } #[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 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "CMP3"] pub type CMP3_A = CMP4_A; #[doc = "Reader of field `CMP3`"] pub type CMP3_R = crate::R<bool, CMP4_A>; #[doc = "Write proxy for field `CMP3`"] pub struct CMP3_W<'a> { w: &'a mut W, } impl<'a> CMP3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP3_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(CMP4_A::NOEFFECT) } #[doc = "Timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(CMP4_A::SETINACTIVE) } #[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 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "CMP2"] pub type CMP2_A = CMP4_A; #[doc = "Reader of field `CMP2`"] pub type CMP2_R = crate::R<bool, CMP4_A>; #[doc = "Write proxy for field `CMP2`"] pub struct CMP2_W<'a> { w: &'a mut W, } impl<'a> CMP2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP2_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(CMP4_A::NOEFFECT) } #[doc = "Timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(CMP4_A::SETINACTIVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "CMP1"] pub type CMP1_A = CMP4_A; #[doc = "Reader of field `CMP1`"] pub type CMP1_R = crate::R<bool, CMP4_A>; #[doc = "Write proxy for field `CMP1`"] pub struct CMP1_W<'a> { w: &'a mut W, } impl<'a> CMP1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CMP1_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer compare event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(CMP4_A::NOEFFECT) } #[doc = "Timer compare event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(CMP4_A::SETINACTIVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "PER\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PER_A { #[doc = "0: Timer period event has no effect"] NOEFFECT = 0, #[doc = "1: Timer period event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<PER_A> for bool { #[inline(always)] fn from(variant: PER_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PER`"] pub type PER_R = crate::R<bool, PER_A>; impl PER_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PER_A { match self.bits { false => PER_A::NOEFFECT, true => PER_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == PER_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == PER_A::SETINACTIVE } } #[doc = "Write proxy for field `PER`"] pub struct PER_W<'a> { w: &'a mut W, } impl<'a> PER_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PER_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer period event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(PER_A::NOEFFECT) } #[doc = "Timer period event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(PER_A::SETINACTIVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "RESYNC\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RESYNC_A { #[doc = "0: Timer reset event coming solely from software or SYNC input event has no effect"] NOEFFECT = 0, #[doc = "1: Timer reset event coming solely from software or SYNC input event forces the output to its inactive state"] SETINACTIVE = 1, } impl From<RESYNC_A> for bool { #[inline(always)] fn from(variant: RESYNC_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RESYNC`"] pub type RESYNC_R = crate::R<bool, RESYNC_A>; impl RESYNC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RESYNC_A { match self.bits { false => RESYNC_A::NOEFFECT, true => RESYNC_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == RESYNC_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == RESYNC_A::SETINACTIVE } } #[doc = "Write proxy for field `RESYNC`"] pub struct RESYNC_W<'a> { w: &'a mut W, } impl<'a> RESYNC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RESYNC_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Timer reset event coming solely from software or SYNC input event has no effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(RESYNC_A::NOEFFECT) } #[doc = "Timer reset event coming solely from software or SYNC input event forces the output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(RESYNC_A::SETINACTIVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "SRT\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SRT_A { #[doc = "0: No effect"] NOEFFECT = 0, #[doc = "1: Force output to its inactive state"] SETINACTIVE = 1, } impl From<SRT_A> for bool { #[inline(always)] fn from(variant: SRT_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SRT`"] pub type SRT_R = crate::R<bool, SRT_A>; impl SRT_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SRT_A { match self.bits { false => SRT_A::NOEFFECT, true => SRT_A::SETINACTIVE, } } #[doc = "Checks if the value of the field is `NOEFFECT`"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == SRT_A::NOEFFECT } #[doc = "Checks if the value of the field is `SETINACTIVE`"] #[inline(always)] pub fn is_set_inactive(&self) -> bool { *self == SRT_A::SETINACTIVE } } #[doc = "Write proxy for field `SRT`"] pub struct SRT_W<'a> { w: &'a mut W, } impl<'a> SRT_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SRT_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut W { self.variant(SRT_A::NOEFFECT) } #[doc = "Force output to its inactive state"] #[inline(always)] pub fn set_inactive(self) -> &'a mut W { self.variant(SRT_A::SETINACTIVE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 31 - UPDATE"] #[inline(always)] pub fn update(&self) -> UPDATE_R { UPDATE_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - EXTEVNT10"] #[inline(always)] pub fn extevnt10(&self) -> EXTEVNT10_R { EXTEVNT10_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 29 - EXTEVNT9"] #[inline(always)] pub fn extevnt9(&self) -> EXTEVNT9_R { EXTEVNT9_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - EXTEVNT8"] #[inline(always)] pub fn extevnt8(&self) -> EXTEVNT8_R { EXTEVNT8_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 27 - EXTEVNT7"] #[inline(always)] pub fn extevnt7(&self) -> EXTEVNT7_R { EXTEVNT7_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - EXTEVNT6"] #[inline(always)] pub fn extevnt6(&self) -> EXTEVNT6_R { EXTEVNT6_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - EXTEVNT5"] #[inline(always)] pub fn extevnt5(&self) -> EXTEVNT5_R { EXTEVNT5_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - EXTEVNT4"] #[inline(always)] pub fn extevnt4(&self) -> EXTEVNT4_R { EXTEVNT4_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - EXTEVNT3"] #[inline(always)] pub fn extevnt3(&self) -> EXTEVNT3_R { EXTEVNT3_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - EXTEVNT2"] #[inline(always)] pub fn extevnt2(&self) -> EXTEVNT2_R { EXTEVNT2_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - EXTEVNT1"] #[inline(always)] pub fn extevnt1(&self) -> EXTEVNT1_R { EXTEVNT1_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - TIMEVNT9"] #[inline(always)] pub fn timevnt9(&self) -> TIMEVNT9_R { TIMEVNT9_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - TIMEVNT8"] #[inline(always)] pub fn timevnt8(&self) -> TIMEVNT8_R { TIMEVNT8_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - TIMEVNT7"] #[inline(always)] pub fn timevnt7(&self) -> TIMEVNT7_R { TIMEVNT7_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - TIMEVNT6"] #[inline(always)] pub fn timevnt6(&self) -> TIMEVNT6_R { TIMEVNT6_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - TIMEVNT5"] #[inline(always)] pub fn timevnt5(&self) -> TIMEVNT5_R { TIMEVNT5_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - TIMEVNT4"] #[inline(always)] pub fn timevnt4(&self) -> TIMEVNT4_R { TIMEVNT4_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - TIMEVNT3"] #[inline(always)] pub fn timevnt3(&self) -> TIMEVNT3_R { TIMEVNT3_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - TIMEVNT2"] #[inline(always)] pub fn timevnt2(&self) -> TIMEVNT2_R { TIMEVNT2_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 12 - TIMEVNT1"] #[inline(always)] pub fn timevnt1(&self) -> TIMEVNT1_R { TIMEVNT1_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 11 - MSTCMP4"] #[inline(always)] pub fn mstcmp4(&self) -> MSTCMP4_R { MSTCMP4_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - MSTCMP3"] #[inline(always)] pub fn mstcmp3(&self) -> MSTCMP3_R { MSTCMP3_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - MSTCMP2"] #[inline(always)] pub fn mstcmp2(&self) -> MSTCMP2_R { MSTCMP2_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - MSTCMP1"] #[inline(always)] pub fn mstcmp1(&self) -> MSTCMP1_R { MSTCMP1_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - MSTPER"] #[inline(always)] pub fn mstper(&self) -> MSTPER_R { MSTPER_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - CMP4"] #[inline(always)] pub fn cmp4(&self) -> CMP4_R { CMP4_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - CMP3"] #[inline(always)] pub fn cmp3(&self) -> CMP3_R { CMP3_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - CMP2"] #[inline(always)] pub fn cmp2(&self) -> CMP2_R { CMP2_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - CMP1"] #[inline(always)] pub fn cmp1(&self) -> CMP1_R { CMP1_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - PER"] #[inline(always)] pub fn per(&self) -> PER_R { PER_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - RESYNC"] #[inline(always)] pub fn resync(&self) -> RESYNC_R { RESYNC_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - SRT"] #[inline(always)] pub fn srt(&self) -> SRT_R { SRT_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - UPDATE"] #[inline(always)] pub fn update(&mut self) -> UPDATE_W { UPDATE_W { w: self } } #[doc = "Bit 30 - EXTEVNT10"] #[inline(always)] pub fn extevnt10(&mut self) -> EXTEVNT10_W { EXTEVNT10_W { w: self } } #[doc = "Bit 29 - EXTEVNT9"] #[inline(always)] pub fn extevnt9(&mut self) -> EXTEVNT9_W { EXTEVNT9_W { w: self } } #[doc = "Bit 28 - EXTEVNT8"] #[inline(always)] pub fn extevnt8(&mut self) -> EXTEVNT8_W { EXTEVNT8_W { w: self } } #[doc = "Bit 27 - EXTEVNT7"] #[inline(always)] pub fn extevnt7(&mut self) -> EXTEVNT7_W { EXTEVNT7_W { w: self } } #[doc = "Bit 26 - EXTEVNT6"] #[inline(always)] pub fn extevnt6(&mut self) -> EXTEVNT6_W { EXTEVNT6_W { w: self } } #[doc = "Bit 25 - EXTEVNT5"] #[inline(always)] pub fn extevnt5(&mut self) -> EXTEVNT5_W { EXTEVNT5_W { w: self } } #[doc = "Bit 24 - EXTEVNT4"] #[inline(always)] pub fn extevnt4(&mut self) -> EXTEVNT4_W { EXTEVNT4_W { w: self } } #[doc = "Bit 23 - EXTEVNT3"] #[inline(always)] pub fn extevnt3(&mut self) -> EXTEVNT3_W { EXTEVNT3_W { w: self } } #[doc = "Bit 22 - EXTEVNT2"] #[inline(always)] pub fn extevnt2(&mut self) -> EXTEVNT2_W { EXTEVNT2_W { w: self } } #[doc = "Bit 21 - EXTEVNT1"] #[inline(always)] pub fn extevnt1(&mut self) -> EXTEVNT1_W { EXTEVNT1_W { w: self } } #[doc = "Bit 20 - TIMEVNT9"] #[inline(always)] pub fn timevnt9(&mut self) -> TIMEVNT9_W { TIMEVNT9_W { w: self } } #[doc = "Bit 19 - TIMEVNT8"] #[inline(always)] pub fn timevnt8(&mut self) -> TIMEVNT8_W { TIMEVNT8_W { w: self } } #[doc = "Bit 18 - TIMEVNT7"] #[inline(always)] pub fn timevnt7(&mut self) -> TIMEVNT7_W { TIMEVNT7_W { w: self } } #[doc = "Bit 17 - TIMEVNT6"] #[inline(always)] pub fn timevnt6(&mut self) -> TIMEVNT6_W { TIMEVNT6_W { w: self } } #[doc = "Bit 16 - TIMEVNT5"] #[inline(always)] pub fn timevnt5(&mut self) -> TIMEVNT5_W { TIMEVNT5_W { w: self } } #[doc = "Bit 15 - TIMEVNT4"] #[inline(always)] pub fn timevnt4(&mut self) -> TIMEVNT4_W { TIMEVNT4_W { w: self } } #[doc = "Bit 14 - TIMEVNT3"] #[inline(always)] pub fn timevnt3(&mut self) -> TIMEVNT3_W { TIMEVNT3_W { w: self } } #[doc = "Bit 13 - TIMEVNT2"] #[inline(always)] pub fn timevnt2(&mut self) -> TIMEVNT2_W { TIMEVNT2_W { w: self } } #[doc = "Bit 12 - TIMEVNT1"] #[inline(always)] pub fn timevnt1(&mut self) -> TIMEVNT1_W { TIMEVNT1_W { w: self } } #[doc = "Bit 11 - MSTCMP4"] #[inline(always)] pub fn mstcmp4(&mut self) -> MSTCMP4_W { MSTCMP4_W { w: self } } #[doc = "Bit 10 - MSTCMP3"] #[inline(always)] pub fn mstcmp3(&mut self) -> MSTCMP3_W { MSTCMP3_W { w: self } } #[doc = "Bit 9 - MSTCMP2"] #[inline(always)] pub fn mstcmp2(&mut self) -> MSTCMP2_W { MSTCMP2_W { w: self } } #[doc = "Bit 8 - MSTCMP1"] #[inline(always)] pub fn mstcmp1(&mut self) -> MSTCMP1_W { MSTCMP1_W { w: self } } #[doc = "Bit 7 - MSTPER"] #[inline(always)] pub fn mstper(&mut self) -> MSTPER_W { MSTPER_W { w: self } } #[doc = "Bit 6 - CMP4"] #[inline(always)] pub fn cmp4(&mut self) -> CMP4_W { CMP4_W { w: self } } #[doc = "Bit 5 - CMP3"] #[inline(always)] pub fn cmp3(&mut self) -> CMP3_W { CMP3_W { w: self } } #[doc = "Bit 4 - CMP2"] #[inline(always)] pub fn cmp2(&mut self) -> CMP2_W { CMP2_W { w: self } } #[doc = "Bit 3 - CMP1"] #[inline(always)] pub fn cmp1(&mut self) -> CMP1_W { CMP1_W { w: self } } #[doc = "Bit 2 - PER"] #[inline(always)] pub fn per(&mut self) -> PER_W { PER_W { w: self } } #[doc = "Bit 1 - RESYNC"] #[inline(always)] pub fn resync(&mut self) -> RESYNC_W { RESYNC_W { w: self } } #[doc = "Bit 0 - SRT"] #[inline(always)] pub fn srt(&mut self) -> SRT_W { SRT_W { w: self } } }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" Measure of difference between the series and it's sma "#; const ARGUMENTS: &'static str = r#" **source (series)** Series of values to process. **length (int)** Number of bars (length). "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "dev", signatures: vec![], description: DESCRIPTION, example: "", returns: "Deviation of x for y bars back.", arguments: ARGUMENTS, remarks: "", links: "[variance](#fun-variance) [stdev](#fun-stdev)", }; vec![fn_doc] }
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let t: usize = rd.get(); for _ in 0..t { let n: usize = rd.get(); let x: Vec<u32> = rd.get_vec(n); solve(n, x); } } fn solve(n: usize, x: Vec<u32>) { let mut ans = vec![0_u32]; for i in 1..n { let p = x[i - 1] ^ ans[ans.len() - 1]; let mut y = 0; for j in 0..30 { if p >> j & 1 == 1 { if x[i] >> j & 1 == 0 { y ^= 1 << j; } } } ans.push(y); } print!("{}", ans[0]); for a in &ans[1..] { print!(" {}", a); } println!(); }
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let t = scan!(usize); for _ in 0..t { let (a, s) = scan!((u64, u64)); solve(a, s); } } fn solve(a: u64, s: u64) { if a * 2 > s { println!("No"); return; } let mut t = a * 2; for i in (0..60).rev() { if a >> i & 1 == 1 { continue; } let p = 2_u64.pow(i as u32); if t + p <= s { t += p; } } if t == s { println!("Yes"); } else { println!("No"); } }
use anyhow::{ Context, Result, }; use std::path::Path; pub mod ds; pub mod utils; use crate::normalize::ds::{ entry::{ Normalized, Raw, }, so_tree, }; pub fn write_file(input_file: &Path, so_term_tree: &Path, output_file: &Path) -> Result<()> { let so_tree = so_tree::load(&so_term_tree)?; let mut reader = rnc_utils::buf_reader(input_file)?; let mut writer = rnc_utils::buf_writer(output_file)?; let mut buf = String::new(); loop { match reader.read_line(&mut buf)? { 0 => break, _ => { let raw: Raw = serde_json::from_str(&buf)?; let norm = Normalized::new(&raw, &so_tree) .with_context(|| format!("Normalizing: {:?}", &raw))?; serde_json::to_writer(&mut writer, &norm)?; writeln!(&mut writer)?; buf.clear(); }, } } Ok(()) }
use crate::object::Point; use crate::global::*; use super::common_step::*; fn jacobi_method(grid: &Vec<Point>) -> bool { let update : Vec<(f64, bool, usize)> = grid.iter().map(move |x|step(grid, x.index, false)).collect(); update.iter().for_each(|x| { let mut t = grid[x.2].temperature.borrow_mut(); *t = x.0; }); update.iter().fold(true, |x, y| x & y.1 ) } fn sor_method(grid: &Vec<Point>, even: bool) -> bool { let index = init_index(even); let flag = &mut true; let update : Vec<(f64, bool, usize)> = index.iter().map( |i| step(grid, grid[*i].index, true)).collect(); update.iter().for_each( |x| { let mut _mut = grid[x.2].temperature.borrow_mut(); *_mut = x.0; }); update.iter().for_each( |x| {*flag &= x.1;}); if even { sor_method(grid, false) & *flag } else { *flag } } pub fn invoke(grid: &Vec<Point>) -> bool { match &*MATH_METHOD { MathMethod::Jacobi => jacobi_method(grid), MathMethod::Sor => sor_method(grid, true) } }
#[cfg(feature = "codegen")] mod tests { use std::{ fmt::Debug, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, }; use legion::{ storage::Component, system, systems::CommandBuffer, world::SubWorld, IntoQuery, Query, Read, Resources, Schedule, World, Write, }; #[test] fn empty() { #[system] fn basic() {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_resource() { #[system] fn basic(#[resource] _: &usize) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_mut_resource() { #[system] fn basic(#[resource] _: &mut usize) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_not_sendsync_resource() { struct NotSync(*const usize); #[system] fn basic(#[resource] _: &NotSync) {} Schedule::builder().add_thread_local(basic_system()).build(); } #[test] fn with_mut_not_sendsync_resource() { struct NotSync(*const usize); #[system] fn basic(#[resource] _: &mut NotSync) {} Schedule::builder().add_thread_local(basic_system()).build(); } #[test] fn with_world() { #[system] #[read_component(usize)] fn basic(_: &SubWorld) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_mut_world() { #[system] #[read_component(usize)] fn basic(_: &mut SubWorld) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_cmd() { #[system] fn basic(_: &CommandBuffer) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_cmd_full_path() { #[system] fn basic(_: &legion::systems::CommandBuffer) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_mut_cmd() { #[system] fn basic(_: &mut CommandBuffer) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_components() { #[system] #[read_component(f32)] #[write_component(usize)] fn basic(world: &mut SubWorld) { let mut query = <(Read<f32>, Write<usize>)>::query(); for (a, b) in query.iter_mut(world) { println!("{:?} {:?}", a, b); } } Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_generics() { #[system] #[read_component(T)] fn basic<T: Component + Debug>(world: &mut SubWorld) { let mut query = Read::<T>::query(); for t in query.iter_mut(world) { println!("{:?}", t); } } Schedule::builder() .add_system(basic_system::<usize>()) .build(); } #[test] fn with_generics_with_where() { #[system] #[read_component(T)] fn basic<T>(world: &mut SubWorld) where T: Component + Debug, { let mut query = Read::<T>::query(); for t in query.iter_mut(world) { println!("{:?}", t); } } Schedule::builder() .add_system(basic_system::<usize>()) .build(); } #[test] fn with_state() { #[system] fn basic<T: 'static>(#[state] _: &T) {} Schedule::builder().add_system(basic_system(false)).build(); } #[test] fn with_mut_state() { #[system] fn basic<T: 'static>(#[state] _: &mut T) {} Schedule::builder().add_system(basic_system(false)).build(); } #[test] fn with_query() { #[system] fn basic(_: &mut SubWorld, _: &mut Query<(&u8, &mut i8)>) {} Schedule::builder().add_system(basic_system()).build(); } #[test] fn with_two_queries() { #[system] fn basic( #[state] a_count: &Arc<AtomicUsize>, #[state] b_count: &Arc<AtomicUsize>, world: &mut SubWorld, a: &mut Query<(&u8, &mut usize)>, b: &mut Query<(&usize, &mut bool)>, ) { a_count.store(a.iter_mut(world).count(), Ordering::SeqCst); b_count.store(b.iter_mut(world).count(), Ordering::SeqCst); } let a_count = Arc::new(AtomicUsize::new(0)); let b_count = Arc::new(AtomicUsize::new(0)); let mut schedule = Schedule::builder() .add_system(basic_system(a_count.clone(), b_count.clone())) .build(); let mut world = World::default(); let mut resources = Resources::default(); world.extend(vec![(1_usize, false), (2_usize, false)]); schedule.execute(&mut world, &mut resources); assert_eq!(0, a_count.load(Ordering::SeqCst)); assert_eq!(2, b_count.load(Ordering::SeqCst)); } }
extern crate messycanvas; fn main() { messycanvas::daemon::main(); }
// Copyright 2023 Datafuse Labs. // // 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 std::any::Any; use std::marker::PhantomData; use std::sync::Arc; use common_exception::Result; use common_expression::BlockMetaInfoDowncast; use common_expression::DataBlock; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::port::OutputPort; use common_pipeline_core::processors::processor::Event; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_core::processors::Processor; use crate::pipelines::processors::transforms::aggregator::aggregate_meta::AggregateMeta; use crate::pipelines::processors::transforms::aggregator::serde::serde_meta::AggregateSerdeMeta; use crate::pipelines::processors::transforms::aggregator::serde::BUCKET_TYPE; use crate::pipelines::processors::transforms::group_by::HashMethodBounds; pub struct TransformDeserializer<Method: HashMethodBounds, V: Send + Sync + 'static> { input: Arc<InputPort>, output: Arc<OutputPort>, _phantom: PhantomData<(Method, V)>, } impl<Method: HashMethodBounds, V: Send + Sync + 'static> TransformDeserializer<Method, V> { pub fn try_create(input: Arc<InputPort>, output: Arc<OutputPort>) -> Result<ProcessorPtr> { Ok(ProcessorPtr::create(Box::new(TransformDeserializer::< Method, V, > { input, output, _phantom: Default::default(), }))) } } #[async_trait::async_trait] impl<Method, V> Processor for TransformDeserializer<Method, V> where Method: HashMethodBounds, V: Send + Sync + 'static, { fn name(&self) -> String { String::from("TransformAggregateDeserializer") } fn as_any(&mut self) -> &mut dyn Any { self } fn event(&mut self) -> Result<Event> { if self.output.is_finished() { self.input.finish(); return Ok(Event::Finished); } if !self.output.can_push() { self.input.set_not_need_data(); return Ok(Event::NeedConsume); } if self.input.has_data() { let mut data_block = self.input.pull_data().unwrap()?; let block_meta = data_block.take_meta(); let meta = block_meta .and_then(AggregateSerdeMeta::downcast_from) .unwrap(); self.output.push_data(Ok(DataBlock::empty_with_meta( match meta.typ == BUCKET_TYPE { true => AggregateMeta::<Method, V>::create_serialized(meta.bucket, data_block), false => AggregateMeta::<Method, V>::create_spilled( meta.bucket, meta.location.unwrap(), meta.columns_layout, ), }, ))); return Ok(Event::NeedConsume); } if self.input.is_finished() { self.output.finish(); return Ok(Event::Finished); } self.input.set_need_data(); Ok(Event::NeedData) } } pub type TransformGroupByDeserializer<Method> = TransformDeserializer<Method, ()>; pub type TransformAggregateDeserializer<Method> = TransformDeserializer<Method, usize>;
use failure::{format_err, Fallible, ResultExt}; use std::ffi::OsStr; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::path::Path; pub fn basename(file_path: &str) -> Fallible<&str> { let file_name = Path::new(file_path) .file_name() .and_then(|s: &OsStr| s.to_str()) .ok_or(format_err!("can not get basename: {}", file_path))?; Ok(file_name) } pub fn dirname(file_path: &str) -> Fallible<&str> { let dir = Path::new(file_path) .parent() .and_then(|p| p.to_str()) .ok_or(format_err!("can not get dirname: {}", file_path))?; Ok(dir) } pub fn filter_by_extension<'a>(files: &Vec<&'a str>, ext: &str) -> Vec<&'a str> { let mut res = vec![]; for file in files { if file.ends_with(ext) { res.push(*file); } } res } pub fn read_file(file_path: &str) -> Fallible<Vec<u8>> { let fin = File::open(file_path).context(format_err!("open file failure: {}", file_path))?; let mut freader = BufReader::new(fin); let mut content = Vec::new(); freader .read_to_end(&mut content) .context(format_err!("read file failure: {}", file_path))?; Ok(content) }
#[macro_use] extern crate hlua; fn main() { let mut lua = hlua::Lua::new(); lua.openlibs(); // we create a fill an array named `Sound` which will be used as a class-like interface { let mut sound_namespace = lua.empty_array("Sound"); // creating the `Sound.new` function sound_namespace.set("new", hlua::function(|| Sound::new())); } lua.execute::<()>(r#" s = Sound.new(); s:play(); print("hello world from within lua!"); print("is the sound playing:", s:is_playing()); s:stop(); print("is the sound playing:", s:is_playing()); "#).unwrap(); } // this `Sound` struct is the object that we will use to demonstrate hlua struct Sound { playing: bool, } // this macro implements the required trait so that we can *push* the object to lua // (ie. move it inside lua) implement_lua_push!(Sound, |mut metatable| { // we create a `__index` entry in the metatable // when the lua code calls `sound:play()`, it will look for `play` in there let mut index = metatable.empty_array("__index"); index.set("play", hlua::function(|snd: &mut Sound| { snd.play() })); index.set("stop", hlua::function(|snd: &mut Sound| { snd.stop() })); index.set("is_playing", hlua::function(|snd: &Sound| { snd.is_playing() })); }); // this macro implements the require traits so that we can *read* the object back implement_lua_read!(Sound); impl Sound { pub fn new() -> Sound { Sound { playing: false } } pub fn play(&mut self) { println!("playing"); self.playing = true; } pub fn stop(&mut self) { println!("stopping"); self.playing = false; } pub fn is_playing(&self) -> bool { self.playing } } // this destructor is here to show you that objects are properly getting destroyed impl Drop for Sound { fn drop(&mut self) { println!("`Sound` object destroyed"); } }
//! # Arithmetic //! //! ## Direct evaluation //! //! ```rust #![doc = include_str!("../../examples/arithmetic/parser.rs")] //! ``` //! //! ## Parse to AST //! //! ```rust #![doc = include_str!("../../examples/arithmetic/parser_ast.rs")] //! ```
mod kamada_kawai; mod mds; mod sgd; mod stress_majorization; use pyo3::prelude::*; pub fn register(py: Python<'_>, m: &PyModule) -> PyResult<()> { mds::register(py, m)?; kamada_kawai::register(py, m)?; stress_majorization::register(py, m)?; sgd::register(py, m)?; Ok(()) }
use ethabi::token::Token; use ethabi::{Address, Uint}; use primitive_types::U256; use std::char; use tiny_keccak; #[derive(Serialize, Debug)] #[serde(untagged)] pub enum Value { STRING(String), NUMBER(f64), BOOLEAN(bool), ARRAY(Vec<Value>), NULL, } static MAX_SAFE_INT: Uint = U256([9007199254740991, 0, 0, 0]); pub fn to_hex(bytes: &[u8], prefix: bool) -> String { let mut res = String::with_capacity((if prefix { 2 } else { 0 }) + bytes.len() * 2); if prefix { res.push_str("0x"); } for b in bytes { res.push(char::from_digit(((b & 0xF0) >> 4) as u32, 16).unwrap()); res.push(char::from_digit((b & 0xF) as u32, 16).unwrap()); } res } /// Decodes "0x"-prefixed hex string into u8 vector pub fn from_hex(hex_str: &String) -> Result<Vec<u8>, ()> { if hex_str.len() % 2 != 0 { return Err(()); } let result: Result<Vec<_>, _> = (0..hex_str.len()) .step_by(2) .skip(1) .map(|i| u8::from_str_radix(&hex_str[i..i + 2], 16)) .collect(); match result { Ok(v) => Ok(v), Err(_) => Err(()), } } pub fn to_checksum(addr: &Address) -> String { let addr_string = to_hex(addr.as_bytes(), false); let hash_str = to_hex(&tiny_keccak::keccak256(addr_string.as_bytes()), false); let mut result = "0x".to_string(); for (i, c) in addr_string.chars().enumerate() { let n = hash_str .chars() .nth(i) .expect("hash char not found") .to_digit(16) .expect("failed to convert hash char to i32"); if n > 7 { let u = match c { 'a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E', 'f' => 'F', other => other, }; result.push(u); } else { result.push(c); } } return result; } fn uint_to_value(n: &Uint) -> Value { if n > &MAX_SAFE_INT { Value::STRING(n.to_string()) } else { match n.to_string().parse::<f64>() { Ok(v) => Value::NUMBER(v), Err(_) => Value::STRING(n.to_string()), } } } pub fn token_to_value(t: &Token) -> Value { match t { Token::Address(addr) => Value::STRING(to_checksum(addr)), Token::Bytes(b) => { if b.len() > 0 { Value::STRING(to_hex(b, true)) } else { Value::NULL } } Token::FixedBytes(b) => { if b.len() > 0 { Value::STRING(to_hex(b, true)) } else { Value::NULL } } Token::Uint(n) => uint_to_value(n), Token::Int(n) => uint_to_value(n), Token::Bool(b) => Value::BOOLEAN(*b), Token::String(s) => Value::STRING(s.clone()), Token::Array(t) => Value::ARRAY(t.iter().map(|e| token_to_value(e)).collect()), Token::FixedArray(t) => Value::ARRAY(t.iter().map(|e| token_to_value(e)).collect()), Token::Tuple(t) => Value::ARRAY(t.iter().map(|e| token_to_value(e)).collect()), } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. pub use crate::errors::ParseError; pub use crate::parse::{check_resource, HASH_RE, NAME_RE}; use std::fmt; use url::percent_encoding::percent_decode; use url::Url; /// Decoded representation of a fuchsia-pkg URI. /// /// Depending on which segments are included, the URI may identify a package /// repository, a package within a repository (with optional variant and hash), /// or a resource within a package. /// /// Repository identifier: /// - fuchsia-pkg://example.com/ /// /// Package identifier: /// - fuchsia-pkg://example.com/some-package /// - fuchsia-pkg://example.com/some-package/some-variant /// - fuchsia-pkg://example.com/some-package/some-variant/<some-hash> /// /// Resource identifier: /// - fuchsia-pkg://example.com/some-package#path/to/resource /// - fuchsia-pkg://example.com/some-package/some-variant#path/to/resource /// - fuchsia-pkg://example.com/some-package/some-variant/<some-hash>#path/to/resource #[derive(Clone, Debug, PartialEq, Eq)] pub struct FuchsiaPkgUri { host: String, name: Option<String>, variant: Option<String>, hash: Option<String>, resource: Option<String>, } impl FuchsiaPkgUri { pub fn parse(input: &str) -> Result<Self, ParseError> { let uri = Url::parse(input)?; let scheme = uri.scheme(); if scheme != "fuchsia-pkg" { return Err(ParseError::InvalidScheme); } let host = if let Some(host) = uri.host() { host.to_string() } else { return Err(ParseError::InvalidHost); }; if host.is_empty() { return Err(ParseError::InvalidHost); } if uri.port().is_some() { return Err(ParseError::CannotContainPort); } if !uri.username().is_empty() { return Err(ParseError::CannotContainUsername); } if uri.password().is_some() { return Err(ParseError::CannotContainPassword); } let (name, variant, hash) = parse_path(uri.path())?; if uri.query().is_some() { return Err(ParseError::CannotContainQueryParameters); } let resource = if let Some(resource) = uri.fragment() { let resource = match percent_decode(resource.as_bytes()).decode_utf8() { Ok(resource) => resource, Err(_) => { return Err(ParseError::InvalidResourcePath); } }; if resource.is_empty() { None } else if check_resource(&resource) { Some(resource.to_string()) } else { return Err(ParseError::InvalidResourcePath); } } else { None }; Ok(FuchsiaPkgUri { host, name, variant, hash, resource }) } pub fn host(&self) -> &str { &self.host } pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| &**s) } pub fn variant(&self) -> Option<&str> { self.variant.as_ref().map(|s| &**s) } pub fn hash(&self) -> Option<&str> { self.hash.as_ref().map(|s| &**s) } pub fn resource(&self) -> Option<&str> { self.resource.as_ref().map(|s| &**s) } pub fn root_uri(&self) -> FuchsiaPkgUri { FuchsiaPkgUri{ host: self.host.clone(), name: self.name.clone(), variant: self.variant.clone(), hash: self.hash.clone(), resource: None, } } pub fn new_repository(host: String) -> Result<FuchsiaPkgUri, ParseError> { if host.is_empty() { return Err(ParseError::InvalidHost); } Ok(FuchsiaPkgUri { host, name: None, variant: None, hash: None, resource: None }) } pub fn new_package( host: String, name: String, variant: Option<String>, hash: Option<String>, ) -> Result<FuchsiaPkgUri, ParseError> { let mut uri = FuchsiaPkgUri::new_repository(host)?; if !NAME_RE.is_match(&name) { return Err(ParseError::InvalidName); } if let Some(ref v) = variant { if !NAME_RE.is_match(v) { return Err(ParseError::InvalidVariant); } } if let Some(ref h) = hash { if variant.is_none() { return Err(ParseError::InvalidVariant); } if !HASH_RE.is_match(h) { return Err(ParseError::InvalidHash); } } uri.name = Some(name); uri.variant = variant; uri.hash = hash; Ok(uri) } pub fn new_resource( host: String, name: String, variant: Option<String>, hash: Option<String>, resource: String, ) -> Result<FuchsiaPkgUri, ParseError> { let mut uri = FuchsiaPkgUri::new_package(host, name, variant, hash)?; if resource.is_empty() || !check_resource(&resource) { return Err(ParseError::InvalidResourcePath); } uri.resource = Some(resource); Ok(uri) } } impl fmt::Display for FuchsiaPkgUri { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "fuchsia-pkg://{}", self.host)?; if let Some(ref name) = self.name { write!(f, "/{}", name)?; if let Some(ref variant) = self.variant { write!(f, "/{}", variant)?; if let Some(ref hash) = self.hash { write!(f, "/{}", hash)?; } } } if let Some(ref resource) = self.resource { write!( f, "#{}", url::percent_encoding::utf8_percent_encode( resource, url::percent_encoding::DEFAULT_ENCODE_SET ) )?; } Ok(()) } } fn parse_path( mut path: &str, ) -> Result<(Option<String>, Option<String>, Option<String>), ParseError> { let mut name = None; let mut variant = None; let mut hash = None; if path.starts_with('/') { path = &path[1..]; if !path.is_empty() { let mut iter = path.split('/').fuse(); if let Some(s) = iter.next() { if NAME_RE.is_match(s) { name = Some(s.to_string()); } else { return Err(ParseError::InvalidName); } } if let Some(s) = iter.next() { if NAME_RE.is_match(s) { variant = Some(s.to_string()); } else { return Err(ParseError::InvalidVariant); } } if let Some(s) = iter.next() { if HASH_RE.is_match(s) { hash = Some(s.to_string()); } else { return Err(ParseError::InvalidHash); } } if let Some(_) = iter.next() { return Err(ParseError::ExtraPathSegments); } } } Ok((name, variant, hash)) } #[cfg(test)] mod tests { use super::*; macro_rules! test_parse_ok { ( $( $test_name:ident => { uri = $pkg_uri:expr, host = $pkg_host:expr, name = $pkg_name:expr, variant = $pkg_variant:expr, hash = $pkg_hash:expr, resource = $pkg_resource:expr, } )+ ) => { $( #[test] fn $test_name() { let pkg_uri = $pkg_uri.to_string(); assert_eq!( FuchsiaPkgUri::parse(&pkg_uri), Ok(FuchsiaPkgUri { host: $pkg_host, name: $pkg_name, variant: $pkg_variant, hash: $pkg_hash, resource: $pkg_resource, }) ); } )+ } } macro_rules! test_parse_err { ( $( $test_name:ident => { uris = $uris:expr, err = $err:expr, } )+ ) => { $( #[test] fn $test_name() { for uri in &$uris { assert_eq!( FuchsiaPkgUri::parse(uri), Err($err), ); } } )+ } } macro_rules! test_format { ( $( $test_name:ident => { parsed = $parsed:expr, formatted = $formatted:expr, } )+ ) => { $( #[test] fn $test_name() { assert_eq!( format!("{}", $parsed), $formatted ); } )+ } } test_parse_ok! { test_parse_host => { uri = "fuchsia-pkg://fuchsia.com", host = "fuchsia.com".to_string(), name = None, variant = None, hash = None, resource = None, } test_parse_host_name => { uri = "fuchsia-pkg://fuchsia.com/fonts", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = None, } test_parse_host_name_special_chars => { uri = "fuchsia-pkg://fuchsia.com/abc123-._", host = "fuchsia.com".to_string(), name = Some("abc123-._".to_string()), variant = None, hash = None, resource = None, } test_parse_host_name_variant => { uri = "fuchsia-pkg://fuchsia.com/fonts/stable", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = Some("stable".to_string()), hash = None, resource = None, } test_parse_host_name_variant_hash => { uri = "fuchsia-pkg://fuchsia.com/fonts/stable/80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = Some("stable".to_string()), hash = Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string()), resource = None, } test_parse_ignoring_empty_resource => { uri = "fuchsia-pkg://fuchsia.com/fonts#", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = None, } test_parse_resource => { uri = "fuchsia-pkg://fuchsia.com/fonts#foo/bar", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = Some("foo/bar".to_string()), } test_parse_resource_decodes_percent_encoding => { uri = "fuchsia-pkg://fuchsia.com/fonts#foo%23bar", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = Some("foo#bar".to_string()), } test_parse_resource_ignores_nul_chars => { uri = "fuchsia-pkg://fuchsia.com/fonts#foo\x00bar", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = Some("foobar".to_string()), } test_parse_resource_allows_encoded_control_chars => { uri = "fuchsia-pkg://fuchsia.com/fonts#foo%09bar", host = "fuchsia.com".to_string(), name = Some("fonts".to_string()), variant = None, hash = None, resource = Some("foo\tbar".to_string()), } } test_parse_err! { test_parse_host_cannot_be_absent => { uris = [ "fuchsia-pkg://", ], err = ParseError::InvalidHost, } test_parse_host_cannot_be_empty => { uris = [ "fuchsia-pkg:///", ], err = ParseError::InvalidHost, } test_parse_name_cannot_be_empty => { uris = [ "fuchsia-pkg://fuchsia.com//", ], err = ParseError::InvalidName, } test_parse_name_cannot_be_longer_than_100_chars => { uris = [ "fuchsia-pkg://fuchsia.com/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901/", ], err = ParseError::InvalidName, } test_parse_name_cannot_have_invalid_characters => { uris = [ "fuchsia-pkg://fuchsia.com/$", "fuchsia-pkg://fuchsia.com/foo$bar", ], err = ParseError::InvalidName, } test_parse_variant_cannot_have_invalid_characters => { uris = [ "fuchsia-pkg://fuchsia.com/fonts/$", "fuchsia-pkg://fuchsia.com/fonts/foo$bar", ], err = ParseError::InvalidVariant, } test_parse_hash_cannot_be_empty => { uris = [ "fuchsia-pkg://fuchsia.com/fonts/stable/", ], err = ParseError::InvalidHash, } test_parse_hash_cannot_have_invalid_characters => { uris = [ "fuchsia-pkg://fuchsia.com/fonts/stable/8$e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a", "fuchsia-pkg://fuchsia.com/fonts/stable/80E8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a", ], err = ParseError::InvalidHash, } test_parse_hash_must_be_64_chars => { uris = [ "fuchsia-pkg://fuchsia.com/fonts/stable/80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4", "fuchsia-pkg://fuchsia.com/fonts/stable/80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4aa", ], err = ParseError::InvalidHash, } test_parse_hash_cannot_have_extra_segments => { uris = [ "fuchsia-pkg://fuchsia.com/fonts/stable/80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a/foo", ], err = ParseError::ExtraPathSegments, } test_parse_resource_cannot_be_slash => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#/", ], err = ParseError::InvalidResourcePath, } test_parse_resource_cannot_start_with_slash => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#/foo", "fuchsia-pkg://fuchsia.com/fonts#/foo/bar", ], err = ParseError::InvalidResourcePath, } test_parse_resource_cannot_end_with_slash => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#foo/", "fuchsia-pkg://fuchsia.com/fonts#foo/bar/", ], err = ParseError::InvalidResourcePath, } test_parse_resource_cannot_contain_dot_dot => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#foo/../bar", ], err = ParseError::InvalidResourcePath, } test_parse_resource_cannot_contain_empty_segments => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#foo//bar", ], err = ParseError::InvalidResourcePath, } test_parse_resource_cannot_contain_percent_encoded_nul_chars => { uris = [ "fuchsia-pkg://fuchsia.com/fonts#foo%00bar", ], err = ParseError::InvalidResourcePath, } test_parse_resource_rejects_port => { uris = [ "fuchsia-pkg://fuchsia.com:1234", ], err = ParseError::CannotContainPort, } test_parse_resource_rejects_username => { uris = [ "fuchsia-pkg://user@fuchsia.com", "fuchsia-pkg://user:password@fuchsia.com", ], err = ParseError::CannotContainUsername, } test_parse_resource_rejects_password => { uris = [ "fuchsia-pkg://:password@fuchsia.com", ], err = ParseError::CannotContainPassword, } test_parse_rejects_query_params => { uris = [ "fuchsia-pkg://fuchsia.com?foo=bar", ], err = ParseError::CannotContainQueryParameters, } } test_format! { test_format_repository_uri => { parsed = FuchsiaPkgUri::new_repository("fuchsia.com".to_string()).unwrap(), formatted = "fuchsia-pkg://fuchsia.com", } test_format_package_uri => { parsed = FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), None, None, ).unwrap(), formatted = "fuchsia-pkg://fuchsia.com/fonts", } test_format_package_uri_with_variant => { parsed = FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), None, ).unwrap(), formatted = "fuchsia-pkg://fuchsia.com/fonts/stable", } test_format_package_uri_with_hash => { parsed = FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string()), ).unwrap(), formatted = "fuchsia-pkg://fuchsia.com/fonts/stable/80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a", } test_format_resource_uri => { parsed = FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), None, None, "foo#bar".to_string(), ).unwrap(), formatted = "fuchsia-pkg://fuchsia.com/fonts#foo%23bar", } } #[test] fn test_new_repository() { let uri = FuchsiaPkgUri::new_repository("fuchsia.com".to_string()).unwrap(); assert_eq!("fuchsia.com", uri.host()); assert_eq!(None, uri.name()); assert_eq!(None, uri.variant()); assert_eq!(None, uri.hash()); assert_eq!(None, uri.resource()); assert_eq!(FuchsiaPkgUri::new_repository("".to_string()), Err(ParseError::InvalidHost)) } #[test] fn test_new_package() { let uri = FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string()), ) .unwrap(); assert_eq!("fuchsia.com", uri.host()); assert_eq!(Some("fonts"), uri.name()); assert_eq!(Some("stable"), uri.variant()); assert_eq!( Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a"), uri.hash() ); assert_eq!(None, uri.resource()); assert_eq!(uri, uri.root_uri()); assert_eq!( FuchsiaPkgUri::new_package("".to_string(), "fonts".to_string(), None, None), Err(ParseError::InvalidHost) ); assert_eq!( FuchsiaPkgUri::new_package("fuchsia.com".to_string(), "".to_string(), None, None), Err(ParseError::InvalidName) ); assert_eq!( FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), Some("$".to_string()), None ), Err(ParseError::InvalidVariant) ); assert_eq!( FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), None, Some( "80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string() ) ), Err(ParseError::InvalidVariant) ); assert_eq!( FuchsiaPkgUri::new_package( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), Some("$".to_string()) ), Err(ParseError::InvalidHash) ); } #[test] fn test_new_resource() { let uri = FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string()), "foo/bar".to_string(), ) .unwrap(); assert_eq!("fuchsia.com", uri.host()); assert_eq!(Some("fonts"), uri.name()); assert_eq!(Some("stable"), uri.variant()); assert_eq!( Some("80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a"), uri.hash() ); assert_eq!(Some("foo/bar"), uri.resource()); let mut uri_no_resource = uri.clone(); uri_no_resource.resource = None; assert_eq!(uri_no_resource, uri.root_uri()); assert_eq!( FuchsiaPkgUri::new_resource( "".to_string(), "fonts".to_string(), None, None, "foo/bar".to_string() ), Err(ParseError::InvalidHost) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "".to_string(), None, None, "foo/bar".to_string() ), Err(ParseError::InvalidName) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), Some("$".to_string()), None, "foo/bar".to_string() ), Err(ParseError::InvalidVariant) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), None, Some( "80e8721f4eba5437c8b6e1604f6ee384f42aed2b6dfbfd0b616a864839cd7b4a".to_string() ), "foo/bar".to_string() ), Err(ParseError::InvalidVariant) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), Some("stable".to_string()), Some("$".to_string()), "foo/bar".to_string() ), Err(ParseError::InvalidHash) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), None, None, "".to_string() ), Err(ParseError::InvalidResourcePath) ); assert_eq!( FuchsiaPkgUri::new_resource( "fuchsia.com".to_string(), "fonts".to_string(), None, None, "a//b".to_string() ), Err(ParseError::InvalidResourcePath) ); } }
//! Particle Swarm Optimization. //! //! # Example //! ``` //! extern crate meta_heuristics; //! extern crate rand; //! //! use meta_heuristics::pso; //! use std::cmp; //! //! #[derive(Clone, Copy)] //! struct Particle { //! pos: f64, //! vel: f64, //! best: (f64, f64), //! } //! //! fn eval_func(x: f64) -> f64 { //! 1.0 - ((x - 3.0) * x + 2.0) * x * x //! } //! //! impl PartialEq for Particle { //! fn eq(&self, rhs: &Self) -> bool { //! self.pos == rhs.pos //! } //! } //! //! impl Eq for Particle {} //! //! impl PartialOrd for Particle { //! fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> { //! Some(self.cmp(rhs)) //! } //! } //! //! impl Ord for Particle { //! fn cmp(&self, rhs: &Self) -> cmp::Ordering { //! let self_eval = eval_func(self.pos); //! let rhs_eval = eval_func(rhs.pos); //! self_eval.partial_cmp(&rhs_eval).unwrap() //! } //! } //! //! impl pso::Particle for Particle { //! type Pos = f64; //! type Eval = f64; //! //! fn new_random() -> Self { //! use rand::{random, Closed01}; //! //! let Closed01(x) = random::<Closed01<f64>>(); //! let x = 4.0 * x - 1.0; //! Self { //! pos: x, //! vel: 0.0, //! best: (x, eval_func(x)), //! } //! } //! //! fn eval(&self) -> Self::Eval { //! eval_func(self.pos) //! } //! //! fn pos(&self) -> Self::Pos { //! self.pos //! } //! fn vel(&self) -> Self::Pos { //! self.vel //! } //! fn best(&self) -> (Self::Pos, Self::Eval) { //! self.best //! } //! fn pos_mut(&mut self) -> &mut Self::Pos { //! &mut self.pos //! } //! fn vel_mut(&mut self) -> &mut Self::Pos { //! &mut self.vel //! } //! fn best_mut(&mut self) -> &mut (Self::Pos, Self::Eval) { //! &mut self.best //! } //! } //! //! fn main() { //! let mut pso: pso::PSO<Particle> = pso::PSO::new(8, 0.9, 0.9, 0.9); //! //! for i in 0..10 { //! pso.update(); //! let (Particle { pos: x, .. }, e) = pso.best(); //! println!("{} {:.3} {:.3}", i, x, e); //! } //! //! assert!(pso.best().1 > 1.5); //! } //! ``` use std::ops; pub trait Particle { type Pos: Copy + ops::Add<Output = Self::Pos> + ops::Sub<Output = Self::Pos> + ops::Mul<f64, Output = Self::Pos>; type Eval: Copy + PartialOrd; fn new_random() -> Self; fn eval(&self) -> Self::Eval; fn pos(&self) -> Self::Pos; fn vel(&self) -> Self::Pos; fn best(&self) -> (Self::Pos, Self::Eval); fn pos_mut(&mut self) -> &mut Self::Pos; fn vel_mut(&mut self) -> &mut Self::Pos; fn best_mut(&mut self) -> &mut (Self::Pos, Self::Eval); } pub struct PSO<T: Particle> { particles: Vec<T>, inetia: f64, c_local: f64, c_global: f64, best: (T, T::Eval), } impl<T> PSO<T> where T: Particle + Ord + Copy { pub fn new(particles_num: usize, inetia: f64, c_local: f64, c_global: f64) -> Self { let mut particles = Vec::with_capacity(particles_num); for _ in 0..particles_num { particles.push(T::new_random()); } let best = Self::calc_best(&particles); Self { particles, inetia, c_local, c_global, best, } } fn calc_best(particles: &[T]) -> (T, T::Eval) { let best = particles.iter().max().unwrap(); (*best, best.eval()) } pub fn update(&mut self) { for p in &mut self.particles { let new_pos = p.pos() + p.vel(); *p.pos_mut() = new_pos; } for mut p in &mut self.particles { let new_vel = p.vel() * self.inetia + (p.best().0 - p.pos()) * self.c_local * Self::rand_01() + (self.best.0.pos() - p.pos()) * self.c_global * Self::rand_01(); *p.vel_mut() = new_vel; } for mut p in &mut self.particles { let e = p.eval(); if e > p.best().1 { *p.best_mut() = (p.pos(), e); } } self.best = Self::calc_best(&self.particles); } pub fn best(&self) -> (T, T::Eval) { self.best } fn rand_01() -> f64 { use rand::{random, Closed01}; let Closed01(val) = random::<Closed01<_>>(); val } }
use std::collections::BTreeSet; use std::sync::Arc; use crate::config::TableConfig; use crate::table::{DetachedRowData, TableSchema}; pub struct MemTable { config: Arc<TableConfig>, schema: Arc<TableSchema>, data: BTreeSet<DetachedRowData>, size: usize, } impl MemTable { pub fn new(config: &Arc<TableConfig>, schema: &Arc<TableSchema>) -> MemTable { MemTable { config: config.clone(), schema: schema.clone(), data: BTreeSet::new(), size: 0 } } pub fn add(&mut self, row: DetachedRowData) { let to_be_added = match self.data.take(&row) { None => row, Some(prev) => { self.size -= prev.row_data_view().buf.len(); row.row_data_view().merge(&prev.row_data_view()) }, }; self.size += &to_be_added.row_data_view().buf.len(); assert!(self.data.insert(to_be_added)); } pub fn get(&self, pk_data: &DetachedRowData) -> Option<&DetachedRowData> { self.data.get(pk_data) } } #[cfg(test)] mod test { use crate::memtable::MemTable; use crate::table::{ColumnId, ColumnValue}; use crate::testutils::{SimpleTableTestSetup, test_table_config}; use crate::time::{HtClock, MergeTimestamp}; #[test] pub fn test_simple() { let config = test_table_config(); let setup = SimpleTableTestSetup::new(); let mut mem_table = MemTable::new(&config, &setup.schema); assert_eq!(0, mem_table.size); let row = setup.full_row(1, Option::Some("abc"), Option::Some(123)); mem_table.add(row); assert!(mem_table.size > 0); let opt_found = mem_table.get(&setup.pk_row(1)); let found = opt_found.unwrap(); let data_view = found.row_data_view(); let data = data_view.read_col_by_id(ColumnId(1)).unwrap(); assert_eq!(ColumnValue::Text("abc"), data.value.unwrap()); assert_eq!(ColumnValue::Int(123), data_view.read_col_by_id(ColumnId(2)).unwrap().value.unwrap()); // different pk -> not found let found = mem_table.get(&setup.pk_row(2)); assert!(found.is_none()); // pk row has a different timestamp setup.clock.set(MergeTimestamp::from_ticks(0)); let opt_found = mem_table.get(&setup.pk_row(1)); let found = opt_found.unwrap(); let data_view = found.row_data_view(); assert_eq!(ColumnValue::Text("abc"), data_view.read_col_by_id(ColumnId(1)).unwrap().value.unwrap()); assert_eq!(ColumnValue::Int(123), data_view.read_col_by_id(ColumnId(2)).unwrap().value.unwrap()); // merge updates setup.clock.set(MergeTimestamp::from_ticks(999999)); mem_table.add(setup.partial_row(1, Option::Some("xyz"))); let opt_found = mem_table.get(&setup.pk_row(1)); let found = opt_found.unwrap(); let data_view = found.row_data_view(); assert_eq!(ColumnValue::Text("xyz"), data_view.read_col_by_id(ColumnId(1)).unwrap().value.unwrap()); assert_eq!(ColumnValue::Int(123), data_view.read_col_by_id(ColumnId(2)).unwrap().value.unwrap()); // second row } //TODO expiry //TODO with cluster key //TODO merging update }
//! Tests auto-converted from "sass-spec/spec/misc" //! version 0f59164a, 2019-02-01 17:21:13 -0800. //! See <https://github.com/sass/sass-spec> for source material.\n //! The following tests are excluded from conversion: //! ["mixin_content", "JMA-pseudo-test", "trailing_comma_in_selector", "warn-directive"] extern crate rsass; use rsass::{compile_scss, OutputStyle}; // Ignoring "JMA-pseudo-test", not expected to work yet. /// From "sass-spec/spec/misc/directive_interpolation" #[test] fn directive_interpolation() { assert_eq!( rsass("$baz: 12;\n@foo bar#{$baz} qux {a: b}\n").unwrap(), "@foo bar12 qux {\n a: b;\n}\n" ); } /// From "sass-spec/spec/misc/empty_content" #[test] fn empty_content() { assert_eq!( rsass("@mixin foo { @content }\na { b: c; @include foo {} }\n") .unwrap(), "a {\n b: c;\n}\n" ); } // Ignoring "error-directive", tests with expected error not implemented yet. /// From "sass-spec/spec/misc/import_in_mixin" #[test] fn import_in_mixin() { assert_eq!( rsass( "@mixin import-google-fonts() {\n @import url(\"http://fonts.googleapis.com/css?family=#{$family}\");\n}\n$family: unquote(\"Droid+Sans\");\n@include import-google-fonts();\n" ) .unwrap(), "@import url(\"http://fonts.googleapis.com/css?family=Droid+Sans\");\n" ); } /// From "sass-spec/spec/misc/import_with_interpolation" #[test] fn import_with_interpolation() { assert_eq!( rsass( "$family: unquote(\"Droid+Sans\");\n@import url(\"http://fonts.googleapis.com/css?family=#{$family}\");\n" ) .unwrap(), "@import url(\"http://fonts.googleapis.com/css?family=Droid+Sans\");\n" ); } /// From "sass-spec/spec/misc/lang-bug" #[test] fn lang_bug() { assert_eq!( rsass("div:lang(nb) {\n color: red;\n}").unwrap(), "div:lang(nb) {\n color: red;\n}\n" ); } /// From "sass-spec/spec/misc/media_interpolation" #[test] fn media_interpolation() { assert_eq!( rsass("$baz: 12;\n@media bar#{$baz} {a {b: c}}\n").unwrap(), "@media bar12 {\n a {\n b: c;\n }\n}\n" ); } // Ignoring "mixin_content", not expected to work yet. /// From "sass-spec/spec/misc/namespace_properties_with_script_value" #[test] fn namespace_properties_with_script_value() { assert_eq!( rsass( "foo {\n bar: baz + bang {\n bip: bop;\n bing: bop; }}\n" ) .unwrap(), "foo {\n bar: bazbang;\n bar-bip: bop;\n bar-bing: bop;\n}\n" ); } /// From "sass-spec/spec/misc/negative_numbers" #[test] fn negative_numbers() { assert_eq!( rsass( "$zero: 0;\na {\n zero: -$zero;\n zero: $zero * -1;\n}\n$near: 0.000000000001;\na {\n near: -$near;\n near: $near * -1;\n}\n" ) .unwrap(), "a {\n zero: 0;\n zero: 0;\n}\n\na {\n near: 0;\n near: 0;\n}\n" ); } /// From "sass-spec/spec/misc/selector_interpolation_before_element_name" #[test] fn selector_interpolation_before_element_name() { assert_eq!( rsass("#{\"foo\" + \" bar\"}baz {a: b}\n").unwrap(), "foo barbaz {\n a: b;\n}\n" ); } /// From "sass-spec/spec/misc/selector_only_interpolation" #[test] fn selector_only_interpolation() { assert_eq!( rsass("#{\"foo\" + \" bar\"} {a: b}\n").unwrap(), "foo bar {\n a: b;\n}\n" ); } // Ignoring "trailing_comma_in_selector", not expected to work yet. /// From "sass-spec/spec/misc/unicode_variables" #[test] fn unicode_variables() { assert_eq!( rsass("$vär: foo;\n\nblat {a: $vär}\n").unwrap(), "blat {\n a: foo;\n}\n" ); } // Ignoring "warn-directive", not expected to work yet. fn rsass(input: &str) -> Result<String, String> { compile_scss(input.as_bytes(), OutputStyle::Expanded) .map_err(|e| format!("rsass failed: {}", e)) .and_then(|s| String::from_utf8(s).map_err(|e| format!("{:?}", e))) }
extern crate byteorder; extern crate http_muncher; extern crate inflector; extern crate libc; #[macro_use] extern crate plugkit; use inflector::Inflector; use std::collections::HashMap; use std::io::{Error, ErrorKind}; use plugkit::layer::Layer; use plugkit::context::Context; use plugkit::worker::Worker; use plugkit::token; use plugkit::token::Token; use plugkit::variant::Value; use http_muncher::{Method, Parser, ParserHandler, ParserType}; use std::cell::RefCell; use std::str; use std::rc::Rc; #[derive(PartialEq)] enum Status { None, Active, Error, } fn get_status_code(val: u16) -> Option<Token> { match val { 100 => Some(token!("http.status.continue")), 101 => Some(token!("http.status.switchingProtocols")), 102 => Some(token!("http.status.processing")), 200 => Some(token!("http.status.ok")), 201 => Some(token!("http.status.created")), 202 => Some(token!("http.status.accepted")), 203 => Some(token!("http.status.nonAuthoritativeInformation")), 204 => Some(token!("http.status.noContent")), 205 => Some(token!("http.status.resetContent")), 206 => Some(token!("http.status.partialContent")), 207 => Some(token!("http.status.multiStatus")), 208 => Some(token!("http.status.alreadyReported")), 226 => Some(token!("http.status.imUsed")), 300 => Some(token!("http.status.multipleChoices")), 301 => Some(token!("http.status.movedPermanently")), 302 => Some(token!("http.status.found")), 303 => Some(token!("http.status.seeOther")), 304 => Some(token!("http.status.notModified")), 305 => Some(token!("http.status.useProxy")), 307 => Some(token!("http.status.temporaryRedirect")), 308 => Some(token!("http.status.permanentRedirect")), 400 => Some(token!("http.status.badRequest")), 401 => Some(token!("http.status.unauthorized")), 402 => Some(token!("http.status.paymentRequired")), 403 => Some(token!("http.status.forbidden")), 404 => Some(token!("http.status.notFound")), 405 => Some(token!("http.status.methodNotAllowed")), 406 => Some(token!("http.status.notAcceptable")), 407 => Some(token!("http.status.proxyAuthenticationRequired")), 408 => Some(token!("http.status.requestTimeout")), 409 => Some(token!("http.status.conflict")), 410 => Some(token!("http.status.gone")), 411 => Some(token!("http.status.lengthRequired")), 412 => Some(token!("http.status.preconditionFailed")), 413 => Some(token!("http.status.payloadTooLarge")), 414 => Some(token!("http.status.uriTooLong")), 415 => Some(token!("http.status.unsupportedMediaType")), 416 => Some(token!("http.status.rangeNotSatisfiable")), 417 => Some(token!("http.status.expectationFailed")), 421 => Some(token!("http.status.misdirectedRequest")), 422 => Some(token!("http.status.unprocessableEntity")), 423 => Some(token!("http.status.locked")), 424 => Some(token!("http.status.failedDependency")), 426 => Some(token!("http.status.upgradeRequired")), 428 => Some(token!("http.status.preconditionRequired")), 429 => Some(token!("http.status.tooManyRequests")), 431 => Some(token!("http.status.requestHeaderFieldsTooLarge")), 451 => Some(token!("http.status.unavailableForLegalReasons")), 500 => Some(token!("http.status.internalServerError")), 501 => Some(token!("http.status.notImplemented")), 502 => Some(token!("http.status.badGateway")), 503 => Some(token!("http.status.serviceUnavailable")), 504 => Some(token!("http.status.gatewayTimeout")), 505 => Some(token!("http.status.httpVersionNotSupported")), 506 => Some(token!("http.status.variantAlsoNegotiates")), 507 => Some(token!("http.status.insufficientStorage")), 508 => Some(token!("http.status.loopDetected")), 510 => Some(token!("http.status.notExtended")), 511 => Some(token!("http.status.networkAuthenticationRequired")), _ => None, } } fn get_method(val: Method) -> Token { match val { Method::HttpDelete => token!("http.method.delete"), Method::HttpGet => token!("http.method.get"), Method::HttpHead => token!("http.method.head"), Method::HttpPost => token!("http.method.post"), Method::HttpPut => token!("http.method.put"), Method::HttpConnect => token!("http.method.connect"), Method::HttpOptions => token!("http.method.options"), Method::HttpTrace => token!("http.method.trace"), Method::HttpCopy => token!("http.method.copy"), Method::HttpLock => token!("http.method.lock"), Method::HttpMkcol => token!("http.method.mkcol"), Method::HttpMove => token!("http.method.move"), Method::HttpPropfind => token!("http.method.propfind"), Method::HttpProppatch => token!("http.method.proppatch"), Method::HttpSearch => token!("http.method.search"), Method::HttpUnlock => token!("http.method.unlock"), Method::HttpBind => token!("http.method.bind"), Method::HttpRebind => token!("http.method.rebind"), Method::HttpUnbind => token!("http.method.unbind"), Method::HttpAcl => token!("http.method.acl"), Method::HttpReport => token!("http.method.report"), Method::HttpMkactivity => token!("http.method.mkactivity"), Method::HttpCheckout => token!("http.method.checkout"), Method::HttpMerge => token!("http.method.merge"), Method::HttpMSearch => token!("http.method.mSearch"), Method::HttpNotify => token!("http.method.notify"), Method::HttpSubscribe => token!("http.method.subscribe"), Method::HttpUnsubscribe => token!("http.method.unsubscribe"), Method::HttpPatch => token!("http.method.patch"), Method::HttpPurge => token!("http.method.purge"), Method::HttpMkcalendar => token!("http.method.mkcalendar"), Method::HttpLink => token!("http.method.link"), Method::HttpUnlink => token!("http.method.unlink"), Method::HttpSource => token!("http.method.source"), } } enum Entry { Url(&'static [u8]), } struct HTTPSession { status: Status, parser: Rc<RefCell<Parser>>, header_field: &'static [u8], headers: Vec<(String, &'static [u8])>, entries: Vec<Entry>, } impl ParserHandler for HTTPSession { fn on_url(&mut self, _parser: &mut Parser, data: &'static [u8]) -> bool { self.entries.push(Entry::Url(data)); true } fn on_header_field(&mut self, _parser: &mut Parser, data: &'static [u8]) -> bool { self.header_field = data; true } fn on_header_value(&mut self, _parser: &mut Parser, data: &'static [u8]) -> bool { if let Ok(key) = str::from_utf8(self.header_field) { self.headers.push((key.to_camel_case(), data)); } true } } impl HTTPSession { pub fn new() -> HTTPSession { HTTPSession { status: Status::None, parser: Rc::new(RefCell::new(Parser::request_and_response())), header_field: &[], headers: Vec::new(), entries: Vec::new(), } } fn parse(&mut self, slice: &'static [u8]) -> usize { let parser = Rc::clone(&self.parser); let size = parser.borrow_mut().parse(self, &slice); size } fn analyze( &mut self, ctx: &mut Context, layer: &mut Layer, stream_id: u64, ) -> Result<(), Error> { let (slice, _) = { let payload = layer .payloads() .next() .ok_or(Error::new(ErrorKind::Other, "no payload"))?; let slice = payload .slices() .next() .ok_or(Error::new(ErrorKind::Other, "no slice"))?; (slice, payload.range()) }; match self.status { Status::None => { self.status = if slice.len() == 0 { Status::None } else if self.parse(slice) == slice.len() { Status::Active } else { Status::Error } } Status::Active => { if self.parse(slice) != slice.len() { self.status = Status::Error; } } _ => (), } if self.status != Status::Active { return Ok(()); } let parser = Rc::clone(&self.parser); let parser = &parser.borrow(); let child = layer.add_layer(ctx, token!("http")); child.add_tag(ctx, token!("http")); ctx.add_layer_linkage(token!("http"), stream_id, child); { let version = parser.http_version(); let attr = child.add_attr(ctx, token!("http.version")); attr.set(&(version.0 as f64 + (version.1 as f64) / 10.0)); } if parser.parser_type() == ParserType::HttpRequest { let attr = child.add_attr(ctx, get_method(parser.http_method())); attr.set(&true); attr.set_typ(token!("@novalue")); } if parser.parser_type() == ParserType::HttpResponse { if let Some(id) = get_status_code(parser.status_code()) { { let attr = child.add_attr(ctx, token!("http.status")); attr.set_typ(token!("@enum")); attr.set(&parser.status_code()); } { let attr = child.add_attr(ctx, id); attr.set(&true); attr.set_typ(token!("@novalue")); } } } if parser.should_keep_alive() { let attr = child.add_attr(ctx, token!("http.keepAlive")); attr.set_typ(token!("@novalue")); attr.set(&true); } while let Some(top) = self.entries.pop() { match top { Entry::Url(data) => { if let Ok(path) = str::from_utf8(data) { let attr = child.add_attr(ctx, token!("http.path")); attr.set(&path); } } } } if self.headers.len() > 0 { while let Some((key, value)) = self.headers.pop() { if let Ok(value_str) = str::from_utf8(value) { let attr = child.add_attr(ctx, token::concat("http.headers.", key.as_str())); attr.set(&value_str); } } } Ok(()) } } struct HTTPWorker { map: HashMap<u64, HTTPSession>, } impl HTTPWorker { pub fn new() -> HTTPWorker { HTTPWorker { map: HashMap::new(), } } } impl Worker for HTTPWorker { fn analyze(&mut self, ctx: &mut Context, layer: &mut Layer) -> Result<(), Error> { let stream_id: u64 = { layer.attr(token!("_.streamId")).unwrap().get() }; let session = self.map .entry(stream_id) .or_insert_with(|| HTTPSession::new()); session.analyze(ctx, layer, stream_id) } } plugkit_module!({}); plugkit_api_layer_hints!(token!("tcp-stream")); plugkit_api_worker!(HTTPWorker, HTTPWorker::new());
enum ExprC { NumC { n : u32 }, BoolC { b : bool }, StringC { s : String }, IfC { i : Box<ExprC>, t : Box<ExprC>, e : Box<ExprC> }, IdC { i : String }, LamC { params : Vec<String>, body : Box<ExprC> }, AppC { fun_def : Box<ExprC>, params: Vec<Box<ExprC>> } } enum ValueV { NumV { n : u32 }, BoolV { b : bool }, StringV { s : String }, PrimV { p : String }, CloV { params : Vec<String>, body : Box<ExprC> } } fn interp(e: ExprC) -> ValueV { match e { ExprC::NumC { n } => ValueV::NumV { n : n }, ExprC::BoolC { b } => ValueV::BoolV { b : b }, ExprC::StringC { s } => ValueV::StringV { s : s }, ExprC::IfC { i, t, e } => if_helper(i, t, e), _ => ValueV::NumV { n : 4 } } } fn if_helper(i: Box<ExprC>, t: Box<ExprC>, e: Box<ExprC>) -> ValueV { match interp(*i) { ValueV::BoolV { b } => if b { interp(*t) } else { interp(*e) } _ => panic!("invalid in if") } } fn serialize(v: ValueV) -> String { match v { ValueV::NumV { n } => n.to_string(), ValueV::BoolV { b } => b.to_string(), ValueV::StringV { s } => s, ValueV::CloV { params, body } => String::from("#<procedure>"), ValueV::PrimV { p } => String::from("#<primop>"), _ => panic!("invalid in serialize") } } fn main() { // primative types let bool_true = ExprC::BoolC { b: true }; let bool_false = ExprC::BoolC { b: false }; let num_45 = ExprC::NumC { n: 45 }; let string_test = ExprC::StringC { s: String::from("just a test") }; // true if case let test_if_i = ExprC::BoolC { b: true }; let test_if_t = ExprC::NumC { n: 5 }; let test_if_e = ExprC::NumC { n: 3 }; let test_if = ExprC::IfC { i: Box::new(test_if_i), t: Box::new(test_if_t), e: Box::new(test_if_e) }; // false if case let test_if_i_2 = ExprC::BoolC { b: false }; let test_if_t_2 = ExprC::NumC { n: 5 }; let test_if_e_2 = ExprC::NumC { n: 3 }; let test_if_2 = ExprC::IfC { i: Box::new(test_if_i_2), t: Box::new(test_if_t_2), e: Box::new(test_if_e_2) }; // tests assert_eq!("45", serialize(interp(num_45))); assert_eq!("false", serialize(interp(bool_false))); assert_eq!("true", serialize(interp(bool_true))); assert_eq!("just a test", serialize(interp(string_test))); assert_eq!("5", serialize(interp(test_if))); assert_eq!("3", serialize(interp(test_if_2))); }
#[macro_use] extern crate conrod_core; extern crate conrod_glium; #[macro_use] extern crate conrod_winit; extern crate find_folder; extern crate glium; extern crate image; use glium::Surface; use conrod_core::color::Color; use rand::prelude::*; mod support; fn generate_gradient() -> Vec<Color> { let mut rng = rand::thread_rng(); let first_color = Color::Rgba(rng.gen(), rng.gen(), rng.gen(), 1.0); let last_color = Color::Rgba(rng.gen(), rng.gen(), rng.gen(), 1.0); let mut grad = Vec::new(); grad.push(first_color); let r_step = ( last_color.red() - first_color.red() ) / 10.0; let g_step = ( last_color.green() - first_color.green() ) / 10.0; let b_step = ( last_color.blue() - first_color.blue() ) / 10.0; for n in 2..10 { let r = r_step * n as f32; let g = g_step * n as f32; let b = b_step * n as f32; grad.push(Color::Rgba(r + first_color.red(), g + first_color.green(), b + first_color.blue(), 1.0)); } grad.push(last_color); grad } fn shuffled_gradient(g: & Vec<Color>) -> Vec<Color> { let mut rng = rand::thread_rng(); let mut result = g.clone(); // don't shuffle first and last elements let len = result.len(); (&mut result[1..len-1]).shuffle(&mut rng); result } fn main() { const WIDTH: u32 = 800; const HEIGHT: u32 = 600; // Build the window. let mut events_loop = glium::glutin::EventsLoop::new(); let window = glium::glutin::WindowBuilder::new() .with_title("Cozzle") .with_dimensions((WIDTH, HEIGHT).into()); let context = glium::glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4); let display = glium::Display::new(window, context, &events_loop).unwrap(); let display = support::GliumDisplayWinitWrapper(display); // construct our `Ui`. let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build(); // A type used for converting `conrod_core::render::Primitives` into `Command`s that can be used // for drawing to the glium `Surface`. let mut renderer = conrod_glium::Renderer::new(&display.0).unwrap(); // The image map describing each of our widget->image mappings (in our case, none). let image_map = conrod_core::image::Map::<glium::texture::Texture2d>::new(); // Instantiate the generated list of widget identifiers. let ids = &mut Ids::new(ui.widget_id_generator()); // base gradient let mut base_gradient = generate_gradient(); // shuffled gradient let mut gradient = shuffled_gradient(&base_gradient); // index of selected cell in the gradient let mut selected : Option<usize> = None; // ends when base gradient == shuffled // Poll events from the window. let mut event_loop = support::EventLoop::new(); 'main: loop { // Handle all events. for event in event_loop.next(&mut events_loop) { // Use the `winit` backend feature to convert the winit event to a conrod one. if let Some(event) = support::convert_event(event.clone(), &display) { ui.handle_event(event); event_loop.needs_update(); } match event { glium::glutin::Event::WindowEvent { event, .. } => match event { // Break from the loop upon `Escape`. glium::glutin::WindowEvent::CloseRequested | glium::glutin::WindowEvent::KeyboardInput { input: glium::glutin::KeyboardInput { virtual_keycode: Some(glium::glutin::VirtualKeyCode::Escape), .. }, .. } => break 'main, _ => (), }, _ => (), } } if base_gradient == gradient { // generate new gradient base_gradient = generate_gradient(); // shuffled gradient gradient = shuffled_gradient(&base_gradient); } // Instantiate all widgets in the GUI. // pass the colors of the buttons (shuffled gradient) set_widgets(ui.set_widgets(), ids, gradient.as_mut_slice(), &mut selected); // Render the `Ui` and then display it on the screen. if let Some(primitives) = ui.draw_if_changed() { renderer.fill(&display.0, primitives, &image_map); let mut target = display.0.draw(); target.clear_color(0.0, 0.0, 0.0, 1.0); renderer.draw(&display.0, &mut target, &image_map).unwrap(); target.finish().unwrap(); } } } // Button matrix dimensions. const ROWS: usize = 1; const COLS: usize = 10; // Draw the Ui. fn set_widgets(ref mut ui: conrod_core::UiCell, ids: &mut Ids, colors: &mut [Color], selected: &mut Option<usize>) { use conrod_core::{widget, Colorable, Positionable, Sizeable, Widget}; // Construct our main `Canvas` tree. widget::Canvas::new().set(ids.master, ui); let master_wh = ui.wh_of(ids.master).unwrap(); let mut elements = widget::Matrix::new(COLS, ROWS) .w_h(master_wh[0], master_wh[1] * 2.0) .mid_top_of(ids.master) .set(ids.matrix, ui); while let Some(elem) = elements.next(ui) { let (r, c) = (elem.row, elem.col); let n = c + r * c; let button = widget::Button::new().color(colors[n]).hover_color(colors[n]); for _click in elem.set(button, ui) { // Prevent selecting first and last // if another already selected and not self, then swap // else select for swap match selected { None => *selected = Some(n), Some(id) => { colors.swap(n, *id); *selected = None; }, }; } } } // Generate a unique `WidgetId` for each widget. widget_ids! { struct Ids { master, matrix, } }
/* * Open Service Cloud API * * Open Service Cloud API to manage different backend cloud services. * * The version of the OpenAPI document: 0.0.3 * Contact: wanghui71leon@gmail.com * Generated by: https://openapi-generator.tech */ #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct CloudServerResourceFragment { #[serde(rename = "hostId", skip_serializing_if = "Option::is_none")] pub host_id: Option<String>, #[serde(rename = "key_name", skip_serializing_if = "Option::is_none")] pub key_name: Option<String>, #[serde( rename = "OS-EXT-STS:vm_state", skip_serializing_if = "Option::is_none" )] pub os_ext_st_svm_state: Option<String>, #[serde(rename = "addresses", skip_serializing_if = "Option::is_none")] pub addresses: Option<serde_json::Value>, #[serde(rename = "flavor", skip_serializing_if = "Option::is_none")] pub flavor: Option<crate::models::CloudServerResourceFragmentFlavor>, #[serde( rename = "OS-EXT-AZ:availability_zone", skip_serializing_if = "Option::is_none" )] pub os_ext_a_zavailability_zone: Option<String>, #[serde(rename = "accessIPv4", skip_serializing_if = "Option::is_none")] pub access_i_pv4: Option<String>, #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] pub metadata: Option<serde_json::Value>, #[serde( rename = "os-extended-volumes:volumes_attached", skip_serializing_if = "Option::is_none" )] pub os_extended_volumesvolumes_attached: Option<Vec<crate::models::CloudServerResourceFragmentOsextendedvolumesvolumesAttached>>, #[serde( rename = "OS-EXT-SRV-ATTR:hostname", skip_serializing_if = "Option::is_none" )] pub os_ext_srv_att_rhostname: Option<String>, } impl CloudServerResourceFragment { pub fn new() -> CloudServerResourceFragment { CloudServerResourceFragment { host_id: None, key_name: None, os_ext_st_svm_state: None, addresses: None, flavor: None, os_ext_a_zavailability_zone: None, access_i_pv4: None, metadata: None, os_extended_volumesvolumes_attached: None, os_ext_srv_att_rhostname: None, } } }
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::config::{BindingVec, Config, MappingMap, OffRampVec, OnRampVec}; use crate::errors::{Error, ErrorKind, Result}; use crate::lifecycle::{ActivationState, ActivatorLifecycleFsm}; use crate::registry::{Registries, ServantId}; use crate::repository::{ Artefact, BindingArtefact, OfframpArtefact, OnrampArtefact, PipelineArtefact, Repositories, }; use crate::url::ports::METRICS; use crate::url::TremorUrl; use async_channel::bounded; use async_std::io::prelude::*; use async_std::path::Path; use async_std::task::{self, JoinHandle}; use hashbrown::HashMap; use tremor_common::asy::file; use tremor_common::time::nanotime; pub(crate) use crate::offramp; pub(crate) use crate::onramp; pub(crate) use crate::pipeline; lazy_static! { pub(crate) static ref METRICS_PIPELINE: TremorUrl = { TremorUrl::parse("/pipeline/system::metrics/system/in") //ALLOW: We want this to panic, it only happens at startup time .expect("Failed to initialize id for metrics piepline") }; pub(crate) static ref PASSTHROUGH_PIPELINE: TremorUrl = { TremorUrl::parse("/pipeline/system::passthrough/system/in") //ALLOW: We want this to panic, it only happens at startup time .expect("Failed to initialize id for metrics piepline") }; pub(crate) static ref STDOUT_OFFRAMP: TremorUrl = { TremorUrl::parse("/offramp/system::stdout/system/in") //ALLOW: We want this to panic, it only happens at startup time .expect("Failed to initialize id for stdout offramp") }; pub(crate) static ref STDERR_OFFRAMP: TremorUrl = { TremorUrl::parse("/offramp/system::stderr/system/in") //ALLOW: We want this to panic, it only happens at startup time .expect("Failed to initialize id for stderr offramp") }; } /// This is control plane pub(crate) enum ManagerMsg { CreatePipeline( async_channel::Sender<Result<pipeline::Addr>>, pipeline::Create, ), CreateOnramp( async_channel::Sender<Result<onramp::Addr>>, Box<onramp::Create>, ), CreateOfframp( async_channel::Sender<Result<offramp::Addr>>, Box<offramp::Create>, ), Stop, } pub(crate) type Sender = async_channel::Sender<ManagerMsg>; #[derive(Debug)] pub(crate) struct Manager { pub offramp: offramp::Sender, pub onramp: onramp::Sender, pub pipeline: pipeline::Sender, pub offramp_h: JoinHandle<Result<()>>, pub onramp_h: JoinHandle<Result<()>>, pub pipeline_h: JoinHandle<Result<()>>, pub qsize: usize, } impl Manager { pub fn start(self) -> (JoinHandle<Result<()>>, Sender) { let (tx, rx) = bounded(crate::QSIZE); let system_h = task::spawn(async move { while let Ok(msg) = rx.recv().await { match msg { ManagerMsg::CreatePipeline(r, c) => { self.pipeline .send(pipeline::ManagerMsg::Create(r, Box::new(c))) .await?; } ManagerMsg::CreateOnramp(r, c) => { self.onramp.send(onramp::ManagerMsg::Create(r, c)).await?; } ManagerMsg::CreateOfframp(r, c) => { self.offramp.send(offramp::ManagerMsg::Create(r, c)).await?; } ManagerMsg::Stop => { info!("Stopping offramps..."); self.offramp.send(offramp::ManagerMsg::Stop).await?; info!("Stopping pipelines..."); self.pipeline.send(pipeline::ManagerMsg::Stop).await?; info!("Stopping onramps..."); self.onramp.send(onramp::ManagerMsg::Stop).await?; break; } } } info!("Stopping onramps in an odd way..."); Ok(()) }); (system_h, tx) } } /// Tremor runtime #[derive(Clone, Debug)] pub struct World { pub(crate) system: Sender, /// Repository pub repo: Repositories, /// Registry pub reg: Registries, storage_directory: Option<String>, } impl World { /// Ensures the existance of an onramp, creating it if required. /// /// # Errors /// * if we can't ensure the onramp is bound pub async fn ensure_onramp(&self, id: &TremorUrl) -> Result<()> { if self.reg.find_onramp(id).await?.is_none() { info!( "Onramp not found during binding process, binding {} to create a new instance.", &id ); self.bind_onramp(id).await?; } else { info!("Existing onramp {} found", id); } Ok(()) } /// Ensures the existance of an offramp, creating it if required. /// /// # Errors /// * if we can't ensure the offramp is bound pub async fn ensure_offramp(&self, id: &TremorUrl) -> Result<()> { if self.reg.find_offramp(id).await?.is_none() { info!( "Offramp not found during binding process, binding {} to create a new instance.", &id ); self.bind_offramp(id).await?; } else { info!("Existing offramp {} found", id); } Ok(()) } /// Ensures the existance of an pipeline, creating it if required. /// /// # Errors /// * if we can't ensure the pipeline is bound pub async fn ensure_pipeline(&self, id: &TremorUrl) -> Result<()> { if self.reg.find_pipeline(id).await?.is_none() { info!( "Pipeline not found during binding process, binding {} to create a new instance.", &id ); self.bind_pipeline(id).await?; } else { info!("Existing pipeline {} found", id); } Ok(()) } /// Bind a pipeline /// /// # Errors /// * if the id isn't a pipeline instance or can't be bound pub async fn bind_pipeline(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Binding pipeline {}", id); match (&self.repo.find_pipeline(id).await?, &id.instance()) { (Some(artefact), Some(_instance_id)) => { let servant = ActivatorLifecycleFsm::new(self.clone(), artefact.artefact.clone(), id.clone()) .await?; self.repo.bind_pipeline(id).await?; // We link to the metrics pipeline let res = self.reg.publish_pipeline(id, servant).await?; let mut id = id.clone(); id.set_port(&METRICS); let m = vec![(METRICS.to_string(), METRICS_PIPELINE.clone())] .into_iter() .collect(); self.link_existing_pipeline(&id, m).await?; Ok(res) } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {} ", id).into()), } } /// Unbind a pipeline /// /// # Errors /// * if the id isn't an pipeline instance or the pipeline can't be unbound pub async fn unbind_pipeline(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Unbinding pipeline {}", id); match (&self.repo.find_pipeline(id).await?, &id.instance()) { (Some(_artefact), Some(_instance_id)) => { let r = self.reg.unpublish_pipeline(id).await?; self.repo.unbind_pipeline(id).await?; Ok(r) } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {}", id).into()), } } /// Stop the runtime /// /// # Errors /// * if the system failed to stop pub async fn stop(&self) -> Result<()> { Ok(self.system.send(ManagerMsg::Stop).await?) } /// Links a pipeline /// /// # Errors /// * if the id isn't a pipeline or the pipeline can't be linked pub async fn link_pipeline( &self, id: &TremorUrl, mappings: HashMap< <PipelineArtefact as Artefact>::LinkLHS, <PipelineArtefact as Artefact>::LinkRHS, >, ) -> Result<<PipelineArtefact as Artefact>::LinkResult> { info!("Linking pipeline {} to {:?}", id, mappings); if let Some(pipeline_a) = self.repo.find_pipeline(id).await? { if self.reg.find_pipeline(id).await?.is_none() { self.bind_pipeline(id).await?; }; pipeline_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Links a pipeline async fn link_existing_pipeline( &self, id: &TremorUrl, mappings: HashMap< <PipelineArtefact as Artefact>::LinkLHS, <PipelineArtefact as Artefact>::LinkRHS, >, ) -> Result<<PipelineArtefact as Artefact>::LinkResult> { info!("Linking pipeline {} to {:?}", id, mappings); if let Some(pipeline_a) = self.repo.find_pipeline(id).await? { pipeline_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Unlink a pipelein /// /// # Errors /// * if the id isn't a pipeline or the pipeline can't be unlinked pub async fn unlink_pipeline( &self, id: &TremorUrl, mappings: HashMap< <PipelineArtefact as Artefact>::LinkLHS, <PipelineArtefact as Artefact>::LinkRHS, >, ) -> Result<<PipelineArtefact as Artefact>::LinkResult> { if let Some(pipeline_a) = self.repo.find_pipeline(id).await? { let r = pipeline_a.artefact.unlink(self, id, mappings).await; if self.reg.find_pipeline(id).await?.is_some() { self.unbind_pipeline(id).await?; }; r } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } #[cfg(test)] pub async fn bind_pipeline_from_artefact( &self, id: &TremorUrl, artefact: PipelineArtefact, ) -> Result<ActivationState> { self.repo.publish_pipeline(id, false, artefact).await?; self.bind_pipeline(id).await } /// Bind an onramp /// /// # Errors /// * if the id isn't a onramp instance or the onramp can't be bound pub async fn bind_onramp(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Binding onramp {}", id); match (&self.repo.find_onramp(id).await?, &id.instance()) { (Some(artefact), Some(_instance_id)) => { let servant = ActivatorLifecycleFsm::new(self.clone(), artefact.artefact.clone(), id.clone()) .await?; self.repo.bind_onramp(id).await?; // We link to the metrics pipeline let res = self.reg.publish_onramp(id, servant).await?; let mut id = id.clone(); id.set_port(&METRICS); let m = vec![(METRICS.to_string(), METRICS_PIPELINE.clone())] .into_iter() .collect(); self.link_existing_onramp(&id, m).await?; Ok(res) } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {} ", id).into()), } } /// Unbind an onramp /// /// # Errors /// * if the id isn't an onramp or the onramp can't be unbound pub async fn unbind_onramp(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Unbinding onramp {}", id); match (&self.repo.find_onramp(id).await?, &id.instance()) { (Some(_artefact), Some(_instsance_id)) => { let r = self.reg.unpublish_onramp(id).await; self.repo.unbind_onramp(id).await?; r } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {} ", id).into()), } } /// Link an onramp /// /// # Errors /// * if the id isn't an onramp or the onramp can't be linked pub async fn link_onramp( &self, id: &TremorUrl, mappings: HashMap< <OnrampArtefact as Artefact>::LinkLHS, <OnrampArtefact as Artefact>::LinkRHS, >, ) -> Result<<OnrampArtefact as Artefact>::LinkResult> { if let Some(onramp_a) = self.repo.find_onramp(id).await? { if self.reg.find_onramp(id).await?.is_none() { self.bind_onramp(id).await?; }; onramp_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } async fn link_existing_onramp( &self, id: &TremorUrl, mappings: HashMap< <OnrampArtefact as Artefact>::LinkLHS, <OnrampArtefact as Artefact>::LinkRHS, >, ) -> Result<<OnrampArtefact as Artefact>::LinkResult> { if let Some(onramp_a) = self.repo.find_onramp(id).await? { onramp_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Unlink an onramp /// /// # Errors /// * if the id isn't a onramp or it cna't be unlinked pub async fn unlink_onramp( &self, id: &TremorUrl, mappings: HashMap< <OnrampArtefact as Artefact>::LinkLHS, <OnrampArtefact as Artefact>::LinkRHS, >, ) -> Result<<OnrampArtefact as Artefact>::LinkResult> { if let Some(onramp_a) = self.repo.find_onramp(id).await? { let r = onramp_a.artefact.unlink(self, id, mappings).await?; if r { self.unbind_onramp(id).await?; }; Ok(r) } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Bind an offramp /// /// # Errors /// * if the id isn't a offramp instance or it can't be bound pub async fn bind_offramp(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Binding offramp {}", id); match (&self.repo.find_offramp(id).await?, &id.instance()) { (Some(artefact), Some(_instance_id)) => { let servant = ActivatorLifecycleFsm::new(self.clone(), artefact.artefact.clone(), id.clone()) .await?; self.repo.bind_offramp(id).await?; // We link to the metrics pipeline let res = self.reg.publish_offramp(id, servant).await?; let mut metrics_id = id.clone(); metrics_id.set_port(&METRICS); let m = vec![(METRICS_PIPELINE.clone(), metrics_id.clone())] .into_iter() .collect(); self.link_existing_offramp(id, m).await?; Ok(res) } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {} ", id).into()), } } /// Unbind an offramp /// /// # Errors /// * if the id isn't an offramp instance or the offramp can't be unbound pub async fn unbind_offramp(&self, id: &TremorUrl) -> Result<ActivationState> { info!("Unbinding offramp {} ..", id); match (&self.repo.find_offramp(id).await?, &id.instance()) { (Some(_artefact), Some(_instsance_id)) => { let r = self.reg.unpublish_offramp(id).await; self.repo.unbind_offramp(id).await?; r } (None, _) => Err(ErrorKind::ArtefactNotFound(id.to_string()).into()), (_, None) => Err(format!("Invalid URI for instance {} ", id).into()), } } /// Link an offramp /// /// # Errors /// * if the id isn't an offramp or can't be linked pub async fn link_offramp( &self, id: &TremorUrl, mappings: HashMap< <OfframpArtefact as Artefact>::LinkLHS, <OfframpArtefact as Artefact>::LinkRHS, >, ) -> Result<<OfframpArtefact as Artefact>::LinkResult> { if let Some(offramp_a) = self.repo.find_offramp(id).await? { if self.reg.find_offramp(id).await?.is_none() { self.bind_offramp(id).await?; }; offramp_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } async fn link_existing_offramp( &self, id: &TremorUrl, mappings: HashMap< <OfframpArtefact as Artefact>::LinkLHS, <OfframpArtefact as Artefact>::LinkRHS, >, ) -> Result<<OfframpArtefact as Artefact>::LinkResult> { if let Some(offramp_a) = self.repo.find_offramp(id).await? { offramp_a.artefact.link(self, id, mappings).await } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Unlink an offramp /// /// # Errors /// * if the id isn't an offramp or it cna't be unlinked pub async fn unlink_offramp( &self, id: &TremorUrl, mappings: HashMap< <OfframpArtefact as Artefact>::LinkLHS, <OfframpArtefact as Artefact>::LinkRHS, >, ) -> Result<<OfframpArtefact as Artefact>::LinkResult> { if let Some(offramp_a) = self.repo.find_offramp(id).await? { let r = offramp_a.artefact.unlink(self, id, mappings).await?; if r { self.unbind_offramp(id).await?; }; Ok(r) } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } pub(crate) async fn bind_binding_a( &self, id: &TremorUrl, artefact: &BindingArtefact, ) -> Result<ActivationState> { info!("Binding binding {}", id); match &id.instance() { Some(_instance_id) => { let servant = ActivatorLifecycleFsm::new(self.clone(), artefact.clone(), id.clone()).await?; self.repo.bind_binding(id).await?; self.reg.publish_binding(id, servant).await } None => Err(format!("Invalid URI for instance {}", id).into()), } } pub(crate) async fn unbind_binding_a( &self, id: &TremorUrl, _artefact: &BindingArtefact, ) -> Result<ActivationState> { info!("Unbinding binding {}", id); match &id.instance() { Some(_instance_id) => { let servant = self.reg.unpublish_binding(id).await?; self.repo.unbind_binding(id).await?; Ok(servant) } None => Err(format!("Invalid URI for instance {}", id).into()), } } /// Links a binding /// /// # Errors /// * If the id isn't a binding or the bindig can't be linked pub async fn link_binding( &self, id: &TremorUrl, mappings: HashMap< <BindingArtefact as Artefact>::LinkLHS, <BindingArtefact as Artefact>::LinkRHS, >, ) -> Result<<BindingArtefact as Artefact>::LinkResult> { if let Some(binding_a) = self.repo.find_binding(id).await? { let r = binding_a.artefact.link(self, id, mappings).await?; if self.reg.find_binding(id).await?.is_none() { self.bind_binding_a(id, &r).await?; }; Ok(r) } else { Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } } /// Turns the running system into a config /// /// # Errors /// * If the systems configuration can't be stored pub async fn to_config(&self) -> Result<Config> { let onramp: OnRampVec = self.repo.serialize_onramps().await?; let offramp: OffRampVec = self.repo.serialize_offramps().await?; let binding: BindingVec = self .repo .serialize_bindings() .await? .into_iter() .map(|b| b.binding) .collect(); let mapping: MappingMap = self.reg.serialize_mappings().await?; let config = crate::config::Config { onramp, offramp, binding, mapping, }; Ok(config) } /// Saves the current config /// /// # Errors /// * if the config can't be saved pub async fn save_config(&self) -> Result<String> { if let Some(storage_directory) = &self.storage_directory { let config = self.to_config().await?; let path = Path::new(storage_directory); let file_name = format!("config_{}.yaml", nanotime()); let mut file_path = path.to_path_buf(); file_path.push(Path::new(&file_name)); info!( "Serializing configuration to file {}", file_path.to_string_lossy() ); let mut f = file::create(&file_path).await?; f.write_all(&serde_yaml::to_vec(&config)?).await?; // lets really sync this! f.sync_all().await?; f.sync_all().await?; f.sync_all().await?; Ok(file_path.to_string_lossy().to_string()) } else { Ok("".to_string()) } } /// Unlinks a binding /// /// # Errors /// * if the id isn't an binding or the binding can't be unbound pub async fn unlink_binding( &self, id: &TremorUrl, mappings: HashMap< <BindingArtefact as Artefact>::LinkLHS, <BindingArtefact as Artefact>::LinkRHS, >, ) -> Result<<BindingArtefact as Artefact>::LinkResult> { if let Some(binding) = self.reg.find_binding(id).await? { if binding.unlink(self, id, mappings).await? { self.unbind_binding_a(id, &binding).await?; } return Ok(binding); } Err(ErrorKind::ArtefactNotFound(id.to_string()).into()) } /// Starts the runtime system /// /// # Errors /// * if the world manager can't be started pub async fn start( qsize: usize, storage_directory: Option<String>, ) -> Result<(Self, JoinHandle<Result<()>>)> { let (onramp_h, onramp) = onramp::Manager::new(qsize).start(); let (offramp_h, offramp) = offramp::Manager::new(qsize).start(); let (pipeline_h, pipeline) = pipeline::Manager::new(qsize).start(); let (system_h, system) = Manager { offramp, onramp, pipeline, offramp_h, onramp_h, pipeline_h, qsize, } .start(); let repo = Repositories::new(); let reg = Registries::new(); let mut world = Self { system, repo, reg, storage_directory, }; world.register_system().await?; Ok((world, system_h)) } async fn register_system(&mut self) -> Result<()> { // register metrics pipeline let module_path = &tremor_script::path::ModulePath { mounts: Vec::new() }; let aggr_reg = tremor_script::aggr_registry(); let artefact_metrics = tremor_pipeline::query::Query::parse( module_path, "#!config id = \"system::metrics\"\nselect event from in into out;", "<metrics>", Vec::new(), &*tremor_pipeline::FN_REGISTRY.lock()?, &aggr_reg, )?; self.repo .publish_pipeline(&METRICS_PIPELINE, true, artefact_metrics) .await?; self.bind_pipeline(&METRICS_PIPELINE).await?; self.reg .find_pipeline(&METRICS_PIPELINE) .await? .ok_or_else(|| Error::from("Failed to initialize metrics pipeline."))?; let artefact_passthrough = tremor_pipeline::query::Query::parse( module_path, "#!config id = \"system::passthrough\"\nselect event from in into out;", "<passthrough>", Vec::new(), &*tremor_pipeline::FN_REGISTRY.lock()?, &aggr_reg, )?; self.repo .publish_pipeline(&PASSTHROUGH_PIPELINE, true, artefact_passthrough) .await?; // Register stdout offramp let artefact: OfframpArtefact = serde_yaml::from_str( r#" id: system::stdout type: stdout "#, )?; self.repo .publish_offramp(&STDOUT_OFFRAMP, true, artefact) .await?; self.bind_offramp(&STDOUT_OFFRAMP).await?; self.reg .find_offramp(&STDOUT_OFFRAMP) .await? .ok_or_else(|| Error::from("Failed to initialize stdout offramp."))?; // Register stderr offramp let artefact: OfframpArtefact = serde_yaml::from_str( r#" id: system::stderr type: stderr "#, )?; self.repo .publish_offramp(&STDERR_OFFRAMP, true, artefact) .await?; self.bind_offramp(&STDERR_OFFRAMP).await?; self.reg .find_offramp(&STDERR_OFFRAMP) .await? .ok_or_else(|| Error::from("Failed to initialize stderr offramp."))?; Ok(()) } pub(crate) async fn start_pipeline( &self, config: PipelineArtefact, id: ServantId, ) -> Result<pipeline::Addr> { let (tx, rx) = bounded(1); self.system .send(ManagerMsg::CreatePipeline( tx, pipeline::Create { config, id }, )) .await?; rx.recv().await? } }
#[doc = "Reader of register IP_HWCFGR0"] pub type R = crate::R<u32, super::IP_HWCFGR0>; #[doc = "Writer for register IP_HWCFGR0"] pub type W = crate::W<u32, super::IP_HWCFGR0>; #[doc = "Register IP_HWCFGR0 `reset()`'s with value 0x1111"] impl crate::ResetValue for super::IP_HWCFGR0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x1111 } } #[doc = "Reader of field `DUAL`"] pub type DUAL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DUAL`"] pub struct DUAL_W<'a> { w: &'a mut W, } impl<'a> DUAL_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 & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `LFSR`"] pub type LFSR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LFSR`"] pub struct LFSR_W<'a> { w: &'a mut W, } impl<'a> LFSR_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 & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Reader of field `TRIANGLE`"] pub type TRIANGLE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRIANGLE`"] pub struct TRIANGLE_W<'a> { w: &'a mut W, } impl<'a> TRIANGLE_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 & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `SAMPLE`"] pub type SAMPLE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SAMPLE`"] pub struct SAMPLE_W<'a> { w: &'a mut W, } impl<'a> SAMPLE_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 & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12); self.w } } #[doc = "Reader of field `OR_CFG`"] pub type OR_CFG_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OR_CFG`"] pub struct OR_CFG_W<'a> { w: &'a mut W, } impl<'a> OR_CFG_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 } } impl R { #[doc = "Bits 0:3 - Dual DAC capability"] #[inline(always)] pub fn dual(&self) -> DUAL_R { DUAL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Pseudonoise wave generation capability"] #[inline(always)] pub fn lfsr(&self) -> LFSR_R { LFSR_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:11 - Triangle wave generation capability"] #[inline(always)] pub fn triangle(&self) -> TRIANGLE_R { TRIANGLE_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:15 - Sample and hold mode capability"] #[inline(always)] pub fn sample(&self) -> SAMPLE_R { SAMPLE_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:23 - option register bit width"] #[inline(always)] pub fn or_cfg(&self) -> OR_CFG_R { OR_CFG_R::new(((self.bits >> 16) & 0xff) as u8) } } impl W { #[doc = "Bits 0:3 - Dual DAC capability"] #[inline(always)] pub fn dual(&mut self) -> DUAL_W { DUAL_W { w: self } } #[doc = "Bits 4:7 - Pseudonoise wave generation capability"] #[inline(always)] pub fn lfsr(&mut self) -> LFSR_W { LFSR_W { w: self } } #[doc = "Bits 8:11 - Triangle wave generation capability"] #[inline(always)] pub fn triangle(&mut self) -> TRIANGLE_W { TRIANGLE_W { w: self } } #[doc = "Bits 12:15 - Sample and hold mode capability"] #[inline(always)] pub fn sample(&mut self) -> SAMPLE_W { SAMPLE_W { w: self } } #[doc = "Bits 16:23 - option register bit width"] #[inline(always)] pub fn or_cfg(&mut self) -> OR_CFG_W { OR_CFG_W { w: self } } }
use std::io::prelude::*; fn primes(n:i32) -> Vec<i32> { let mut t : Vec<i32> = (0..n).collect(); t[1] = 0; let mut p : usize = 2; let nn = n as usize; 'outer : while p < nn { 'inner : loop { if p >= nn { break 'outer } else if t[p] != 0 { break 'inner; } else { p = p + 1; } } let mut q = p * 2; while q < nn { t[q] = 0; q = q + p; } p = p + 1; } t.retain(|&x| x != 0); t } fn ans(n:i32, p:&Vec<i32>) -> i32 { let mut i = 0; for x in p.iter() { if *x > n { break; } i = i + 1; } i as i32 } fn main() { let p = primes(1000000); let stdin = std::io::stdin(); for line in stdin.lock().lines() { let d : i32 = line.unwrap().parse().unwrap(); let a = ans(d, &p); println!("{}",a); } }
//! FFI Bindings for Berkeley DB 4.8. extern crate libc; pub mod ffi;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IRemoteTextConnection(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRemoteTextConnection { type Vtable = IRemoteTextConnection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e7bb02a_183e_5e66_b5e4_3e6e5c570cf1); } #[repr(C)] #[doc(hidden)] pub struct IRemoteTextConnection_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, threadid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, threadid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pduData_array_size: u32, pdudata: *const u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IRemoteTextConnectionFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IRemoteTextConnectionFactory { type Vtable = IRemoteTextConnectionFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x88e075c2_0cae_596c_850f_78d345cd728b); } #[repr(C)] #[doc(hidden)] pub struct IRemoteTextConnectionFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, connectionid: ::windows::core::GUID, pduforwarder: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RemoteTextConnection(pub ::windows::core::IInspectable); impl RemoteTextConnection { #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn IsEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsEnabled(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn RegisterThread(&self, threadid: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), threadid).ok() } } pub fn UnregisterThread(&self, threadid: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), threadid).ok() } } pub fn ReportDataReceived(&self, pdudata: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), pdudata.len() as u32, ::core::mem::transmute(pdudata.as_ptr())).ok() } } pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, RemoteTextConnectionDataHandler>>(connectionid: Param0, pduforwarder: Param1) -> ::windows::core::Result<RemoteTextConnection> { Self::IRemoteTextConnectionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), connectionid.into_param().abi(), pduforwarder.into_param().abi(), &mut result__).from_abi::<RemoteTextConnection>(result__) }) } pub fn IRemoteTextConnectionFactory<R, F: FnOnce(&IRemoteTextConnectionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<RemoteTextConnection, IRemoteTextConnectionFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for RemoteTextConnection { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.System.RemoteDesktop.Input.RemoteTextConnection;{4e7bb02a-183e-5e66-b5e4-3e6e5c570cf1})"); } unsafe impl ::windows::core::Interface for RemoteTextConnection { type Vtable = IRemoteTextConnection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e7bb02a_183e_5e66_b5e4_3e6e5c570cf1); } impl ::windows::core::RuntimeName for RemoteTextConnection { const NAME: &'static str = "Windows.System.RemoteDesktop.Input.RemoteTextConnection"; } impl ::core::convert::From<RemoteTextConnection> for ::windows::core::IUnknown { fn from(value: RemoteTextConnection) -> Self { value.0 .0 } } impl ::core::convert::From<&RemoteTextConnection> for ::windows::core::IUnknown { fn from(value: &RemoteTextConnection) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<RemoteTextConnection> for ::windows::core::IInspectable { fn from(value: RemoteTextConnection) -> Self { value.0 } } impl ::core::convert::From<&RemoteTextConnection> for ::windows::core::IInspectable { fn from(value: &RemoteTextConnection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<RemoteTextConnection> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: RemoteTextConnection) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&RemoteTextConnection> for super::super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &RemoteTextConnection) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Foundation::IClosable> for &RemoteTextConnection { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for RemoteTextConnection {} unsafe impl ::core::marker::Sync for RemoteTextConnection {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct RemoteTextConnectionDataHandler(::windows::core::IUnknown); impl RemoteTextConnectionDataHandler { pub fn new<F: FnMut(&[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<bool> + 'static>(invoke: F) -> Self { let com = RemoteTextConnectionDataHandler_box::<F> { vtable: &RemoteTextConnectionDataHandler_box::<F>::VTABLE, count: ::windows::core::RefCount::new(1), invoke, }; unsafe { core::mem::transmute(::windows::core::alloc::boxed::Box::new(com)) } } pub fn Invoke(&self, pdudata: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).3)(::core::mem::transmute_copy(this), pdudata.len() as u32, ::core::mem::transmute(pdudata.as_ptr()), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for RemoteTextConnectionDataHandler { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"delegate({099ffbc8-8bcb-41b5-b056-57e77021bf1b})"); } unsafe impl ::windows::core::Interface for RemoteTextConnectionDataHandler { type Vtable = RemoteTextConnectionDataHandler_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x099ffbc8_8bcb_41b5_b056_57e77021bf1b); } #[repr(C)] #[doc(hidden)] pub struct RemoteTextConnectionDataHandler_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pduData_array_size: u32, pdudata: *const u8, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(C)] struct RemoteTextConnectionDataHandler_box<F: FnMut(&[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<bool> + 'static> { vtable: *const RemoteTextConnectionDataHandler_abi, invoke: F, count: ::windows::core::RefCount, } impl<F: FnMut(&[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<bool> + 'static> RemoteTextConnectionDataHandler_box<F> { const VTABLE: RemoteTextConnectionDataHandler_abi = RemoteTextConnectionDataHandler_abi(Self::QueryInterface, Self::AddRef, Self::Release, Self::Invoke); unsafe extern "system" fn QueryInterface(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; *interface = if iid == &<RemoteTextConnectionDataHandler as ::windows::core::Interface>::IID || iid == &<::windows::core::IUnknown as ::windows::core::Interface>::IID || iid == &<::windows::core::IAgileObject as ::windows::core::Interface>::IID { &mut (*this).vtable as *mut _ as _ } else { ::core::ptr::null_mut() }; if (*interface).is_null() { ::windows::core::HRESULT(0x8000_4002) } else { (*this).count.add_ref(); ::windows::core::HRESULT(0) } } unsafe extern "system" fn AddRef(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; (*this).count.add_ref() } unsafe extern "system" fn Release(this: ::windows::core::RawPtr) -> u32 { let this = this as *mut ::windows::core::RawPtr as *mut Self; let remaining = (*this).count.release(); if remaining == 0 { ::windows::core::alloc::boxed::Box::from_raw(this); } remaining } unsafe extern "system" fn Invoke(this: ::windows::core::RawPtr, pduData_array_size: u32, pdudata: *const u8, result__: *mut bool) -> ::windows::core::HRESULT { let this = this as *mut ::windows::core::RawPtr as *mut Self; match ((*this).invoke)(::core::slice::from_raw_parts(::core::mem::transmute_copy(&pdudata), pduData_array_size as _)) { ::core::result::Result::Ok(ok__) => { *result__ = ::core::mem::transmute_copy(&ok__); ::core::mem::forget(ok__); ::windows::core::HRESULT(0) } ::core::result::Result::Err(err) => err.into(), } } }
use defs::{FloatType, Vector3}; use core::{Ray, RayError, RayIntersection, ColorComponent}; use tools::{CompareWithTolerance}; use na; use na::{Rotation3, Unit}; #[derive(Debug)] pub enum RayPropagatorError { RayRelated(RayError), NoRefraction, NotRefractiveMaterial } pub struct RayPropagator<'intersection> { intersection: &'intersection RayIntersection, view_axis: Unit<Vector3> } impl<'intersection> RayPropagator<'intersection> { pub fn new(intersection: &'intersection RayIntersection) -> Self { let normal = intersection.get_normal_vector(); let view = intersection.get_view_direction(); let view_axis = normal.cross(&view); Self { intersection: intersection, view_axis: Unit::new_normalize(view_axis) } } pub fn get_mirrored_ray(&self) -> Result<Ray, RayPropagatorError> { let view = self.intersection.get_view_direction(); let normal = self.intersection.get_normal_vector(); let mirror_direction = -view + (normal * 2.0); Ray::continue_ray_from_intersection(self.intersection, mirror_direction).map_err(|ray_error| { match ray_error { RayError::DepthLimitReached => RayPropagatorError::RayRelated(ray_error), _ => panic!("RayPropagator encountered unhandleable RayError") } }) } pub fn get_refracted_ray_custom_index_ratio(&self, refractive_index_ratio: FloatType) -> Result<Ray, RayPropagatorError> { let view = self.intersection.get_view_direction(); let normal = self.intersection.get_normal_vector(); let cosa = normal.dot(&view); let rooted = 1.0-((1.0-cosa.powi(2)) / refractive_index_ratio.powi(2)); if rooted.greater_eq_eps(&0.0) { let refraction_direction = view * (-refractive_index_ratio.recip()) + normal * (cosa/refractive_index_ratio - rooted.sqrt()); Ray::continue_ray_from_intersection_into_medium(self.intersection, refraction_direction).map_err(|ray_error| { match ray_error { RayError::DepthLimitReached => RayPropagatorError::RayRelated(ray_error), _ => panic!("RayPropagator encountered unhandleable RayError") } }) } else { Err(RayPropagatorError::NoRefraction) } } pub fn get_transition_refraction_index(&self) -> Option<FloatType> { let target_material = self.intersection.get_material(); if target_material.is_refractive() { if let Some(source_material) = self.intersection.get_ray_medium() { let source_material_index = if source_material.is_refractive() { source_material.get_average_refractive_index().unwrap() } else { 1.0 }; let target_material_index = target_material.get_average_refractive_index().unwrap(); Some(target_material_index / source_material_index) } else { target_material.get_average_refractive_index() } } else { None } } pub fn get_transition_refraction_index_component(&self, component: ColorComponent) -> Option<FloatType> { let target_material = self.intersection.get_material(); if target_material.is_refractive() { if let Some(source_material) = self.intersection.get_ray_medium() { let source_material_index = if source_material.is_refractive() { source_material.get_refractive_index_for_component(component).unwrap() } else { 1.0 }; let target_material_index = target_material.get_refractive_index_for_component(component).unwrap(); Some(target_material_index / source_material_index) } else { target_material.get_refractive_index_for_component(component) } } else { None } } pub fn get_refracted_ray(&self) -> Result<Ray, RayPropagatorError> { if let Some(refractive_index) = self.get_transition_refraction_index() { self.get_refracted_ray_custom_index_ratio(refractive_index) } else { Err(RayPropagatorError::NotRefractiveMaterial) } } pub fn get_refracted_component_ray(&self, component: ColorComponent) -> Result<Ray, RayPropagatorError> { if let Some(refractive_index) = self.get_transition_refraction_index_component(component) { self.get_refracted_ray_custom_index_ratio(refractive_index) } else { Err(RayPropagatorError::NotRefractiveMaterial) } } pub fn get_diffuse_direction_vector(&self, angle_to_normal: FloatType, angle_to_view_direction: FloatType) -> Vector3 { let normal = self.intersection.get_normal_vector(); let view = self.intersection.get_view_direction(); let angle_to_rotate_view = na::angle(normal, &view) - angle_to_normal; let rotate_to_normal = Rotation3::from_axis_angle(&self.view_axis, angle_to_rotate_view); let rotate_around_normal = Rotation3::from_axis_angle(&Unit::new_unchecked(*normal), angle_to_view_direction); rotate_around_normal * rotate_to_normal * view } pub fn get_diffuse_direction_ray(&self, pitch: FloatType, yaw: FloatType) -> Result<Ray, RayPropagatorError> { Ray::continue_ray_from_intersection(self.intersection, self.get_diffuse_direction_vector(pitch, yaw)).map_err(|ray_error| { match ray_error { RayError::DepthLimitReached => RayPropagatorError::RayRelated(ray_error), _ => panic!("RayPropagator encountered unhandleable RayError") } }) } } #[cfg(test)] mod tests { use super::*; use defs::{Point3}; use core::{Material}; use na::{Unit}; use std::f64::consts::{PI}; #[test] fn diffuse_direction_vector() { let ray = Ray::new(Point3::new(1.0, 0.0, 1.0), Vector3::new(-1.0, 0.0, -1.0)); let intersection = RayIntersection::new(Vector3::new(0.0, 0.0, 1.0), Point3::new(0.0, 0.0, 0.0), &ray, Material::new_useless(), false).unwrap(); let propagator = RayPropagator::new(&intersection); assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/4.0, 0.0), Unit::new_normalize(Vector3::new(1.0, 0.0, 1.0)).unwrap()); assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, 0.0), Unit::new_normalize(Vector3::new((3.0*PI/8.0).tan(), 0.0, 1.0)).unwrap()); assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, PI/2.0), Unit::new_normalize(Vector3::new(0.0, (3.0*PI/8.0).tan(), 1.0)).unwrap()); assert_relative_eq!(propagator.get_diffuse_direction_vector(PI/8.0, PI), Unit::new_normalize(Vector3::new(-((3.0*PI/8.0).tan()), 0.0, 1.0)).unwrap()); } }
pub fn u32_in_range(val: u32, min: u32, max: u32) -> bool { val >= min && val <= max } pub fn valid_color_temp_range(model: &str) -> (u32, u32) { let devices = [("LB120", (2700, 6500)), ("LB130", (2500, 9000))] .iter() .filter(|(name, _)| model.contains(name)) .map(|(_, range)| *range) .collect::<Vec<_>>(); // TODO: Verify range before returning. devices[0] }
pub mod other { pub fn print_from_other(){ println!("Some text from a sub module") } }
use std::convert::TryInto; use std::panic; use hashbrown::HashMap; use liblumen_alloc::erts::exception::{self, badmap, ErlangException, RuntimeException}; use liblumen_alloc::erts::process::ffi::ErlangResult; use liblumen_alloc::erts::process::trace::Trace; use liblumen_alloc::erts::term::{binary, prelude::*}; use liblumen_core::sys::Endianness; use crate::process::current_process; #[export_name = "__lumen_builtin_raise/2"] pub extern "C" fn capture_and_raise(kind: Term, reason: Term) -> *mut ErlangException { let kind: Atom = kind.decode().unwrap().try_into().unwrap(); let trace = Trace::capture(); let exception = match kind.name() { "throw" => RuntimeException::Throw(exception::Throw::new(reason, trace, None)), "error" => RuntimeException::Error(exception::Error::new(reason, None, trace, None)), "exit" => RuntimeException::Exit(exception::Exit::new(reason, trace, None)), other => panic!("invalid exception kind: {}", &other), }; current_process().raise(exception) } #[export_name = "__lumen_builtin_raise/3"] pub extern "C" fn raise(kind: Term, reason: Term, trace: *mut Trace) -> *mut ErlangException { debug_assert!(!trace.is_null()); let trace = unsafe { Trace::from_raw(trace) }; let kind: Atom = kind.decode().unwrap().try_into().unwrap(); let exception = match kind.name() { "throw" => RuntimeException::Throw(exception::Throw::new(reason, trace, None)), "error" => RuntimeException::Error(exception::Error::new(reason, None, trace, None)), "exit" => RuntimeException::Exit(exception::Exit::new(reason, trace, None)), other => panic!("invalid exception kind: {}", &other), }; current_process().raise(exception) } #[export_name = "__lumen_build_stacktrace"] pub extern "C" fn capture_trace() -> *mut Trace { let trace = Trace::capture(); Trace::into_raw(trace) } #[export_name = "__lumen_stacktrace_to_term"] pub extern "C" fn trace_to_term(trace: *mut Trace) -> Term { if trace.is_null() { return Term::NIL; } let trace = unsafe { Trace::from_raw(trace) }; if let Ok(term) = trace.as_term() { term } else { Term::NIL } } #[export_name = "__lumen_cleanup_exception"] pub unsafe extern "C" fn cleanup(ptr: *mut ErlangException) { let _ = Box::from_raw(ptr); } #[export_name = "__lumen_builtin_bigint_from_cstr"] pub extern "C" fn builtin_bigint_from_cstr(ptr: *const u8, size: usize) -> Term { let bytes = unsafe { core::slice::from_raw_parts(ptr, size) }; let value = BigInteger::from_bytes(bytes).unwrap(); current_process().integer(value) } #[export_name = "__lumen_builtin_map.new"] pub extern "C" fn builtin_map_new() -> Term { current_process().map_from_hash_map(HashMap::default()) } #[export_name = "__lumen_builtin_map.insert"] pub extern "C" fn builtin_map_insert(map: Term, key: Term, value: Term) -> ErlangResult { let decoded_map: Result<Boxed<Map>, _> = map.decode().unwrap().try_into(); if let Ok(m) = decoded_map { if let Some(new_map) = m.put(key, value) { ErlangResult::ok(current_process().map_from_hash_map(new_map)) } else { ErlangResult::ok(map) } } else { let arc_process = current_process(); let exception = badmap(&arc_process, map, Trace::capture(), None); ErlangResult::error(arc_process.raise(exception)) } } #[export_name = "__lumen_builtin_map.update"] pub extern "C" fn builtin_map_update(map: Term, key: Term, value: Term) -> Term { let decoded_map: Result<Boxed<Map>, _> = map.decode().unwrap().try_into(); if let Ok(m) = decoded_map { if let Some(new_map) = m.update(key, value) { current_process().map_from_hash_map(new_map) } else { // TODO: Trigger badkey error Term::NONE } } else { Term::NONE } } #[export_name = "__lumen_builtin_map.is_key"] pub extern "C" fn builtin_map_is_key(map: Term, key: Term) -> bool { let decoded_map: Result<Boxed<Map>, _> = map.decode().unwrap().try_into(); let m = decoded_map.unwrap(); m.is_key(key) } #[export_name = "__lumen_builtin_map.get"] pub extern "C" fn builtin_map_get(map: Term, key: Term) -> Term { let decoded_map: Result<Boxed<Map>, _> = map.decode().unwrap().try_into(); let m = decoded_map.unwrap(); m.get(key).unwrap_or(Term::NONE) } #[export_name = "__lumen_builtin_fatal_error"] pub extern "C" fn builtin_fatal_error() -> ! { core::intrinsics::abort(); } /// Binary Construction #[export_name = "__lumen_builtin_binary_start"] pub extern "C" fn builtin_binary_start() -> *mut BinaryBuilder { let builder = Box::new(BinaryBuilder::new()); Box::into_raw(builder) } #[export_name = "__lumen_builtin_binary_finish"] pub extern "C" fn builtin_binary_finish(builder: *mut BinaryBuilder) -> Term { let builder = unsafe { Box::from_raw(builder) }; let bytes = builder.finish(); current_process().binary_from_bytes(bytes.as_slice()) } #[export_name = "__lumen_builtin_binary_push_integer"] pub extern "C" fn builtin_binary_push_integer( builder: &mut BinaryBuilder, value: Term, size: Term, unit: u8, signed: bool, endianness: Endianness, ) -> BinaryPushResult { let tt = value.decode().unwrap(); let val: Result<Integer, _> = tt.try_into(); let result = if let Ok(i) = val { let flags = BinaryPushFlags::new(signed, endianness); let bit_size = calculate_bit_size(size, unit, flags).unwrap(); builder.push_integer(i, bit_size, flags) } else { Err(()) }; BinaryPushResult { builder, success: result.is_ok(), } } #[export_name = "__lumen_builtin_binary_push_float"] pub extern "C" fn builtin_binary_push_float( builder: &mut BinaryBuilder, value: Term, size: Term, unit: u8, signed: bool, endianness: Endianness, ) -> BinaryPushResult { let tt = value.decode().unwrap(); let val: Result<Float, _> = tt.try_into(); let result = if let Ok(f) = val { let flags = BinaryPushFlags::new(signed, endianness); let bit_size = calculate_bit_size(size, unit, flags).unwrap(); builder.push_float(f.into(), bit_size, flags) } else { Err(()) }; BinaryPushResult { builder, success: result.is_ok(), } } #[export_name = "__lumen_builtin_binary_push_utf8"] pub extern "C" fn builtin_binary_push_utf8( builder: &mut BinaryBuilder, value: Term, ) -> BinaryPushResult { let tt = value.decode().unwrap(); let val: Result<SmallInteger, _> = tt.try_into(); let result = if let Ok(small) = val { builder.push_utf8(small.into()) } else { Err(()) }; BinaryPushResult { builder, success: result.is_ok(), } } #[export_name = "__lumen_builtin_binary_push_utf16"] pub extern "C" fn builtin_binary_push_utf16( builder: &mut BinaryBuilder, value: Term, signed: bool, endianness: Endianness, ) -> BinaryPushResult { let tt = value.decode().unwrap(); let val: Result<SmallInteger, _> = tt.try_into(); let result = if let Ok(small) = val { let flags = BinaryPushFlags::new(signed, endianness); builder.push_utf16(small.into(), flags) } else { Err(()) }; BinaryPushResult { builder, success: result.is_ok(), } } #[export_name = "__lumen_builtin_binary_push_utf32"] pub extern "C" fn builtin_binary_push_utf32( builder: &mut BinaryBuilder, value: Term, size: Term, unit: u8, signed: bool, endianness: Endianness, ) -> BinaryPushResult { let tt = value.decode().unwrap(); let result: Result<SmallInteger, _> = tt.try_into(); if let Ok(small) = result { let i: isize = small.into(); if i > 0x10FFFF || (0xD800 <= i && i <= 0xDFFF) { // Invalid utf32 integer return BinaryPushResult { builder, success: false, }; } let flags = BinaryPushFlags::new(signed, endianness); let bit_size = calculate_bit_size(size, unit, flags).unwrap(); let success = builder.push_integer(small.into(), bit_size, flags).is_ok(); BinaryPushResult { builder, success } } else { BinaryPushResult { builder, success: false, } } } #[export_name = "__lumen_builtin_binary_push_byte_size_unit"] pub extern "C" fn builtin_binary_push_byte_size_unit( _builder: &mut BinaryBuilder, _value: Term, _size: Term, _unit: u8, ) -> BinaryPushResult { unimplemented!() } #[export_name = "__lumen_builtin_binary_push_byte_unit"] pub extern "C" fn builtin_binary_push_byte_unit( builder: &mut BinaryBuilder, value: Term, unit: u8, ) -> BinaryPushResult { BinaryPushResult { builder, success: builder.push_byte_unit(value, unit).is_ok(), } } #[export_name = "__lumen_builtin_binary_push_bits_size_unit"] pub extern "C" fn builtin_binary_push_bits_size_unit( _builder: &mut BinaryBuilder, _value: Term, _size: Term, _unit: u8, ) -> BinaryPushResult { unimplemented!(); } #[export_name = "__lumen_builtin_binary_push_bits_unit"] pub extern "C" fn builtin_binary_push_bits_unit( builder: &mut BinaryBuilder, value: Term, unit: u8, ) -> BinaryPushResult { BinaryPushResult { builder, success: builder.push_bits_unit(value, unit).is_ok(), } } #[export_name = "__lumen_builtin_binary_push_string"] pub extern "C" fn builtin_binary_push_string( builder: &mut BinaryBuilder, buffer: *const u8, len: usize, ) -> BinaryPushResult { let bytes = unsafe { core::slice::from_raw_parts(buffer, len) }; let success = builder.push_string(bytes).is_ok(); BinaryPushResult { builder, success } } #[export_name = "__lumen_builtin_binary_match.raw"] pub extern "C" fn builtin_binary_match_raw(bin: Term, unit: u8, size: Term) -> BinaryMatchResult { let size_opt = if size.is_none() { None } else { let size_decoded: Result<SmallInteger, _> = size.decode().unwrap().try_into(); // TODO: Should throw badarg let size: usize = size_decoded.unwrap().try_into().unwrap(); Some(size) }; let result = match bin.decode().unwrap() { TypedTerm::HeapBinary(bin) => binary::matcher::match_raw(bin, unit, size_opt), TypedTerm::ProcBin(bin) => binary::matcher::match_raw(bin, unit, size_opt), TypedTerm::BinaryLiteral(bin) => binary::matcher::match_raw(bin, unit, size_opt), TypedTerm::SubBinary(bin) => binary::matcher::match_raw(bin, unit, size_opt), TypedTerm::MatchContext(bin) => binary::matcher::match_raw(bin, unit, size_opt), _ => Err(()), }; result.unwrap_or_else(|_| BinaryMatchResult::failed()) } #[export_name = "__lumen_builtin_binary_match.integer"] pub extern "C" fn builtin_binary_match_integer( _bin: Term, _signed: bool, _endianness: Endianness, _unit: u8, _size: Term, ) -> BinaryMatchResult { unimplemented!() } #[export_name = "__lumen_builtin_binary_match.float"] pub extern "C" fn builtin_binary_match_float( _bin: Term, _endianness: Endianness, _unit: u8, _size: Term, ) -> BinaryMatchResult { unimplemented!() } #[export_name = "__lumen_builtin_binary_match.utf8"] pub extern "C" fn builtin_binary_match_utf8(_bin: Term, _size: Term) -> BinaryMatchResult { unimplemented!() } #[export_name = "__lumen_builtin_binary_match.utf16"] pub extern "C" fn builtin_binary_match_utf16( _bin: Term, _endianness: Endianness, _size: Term, ) -> BinaryMatchResult { unimplemented!() } #[export_name = "__lumen_builtin_binary_match.utf32"] pub extern "C" fn builtin_binary_match_utf32( _bin: Term, _endianness: Endianness, _size: Term, ) -> BinaryMatchResult { unimplemented!(); }
use crate::AUCTIONS; use rust_decimal::Decimal; use shylock_data::types::Asset; use yew::prelude::*; use yewtil::NeqAssign; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub position: usize, pub asset: &'static Asset, } pub struct AssetView { props: Props, // link: ComponentLink<Self>, } impl Component for AssetView { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> ShouldRender { false } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props.neq_assign(props) } fn view(&self) -> Html { match self.props.asset { Asset::Property(property) => html! { <div key=self.props.position.to_string() class="asset_container"> <div class="asset_name">{&property.description}</div> <div class="asset_auction">{get_valuation(&property.auction_id)}</div> </div> }, Asset::Vehicle(vehicle) => html! { <div key=self.props.position.to_string() class="asset_container"> <div class="asset_name">{&vehicle.description}</div> <div class="asset_auction">{get_valuation(&vehicle.auction_id)}</div> </div> }, Asset::Other(other) => html! { <div key=self.props.position.to_string() class="asset_container"> <div class="asset_name">{&other.description}</div> <div class="asset_auction">{get_valuation(&other.auction_id)}</div> </div> }, } } } fn get_valuation(auction_id: &str) -> &Decimal { &AUCTIONS.get().unwrap().get(auction_id).unwrap().value }
#[doc = "Reader of register RDATA13R"] pub type R = crate::R<u32, super::RDATA13R>; #[doc = "Reader of field `RDATA3`"] pub type RDATA3_R = crate::R<u16, u16>; #[doc = "Reader of field `RDATA1`"] pub type RDATA1_R = crate::R<u16, u16>; impl R { #[doc = "Bits 16:31 - Regular conversion data for SDADC3"] #[inline(always)] pub fn rdata3(&self) -> RDATA3_R { RDATA3_R::new(((self.bits >> 16) & 0xffff) as u16) } #[doc = "Bits 0:15 - Regular conversion data for SDADC1"] #[inline(always)] pub fn rdata1(&self) -> RDATA1_R { RDATA1_R::new((self.bits & 0xffff) as u16) } }
/// /// 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 /// /// 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 /// /// 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 /// /// 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 /// /// 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 /// /// 在任何情况下,若函数不能进行有效的转换时,请返回 0。 /// /// 说明: /// /// 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231, 231 − 1]。如果数值超过这个范围,qing返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。 /// /// 示例 1: /// /// 输入: "42" /// 输出: 42 /// /// 示例 2: /// /// 输入: " -42" /// 输出: -42 /// 解释: 第一个非空白字符为 '-', 它是一个负号。 /// 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 /// /// 示例 3: /// /// 输入: "4193 with words" /// 输出: 4193 /// 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 /// /// 示例 4: /// /// 输入: "words and 987" /// 输出: 0 /// 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 /// 因此无法执行有效的转换。 /// /// 示例 5: /// /// 输入: "-91283472332" /// 输出: -2147483648 /// 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 /// 因此返回 INT_MIN (−231) 。 /// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] enum State { Init, Sign, NumBeg, } pub fn my_atoi(str: String) -> i32 { let mut state = State::Init; let mut beg_pos = 0; let mut end_pos = 0; let mut s = str.trim().to_string(); for (i, c) in s.char_indices() { match c { '0'..='9' => { if state == State::Init { state = State::NumBeg; beg_pos = i; end_pos = i + 1; } else if state == State::Sign { state = State::NumBeg; end_pos = i + 1; } else if state == State::NumBeg { end_pos = i + 1; } else { return 0; } } '-'=> { if state == State::Init { state = State::Sign; beg_pos = i; end_pos = i + 1; } else if state == State::NumBeg { end_pos = i; break } else { return 0; } } '+' => { if state == State::Init { state = State::Sign; beg_pos = i; end_pos = i + 1; } else if state == State::NumBeg { end_pos = i; break } else { return 0; } } _ => { if state == State::NumBeg { end_pos = i; break } else { return 0; } } } } s.split_off(end_pos); s = s.split_off(beg_pos); // println!("beg_pos = {}, end_pos = {}, s = {}", beg_pos, end_pos, s); if s.len() == 0 { return 0; } let overflow = "1231123123123123".parse::<u32>().err().unwrap(); let underflow = "-1231123123123123".parse::<i32>().err().unwrap(); // println!("min_value = {}, max_value = {}", i32::min_value(), i32::max_value()); let result = match s.parse::<i32>() { Ok(result) => result, Err(ref e) if *e == overflow => i32::max_value(), Err(ref e) if *e == underflow => i32::min_value(), _ => {0}, }; // println!("result = {}", result); result as i32 } #[cfg(test)] mod test { use super::my_atoi; #[test] fn test_my_atoi() { assert_eq!(my_atoi("-5-".to_string()), -5); assert_eq!(my_atoi("+".to_string()), 0); assert_eq!(my_atoi("+1".to_string()), 1); assert_eq!(my_atoi("42".to_string()), 42); assert_eq!(my_atoi("9223372036854775808".to_string()), 2147483647); assert_eq!(my_atoi("-91283472332".to_string()), -2147483648); assert_eq!(my_atoi("3.14159".to_string()), 3); assert_eq!(my_atoi("4193 with words".to_string()), 4193); } }
#[allow(unused_imports)] use proconio::{marker::*, *}; use std::collections::{HashMap, HashSet}; #[allow(unused_imports)] use std::{cmp::Ordering, convert::TryInto}; #[fastout] fn main() { input! { n: usize, m: usize, mut h: i32, k: i32, s: Chars, mut items: [(i32, i32); m], } let mut can_consume = HashSet::new(); for item in items { can_consume.insert(item); } let mut p = (0, 0); for i in 0..n { h -= 1; match s[i] { 'R' => { p.0 += 1 }, 'L' => { p.0 -= 1 }, 'U' => { p.1 += 1 }, 'D' => { p.1 -= 1 }, _ => unreachable!(), } if h < 0 { println!("No"); return; } else { if can_consume.contains(&p) { if h < k { can_consume.remove(&p); h = k; } } } } println!("Yes"); } pub trait CumlativeSum { /// 累積和を取る /// 返り値の先頭要素は番兵の 0 である。 fn cumlative_sum(&self) -> Self; /// in-place に累積和を取る fn cumlative_sum_in_place(&mut self) -> &Self; } impl CumlativeSum for Vec<i32> { fn cumlative_sum(&self) -> Self { let mut s = vec![0; self.len() + 1]; for (i, v) in self.iter().enumerate() { s[i + 1] = s[i] + v; } s } fn cumlative_sum_in_place(&mut self) -> &Self { let mut prev = *self.get(0).unwrap(); for v in self.iter_mut().skip(1) { *v += prev; prev = *v; } self } } impl CumlativeSum for Vec<Vec<i32>> { fn cumlative_sum(&self) -> Self { let h = self.len() as usize; let w = self.get(0).unwrap().len() as usize; let mut s = Vec::with_capacity(h + 1); s.push(vec![0; w + 1]); // 横方向合計 for xs in self.iter() { s.push(xs.cumlative_sum()); } // 縦方向合計 for c in 1..=w { for r in 1..=h { s[r][c] += s[r - 1][c]; } } s } fn cumlative_sum_in_place(&mut self) -> &Self { let h = self.len() as usize; let w = self.get(0).unwrap().len() as usize; // 横方向合計 for xs in self.iter_mut() { xs.cumlative_sum_in_place(); } // 縦方向合計 for c in 0..w { for r in 1..h { self[r][c] += self[r - 1][c]; } } self } }
use crate::file_util::read_non_blank_lines; use crate::day_eleven::Seat::{TAKEN, EMPTY, FLOOR}; #[derive(Debug, Eq, PartialEq, Clone)] enum Seat { TAKEN, EMPTY, FLOOR } trait SafeGet<'a, T> { fn safe_get(self, index: isize) -> Option<&'a T>; } impl <'a, T> SafeGet<'a, T> for &'a [T] { fn safe_get(self, index: isize) -> Option<&'a T> { if index < 0 { None } else { self.get(index as usize) } } } #[allow(dead_code)] pub fn run_day_eleven() { let mut rows = read_non_blank_lines("assets/day_eleven"); let first_row = rows.by_ref().next().unwrap(); let row_width = first_row.len(); let mut seats = first_row.chars() .chain(rows.flat_map(|line| line.chars().collect::<Vec<char>>().into_iter())) .map(|seat| match seat { 'L' => EMPTY, '#' => TAKEN, _ => FLOOR }) .collect::<Vec<Seat>>(); let mut seats_part_2 = seats.clone(); let mut revisions = 0; while revise_seats(row_width, 3, &mut seats, get_adjacent_seats) { revisions += 1; } println!( "Part 1 seats taken {} after {} revisions", seats.iter().filter(|x| **x == TAKEN).count(), revisions ); revisions = 0; while revise_seats(row_width, 4, &mut seats_part_2, get_non_floor_adjacent_seats) { revisions += 1; } println!( "Part 2 seats taken {} after {} revisions", seats_part_2.iter().filter(|x| **x == TAKEN).count(), revisions ) } fn revise_seats( row_width: usize, max_taken: usize, seats: &mut[Seat], adjacent_seat_resolver: impl Fn(usize, usize, &[Seat]) -> [Option<&Seat>; 8] ) -> bool { let mut changes = Vec::new(); for index in 0..seats.len() { if seats[index] == EMPTY && !is_any_taken(&adjacent_seat_resolver(index, row_width, &seats)){ changes.push((index, TAKEN)); } else if seats[index] == TAKEN && number_taken(&adjacent_seat_resolver(index, row_width, &seats)) > max_taken { changes.push((index, EMPTY)); } } let changed = !changes.is_empty(); for (index, change) in changes.into_iter() { seats[index] = change; } changed } fn number_taken(seats: &[Option<&Seat>]) -> usize { seats.iter().filter(|x| if let Some(seat) = x { **seat == TAKEN } else { false } ).count() } fn is_any_taken(seats: &[Option<&Seat>]) -> bool { seats .iter() .any(|x| if let Some(seat) = x { **seat == TAKEN } else { false } ) } fn find_non_floor_seat(mut index: isize, row_width: isize, seats: &[Seat], direction: impl Fn(isize, isize) -> Option<isize>) -> Option<&Seat> { while let Some(seat_location) = direction(index, row_width) { let seat = seats.safe_get(seat_location); if match seat { Some(x) => *x != FLOOR, None => true } { return seat } index = seat_location; } None } fn on_left(index: isize, row_width: isize) -> bool { index % row_width == 0 } fn on_right(index: isize, row_width: isize) -> bool { (index + 1) % row_width == 0 } fn get_top_left_index(i: isize, row_width: isize) -> Option<isize> { if on_left(i, row_width) { None } else { Some(i - row_width - 1) } } fn get_top_right_index(i: isize, row_width: isize) -> Option<isize> { if on_right(i, row_width) { None } else { Some(i - row_width + 1) } } fn get_top_middle_index(i: isize, row_width: isize) -> Option<isize> { Some(i - row_width) } fn get_left_index(i: isize, row_width: isize) -> Option<isize> { if on_left(i, row_width) { None } else { Some(i - 1) } } fn get_right_index(i: isize, row_width: isize) -> Option<isize> { if on_right(i, row_width) { None } else { Some(i + 1) } } fn get_bottom_left_index(i: isize, row_width: isize) -> Option<isize> { if on_left(i, row_width) { None } else { Some(i + row_width - 1) } } fn get_bottom_middle_index(i: isize, row_width: isize) -> Option<isize> { Some(i + row_width) } fn get_bottom_right_index(i: isize, row_width: isize) -> Option<isize> { if on_right(i, row_width) { None } else { Some(i + row_width + 1) } } fn get_non_floor_adjacent_seats(index: usize, row_width: usize, seats: &[Seat]) -> [Option<&Seat>; 8] { let index = index as isize; let row_width = row_width as isize; return [ find_non_floor_seat(index, row_width, &seats, get_top_left_index), find_non_floor_seat(index, row_width, &seats, get_top_middle_index), find_non_floor_seat(index, row_width, &seats, get_top_right_index), find_non_floor_seat(index, row_width, &seats, get_left_index), find_non_floor_seat(index, row_width, &seats, get_right_index), find_non_floor_seat(index, row_width, &seats, get_bottom_left_index), find_non_floor_seat(index, row_width, &seats, get_bottom_middle_index), find_non_floor_seat(index, row_width, &seats, get_bottom_right_index) ]; } fn retrieve(maybe_index: Option<isize>, seats: &[Seat]) -> Option<&Seat> { maybe_index.and_then(|i| seats.safe_get(i)) } fn get_adjacent_seats(index: usize, row_width: usize, seats: &[Seat]) -> [Option<&Seat>; 8] { let index = index as isize; let row_width = row_width as isize; return [ retrieve(get_top_left_index(index, row_width), &seats), retrieve(get_top_middle_index(index, row_width), &seats), retrieve(get_top_right_index(index, row_width), &seats), retrieve(get_left_index(index, row_width), &seats), retrieve(get_right_index(index, row_width), &seats), retrieve(get_bottom_left_index(index, row_width), &seats), retrieve(get_bottom_middle_index(index, row_width), &seats), retrieve(get_bottom_right_index(index, row_width), &seats) ]; } #[cfg(test)] mod tests { use crate::day_eleven::*; #[test] fn should_get_seat_positions() { let under_test = [ TAKEN, EMPTY, TAKEN, EMPTY, TAKEN, FLOOR, TAKEN, FLOOR, TAKEN, EMPTY, TAKEN, EMPTY, EMPTY, EMPTY, FLOOR, EMPTY, ]; assert_eq!( get_adjacent_seats(9, 4, &under_test), [ Some(&under_test[4]), Some(&under_test[5]), Some(&under_test[6]), Some(&under_test[8]), Some(&under_test[10]), Some(&under_test[12]), Some(&under_test[13]), Some(&under_test[14]) ] ); assert_eq!( get_adjacent_seats(4, 4, &under_test), [ None, Some(&under_test[0]), Some(&under_test[1]), None, Some(&under_test[5]), None, Some(&under_test[8]), Some(&under_test[9]) ] ); assert_eq!( get_adjacent_seats(7, 4, &under_test), [ Some(&under_test[2]), Some(&under_test[3]), None, Some(&under_test[6]), None, Some(&under_test[10]), Some(&under_test[11]), None ] ); } #[test] fn should_get_seat_positions_part_2() { let under_test = [ TAKEN, EMPTY, TAKEN, EMPTY, TAKEN, FLOOR, TAKEN, FLOOR, TAKEN, EMPTY, TAKEN, EMPTY, EMPTY, EMPTY, FLOOR, EMPTY, ]; assert_eq!( get_non_floor_adjacent_seats(9, 4, &under_test), [ Some(&under_test[4]), Some(&under_test[1]), Some(&under_test[6]), Some(&under_test[8]), Some(&under_test[10]), Some(&under_test[12]), Some(&under_test[13]), None ] ); } }
mod heap; mod iter; mod process_heap_alloc; mod semispace; mod stack_alloc; mod stack_primitives; mod term_alloc; mod virtual_alloc; mod virtual_binary_heap; pub use self::heap::{Heap, HeapAlloc}; pub use self::iter::HeapIter; pub use self::process_heap_alloc::ProcessHeapAlloc; pub use self::semispace::{GenerationalHeap, SemispaceHeap}; pub use self::stack_alloc::StackAlloc; pub use self::stack_primitives::StackPrimitives; pub use self::term_alloc::TermAlloc; pub use self::virtual_alloc::{VirtualAlloc, VirtualAllocator, VirtualHeap}; pub use self::virtual_binary_heap::VirtualBinaryHeap; use core::alloc::{AllocError, Layout}; use core::ffi::c_void; use core::mem::transmute; use core::ptr::{self, NonNull}; use lazy_static::lazy_static; use crate::erts::apply::DynamicCallee; use crate::erts::exception::AllocResult; use crate::erts::term::prelude::Term; use super::Frame; pub const DEFAULT_STACK_SIZE: usize = 1; // 1 page pub const STACK_ALIGNMENT: usize = 16; // The global process heap allocator lazy_static! { static ref PROC_ALLOC: ProcessHeapAlloc = ProcessHeapAlloc::new(); } pub struct Stack { pub base: *mut u8, pub top: *mut u8, pub size: usize, pub end: *mut u8, } impl Stack { fn new(base: *mut u8, pages: usize) -> Self { use liblumen_core::alloc::utils::align_up_to; use liblumen_core::sys::sysconf; let page_size = sysconf::pagesize(); let size = (pages + 1) * page_size; // The bottom is where the guard page begins (remember: stack grows downwards) let bottom = unsafe { base.offset(page_size as isize) }; // We add some reserved space, called red zone, at the bottom of the stack. // The starting address of the red zone is also the "end" of the usable stack let with_red_zone = unsafe { bottom.offset(128) }; let end = align_up_to(with_red_zone, STACK_ALIGNMENT); // The start, or top, of the stack is given by offsetting our base by the size // of the entire mapped region let top = unsafe { base.offset(size as isize) }; Self { base, top, size, end, } } pub unsafe fn push_frame(&mut self, frame: &Frame) { let symbol = frame.native().ptr(); let dynamic_callee = transmute::<*const c_void, DynamicCallee>(symbol); self.push64(dynamic_callee as u64) } pub unsafe fn push64(&mut self, value: u64) { let mut top64 = self.top as *mut u64; top64 = top64.offset(-1); top64.write(value); self.top = top64 as *mut u8; } #[inline] pub fn limit(&self) -> *mut u8 { self.end } #[inline] pub fn is_guard_page<T>(&self, addr: *mut T) -> bool { use liblumen_core::util::pointer::in_area_inclusive; in_area_inclusive(addr, self.base, self.end) } } impl Default for Stack { fn default() -> Self { Self { base: ptr::null_mut(), top: ptr::null_mut(), size: 0, end: ptr::null_mut(), } } } /// This can be safely marked Sync when used in Process; /// this is because the stack metadata is only ever accessed /// by the executing process. unsafe impl Sync for Stack {} impl Drop for Stack { fn drop(&mut self) { use liblumen_core::alloc::mmap; use liblumen_core::sys::sysconf; if self.base.is_null() { return; } let page_size = sysconf::pagesize(); let pages = (self.size / page_size) - 1; let (layout, _offset) = Layout::from_size_align(page_size, page_size) .unwrap() .repeat(pages) .unwrap(); unsafe { mmap::unmap(self.base, layout); } } } /// Allocate a new default-sized process heap #[inline] pub fn default_heap() -> AllocResult<(*mut Term, usize)> { let size = default_heap_size(); PROC_ALLOC.alloc(size).map(|ptr| (ptr, size)) } /// Returns the default heap size for a process heap pub fn default_heap_size() -> usize { ProcessHeapAlloc::HEAP_SIZES[ProcessHeapAlloc::MIN_HEAP_SIZE_INDEX] } /// Allocate a new process heap of the given size #[inline] pub fn heap(size: usize) -> AllocResult<*mut Term> { PROC_ALLOC.alloc(size) } /// Allocate a new process stack of the given size (in pages) #[inline] pub fn stack(num_pages: usize) -> AllocResult<Stack> { use liblumen_core::alloc::mmap; debug_assert!(num_pages > 0, "stack size in pages must be greater than 0"); let ptr = unsafe { mmap::map_stack(num_pages)? }; Ok(Stack::new(ptr.as_ptr(), num_pages)) } /// Shrink a process heap /// /// If reallocating and trying to grow the heap, if the allocation cannot be done /// in place, then `Err(AllocError)` will be returned #[inline] pub unsafe fn shrink( heap: NonNull<Term>, old_size: usize, new_size: usize, ) -> Result<NonNull<Term>, AllocError> { PROC_ALLOC.shrink(heap, old_size, new_size) } /// Deallocate a heap previously allocated via `heap` #[inline] pub unsafe fn free(heap: *mut Term, size: usize) { PROC_ALLOC.dealloc(heap, size) } /// Calculates the next largest heap size equal to or greater than `size` #[inline] pub fn next_heap_size(size: usize) -> usize { ProcessHeapAlloc::next_heap_size(size) }
use std::fmt; use std::fmt::{Display, Formatter}; use std::time::{Duration, Instant}; pub struct Bench { name: String, pub loops: usize, pub ops: usize, start: Instant, duration: Duration, speed_factor: Option<f32>, } impl Bench { pub fn new(name: &str) -> Bench { Bench { name: String::from(name), loops: 0, ops: 0, start: Instant::now(), duration: Duration::from_secs(0), speed_factor: None, } } pub fn with_speed(name: &str, speed_factor: f32) -> Bench { Bench { name: String::from(name), loops: 0, ops: 0, start: Instant::now(), duration: Duration::from_secs(0), speed_factor: Some(speed_factor), } } pub fn speed(&self) -> f32 { self.ops as f32 / self.duration.as_secs_f32() } pub fn inc_bench(&mut self, other: &Bench) { self.inc(other.ops); } pub fn inc(&mut self, value: usize) { self.ops += value; } pub fn for_iterations(&mut self, limit: usize) -> bool { self.until_condition(self.loops >= limit) } pub fn for_duration(&mut self, time_limit: Duration) -> bool { self.until_condition(self.duration >= time_limit) } pub fn until_condition(&mut self, finished: bool) -> bool { self.duration = self.start.elapsed(); if !finished { self.loops += 1; } !finished } } impl Drop for Bench { fn drop(&mut self) { if self.ops == 0 { self.ops = self.loops; } println!("Bench: {}", self) } } impl Display for Bench { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let speed = self.speed() * self.speed_factor.unwrap_or(1.); write!( f, "{}\n\ Speed: {} ops {:?}\n\ {} op/sec\n\ {} op/hour", self.name, self.ops, self.duration, (speed) as u32, (3600. * speed) as u32 ) } } #[test] fn test_bench() { let mut cpt = 0; let mut bench = Bench::new("Testing Bench"); let mut i = 0; while bench.for_duration(Duration::from_millis(60)) { let mut round = Bench::new(&format!("Round-{}", i)); while round.for_duration(Duration::from_millis(60)) { cpt += 3; round.inc(1); } bench.inc_bench(&round); i += 1; } }
use std::future::Future; pub trait Executor { type Item; fn run(&self) -> Vec<Self::Item>; } pub struct MyExecutor; #[cfg(feature = "string-exec")] pub mod string_executor; #[cfg(feature = "num-exec")] pub mod number_executor;
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The api module only used for internal communication, such as GRPC between cluster and the managed HTTP REST API. pub use http_service::HttpService; pub use rpc::serialize_block; pub use rpc::BroadcastExchange; pub use rpc::BroadcastFlightScatter; pub use rpc::ConnectionInfo; pub use rpc::DataExchange; pub use rpc::DataExchangeManager; pub use rpc::DataPacket; pub use rpc::DatabendQueryFlightService; pub use rpc::DefaultExchangeInjector; pub use rpc::ExchangeDeserializeMeta; pub use rpc::ExchangeInjector; pub use rpc::ExchangeSerializeMeta; pub use rpc::ExchangeShuffleMeta; pub use rpc::ExchangeSorting; pub use rpc::ExecutePartialQueryPacket; pub use rpc::FlightAction; pub use rpc::FlightClient; pub use rpc::FlightScatter; pub use rpc::FragmentData; pub use rpc::FragmentPlanPacket; pub use rpc::HashFlightScatter; pub use rpc::InitNodesChannelPacket; pub use rpc::MergeExchange; pub use rpc::MergeExchangeParams; pub use rpc::PrecommitBlock; pub use rpc::QueryFragmentsPlanPacket; pub use rpc::ShuffleDataExchange; pub use rpc::ShuffleExchangeParams; pub use rpc::TransformExchangeDeserializer; pub use rpc_service::RpcService; pub mod http; mod http_service; mod rpc; mod rpc_service;
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Common utilities used by both directory and file traits. use { fidl::endpoints::ServerEnd, fidl_fuchsia_io::{ NodeMarker, CLONE_FLAG_SAME_RIGHTS, OPEN_FLAG_APPEND, OPEN_FLAG_DESCRIBE, OPEN_FLAG_NODE_REFERENCE, OPEN_RIGHT_ADMIN, OPEN_RIGHT_READABLE, OPEN_RIGHT_WRITABLE, }, fuchsia_zircon::Status, std::{future::Future, pin::Pin}, }; /// A dynamically-dispatched asynchronous function. pub(crate) type AsyncFnOnce<'a, ArgTy, OutputTy> = Box<dyn FnOnce(ArgTy) -> Pin<Box<dyn Future<Output = OutputTy> + 'a>> + 'a>; /// Set of known rights. const FS_RIGHTS: u32 = OPEN_RIGHT_READABLE | OPEN_RIGHT_WRITABLE | OPEN_RIGHT_ADMIN; /// Returns true if the rights flags in `flags` do not exceed those in `parent_flags`. pub fn stricter_or_same_rights(parent_flags: u32, flags: u32) -> bool { let parent_rights = parent_flags & FS_RIGHTS; let rights = flags & FS_RIGHTS; return (rights & !parent_rights) == 0; } /// Common logic for rights processing during cloning a node, shared by both file and directory /// implementations. pub fn inherit_rights_for_clone(parent_flags: u32, mut flags: u32) -> Result<u32, Status> { if (flags & CLONE_FLAG_SAME_RIGHTS != 0) && (flags & FS_RIGHTS != 0) { return Err(Status::INVALID_ARGS); } // We preserve OPEN_FLAG_APPEND as this is what is the most convenient for the POSIX emulation. // // OPEN_FLAG_NODE_REFERENCE is enforced, according to our current FS permissions design. flags |= parent_flags & (OPEN_FLAG_APPEND | OPEN_FLAG_NODE_REFERENCE); // If CLONE_FLAG_SAME_RIGHTS is requested, cloned connection will inherit the same rights // as those from the originating connection. We have ensured that no FS_RIGHTS flags are set // above. if flags & CLONE_FLAG_SAME_RIGHTS != 0 { flags &= !CLONE_FLAG_SAME_RIGHTS; flags |= parent_flags & FS_RIGHTS; } if !stricter_or_same_rights(parent_flags, flags) { return Err(Status::ACCESS_DENIED); } Ok(flags) } /// A helper method to send OnOpen event on the handle owned by the `server_end` in case `flags` /// contains `OPEN_FLAG_STATUS`. /// /// If the send operation fails for any reason, the error is ignored. This helper is used during /// an Open() or a Clone() FIDL methods, and these methods have no means to propagate errors to the /// caller. OnOpen event is the only way to do that, so there is nowhere to report errors in /// OnOpen dispatch. `server_end` will be closed, so there will be some kind of indication of the /// issue. /// /// TODO Maybe send an epitaph on the `server_end`? /// /// # Panics /// If `status` is `Status::OK`. In this case `OnOpen` may need to contain a description of the /// object, and server_end should not be droppped. pub fn send_on_open_with_error(flags: u32, server_end: ServerEnd<NodeMarker>, status: Status) { if status == Status::OK { panic!("send_on_open_with_error() should not be used to respond with Status::OK"); } if flags & OPEN_FLAG_DESCRIBE == 0 { return; } match server_end.into_stream_and_control_handle() { Ok((_, control_handle)) => { // There is no reasonable way to report this error. Assuming the `server_end` has just // disconnected or failed in some other way why we are trying to send OnOpen. let _ = control_handle.send_on_open_(status.into_raw(), None); } Err(_) => { // Same as above, ignore the error. return; } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const CCH_RM_MAX_APP_NAME: u32 = 255u32; pub const CCH_RM_MAX_SVC_NAME: u32 = 63u32; pub const CCH_RM_SESSION_KEY: u32 = 32u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_APP_STATUS(pub i32); pub const RmStatusUnknown: RM_APP_STATUS = RM_APP_STATUS(0i32); pub const RmStatusRunning: RM_APP_STATUS = RM_APP_STATUS(1i32); pub const RmStatusStopped: RM_APP_STATUS = RM_APP_STATUS(2i32); pub const RmStatusStoppedOther: RM_APP_STATUS = RM_APP_STATUS(4i32); pub const RmStatusRestarted: RM_APP_STATUS = RM_APP_STATUS(8i32); pub const RmStatusErrorOnStop: RM_APP_STATUS = RM_APP_STATUS(16i32); pub const RmStatusErrorOnRestart: RM_APP_STATUS = RM_APP_STATUS(32i32); pub const RmStatusShutdownMasked: RM_APP_STATUS = RM_APP_STATUS(64i32); pub const RmStatusRestartMasked: RM_APP_STATUS = RM_APP_STATUS(128i32); impl ::core::convert::From<i32> for RM_APP_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_APP_STATUS { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_APP_TYPE(pub i32); pub const RmUnknownApp: RM_APP_TYPE = RM_APP_TYPE(0i32); pub const RmMainWindow: RM_APP_TYPE = RM_APP_TYPE(1i32); pub const RmOtherWindow: RM_APP_TYPE = RM_APP_TYPE(2i32); pub const RmService: RM_APP_TYPE = RM_APP_TYPE(3i32); pub const RmExplorer: RM_APP_TYPE = RM_APP_TYPE(4i32); pub const RmConsole: RM_APP_TYPE = RM_APP_TYPE(5i32); pub const RmCritical: RM_APP_TYPE = RM_APP_TYPE(1000i32); impl ::core::convert::From<i32> for RM_APP_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_APP_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_FILTER_ACTION(pub i32); pub const RmInvalidFilterAction: RM_FILTER_ACTION = RM_FILTER_ACTION(0i32); pub const RmNoRestart: RM_FILTER_ACTION = RM_FILTER_ACTION(1i32); pub const RmNoShutdown: RM_FILTER_ACTION = RM_FILTER_ACTION(2i32); impl ::core::convert::From<i32> for RM_FILTER_ACTION { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_FILTER_ACTION { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RM_FILTER_INFO { pub FilterAction: RM_FILTER_ACTION, pub FilterTrigger: RM_FILTER_TRIGGER, pub cbNextOffset: u32, pub Anonymous: RM_FILTER_INFO_0, } #[cfg(feature = "Win32_Foundation")] impl RM_FILTER_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for RM_FILTER_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for RM_FILTER_INFO { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for RM_FILTER_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for RM_FILTER_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union RM_FILTER_INFO_0 { pub strFilename: super::super::Foundation::PWSTR, pub Process: RM_UNIQUE_PROCESS, pub strServiceShortName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl RM_FILTER_INFO_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for RM_FILTER_INFO_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for RM_FILTER_INFO_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for RM_FILTER_INFO_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for RM_FILTER_INFO_0 { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_FILTER_TRIGGER(pub i32); pub const RmFilterTriggerInvalid: RM_FILTER_TRIGGER = RM_FILTER_TRIGGER(0i32); pub const RmFilterTriggerFile: RM_FILTER_TRIGGER = RM_FILTER_TRIGGER(1i32); pub const RmFilterTriggerProcess: RM_FILTER_TRIGGER = RM_FILTER_TRIGGER(2i32); pub const RmFilterTriggerService: RM_FILTER_TRIGGER = RM_FILTER_TRIGGER(3i32); impl ::core::convert::From<i32> for RM_FILTER_TRIGGER { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_FILTER_TRIGGER { type Abi = Self; } pub const RM_INVALID_PROCESS: i32 = -1i32; pub const RM_INVALID_TS_SESSION: i32 = -1i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RM_PROCESS_INFO { pub Process: RM_UNIQUE_PROCESS, pub strAppName: [u16; 256], pub strServiceShortName: [u16; 64], pub ApplicationType: RM_APP_TYPE, pub AppStatus: u32, pub TSSessionId: u32, pub bRestartable: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl RM_PROCESS_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for RM_PROCESS_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for RM_PROCESS_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RM_PROCESS_INFO") .field("Process", &self.Process) .field("strAppName", &self.strAppName) .field("strServiceShortName", &self.strServiceShortName) .field("ApplicationType", &self.ApplicationType) .field("AppStatus", &self.AppStatus) .field("TSSessionId", &self.TSSessionId) .field("bRestartable", &self.bRestartable) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for RM_PROCESS_INFO { fn eq(&self, other: &Self) -> bool { self.Process == other.Process && self.strAppName == other.strAppName && self.strServiceShortName == other.strServiceShortName && self.ApplicationType == other.ApplicationType && self.AppStatus == other.AppStatus && self.TSSessionId == other.TSSessionId && self.bRestartable == other.bRestartable } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for RM_PROCESS_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for RM_PROCESS_INFO { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_REBOOT_REASON(pub i32); pub const RmRebootReasonNone: RM_REBOOT_REASON = RM_REBOOT_REASON(0i32); pub const RmRebootReasonPermissionDenied: RM_REBOOT_REASON = RM_REBOOT_REASON(1i32); pub const RmRebootReasonSessionMismatch: RM_REBOOT_REASON = RM_REBOOT_REASON(2i32); pub const RmRebootReasonCriticalProcess: RM_REBOOT_REASON = RM_REBOOT_REASON(4i32); pub const RmRebootReasonCriticalService: RM_REBOOT_REASON = RM_REBOOT_REASON(8i32); pub const RmRebootReasonDetectedSelf: RM_REBOOT_REASON = RM_REBOOT_REASON(16i32); impl ::core::convert::From<i32> for RM_REBOOT_REASON { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_REBOOT_REASON { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RM_SHUTDOWN_TYPE(pub i32); pub const RmForceShutdown: RM_SHUTDOWN_TYPE = RM_SHUTDOWN_TYPE(1i32); pub const RmShutdownOnlyRegistered: RM_SHUTDOWN_TYPE = RM_SHUTDOWN_TYPE(16i32); impl ::core::convert::From<i32> for RM_SHUTDOWN_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RM_SHUTDOWN_TYPE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RM_UNIQUE_PROCESS { pub dwProcessId: u32, pub ProcessStartTime: super::super::Foundation::FILETIME, } #[cfg(feature = "Win32_Foundation")] impl RM_UNIQUE_PROCESS {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for RM_UNIQUE_PROCESS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for RM_UNIQUE_PROCESS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RM_UNIQUE_PROCESS").field("dwProcessId", &self.dwProcessId).field("ProcessStartTime", &self.ProcessStartTime).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for RM_UNIQUE_PROCESS { fn eq(&self, other: &Self) -> bool { self.dwProcessId == other.dwProcessId && self.ProcessStartTime == other.ProcessStartTime } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for RM_UNIQUE_PROCESS {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for RM_UNIQUE_PROCESS { type Abi = Self; } pub type RM_WRITE_STATUS_CALLBACK = unsafe extern "system" fn(npercentcomplete: u32); #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmAddFilter<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dwsessionhandle: u32, strmodulename: Param1, pprocess: *const RM_UNIQUE_PROCESS, strserviceshortname: Param3, filteraction: RM_FILTER_ACTION) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmAddFilter(dwsessionhandle: u32, strmodulename: super::super::Foundation::PWSTR, pprocess: *const RM_UNIQUE_PROCESS, strserviceshortname: super::super::Foundation::PWSTR, filteraction: RM_FILTER_ACTION) -> u32; } ::core::mem::transmute(RmAddFilter(::core::mem::transmute(dwsessionhandle), strmodulename.into_param().abi(), ::core::mem::transmute(pprocess), strserviceshortname.into_param().abi(), ::core::mem::transmute(filteraction))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RmCancelCurrentTask(dwsessionhandle: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmCancelCurrentTask(dwsessionhandle: u32) -> u32; } ::core::mem::transmute(RmCancelCurrentTask(::core::mem::transmute(dwsessionhandle))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RmEndSession(dwsessionhandle: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmEndSession(dwsessionhandle: u32) -> u32; } ::core::mem::transmute(RmEndSession(::core::mem::transmute(dwsessionhandle))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RmGetFilterList(dwsessionhandle: u32, pbfilterbuf: *mut u8, cbfilterbuf: u32, cbfilterbufneeded: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmGetFilterList(dwsessionhandle: u32, pbfilterbuf: *mut u8, cbfilterbuf: u32, cbfilterbufneeded: *mut u32) -> u32; } ::core::mem::transmute(RmGetFilterList(::core::mem::transmute(dwsessionhandle), ::core::mem::transmute(pbfilterbuf), ::core::mem::transmute(cbfilterbuf), ::core::mem::transmute(cbfilterbufneeded))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmGetList(dwsessionhandle: u32, pnprocinfoneeded: *mut u32, pnprocinfo: *mut u32, rgaffectedapps: *mut RM_PROCESS_INFO, lpdwrebootreasons: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmGetList(dwsessionhandle: u32, pnprocinfoneeded: *mut u32, pnprocinfo: *mut u32, rgaffectedapps: *mut RM_PROCESS_INFO, lpdwrebootreasons: *mut u32) -> u32; } ::core::mem::transmute(RmGetList(::core::mem::transmute(dwsessionhandle), ::core::mem::transmute(pnprocinfoneeded), ::core::mem::transmute(pnprocinfo), ::core::mem::transmute(rgaffectedapps), ::core::mem::transmute(lpdwrebootreasons))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmJoinSession<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(psessionhandle: *mut u32, strsessionkey: Param1) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmJoinSession(psessionhandle: *mut u32, strsessionkey: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RmJoinSession(::core::mem::transmute(psessionhandle), strsessionkey.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmRegisterResources(dwsessionhandle: u32, nfiles: u32, rgsfilenames: *const super::super::Foundation::PWSTR, napplications: u32, rgapplications: *const RM_UNIQUE_PROCESS, nservices: u32, rgsservicenames: *const super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmRegisterResources(dwsessionhandle: u32, nfiles: u32, rgsfilenames: *const super::super::Foundation::PWSTR, napplications: u32, rgapplications: *const RM_UNIQUE_PROCESS, nservices: u32, rgsservicenames: *const super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RmRegisterResources(::core::mem::transmute(dwsessionhandle), ::core::mem::transmute(nfiles), ::core::mem::transmute(rgsfilenames), ::core::mem::transmute(napplications), ::core::mem::transmute(rgapplications), ::core::mem::transmute(nservices), ::core::mem::transmute(rgsservicenames))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmRemoveFilter<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dwsessionhandle: u32, strmodulename: Param1, pprocess: *const RM_UNIQUE_PROCESS, strserviceshortname: Param3) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmRemoveFilter(dwsessionhandle: u32, strmodulename: super::super::Foundation::PWSTR, pprocess: *const RM_UNIQUE_PROCESS, strserviceshortname: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RmRemoveFilter(::core::mem::transmute(dwsessionhandle), strmodulename.into_param().abi(), ::core::mem::transmute(pprocess), strserviceshortname.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RmRestart(dwsessionhandle: u32, dwrestartflags: u32, fnstatus: ::core::option::Option<RM_WRITE_STATUS_CALLBACK>) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmRestart(dwsessionhandle: u32, dwrestartflags: u32, fnstatus: ::windows::core::RawPtr) -> u32; } ::core::mem::transmute(RmRestart(::core::mem::transmute(dwsessionhandle), ::core::mem::transmute(dwrestartflags), ::core::mem::transmute(fnstatus))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn RmShutdown(dwsessionhandle: u32, lactionflags: u32, fnstatus: ::core::option::Option<RM_WRITE_STATUS_CALLBACK>) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmShutdown(dwsessionhandle: u32, lactionflags: u32, fnstatus: ::windows::core::RawPtr) -> u32; } ::core::mem::transmute(RmShutdown(::core::mem::transmute(dwsessionhandle), ::core::mem::transmute(lactionflags), ::core::mem::transmute(fnstatus))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn RmStartSession(psessionhandle: *mut u32, dwsessionflags: u32, strsessionkey: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn RmStartSession(psessionhandle: *mut u32, dwsessionflags: u32, strsessionkey: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(RmStartSession(::core::mem::transmute(psessionhandle), ::core::mem::transmute(dwsessionflags), ::core::mem::transmute(strsessionkey))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
use std::io::Write; use std::fs::File; use rand::Rng; mod entropy; mod strategies; mod sim; mod test; use strategies::*; use sim::*; fn output(f: &mut File, s: String) { println!("{}", s); f.write_all(s.as_bytes()).expect("couldnt write to file"); f.write_all(b"\n").expect("couldnt write newline to file"); } fn run_trial<S: BisectStrategy>(strat_fn: impl Fn(&SimulationState) -> S) { let strat_name = strat_fn(&SimulationState::new(1, 0.5)).name(); let filename_suffix: usize = rand::thread_rng().gen(); let filename = format!("trial-{}-{}.txt", strat_name, filename_suffix); println!("(emitting output to {})", filename); let mut f = File::create(filename).expect("couldn't make ouptput file"); let n = 1024; let conf_thresh = 0.99999; let conf_thresh = 0.50001; let trials = 65536; let trials = 16384; output(&mut f, format!("==== {}; n = {}, confidence goal = {}, trials = {} ====", strat_name, n, conf_thresh, trials)); for &false_negative_prob in &[ 0.9, // 0.0, // 0.00001, 0.0001, 0.001, 0.01, // 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, // 0.99, // 0.999, 0.9999, 0.99999, // these will take FOREVER ] { let mut result_steps = vec![]; let mut wrongs = 0; for i in 0..trials { if i % 1024 == 0 { println!("making progress; trial {}", i); } 'inner: loop { // TODO: time these suckas let s = SimulationState::new_with_bug_at(n, false_negative_prob, i % n); let strat = strat_fn(&s); let res = s.simulate_til_confident(strat, conf_thresh); if res.suspected_buggy_commit == res.actual_buggy_commit { result_steps.push(res.steps); break 'inner; } else { wrongs += 1; } } } let total_steps: usize = result_steps.iter().sum(); let avg_steps = total_steps as f64 / trials as f64; output(&mut f, format!( "fnprob {} -> {} steps ({} times wrong)", false_negative_prob, avg_steps, wrongs, )); } } fn main() { for &bisect_point in &[ // 0.30, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, // 0.40, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, // 0.50, 0.51, 0.52, 0.53, 0.54, 0.55, ] { run_trial(|s| CdfBisect::new(s, bisect_point)); } // squash compiler warnings if false { run_trial(MinExpectedEntropy::new); run_trial(LinearSearch::new); run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::UsePreviousLow)); run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::ForgetEverything)); run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::Mistrustful(0))); run_trial(|s| ChooseRandomly::new(s, RandomMode::Uniformly)); run_trial(|s| ChooseRandomly::new(s, RandomMode::WeightedByCDF)); } run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::UsePreviousLow)); // run_trial(|s| ChooseRandomly::new(s, RandomMode::Uniformly)); // run_trial(MinExpectedEntropy::new); // run_trial(|s| CdfBisect::new(s, 1.0 / 3.0)); // run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::UsePreviousLow)); // run_trial(|s| NaiveBinarySearch::new(s, ConfusedHumanMode::ForgetEverything)); }
use crate::config::{TargetPadding, TimeFormat}; use crate::{Config, LevelPadding, ThreadLogMode, ThreadPadding}; use log::{LevelFilter, Record}; use std::io::{Error, Write}; use std::thread; #[cfg(all(feature = "termcolor", feature = "ansi_term"))] use termcolor::Color; #[cfg(all(feature = "termcolor", feature = "ansi_term"))] pub fn termcolor_to_ansiterm(color: &Color) -> Option<ansi_term::Color> { match color { Color::Black => Some(ansi_term::Color::Black), Color::Red => Some(ansi_term::Color::Red), Color::Green => Some(ansi_term::Color::Green), Color::Yellow => Some(ansi_term::Color::Yellow), Color::Blue => Some(ansi_term::Color::Blue), Color::Magenta => Some(ansi_term::Color::Purple), Color::Cyan => Some(ansi_term::Color::Cyan), Color::White => Some(ansi_term::Color::White), _ => None, } } #[inline(always)] pub fn try_log<W>(config: &Config, record: &Record<'_>, write: &mut W) -> Result<(), Error> where W: Write + Sized, { if should_skip(config, record) { return Ok(()); } if config.time <= record.level() && config.time != LevelFilter::Off { write_time(write, config)?; } if config.level <= record.level() && config.level != LevelFilter::Off { write_level(record, write, config)?; } if config.thread <= record.level() && config.thread != LevelFilter::Off { match config.thread_log_mode { ThreadLogMode::IDs => { write_thread_id(write, config)?; } ThreadLogMode::Names | ThreadLogMode::Both => { write_thread_name(write, config)?; } } } if config.target <= record.level() && config.target != LevelFilter::Off { write_target(record, write, config)?; } if config.location <= record.level() && config.location != LevelFilter::Off { write_location(record, write)?; } if config.module <= record.level() && config.module != LevelFilter::Off { write_module(record, write)?; } #[cfg(feature = "paris")] return write_args(record, write, config.enable_paris_formatting); #[cfg(not(feature = "paris"))] return write_args(record, write); } #[inline(always)] pub fn write_time<W>(write: &mut W, config: &Config) -> Result<(), Error> where W: Write + Sized, { use time::error::Format; use time::format_description::well_known::*; let time = time::OffsetDateTime::now_utc().to_offset(config.time_offset); let res = match config.time_format { TimeFormat::Rfc2822 => time.format_into(write, &Rfc2822), TimeFormat::Rfc3339 => time.format_into(write, &Rfc3339), TimeFormat::Custom(format) => time.format_into(write, &format), }; match res { Err(Format::StdIo(err)) => return Err(err), Err(err) => panic!("Invalid time format: {}", err), _ => {} }; write!(write, " ")?; Ok(()) } #[inline(always)] pub fn write_level<W>(record: &Record<'_>, write: &mut W, config: &Config) -> Result<(), Error> where W: Write + Sized, { #[cfg(all(feature = "termcolor", feature = "ansi_term"))] let color = match &config.level_color[record.level() as usize] { Some(termcolor) => { if config.write_log_enable_colors { termcolor_to_ansiterm(termcolor) } else { None } } None => None, }; let level = match config.level_padding { LevelPadding::Left => format!("[{: >5}]", record.level()), LevelPadding::Right => format!("[{: <5}]", record.level()), LevelPadding::Off => format!("[{}]", record.level()), }; #[cfg(all(feature = "termcolor", feature = "ansi_term"))] match color { Some(c) => write!(write, "{} ", c.paint(level))?, None => write!(write, "{} ", level)?, }; #[cfg(not(feature = "ansi_term"))] write!(write, "{} ", level)?; Ok(()) } #[inline(always)] pub fn write_target<W>(record: &Record<'_>, write: &mut W, config: &Config) -> Result<(), Error> where W: Write + Sized, { // dbg!(&config.target_padding); match config.target_padding { TargetPadding::Left(pad) => { write!( write, "{target:>pad$}: ", pad = pad, target = record.target() )?; } TargetPadding::Right(pad) => { write!( write, "{target:<pad$}: ", pad = pad, target = record.target() )?; } TargetPadding::Off => { write!(write, "{}: ", record.target())?; } } Ok(()) } #[inline(always)] pub fn write_location<W>(record: &Record<'_>, write: &mut W) -> Result<(), Error> where W: Write + Sized, { let file = record.file().unwrap_or("<unknown>"); if let Some(line) = record.line() { write!(write, "[{}:{}] ", file, line)?; } else { write!(write, "[{}:<unknown>] ", file)?; } Ok(()) } #[inline(always)] pub fn write_module<W>(record: &Record<'_>, write: &mut W) -> Result<(), Error> where W: Write + Sized, { let module = record.module_path().unwrap_or("<unknown>"); write!(write, "[{}] ", module)?; Ok(()) } pub fn write_thread_name<W>(write: &mut W, config: &Config) -> Result<(), Error> where W: Write + Sized, { if let Some(name) = thread::current().name() { match config.thread_padding { ThreadPadding::Left { 0: qty } => { write!(write, "({name:>0$}) ", qty, name = name)?; } ThreadPadding::Right { 0: qty } => { write!(write, "({name:<0$}) ", qty, name = name)?; } ThreadPadding::Off => { write!(write, "({}) ", name)?; } } } else if config.thread_log_mode == ThreadLogMode::Both { write_thread_id(write, config)?; } Ok(()) } pub fn write_thread_id<W>(write: &mut W, config: &Config) -> Result<(), Error> where W: Write + Sized, { let id = format!("{:?}", thread::current().id()); let id = id.replace("ThreadId(", ""); let id = id.replace(")", ""); match config.thread_padding { ThreadPadding::Left { 0: qty } => { write!(write, "({id:>0$}) ", qty, id = id)?; } ThreadPadding::Right { 0: qty } => { write!(write, "({id:<0$}) ", qty, id = id)?; } ThreadPadding::Off => { write!(write, "({}) ", id)?; } } Ok(()) } #[inline(always)] #[cfg(feature = "paris")] pub fn write_args<W>(record: &Record<'_>, write: &mut W, with_colors: bool) -> Result<(), Error> where W: Write + Sized, { writeln!( write, "{}", crate::__private::paris::formatter::format_string( format!("{}", record.args()), with_colors ) )?; Ok(()) } #[inline(always)] #[cfg(not(feature = "paris"))] pub fn write_args<W>(record: &Record<'_>, write: &mut W) -> Result<(), Error> where W: Write + Sized, { writeln!(write, "{}", record.args())?; Ok(()) } #[inline(always)] pub fn should_skip(config: &Config, record: &Record<'_>) -> bool { // If a module path and allowed list are available match (record.target(), &*config.filter_allow) { (path, allowed) if !allowed.is_empty() => { // Check that the module path matches at least one allow filter if !allowed.iter().any(|v| path.starts_with(&**v)) { // If not, skip any further writing return true; } } _ => {} } // If a module path and ignore list are available match (record.target(), &*config.filter_ignore) { (path, ignore) if !ignore.is_empty() => { // Check that the module path does not match any ignore filters if ignore.iter().any(|v| path.starts_with(&**v)) { // If not, skip any further writing return true; } } _ => {} } false }
pub mod model_selection; pub mod quick_start; pub mod supervised; pub mod unsupervised; pub mod utils; use std::collections::HashMap; use structopt::StructOpt; #[derive(StructOpt)] /// Run SmartCore example struct Cli { /// The example to run. Pass `list_examples` to list all available examples! example_name: String, } fn main() { let args = Cli::from_args(); let examples = args.example_name; let all_examples: HashMap<&str, &dyn Fn()> = vec![ ( "quick-start:iris-knn", &quick_start::iris_knn_example as &dyn Fn(), ), ( "quick-start:iris-lr", &quick_start::iris_lr_example as &dyn Fn(), ), ( "quick-start:iris-lr-ndarray", &quick_start::iris_lr_ndarray_example as &dyn Fn(), ), ( "quick-start:iris-lr-nalgebra", &quick_start::iris_lr_nalgebra_example as &dyn Fn(), ), ( "quick-start:iris-gaussiannb", &quick_start::iris_gaussiannb_example as &dyn Fn(), ), ( "supervised:breast-cancer", &supervised::breast_cancer as &dyn Fn(), ), ("supervised:diabetes", &supervised::diabetes as &dyn Fn()), ("supervised:boston", &supervised::boston as &dyn Fn()), ( "unsupervised:digits_clusters", &unsupervised::digits_clusters as &dyn Fn(), ), ( "unsupervised:digits_pca", &unsupervised::digits_pca as &dyn Fn(), ), ("unsupervised:circles", &unsupervised::circles as &dyn Fn()), ( "unsupervised:digits_svd1", &unsupervised::digits_svd1 as &dyn Fn(), ), ( "unsupervised:digits_svd2", &unsupervised::digits_svd2 as &dyn Fn(), ), ( "model_selection:save_restore_knn", &model_selection::save_restore_knn as &dyn Fn(), ), ( "model_selection:plot_cross_val_predict", &model_selection::plot_cross_val_predict as &dyn Fn(), ), ( "model_selection:lr_cross_validate", &model_selection::lr_cross_validate as &dyn Fn(), ), ("supervised:svm", &supervised::svm as &dyn Fn()), ] .into_iter() .collect(); match examples { example if all_examples.contains_key(&example.as_str()) => { println!("Running {} ...\n", example); for example_fn in all_examples.get(example.as_str()) { example_fn(); } println!("\nDone!"); } example if example == "list_examples" || example == "list" => { println!("You can run following examples:"); let mut keys: Vec<&&str> = all_examples.keys().collect(); keys.sort(); for c in keys { println!("\t{}", c); } } example => eprintln!( "Can't find this example: [{}]. Type `list` to list all available examples", example ), } }
#![feature(test)] extern crate rtfmt; extern crate test; use std::collections::BTreeMap; use test::Bencher; use rtfmt::{Generator, Value}; #[bench] fn complex(b: &mut Bencher) { let g = Generator::new("le message: {id}!").unwrap(); let mut map = BTreeMap::new(); map.insert("id".into(), Value::I64(42)); let value = Value::Object(map); b.iter(|| { let result = g.consume(&value).unwrap(); test::black_box(result); }); }
use super::{Token, parsers::{parse_block_comments, parse_curly_brace, parse_identifier, parse_line_comment, parse_number, parse_operator, parse_parenthesis, parse_separator, parse_string, parse_terminator, parse_whitespace}}; pub struct Tokenizer { pub index: usize, pub file_content: Vec<char>, } impl Tokenizer { pub fn new(file_content: &String) -> Tokenizer { Tokenizer { index: 0, file_content: file_content.chars().collect() } } pub fn has_tokens(&self) -> bool { self.token().is_some() } pub fn token(&self) -> Option<&char> { self.file_content.get(self.index) } pub fn peek(&self) -> Option<&char> { self.file_content.get(self.index + 1) } pub fn peek_back(&self) -> Option<&char> { self.file_content.get(self.index - 1) } pub fn walk_back(&mut self) { self.index -= 1; } pub fn consume(&mut self) -> Option<&char> { let value = self.file_content.get(self.index); self.index += 1; return value; } } pub fn tokenize(file_content: &String) -> Vec<Token> { let mut tokens = Vec::new(); let mut tokenizer = Tokenizer::new(file_content); while tokenizer.has_tokens() { if parse_whitespace(&mut tokenizer).is_some() { continue; } if parse_line_comment(&mut tokenizer).is_some() { continue; } if parse_block_comments(&mut tokenizer).is_some() { continue; } let identifier = parse_identifier(&mut tokenizer); if identifier.is_some() { tokens.push(identifier.unwrap()); continue; } let number = parse_number(&mut tokenizer); if number.is_some() { tokens.push(number.unwrap()); continue; } let string = parse_string(&mut tokenizer); if string.is_some() { tokens.push(string.unwrap()); continue; } let operator = parse_operator(&mut tokenizer); if operator.is_some() { tokens.push(operator.unwrap()); continue; } let curly_brace = parse_curly_brace(&mut tokenizer); if curly_brace.is_some() { tokens.push(curly_brace.unwrap()); continue; } let seperator = parse_separator(&mut tokenizer); if seperator.is_some() { tokens.push(seperator.unwrap()); continue; } let parenthesis = parse_parenthesis(&mut tokenizer); if parenthesis.is_some() { tokens.push(parenthesis.unwrap()); continue; } let terminator = parse_terminator(&mut tokenizer); if terminator.is_some() { tokens.push(terminator.unwrap()); continue; } panic!("Unknown token: {} at index: {}", tokenizer.token().unwrap().clone().to_string(), tokenizer.index); } tokens }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_operation_create_container( input: &crate::input::CreateContainerInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_create_container_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_container( input: &crate::input::DeleteContainerInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_container_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_container_policy( input: &crate::input::DeleteContainerPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_container_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_cors_policy( input: &crate::input::DeleteCorsPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_cors_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_lifecycle_policy( input: &crate::input::DeleteLifecyclePolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_lifecycle_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_delete_metric_policy( input: &crate::input::DeleteMetricPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_delete_metric_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_describe_container( input: &crate::input::DescribeContainerInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_describe_container_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_container_policy( input: &crate::input::GetContainerPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_container_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_cors_policy( input: &crate::input::GetCorsPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_cors_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_lifecycle_policy( input: &crate::input::GetLifecyclePolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_lifecycle_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_get_metric_policy( input: &crate::input::GetMetricPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_get_metric_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_containers( input: &crate::input::ListContainersInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_containers_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_list_tags_for_resource( input: &crate::input::ListTagsForResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_list_tags_for_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_container_policy( input: &crate::input::PutContainerPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_container_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_cors_policy( input: &crate::input::PutCorsPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_cors_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_lifecycle_policy( input: &crate::input::PutLifecyclePolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_lifecycle_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_put_metric_policy( input: &crate::input::PutMetricPolicyInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_put_metric_policy_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_start_access_logging( input: &crate::input::StartAccessLoggingInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_start_access_logging_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_stop_access_logging( input: &crate::input::StopAccessLoggingInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_stop_access_logging_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_tag_resource( input: &crate::input::TagResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_tag_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_untag_resource( input: &crate::input::UntagResourceInput, ) -> Result<smithy_http::body::SdkBody, smithy_types::Error> { let mut out = String::new(); let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out); crate::json_ser::serialize_structure_untag_resource_input(&mut object, input); object.finish(); Ok(smithy_http::body::SdkBody::from(out)) }
// This file is derived from the lupine crate, which is licensed under MIT // and available at https://github.com/greglaurent/lupine/ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use ahash::AHasher; use bit_vec::BitVec; const FALSE_POS_PROB: f64 = -1.0; const LN_2: f64 = core::f64::consts::LN_2; const LN_2_SQR: f64 = LN_2 * LN_2; /// Representation of a bloom filter pub struct BloomFilter<T: ?Sized> { k: u64, m: usize, hashers: [AHasher; 2], pub bitmap: BitVec, _phantom: PhantomData<T>, } impl<T: ?Sized> BloomFilter<T> { /// Returns a BloomFilter with an optimized k and m /// /// # Arguments /// /// * 'size' - A usize that sets the size of the filter /// * 'false_pos_rate' - The acceptable false positive rate #[no_coverage] pub fn new(size: usize, false_pos_rate: f64) -> Self { let k = Self::optimal_k(false_pos_rate); let m = Self::optimal_m(false_pos_rate, size); let bitmap = BitVec::from_elem(m, false); let hashers = [ AHasher::new_with_keys(fastrand::u128(..), fastrand::u128(..)), AHasher::new_with_keys(fastrand::u128(..), fastrand::u128(..)), ]; BloomFilter { k, m, hashers, bitmap, _phantom: PhantomData, } } /// Calculate optimal m value for the filter /// where m is the optimal number of bits in the bit array /// while preventing overfill /// /// where P is the probability of false positives /// and n is the acceptable false postive rate /// k = ( -( n * lnP ) / (ln2)^2 ) #[no_coverage] fn optimal_m(false_pos_rate: f64, size: usize) -> usize { ((size as f64 * FALSE_POS_PROB * false_pos_rate.ln()) / LN_2_SQR).ceil() as usize } /// Calculate optimal k value for the filter /// where k is the number of functions to hash input T /// yielding k indices into the bit array /// /// where P is the probability of false positives /// k = ( - lnP / ln2 ) #[no_coverage] fn optimal_k(false_pos_rate: f64) -> u64 { (false_pos_rate.ln() * FALSE_POS_PROB / LN_2).ceil() as u64 } /// Hash values T for Bloomfilter #[no_coverage] fn hash(&self, t: &T) -> (u64, u64) where T: Hash, { let hash1 = &mut self.hashers[0].clone(); let hash2 = &mut self.hashers[1].clone(); t.hash(hash1); t.hash(hash2); (hash1.finish(), hash2.finish()) } /// Retrieve the index of indexes by simulating /// more than 2 hashers /// /// Prevent Overflow: /// wrapping_add: wrapping add around at the boundary type /// wrapping_mul: wrapping mult around at the boundary type #[no_coverage] fn find_index(&self, i: u64, hash1: u64, hash2: u64) -> usize { hash1.wrapping_add((i).wrapping_mul(hash2)) as usize % self.m } /// Insert T into the BloomFilter index #[no_coverage] pub fn insert(&mut self, t: &T) where T: Hash, { let (hash1, hash2) = self.hash(t); for i in 0..self.k { let index = self.find_index(i, hash1, hash2); self.bitmap.set(index, true); } } /// Check if t of type T is in the BloomFilter index #[no_coverage] pub fn contains(&mut self, t: &T) -> bool where T: Hash, { let (hash1, hash2) = self.hash(t); for i in 0..self.k { let index = self.find_index(i, hash1, hash2); if !self.bitmap.get(index).unwrap() { return false; } } true } }
struct Solution; impl Solution { pub fn first_missing_positive(nums: Vec<i32>) -> i32 { let mut nums = nums; let len = nums.len(); let mut i = 0; while i < len { let num = nums[i]; // segregate the negative and positive // we don't care those value larger than the (len + 1) if num > 0 && num - 1 < (len as i32) { // swap: https://doc.rust-lang.org/std/primitive.slice.html#method.swap nums.swap((num - 1) as usize, i); if (num - 1) > (i as i32) && (num != nums[i]) { continue; } } i += 1; } for (k, &num) in nums.iter().enumerate() { if num != ((k + 1) as i32) { return (k + 1) as i32 } } return (len + 1) as i32 } }
// Copyright (C) 2020, Cloudflare, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pub const STATIC_TABLE: [(&[u8], &[u8]); 99] = [ (b":authority", b""), (b":path", b"/"), (b"age", b"0"), (b"content-disposition", b""), (b"content-length", b"0"), (b"cookie", b""), (b"date", b""), (b"etag", b""), (b"if-modified-since", b""), (b"if-none-match", b""), (b"last-modified", b""), (b"link", b""), (b"location", b""), (b"referer", b""), (b"set-cookie", b""), (b":method", b"CONNECT"), (b":method", b"DELETE"), (b":method", b"GET"), (b":method", b"HEAD"), (b":method", b"OPTIONS"), (b":method", b"POST"), (b":method", b"PUT"), (b":scheme", b"http"), (b":scheme", b"https"), (b":status", b"103"), (b":status", b"200"), (b":status", b"304"), (b":status", b"404"), (b":status", b"503"), (b"accept", b"*/*"), (b"accept", b"application/dns-message"), (b"accept-encoding", b"gzip, deflate, br"), (b"accept-ranges", b"bytes"), (b"access-control-allow-headers", b"cache-control"), (b"access-control-allow-headers", b"content-type"), (b"access-control-allow-origin", b"*"), (b"cache-control", b"max-age=0"), (b"cache-control", b"max-age=2592000"), (b"cache-control", b"max-age=604800"), (b"cache-control", b"no-cache"), (b"cache-control", b"no-store"), (b"cache-control", b"public, max-age=31536000"), (b"content-encoding", b"br"), (b"content-encoding", b"gzip"), (b"content-type", b"application/dns-message"), (b"content-type", b"application/javascript"), (b"content-type", b"application/json"), (b"content-type", b"application/x-www-form-urlencoded"), (b"content-type", b"image/gif"), (b"content-type", b"image/jpeg"), (b"content-type", b"image/png"), (b"content-type", b"text/css"), (b"content-type", b"text/html; charset=utf-8"), (b"content-type", b"text/plain"), (b"content-type", b"text/plain;charset=utf-8"), (b"range", b"bytes=0-"), (b"strict-transport-security", b"max-age=31536000"), ( b"strict-transport-security", b"max-age=31536000; includesubdomains", ), ( b"strict-transport-security", b"max-age=31536000; includesubdomains; preload", ), (b"vary", b"accept-encoding"), (b"vary", b"origin"), (b"x-content-type-options", b"nosniff"), (b"x-xss-protection", b"1; mode=block"), (b":status", b"100"), (b":status", b"204"), (b":status", b"206"), (b":status", b"302"), (b":status", b"400"), (b":status", b"403"), (b":status", b"421"), (b":status", b"425"), (b":status", b"500"), (b"accept-language", b""), (b"access-control-allow-credentials", b"FALSE"), (b"access-control-allow-credentials", b"TRUE"), (b"access-control-allow-headers", b"*"), (b"access-control-allow-methods", b"get"), (b"access-control-allow-methods", b"get, post, options"), (b"access-control-allow-methods", b"options"), (b"access-control-expose-headers", b"content-length"), (b"access-control-request-headers", b"content-type"), (b"access-control-request-method", b"get"), (b"access-control-request-method", b"post"), (b"alt-svc", b"clear"), (b"authorization", b""), ( b"content-security-policy", b"script-src 'none'; object-src 'none'; base-uri 'none'", ), (b"early-data", b"1"), (b"expect-ct", b""), (b"forwarded", b""), (b"if-range", b""), (b"origin", b""), (b"purpose", b"prefetch"), (b"server", b""), (b"timing-allow-origin", b"*"), (b"upgrade-insecure-requests", b"1"), (b"user-agent", b""), (b"x-forwarded-for", b""), (b"x-frame-options", b"deny"), (b"x-frame-options", b"sameorigin"), ];
use std::{any::TypeId, collections::HashMap}; use crate::{ actors::{actor_builder::ActorBuilder, actor_type::ActorType}, events::{event_builder::EventBuilder, event_type::EventType}, PacketReader, }; /// Contains the shared protocol between Client & Server, with a data that is /// able to map Event/Actor TypeIds to their representation within specified /// enums. Also is able to create new Event/Actors using registered Builders, /// given a specific TypeId. #[derive(Debug)] pub struct Manifest<T: EventType, U: ActorType> { event_naia_id_count: u16, event_builder_map: HashMap<u16, Box<dyn EventBuilder<T>>>, event_type_map: HashMap<TypeId, u16>, //// actor_naia_id_count: u16, actor_builder_map: HashMap<u16, Box<dyn ActorBuilder<U>>>, actor_type_map: HashMap<TypeId, u16>, } impl<T: EventType, U: ActorType> Manifest<T, U> { /// Create a new Manifest pub fn new() -> Self { Manifest { event_naia_id_count: 0, event_builder_map: HashMap::new(), event_type_map: HashMap::new(), /// actor_naia_id_count: 0, actor_builder_map: HashMap::new(), actor_type_map: HashMap::new(), } } /// Register an EventBuilder to handle the creation of Event instances pub fn register_event(&mut self, event_builder: Box<dyn EventBuilder<T>>) { let new_naia_id = self.event_naia_id_count; let type_id = event_builder.get_type_id(); self.event_type_map.insert(type_id, new_naia_id); self.event_builder_map.insert(new_naia_id, event_builder); self.event_naia_id_count += 1; } /// Given an Event's TypeId, get a NaiaId (that can be written/read from /// packets) pub fn get_event_naia_id(&self, type_id: &TypeId) -> u16 { let naia_id = self .event_type_map .get(type_id) .expect("hey I should get a TypeId here..."); return *naia_id; } /// Creates an Event instance, given a NaiaId and a payload, typically from /// an incoming packet pub fn create_event(&self, naia_id: u16, reader: &mut PacketReader) -> Option<T> { match self.event_builder_map.get(&naia_id) { Some(event_builder) => { return Some(event_builder.as_ref().build(reader)); } None => {} } return None; } /// Register an ActorBuilder to handle the creation of Actor instances pub fn register_actor(&mut self, actor_builder: Box<dyn ActorBuilder<U>>) { let new_naia_id = self.actor_naia_id_count; let type_id = actor_builder.get_type_id(); self.actor_type_map.insert(type_id, new_naia_id); self.actor_builder_map.insert(new_naia_id, actor_builder); self.actor_naia_id_count += 1; } /// Given an Actor's TypeId, get a NaiaId (that can be written/read from /// packets) pub fn get_actor_naia_id(&self, type_id: &TypeId) -> u16 { let naia_id = self .actor_type_map .get(type_id) .expect("hey I should get a TypeId here..."); return *naia_id; } /// Creates an Event instance, given a NaiaId and a payload, typically from /// an incoming packet pub fn create_actor(&self, naia_id: u16, reader: &mut PacketReader) -> Option<U> { match self.actor_builder_map.get(&naia_id) { Some(actor_builder) => { return Some(actor_builder.as_ref().build(reader)); } None => {} } return None; } /// Register both an ActorBuilder and an EventBuilder to handle the /// creation of both as a Pawn & Command, respectively. Pawns & Commands /// should be used for any player-controlled actor that requires clientside /// prediction pub fn register_pawn( &mut self, actor_builder: Box<dyn ActorBuilder<U>>, event_builder: Box<dyn EventBuilder<T>>, ) { self.register_actor(actor_builder); self.register_event(event_builder); } }
use super::Pg; use crate::backend::BinaryRawValue; use std::num::NonZeroU32; use std::ops::Range; /// Raw postgres value as received from the database #[derive(Clone, Copy)] #[allow(missing_debug_implementations)] pub struct PgValue<'a> { raw_value: &'a [u8], type_oid_lookup: &'a dyn TypeOidLookup, } #[doc(hidden)] pub trait TypeOidLookup { fn lookup(&self) -> NonZeroU32; } impl<F> TypeOidLookup for F where F: Fn() -> NonZeroU32, { fn lookup(&self) -> NonZeroU32 { (self)() } } impl<'a> TypeOidLookup for PgValue<'a> { fn lookup(&self) -> NonZeroU32 { self.type_oid_lookup.lookup() } } impl TypeOidLookup for NonZeroU32 { fn lookup(&self) -> NonZeroU32 { *self } } impl<'a> BinaryRawValue<'a> for Pg { fn as_bytes(value: PgValue<'a>) -> &'a [u8] { value.raw_value } } impl<'a> PgValue<'a> { #[cfg(test)] pub(crate) fn for_test(raw_value: &'a [u8]) -> Self { static FAKE_OID: NonZeroU32 = unsafe { // 42 != 0, so this is actually safe NonZeroU32::new_unchecked(42) }; Self { raw_value, type_oid_lookup: &FAKE_OID, } } #[doc(hidden)] pub fn new(raw_value: &'a [u8], type_oid_lookup: &'a dyn TypeOidLookup) -> Self { Self { raw_value, type_oid_lookup, } } /// Get the underlying raw byte representation pub fn as_bytes(&self) -> &[u8] { self.raw_value } /// Get the type oid of this value pub fn get_oid(&self) -> NonZeroU32 { self.type_oid_lookup.lookup() } pub(crate) fn subslice(&self, range: Range<usize>) -> Self { Self { raw_value: &self.raw_value[range], ..*self } } }
#![cfg_attr(not(test), no_std)] #![feature(test)] // Used for #[may_dangle] on TypedArena #![feature(dropck_eyepatch)] // Used for arith_offset #![feature(core_intrinsics)] #![feature(new_uninit)] #![feature(maybe_uninit_slice)] // Used for the implementation of the arenas #![feature(raw_vec_internals)] extern crate alloc; #[cfg(test)] extern crate test; mod arena; pub use self::arena::*;
use crate::{Error, mock::*, PersonInfo}; use frame_support::{assert_ok, assert_noop}; use sp_runtime::DispatchError; #[test] fn it_works_for_health_ai() { new_test_ext().execute_with(|| { // 保存慢性病禁忌菜品 assert_noop!(HealthAi::save_taboo_foods(Origin::signed(0),1, vec![10, 10]),DispatchError::BadOrigin); // 移除慢性病禁忌菜品 assert_noop!(HealthAi::remove_taboo_foods(Origin::signed(0),1),DispatchError::BadOrigin); //绑定亲属 let ps_info = PersonInfo { name: vec![111, 201, 112], id_card: vec![11, 112, 132], relation_type: 1, height: 170, weight: 120, chronic: vec![1, 2, 3], }; assert_ok!(HealthAi::bind(Origin::signed(101),1,ps_info)); //解绑亲属关系 assert_ok!(HealthAi::unbind(Origin::signed(101),1)); assert_noop!(HealthAi::unbind(Origin::signed(102),1),Error::<Test>::NoSuchRelation); }); }
#[macro_use] extern crate serde_derive; extern crate cargo_edit; extern crate cargo; extern crate docopt; use std::process::Command; use std::os::unix::process::CommandExt; use cargo_edit::Manifest; use cargo::core::shell::Verbosity; use cargo::core::Workspace; use cargo::ops::{compile, CompileOptions, CompileMode, CompileFilter}; use cargo::util::config::Config; use docopt::Docopt; const USAGE: &'static str = " cargo-dredd Usage: cargo dredd <blueprint> <server-url> [options] Options: --language=<rust> The language flag that will be passed to dredd [default: rust]. "; #[derive(Debug, Deserialize)] struct Args { arg_blueprint: String, arg_server_url: String, flag_language: Option<String>, } fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let hook_binaries = cargo_compile(); let mut cmd = Command::new("dredd"); cmd.args(&[args.arg_blueprint, args.arg_server_url]); cmd.arg(format!("--language={}", args.flag_language.unwrap_or("rust".to_owned()).to_owned())); for binary in hook_binaries { cmd.args(&[format!("--hookfiles={}", binary)]); } cmd.exec(); } fn cargo_compile() -> Vec<String> { let mut manifest = Manifest::open(&None).unwrap(); let config = manifest.get_table(&[ "package".to_owned(), "metadata".to_owned(), "dredd_hooks".to_owned()] ).expect("No [package.metadata.dredd_hooks] value found in Cargo.toml"); if config.is_empty() { panic!("No [package.metadata.dredd_hooks] value found in Cargo.toml"); } let hook_targets: Vec<String> = config.get("hook_targets") .expect("No `hook_targets` value found.") .as_array() .expect("`hook_targets` is not an array.") .iter() .filter(|n| n.is_str()) .map(|n| n.as_str().unwrap().to_owned()) .collect(); let config = Config::default().unwrap(); config.shell().set_verbosity(Verbosity::Normal); let manifest_path = config.cwd().join("Cargo.toml"); let workspace = Workspace::new(&manifest_path, &config).unwrap(); let mut compile_config = CompileOptions::default(&config, CompileMode::Test); compile_config.filter = CompileFilter::new(false, &[], false, &hook_targets, false, &[], false, &[], false); let res = compile(&workspace, &compile_config).unwrap(); res.tests.iter().map(|n| n.3.to_str().unwrap().to_owned()).collect() }
use crate::geom::{Vector, Rectangle, Transform}; #[derive(Clone, Copy, Debug)] ///A view into the world, used as a camera and a viewport pub struct View { pub(crate) normalize: Transform, pub(crate) opengl: Transform } impl View { ///Create a new view that looks at a given area pub fn new(world: Rectangle) -> View { View::new_transformed(world, Transform::IDENTITY) } ///Create a new view that looks at a given area with a transform /// ///The transform is relative to the center of the region pub fn new_transformed(world: Rectangle, transform: Transform) -> View { let normalize = Transform::scale(world.size().recip()) * Transform::translate(world.size() / 2) * transform * Transform::translate(-world.top_left() - world.size() / 2); let opengl = Transform::scale(Vector::new(2, -2)) * Transform::translate(-Vector::ONE / 2) * normalize; View { normalize, opengl } } } #[cfg(test)] mod tests { use super::*; #[test] fn opengl_projection() { let view = View::new(Rectangle::new_sized((50, 50))); let world_bottom = Vector::Y * 50; assert_eq!(view.opengl * world_bottom, -Vector::ONE); let view = View::new(Rectangle::new((50, 50), (50, 50))); let world_top = Vector::ONE * 50; let expected = -Vector::X + Vector::Y; assert_eq!(view.opengl * world_top, expected); } #[test] fn projection() { let view = View::new(Rectangle::new_sized((50, 50))); let screen_size = Vector::new(100, 100); let unproject = Transform::scale(screen_size) * view.normalize; let project = unproject.inverse(); let screen_bottom = Vector::Y * 100; let world_bottom = Vector::Y * 50; assert_eq!(project * screen_bottom, world_bottom); assert_eq!(unproject * world_bottom, screen_bottom); } // #[test] // fn custom_transform() { // let rect = Rectangle::new(-10, -10, 10, 10); // let view = View::new_transformed(rect, Transform::rotate(-90f32)); // let unproject = Transform::scale(rect.size()) * view.normalize; // let project = unproject.inverse(); // let point = Vector::X * 5; // let expected = Vector::Y * 5; // assert_eq!(project * point, expected); // } }
/* Timely code for the generators (data producers) specific to the Value Barrier example. */ use super::common::{Duration, Scope, Stream}; use super::generators::fixed_rate_source; use super::util::rand_range; use super::vb_data::{VBData, VBItem}; pub fn value_source<G>( scope: &G, loc: usize, frequency: Duration, total: Duration, ) -> Stream<G, VBItem> where G: Scope<Timestamp = u128>, { let item_gen = move |time| { let value = rand_range(0, 1000) as usize; VBItem { data: VBData::Value(value), time, loc } }; fixed_rate_source(item_gen, scope, frequency, total) } pub fn barrier_source<G>( scope: &G, loc: usize, heartbeat_frequency: Duration, heartbeats_per_barrier: u64, total: Duration, ) -> Stream<G, VBItem> where G: Scope<Timestamp = u128>, { let mut count = 0; let item_gen = move |time| { count += 1; if count % heartbeats_per_barrier == 0 { VBItem { data: VBData::Barrier, time, loc } } else { VBItem { data: VBData::BarrierHeartbeat, time, loc } } }; fixed_rate_source(item_gen, scope, heartbeat_frequency, total) }
//! Object traits. use crate::{ error::{MaxError, MaxResult}, notify::{Attachment, AttachmentError, Registration, RegistrationError, Subscription}, symbol::SymbolRef, }; use std::convert::TryInto; macro_rules! impl_obj_methods { ($o:expr) => { /// Post a message to max. fn post<M: Into<Vec<u8>>>(&self, msg: M) { crate::object::post($o(self), msg) } /// Post an error message to max. fn post_error<M: Into<Vec<u8>>>(&self, msg: M) { crate::object::error($o(self), msg) } /// Try to register this object with the given namespace and name. fn try_register( &self, namespace: SymbolRef, name: SymbolRef, ) -> Result<Registration, RegistrationError> { unsafe { Registration::try_register($o(self), namespace, name) } } /// Try to attach to the namespace and name. fn try_attach( &self, namespace: SymbolRef, name: SymbolRef, ) -> Result<Attachment, AttachmentError> { unsafe { Attachment::try_attach($o(self), namespace, name) } } /// Subscribe to be attached to the namespace, name and optionally filter by class /// name. fn subscribe( &self, namespace: SymbolRef, name: SymbolRef, class_name: Option<SymbolRef>, ) -> Subscription { unsafe { Subscription::new($o(self), namespace, name, class_name) } } /// Broadcast a message from a registered object to any attached client objects. fn notify(&self, msg: SymbolRef) -> MaxResult<()> { crate::error::MaxError::from( unsafe { max_sys::object_notify($o(self) as _, msg.inner(), std::ptr::null_mut()) as _ }, (), ) } /// Indicate that an attribute has had a change (outside of its setter). /// /// # Arguments /// * `name` - the name of the attribute fn attr_touch_with_name<I: Into<SymbolRef>>(&self, name: I) -> MaxResult<()> { crate::attr::touch_with_name($o(self), name) } /// Indicate that an attribute has had a change (outside of its setter). /// /// # Arguments /// * `name` - the name of the attribute fn attr_try_touch_with_name<I: TryInto<SymbolRef>>(&self, name: I) -> MaxResult<()> { if let Ok(name) = name.try_into() { crate::attr::touch_with_name($o(self), name) } else { Err(MaxError::Generic) } } }; } /// Indicates that your struct can be safely cast to a max_sys::t_object this means your struct /// must be `#[repr(C)]` and have a `max_sys::t_object` as its first member. pub unsafe trait MaxObj: Sized { fn max_obj(&self) -> *mut max_sys::t_object { unsafe { std::mem::transmute::<_, *mut max_sys::t_object>(self) } } impl_obj_methods!(Self::max_obj); } /// Indicates that your struct can be safely cast to a max_sys::t_pxobject this means your struct /// must be `#[repr(C)]` and have a `max_sys::t_pxobject` as its first member. pub unsafe trait MSPObj: Sized { fn msp_obj(&self) -> *mut max_sys::t_pxobject { unsafe { std::mem::transmute::<_, *mut max_sys::t_pxobject>(self) } } /// any MSP object can be safely cast to and used as a max_sys::t_object fn as_max_obj(&self) -> *mut max_sys::t_object { unsafe { std::mem::transmute::<_, *mut max_sys::t_object>(self.msp_obj()) } } impl_obj_methods!(Self::as_max_obj); } use std::ffi::CString; use std::ops::{Deref, DerefMut}; /// Post a message to the Max console, associated with the given object. pub fn post<T: Into<Vec<u8>>>(obj: *mut max_sys::t_object, msg: T) { unsafe { match CString::new(msg) { Ok(p) => max_sys::object_post(obj, p.as_ptr()), //TODO make CString below a const static Err(_) => self::error(obj, "failed to create CString"), } } } /// Post an error to the Max console, associated with the given object pub fn error<T: Into<Vec<u8>>>(obj: *mut max_sys::t_object, msg: T) { unsafe { match CString::new(msg) { Ok(p) => max_sys::object_error(obj, p.as_ptr()), //TODO make CString below a const static Err(_) => { let m = CString::new("failed to create CString").unwrap(); max_sys::object_error(obj, m.as_ptr()) } } } } /// A smart pointer for an object that max allocated pub struct ObjBox<T: MaxObj> { pub value: Option<Box<T>>, //option box so that we can drop if the value still exists } impl<T: MaxObj> ObjBox<T> { pub unsafe fn alloc(class: *mut max_sys::t_class) -> Self { //convert to t_object for debugging let value: *mut max_sys::t_object = std::mem::transmute::<_, _>(max_sys::object_alloc(class)); let value = std::mem::transmute::<_, *mut T>(value); Self::from_raw(value) } pub unsafe fn from_raw(value: *mut T) -> Self { Self { value: Some(Box::from_raw(value)), } } pub fn into_raw(mut self) -> *mut T { let value = self.value.take().unwrap(); Box::into_raw(value) } } impl<T: MaxObj> Deref for ObjBox<T> { type Target = T; fn deref(&self) -> &Self::Target { self.value.as_ref().unwrap().deref() } } impl<T: MaxObj> DerefMut for ObjBox<T> { fn deref_mut(&mut self) -> &mut Self::Target { self.value.as_mut().unwrap().deref_mut() } } impl<T: MaxObj> Drop for ObjBox<T> { fn drop(&mut self) { if let Some(v) = self.value.take() { unsafe { max_sys::object_free(std::mem::transmute::<_, _>(v)); } } } } unsafe impl<T: MaxObj + Sync> Sync for ObjBox<T> {} unsafe impl<T: MaxObj + Send> Send for ObjBox<T> {}
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::audio::{facade::AudioFacade, types::AudioMethod}; use failure::Error; use serde_json::Value; use std::sync::Arc; // Takes SL4F method command and executes corresponding Audio Client methods. pub async fn audio_method_to_fidl( method_name: String, args: Value, facade: Arc<AudioFacade>, ) -> Result<Value, Error> { match method_name.parse()? { AudioMethod::PutInputAudio => facade.put_input_audio(args).await, AudioMethod::StartInputInjection => facade.start_input_injection(args).await, AudioMethod::StopInputInjection => facade.stop_input_injection().await, AudioMethod::StartOutputSave => facade.start_output_save().await, AudioMethod::StopOutputSave => facade.stop_output_save().await, AudioMethod::GetOutputAudio => facade.get_output_audio().await, } }
extern crate gl; extern crate glfw; use std::ffi::CStr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ptr; use cgmath::{Matrix4, vec2, vec3, Vector2, Vector3}; use image::GenericImage; use noise::{NoiseFn, Value}; use rand::Rng; use crate::shader::Shader; use self::gl::types::*; /* landscape either water,grass,earth,concrete */ pub const SQUARES: usize = 96; pub const CELL: f32 = 0.25; pub const ACTUAL_WIDTH: f32 = SQUARES as f32 * CELL * 2.0; pub const LAND_X: usize = 4; pub const LAND_Z: usize = 4; pub const WATER: u8 = 0; pub const LAND: u8 = 1; pub const AIR_STRIP: u8 = 2; pub const SAND: u8 = 3; pub struct Landscape { our_shader: Shader, vao: u32, texture1: u32, pub land_position: [Vector3<f32>; 1], pub height: [[f32; SQUARES + 1]; SQUARES + 1], pub what: [[u8; SQUARES + 1]; SQUARES + 1], pub min: Vector2<f32>, pub max: Vector2<f32>, pub centre: Vector2<f32>, wave: Vector3<f32>, } static mut SINE: f32 = 0.0; impl Landscape { pub fn new(noise: &Value, left: Option<[[f32; SQUARES + 1]; SQUARES + 1]>, below: Option<[[f32; SQUARES + 1]; SQUARES + 1]>, centre_x: f32, centre_z: f32) -> Landscape { let (our_shader, _vbo, vao, texture1, height, what) = unsafe { let mut rng = rand::thread_rng(); let get_sine = |radius: f32| -> f32 { (radius).to_radians().sin() }; let get_cosine = |radius: f32| -> f32 { (radius).to_radians().cos() }; let our_shader = Shader::new( "resources/ground.vs", "resources/ground.fs"); let mut height: [[f32; SQUARES + 1]; SQUARES + 1] = [[0.0; SQUARES + 1]; SQUARES + 1]; let mut what: [[u8; SQUARES + 1]; SQUARES + 1] = [[WATER; SQUARES + 1]; SQUARES + 1]; left.map(|left_height| { for zz in 0..SQUARES + 1 { height[zz][0] = left_height[zz][SQUARES]; } }); below.map(|below_height| { for xx in 0..SQUARES + 1 { height[0][xx] = below_height[SQUARES][xx]; } }); let start_sine = SINE; let from_side = rng.gen_range(20, SQUARES / 2); for zz in from_side..SQUARES - from_side { SINE = start_sine + zz as f32; for xx in from_side..SQUARES - from_side { let v: f64 = noise.get([xx as f64, zz as f64]) / 2.0; if v > 0.49 { let mut start_height = rng.gen_range(2.0, 3.0); height[zz][xx] = start_height; what[zz][xx] = LAND; for scale in 1..SQUARES { for r in 0..45 { let x = get_cosine(r as f32 * 16.0) * scale as f32 + xx as f32; let y = get_sine(r as f32 * 16.0) * scale as f32 + zz as f32; if x > 1.0 && x < SQUARES as f32 - 1.0 && y > 1.0 && y < SQUARES as f32 - 1.0 { if height[y as usize][x as usize] < start_height { height[y as usize][x as usize] = start_height; what[y as usize][x as usize] = LAND; } } } let less: f32 = (noise.get([xx as f64, zz as f64]).abs() / 16.0) as f32; start_height = start_height - less * scale as f32 / 5.0; } } } } for zz in 2..SQUARES-3 { for xx in 2..SQUARES-3 { if what[zz][xx] == LAND { for zzz in zz-2..zz+2 { for xxx in xx-2..xx+2 { if what[zzz][xxx] == WATER { what[zzz][xxx] = SAND; } } } } } } let landing_width = 6; let landing_length = SQUARES / 3; let centre = SQUARES / 2; let landing_height = height[centre][centre]; if landing_height > 1.0 && rng.gen_range(0, 5) >= 2 { Landscape::landing_strip(&mut height, &mut what, landing_width, landing_length, centre, landing_height) } let mut vertices: [f32; SQUARES * SQUARES * 30] = [0.0; SQUARES * SQUARES * 30]; let image_add = 1.0 / 10.0; let mut col: f32 = 0.0; let mut water_flip = 1.0; for zz in 0..SQUARES { let offset = SQUARES * 30 * zz; let z: f32 = CELL * 2.0 * (zz as f32 - (SQUARES as f32 / 2.0)) as f32; for xx in 0..SQUARES { water_flip = water_flip + 0.3; let x: f32 = CELL * 2.0 * (xx as f32 - (SQUARES as f32 / 2.0)) as f32; let py1: f32 = height[zz][xx]; let py2: f32 = height[zz][xx + 1]; let ny1: f32 = height[zz + 1][xx]; let ny2: f32 = height[zz + 1][xx + 1]; col = Landscape::next_tex(xx,zz,col, image_add); //if py1 == 0.0 && py2 == 0.0 { if what[zz][xx] == WATER { col = 5.0 * image_add + (image_add * (water_flip as i32 % 3 + 0) as f32); } //if py1 >0.0 && py1 < 0.99 && py2 > 0.0 && py2 < 0.99 { col = 0.4 ; } if what[zz][xx] == SAND { col = 0.4 ; } if what[zz][xx] == AIR_STRIP { col = 8.0 * image_add + (image_add * (water_flip as i32 % 2 + 0) as f32); } let c: [f32; 30] = [ x + -CELL, py1, z + -CELL, col, 0.0, x + CELL, py2, z + -CELL, col + image_add, 0.0, x + CELL, ny2, z + CELL, col + image_add, 1.0, x + CELL, ny2, z + CELL, col + image_add, 1.0, x + -CELL, ny1, z + CELL, col, 1.0, x + -CELL, py1, z + -CELL, col, 0.0, ]; for i in 0..30 { vertices[offset + i + xx * 30] = c[i]; } } water_flip = water_flip + 0.3; col = Landscape::next_tex(0,zz,col, image_add); } let (mut vbo, mut vao) = (0, 0); gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut vbo); gl::BindVertexArray(vao); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); let mut texture1 = 0; gl::GenTextures(1, &mut texture1); gl::BindTexture(gl::TEXTURE_2D, texture1); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32); let img = image::open(&Path::new("resources/textures/landscape.png")).expect("Failed to load texture"); let data = img.raw_pixels(); gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, img.width() as i32, img.height() as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const c_void); gl::GenerateMipmap(gl::TEXTURE_2D); our_shader.useProgram(); our_shader.setInt(c_str!("texture1"), 0); (our_shader, vbo, vao, texture1, height, what) }; let land_position: [Vector3<f32>; 1] = [vec3(centre_x, 0.0, centre_z)]; let min = vec2(centre_x - SQUARES as f32 * CELL, centre_z - SQUARES as f32 * CELL); let max = vec2(centre_x + SQUARES as f32 * CELL, centre_z + SQUARES as f32 * CELL); let centre = vec2(centre_x + SQUARES as f32 * CELL / 2.0, centre_z + SQUARES as f32 * CELL / 2.0); //println!("Created landscape {},{}", centre_x, centre_z); Landscape { our_shader, vao, texture1, land_position, height, what, min, max, centre, wave: vec3(1.0, 0.0, 0.0), } } fn landing_strip(height: &mut [[f32; 97]; 97], what: &mut [[u8; 97]; 97], landing_width: i32, landing_length: usize, centre: usize, landing_height: f32) { let mut rng = rand::thread_rng(); let angle: f32 = rng.gen_range(0, 360) as f32; let r = 1.0; let add_x: f32 = angle.to_radians().sin() * r; let add_z: f32 = angle.to_radians().cos() * r; let i_add_x: f32 = (270.0 + angle).to_radians().sin() * r; let i_add_z: f32 = (270.0 + angle).to_radians().cos() * r; let mut xx = centre as f32 - (add_x * landing_length as f32 / 2.0); let mut zz = centre as f32 - (add_z * landing_length as f32 / 2.0); for _i in 0..landing_length { let z_index = zz as usize; let x_index = xx as usize; height[z_index][x_index] = landing_height; what[z_index][x_index] = AIR_STRIP; { let mut xx = xx; let mut zz = zz; for _ii in 0..landing_width { for round_error in 0..2 { // make sure no gaps height[round_error + zz as usize - 1][round_error + xx as usize - 1] = landing_height; what[round_error + zz as usize - 1][round_error + xx as usize - 1] = AIR_STRIP; } xx = xx + i_add_x; zz = zz + i_add_z } } xx = xx + add_x; zz = zz + add_z } } fn next_tex(_x:usize,_z:usize,current_col: f32, image_add: f32) -> f32 { let mut col: f32 = current_col; col = col + image_add ; //* x as f32 /z as f32 ; if col >= image_add * 4.0 { col = 0.0; } //println!("Col is {}", col); return col; } pub fn update(&mut self) { let mut rng = rand::thread_rng(); self.wave.y = self.wave.y + (self.wave.x * rng.gen_range(0.0, 0.005)); if self.wave.y > 0.2 { self.wave.x = -1.0; } if self.wave.y <= 0.0 { self.wave.x = 1.0; } } pub fn render(&self, projection: &Matrix4<f32>, view: &Matrix4<f32>, at_position: Vector3<f32>) { unsafe { gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, self.texture1); self.our_shader.useProgram(); self.our_shader.setMat4(c_str!("projection"), projection); self.our_shader.setMat4(c_str!("view"), view); self.our_shader.setVec3(c_str!("wave"), self.wave.x, self.wave.y, self.wave.z); gl::BindVertexArray(self.vao); let model: Matrix4<f32> = Matrix4::from_translation(at_position); self.our_shader.setMat4(c_str!("model"), &model); gl::DrawArrays(gl::TRIANGLES, 0, (SQUARES * SQUARES) as i32 * 6); } } }
pub mod cmd; pub mod logger; pub mod resources; pub type Logger = slog::Logger; pub type ArgFlags = clap::ArgMatches<'static>;
#[doc = "Reader of register MMCTIR"] pub type R = crate::R<u32, super::MMCTIR>; #[doc = "Writer for register MMCTIR"] pub type W = crate::W<u32, super::MMCTIR>; #[doc = "Register MMCTIR `reset()`'s with value 0"] impl crate::ResetValue for super::MMCTIR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TGFSCS`"] pub type TGFSCS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TGFSCS`"] pub struct TGFSCS_W<'a> { w: &'a mut W, } impl<'a> TGFSCS_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `TGFMSCS`"] pub type TGFMSCS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TGFMSCS`"] pub struct TGFMSCS_W<'a> { w: &'a mut W, } impl<'a> TGFMSCS_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `TGFS`"] pub type TGFS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TGFS`"] pub struct TGFS_W<'a> { w: &'a mut W, } impl<'a> TGFS_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } impl R { #[doc = "Bit 14 - Transmitted good frames single collision status"] #[inline(always)] pub fn tgfscs(&self) -> TGFSCS_R { TGFSCS_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - Transmitted good frames more than single collision status"] #[inline(always)] pub fn tgfmscs(&self) -> TGFMSCS_R { TGFMSCS_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 21 - Transmitted good frames status"] #[inline(always)] pub fn tgfs(&self) -> TGFS_R { TGFS_R::new(((self.bits >> 21) & 0x01) != 0) } } impl W { #[doc = "Bit 14 - Transmitted good frames single collision status"] #[inline(always)] pub fn tgfscs(&mut self) -> TGFSCS_W { TGFSCS_W { w: self } } #[doc = "Bit 15 - Transmitted good frames more than single collision status"] #[inline(always)] pub fn tgfmscs(&mut self) -> TGFMSCS_W { TGFMSCS_W { w: self } } #[doc = "Bit 21 - Transmitted good frames status"] #[inline(always)] pub fn tgfs(&mut self) -> TGFS_W { TGFS_W { w: self } } }
use url; use futures::future; use hyper::{Body, Request, Response, Server, StatusCode, Method, header}; use serde::Serialize; use hyper::rt::{self, Future}; use hyper::service::service_fn; use chrono_tz; use chrono::{DateTime, TimeZone}; use std::collections::HashMap; use when::{self, DateTimeError}; #[derive(Serialize, Debug)] struct ParsedQuery { source_str: String, merge_dist: usize, timezone: String, exact_match: bool, } #[derive(Serialize, Debug)] struct ServerResponse { #[serde(flatten)] parsed_args: ParsedQuery, result: Result<Vec<String>, DateTimeError>, } fn prepare_result<Tz: TimeZone>(parsed: Vec<Result<DateTime<Tz>, DateTimeError>>, into_unix_ts: bool) -> Result<Vec<String>, DateTimeError> { let mut result = Vec::new(); for item in parsed { let x = match item { Ok(x) => { if into_unix_ts { format!("{}", x.timestamp()) } else { format!("{:?}", x) } }, Err(err) => return Err(err), }; result.push(x); } Ok(result) } fn str2bool(input: &str) -> bool { let input = input.to_lowercase(); if input == "false" || input == "0" || input == "f" { return false } true } fn parse_timezone(tz: &str) -> chrono_tz::Tz { let tz: chrono_tz::Tz = tz.parse().unwrap(); tz } fn do_parse(hash_query: HashMap<String, String>, into_unix_ts: bool) -> (ParsedQuery, Result<Vec<std::string::String>, DateTimeError>) { let default_tz = "Europe/Moscow".to_owned(); // parse get arguments let input_str = hash_query .get("input") .unwrap(); let tz_str = hash_query .get("tz") .unwrap_or(&default_tz); let timezone = parse_timezone(tz_str); let exact_match = str2bool(hash_query .get("exact_match") .unwrap_or(&String::from("false"))); let merge_dist = hash_query .get("dist") .unwrap_or(&String::from("5")) .parse::<usize>() .unwrap(); let query = ParsedQuery { source_str: input_str.clone(), timezone: tz_str.clone(), exact_match, merge_dist, }; let parser = when::parser::Parser::new(timezone) .parser(Box::new(&when::en)) .max_dist(merge_dist) .fuzzy_parse(true); (query, prepare_result(parser.parse(&input_str), into_unix_ts)) } type BoxFut = Box<dyn Future<Item = Response<Body>, Error = hyper::Error> + Send>; fn handler(req: Request<Body>) -> BoxFut { let mut response = Response::new(Body::empty()); match (req.method(), req.uri().path()) { // Parse natural language time/date at /get (&Method::GET, "/get") => { let parsed_url = url::form_urlencoded::parse(req.uri().query().unwrap().as_bytes()); let hash_query: HashMap<_, _> = parsed_url.into_owned().collect(); let (query_params, result) = do_parse(hash_query, false); let resp = serde_json::to_string(&ServerResponse { parsed_args: query_params, result, }).unwrap(); response = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "application/json") .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .body(Body::from(resp)) .unwrap(); } (&Method::GET, "/get_unix") => { let parsed_url = url::form_urlencoded::parse(req.uri().query().unwrap().as_bytes()); let hash_query: HashMap<_, _> = parsed_url.into_owned().collect(); let (query_params, result) = do_parse(hash_query, true); let resp = serde_json::to_string(&ServerResponse { parsed_args: query_params, result, }).unwrap(); response = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "application/json") .header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .body(Body::from(resp)) .unwrap(); } // The 404 Not Found route... _ => { *response.status_mut() = StatusCode::NOT_FOUND; } } Box::new(future::ok(response)) } fn main() { pretty_env_logger::init(); let addr = ([0, 0, 0, 0], 3000).into(); let server = Server::bind(&addr) .serve(|| service_fn(handler)) .map_err(|e| eprintln!("server error: {}", e)); println!("Listening on http://{}", addr); rt::run(server); }
#[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::PINENABLE0 { #[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 `ACMP_I1_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ACMP_I1_ENR { #[doc = "Enable ACMP_I1. This function is enabled on pin PIO0_0."] ENABLE_ACMP_I1_THIS, #[doc = "Disable ACMP_I1. GPIO function PIO0_0 (default) or any other movable function can be assigned to pin PIO0_0."] DISABLE_ACMP_I1_GPI, } impl ACMP_I1_ENR { #[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 { ACMP_I1_ENR::ENABLE_ACMP_I1_THIS => false, ACMP_I1_ENR::DISABLE_ACMP_I1_GPI => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ACMP_I1_ENR { match value { false => ACMP_I1_ENR::ENABLE_ACMP_I1_THIS, true => ACMP_I1_ENR::DISABLE_ACMP_I1_GPI, } } #[doc = "Checks if the value of the field is `ENABLE_ACMP_I1_THIS`"] #[inline] pub fn is_enable_acmp_i1_this(&self) -> bool { *self == ACMP_I1_ENR::ENABLE_ACMP_I1_THIS } #[doc = "Checks if the value of the field is `DISABLE_ACMP_I1_GPI`"] #[inline] pub fn is_disable_acmp_i1_gpi(&self) -> bool { *self == ACMP_I1_ENR::DISABLE_ACMP_I1_GPI } } #[doc = "Possible values of the field `ACMP_I2_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ACMP_I2_ENR { #[doc = "Enable ACMP_I2. This function is enabled on pin PIO0_1."] ENABLE_ACMP_I2_THIS, #[doc = "Disable ACMP_I2. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin PIO0_1."] DISABLE_ACMP_I2_GPI, } impl ACMP_I2_ENR { #[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 { ACMP_I2_ENR::ENABLE_ACMP_I2_THIS => false, ACMP_I2_ENR::DISABLE_ACMP_I2_GPI => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ACMP_I2_ENR { match value { false => ACMP_I2_ENR::ENABLE_ACMP_I2_THIS, true => ACMP_I2_ENR::DISABLE_ACMP_I2_GPI, } } #[doc = "Checks if the value of the field is `ENABLE_ACMP_I2_THIS`"] #[inline] pub fn is_enable_acmp_i2_this(&self) -> bool { *self == ACMP_I2_ENR::ENABLE_ACMP_I2_THIS } #[doc = "Checks if the value of the field is `DISABLE_ACMP_I2_GPI`"] #[inline] pub fn is_disable_acmp_i2_gpi(&self) -> bool { *self == ACMP_I2_ENR::DISABLE_ACMP_I2_GPI } } #[doc = "Possible values of the field `SWCLK_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWCLK_ENR { #[doc = "Enable SWCLK. This function is enabled on pin PIO0_3."] ENABLE_SWCLK_THIS_F, #[doc = "Disable SWCLK. GPIO function PIO0_3 is selected on this pin. Any other movable function can be assigned to pin PIO0_3."] DISABLE_SWCLK_GPIO_, } impl SWCLK_ENR { #[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 { SWCLK_ENR::ENABLE_SWCLK_THIS_F => false, SWCLK_ENR::DISABLE_SWCLK_GPIO_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SWCLK_ENR { match value { false => SWCLK_ENR::ENABLE_SWCLK_THIS_F, true => SWCLK_ENR::DISABLE_SWCLK_GPIO_, } } #[doc = "Checks if the value of the field is `ENABLE_SWCLK_THIS_F`"] #[inline] pub fn is_enable_swclk_this_f(&self) -> bool { *self == SWCLK_ENR::ENABLE_SWCLK_THIS_F } #[doc = "Checks if the value of the field is `DISABLE_SWCLK_GPIO_`"] #[inline] pub fn is_disable_swclk_gpio_(&self) -> bool { *self == SWCLK_ENR::DISABLE_SWCLK_GPIO_ } } #[doc = "Possible values of the field `SWDIO_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWDIO_ENR { #[doc = "Enable SWDIO. This function is enabled on pin PIO0_2."] ENABLE_SWDIO_THIS_F, #[doc = "Disable SWDIO. GPIO function PIO0_2 is selected on this pin. Any other movable function can be assigned to pin PIO0_2."] DISABLE_SWDIO_GPIO_, } impl SWDIO_ENR { #[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 { SWDIO_ENR::ENABLE_SWDIO_THIS_F => false, SWDIO_ENR::DISABLE_SWDIO_GPIO_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SWDIO_ENR { match value { false => SWDIO_ENR::ENABLE_SWDIO_THIS_F, true => SWDIO_ENR::DISABLE_SWDIO_GPIO_, } } #[doc = "Checks if the value of the field is `ENABLE_SWDIO_THIS_F`"] #[inline] pub fn is_enable_swdio_this_f(&self) -> bool { *self == SWDIO_ENR::ENABLE_SWDIO_THIS_F } #[doc = "Checks if the value of the field is `DISABLE_SWDIO_GPIO_`"] #[inline] pub fn is_disable_swdio_gpio_(&self) -> bool { *self == SWDIO_ENR::DISABLE_SWDIO_GPIO_ } } #[doc = "Possible values of the field `XTALIN_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum XTALIN_ENR { #[doc = "Enable XTALIN. This function is enabled on pin PIO0_8."] ENABLE_XTALIN_THIS_, #[doc = "Disable XTALIN. GPIO function PIO0_8 (default) or any other movable function can be assigned to pin PIO0_8."] DISABLE_XTALIN_GPIO, } impl XTALIN_ENR { #[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 { XTALIN_ENR::ENABLE_XTALIN_THIS_ => false, XTALIN_ENR::DISABLE_XTALIN_GPIO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> XTALIN_ENR { match value { false => XTALIN_ENR::ENABLE_XTALIN_THIS_, true => XTALIN_ENR::DISABLE_XTALIN_GPIO, } } #[doc = "Checks if the value of the field is `ENABLE_XTALIN_THIS_`"] #[inline] pub fn is_enable_xtalin_this_(&self) -> bool { *self == XTALIN_ENR::ENABLE_XTALIN_THIS_ } #[doc = "Checks if the value of the field is `DISABLE_XTALIN_GPIO`"] #[inline] pub fn is_disable_xtalin_gpio(&self) -> bool { *self == XTALIN_ENR::DISABLE_XTALIN_GPIO } } #[doc = "Possible values of the field `XTALOUT_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum XTALOUT_ENR { #[doc = "Enable XTALOUT. This function is enabled on pin PIO0_9."] ENABLE_XTALOUT_THIS, #[doc = "Disable XTALOUT. GPIO function PIO0_9 (default) or any other movable function can be assigned to pin PIO0_9."] DISABLE_XTALOUT_GPI, } impl XTALOUT_ENR { #[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 { XTALOUT_ENR::ENABLE_XTALOUT_THIS => false, XTALOUT_ENR::DISABLE_XTALOUT_GPI => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> XTALOUT_ENR { match value { false => XTALOUT_ENR::ENABLE_XTALOUT_THIS, true => XTALOUT_ENR::DISABLE_XTALOUT_GPI, } } #[doc = "Checks if the value of the field is `ENABLE_XTALOUT_THIS`"] #[inline] pub fn is_enable_xtalout_this(&self) -> bool { *self == XTALOUT_ENR::ENABLE_XTALOUT_THIS } #[doc = "Checks if the value of the field is `DISABLE_XTALOUT_GPI`"] #[inline] pub fn is_disable_xtalout_gpi(&self) -> bool { *self == XTALOUT_ENR::DISABLE_XTALOUT_GPI } } #[doc = "Possible values of the field `RESET_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RESET_ENR { #[doc = "Enable RESET. This function is enabled on pin PIO0_5."] ENABLE_RESET_THIS_F, #[doc = "Disable RESET. GPIO function PIO0_5 is selected on this pin. Any other movable function can be assigned to pin PIO0_5."] DISABLE_RESET_GPIO_, } impl RESET_ENR { #[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 { RESET_ENR::ENABLE_RESET_THIS_F => false, RESET_ENR::DISABLE_RESET_GPIO_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> RESET_ENR { match value { false => RESET_ENR::ENABLE_RESET_THIS_F, true => RESET_ENR::DISABLE_RESET_GPIO_, } } #[doc = "Checks if the value of the field is `ENABLE_RESET_THIS_F`"] #[inline] pub fn is_enable_reset_this_f(&self) -> bool { *self == RESET_ENR::ENABLE_RESET_THIS_F } #[doc = "Checks if the value of the field is `DISABLE_RESET_GPIO_`"] #[inline] pub fn is_disable_reset_gpio_(&self) -> bool { *self == RESET_ENR::DISABLE_RESET_GPIO_ } } #[doc = "Possible values of the field `CLKIN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLKINR { #[doc = "Enable CLKIN. This function is enabled on pin PIO0_1."] ENABLE_CLKIN_THIS_F, #[doc = "Disable CLKIN. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin CLKIN."] DISABLE_CLKIN_GPIO_, } impl CLKINR { #[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 { CLKINR::ENABLE_CLKIN_THIS_F => false, CLKINR::DISABLE_CLKIN_GPIO_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> CLKINR { match value { false => CLKINR::ENABLE_CLKIN_THIS_F, true => CLKINR::DISABLE_CLKIN_GPIO_, } } #[doc = "Checks if the value of the field is `ENABLE_CLKIN_THIS_F`"] #[inline] pub fn is_enable_clkin_this_f(&self) -> bool { *self == CLKINR::ENABLE_CLKIN_THIS_F } #[doc = "Checks if the value of the field is `DISABLE_CLKIN_GPIO_`"] #[inline] pub fn is_disable_clkin_gpio_(&self) -> bool { *self == CLKINR::DISABLE_CLKIN_GPIO_ } } #[doc = "Possible values of the field `VDDCMP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDDCMPR { #[doc = "Enable VDDCMP. This function is enabled on pin PIO0_6."] ENABLE_VDDCMP_THIS_, #[doc = "Disable VDDCMP. GPIO function PIO0_6 (default) or any other movable function can be assigned to pin PIO0_6."] DISABLE_VDDCMP_GPIO, } impl VDDCMPR { #[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 { VDDCMPR::ENABLE_VDDCMP_THIS_ => false, VDDCMPR::DISABLE_VDDCMP_GPIO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> VDDCMPR { match value { false => VDDCMPR::ENABLE_VDDCMP_THIS_, true => VDDCMPR::DISABLE_VDDCMP_GPIO, } } #[doc = "Checks if the value of the field is `ENABLE_VDDCMP_THIS_`"] #[inline] pub fn is_enable_vddcmp_this_(&self) -> bool { *self == VDDCMPR::ENABLE_VDDCMP_THIS_ } #[doc = "Checks if the value of the field is `DISABLE_VDDCMP_GPIO`"] #[inline] pub fn is_disable_vddcmp_gpio(&self) -> bool { *self == VDDCMPR::DISABLE_VDDCMP_GPIO } } #[doc = "Values that can be written to the field `ACMP_I1_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ACMP_I1_ENW { #[doc = "Enable ACMP_I1. This function is enabled on pin PIO0_0."] ENABLE_ACMP_I1_THIS, #[doc = "Disable ACMP_I1. GPIO function PIO0_0 (default) or any other movable function can be assigned to pin PIO0_0."] DISABLE_ACMP_I1_GPI, } impl ACMP_I1_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ACMP_I1_ENW::ENABLE_ACMP_I1_THIS => false, ACMP_I1_ENW::DISABLE_ACMP_I1_GPI => true, } } } #[doc = r" Proxy"] pub struct _ACMP_I1_ENW<'a> { w: &'a mut W, } impl<'a> _ACMP_I1_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ACMP_I1_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable ACMP_I1. This function is enabled on pin PIO0_0."] #[inline] pub fn enable_acmp_i1_this(self) -> &'a mut W { self.variant(ACMP_I1_ENW::ENABLE_ACMP_I1_THIS) } #[doc = "Disable ACMP_I1. GPIO function PIO0_0 (default) or any other movable function can be assigned to pin PIO0_0."] #[inline] pub fn disable_acmp_i1_gpi(self) -> &'a mut W { self.variant(ACMP_I1_ENW::DISABLE_ACMP_I1_GPI) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `ACMP_I2_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ACMP_I2_ENW { #[doc = "Enable ACMP_I2. This function is enabled on pin PIO0_1."] ENABLE_ACMP_I2_THIS, #[doc = "Disable ACMP_I2. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin PIO0_1."] DISABLE_ACMP_I2_GPI, } impl ACMP_I2_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ACMP_I2_ENW::ENABLE_ACMP_I2_THIS => false, ACMP_I2_ENW::DISABLE_ACMP_I2_GPI => true, } } } #[doc = r" Proxy"] pub struct _ACMP_I2_ENW<'a> { w: &'a mut W, } impl<'a> _ACMP_I2_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ACMP_I2_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable ACMP_I2. This function is enabled on pin PIO0_1."] #[inline] pub fn enable_acmp_i2_this(self) -> &'a mut W { self.variant(ACMP_I2_ENW::ENABLE_ACMP_I2_THIS) } #[doc = "Disable ACMP_I2. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin PIO0_1."] #[inline] pub fn disable_acmp_i2_gpi(self) -> &'a mut W { self.variant(ACMP_I2_ENW::DISABLE_ACMP_I2_GPI) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SWCLK_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWCLK_ENW { #[doc = "Enable SWCLK. This function is enabled on pin PIO0_3."] ENABLE_SWCLK_THIS_F, #[doc = "Disable SWCLK. GPIO function PIO0_3 is selected on this pin. Any other movable function can be assigned to pin PIO0_3."] DISABLE_SWCLK_GPIO_, } impl SWCLK_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SWCLK_ENW::ENABLE_SWCLK_THIS_F => false, SWCLK_ENW::DISABLE_SWCLK_GPIO_ => true, } } } #[doc = r" Proxy"] pub struct _SWCLK_ENW<'a> { w: &'a mut W, } impl<'a> _SWCLK_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SWCLK_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable SWCLK. This function is enabled on pin PIO0_3."] #[inline] pub fn enable_swclk_this_f(self) -> &'a mut W { self.variant(SWCLK_ENW::ENABLE_SWCLK_THIS_F) } #[doc = "Disable SWCLK. GPIO function PIO0_3 is selected on this pin. Any other movable function can be assigned to pin PIO0_3."] #[inline] pub fn disable_swclk_gpio_(self) -> &'a mut W { self.variant(SWCLK_ENW::DISABLE_SWCLK_GPIO_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SWDIO_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWDIO_ENW { #[doc = "Enable SWDIO. This function is enabled on pin PIO0_2."] ENABLE_SWDIO_THIS_F, #[doc = "Disable SWDIO. GPIO function PIO0_2 is selected on this pin. Any other movable function can be assigned to pin PIO0_2."] DISABLE_SWDIO_GPIO_, } impl SWDIO_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SWDIO_ENW::ENABLE_SWDIO_THIS_F => false, SWDIO_ENW::DISABLE_SWDIO_GPIO_ => true, } } } #[doc = r" Proxy"] pub struct _SWDIO_ENW<'a> { w: &'a mut W, } impl<'a> _SWDIO_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SWDIO_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable SWDIO. This function is enabled on pin PIO0_2."] #[inline] pub fn enable_swdio_this_f(self) -> &'a mut W { self.variant(SWDIO_ENW::ENABLE_SWDIO_THIS_F) } #[doc = "Disable SWDIO. GPIO function PIO0_2 is selected on this pin. Any other movable function can be assigned to pin PIO0_2."] #[inline] pub fn disable_swdio_gpio_(self) -> &'a mut W { self.variant(SWDIO_ENW::DISABLE_SWDIO_GPIO_) } #[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 `XTALIN_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum XTALIN_ENW { #[doc = "Enable XTALIN. This function is enabled on pin PIO0_8."] ENABLE_XTALIN_THIS_, #[doc = "Disable XTALIN. GPIO function PIO0_8 (default) or any other movable function can be assigned to pin PIO0_8."] DISABLE_XTALIN_GPIO, } impl XTALIN_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { XTALIN_ENW::ENABLE_XTALIN_THIS_ => false, XTALIN_ENW::DISABLE_XTALIN_GPIO => true, } } } #[doc = r" Proxy"] pub struct _XTALIN_ENW<'a> { w: &'a mut W, } impl<'a> _XTALIN_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: XTALIN_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable XTALIN. This function is enabled on pin PIO0_8."] #[inline] pub fn enable_xtalin_this_(self) -> &'a mut W { self.variant(XTALIN_ENW::ENABLE_XTALIN_THIS_) } #[doc = "Disable XTALIN. GPIO function PIO0_8 (default) or any other movable function can be assigned to pin PIO0_8."] #[inline] pub fn disable_xtalin_gpio(self) -> &'a mut W { self.variant(XTALIN_ENW::DISABLE_XTALIN_GPIO) } #[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 `XTALOUT_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum XTALOUT_ENW { #[doc = "Enable XTALOUT. This function is enabled on pin PIO0_9."] ENABLE_XTALOUT_THIS, #[doc = "Disable XTALOUT. GPIO function PIO0_9 (default) or any other movable function can be assigned to pin PIO0_9."] DISABLE_XTALOUT_GPI, } impl XTALOUT_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { XTALOUT_ENW::ENABLE_XTALOUT_THIS => false, XTALOUT_ENW::DISABLE_XTALOUT_GPI => true, } } } #[doc = r" Proxy"] pub struct _XTALOUT_ENW<'a> { w: &'a mut W, } impl<'a> _XTALOUT_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: XTALOUT_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable XTALOUT. This function is enabled on pin PIO0_9."] #[inline] pub fn enable_xtalout_this(self) -> &'a mut W { self.variant(XTALOUT_ENW::ENABLE_XTALOUT_THIS) } #[doc = "Disable XTALOUT. GPIO function PIO0_9 (default) or any other movable function can be assigned to pin PIO0_9."] #[inline] pub fn disable_xtalout_gpi(self) -> &'a mut W { self.variant(XTALOUT_ENW::DISABLE_XTALOUT_GPI) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `RESET_EN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RESET_ENW { #[doc = "Enable RESET. This function is enabled on pin PIO0_5."] ENABLE_RESET_THIS_F, #[doc = "Disable RESET. GPIO function PIO0_5 is selected on this pin. Any other movable function can be assigned to pin PIO0_5."] DISABLE_RESET_GPIO_, } impl RESET_ENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { RESET_ENW::ENABLE_RESET_THIS_F => false, RESET_ENW::DISABLE_RESET_GPIO_ => true, } } } #[doc = r" Proxy"] pub struct _RESET_ENW<'a> { w: &'a mut W, } impl<'a> _RESET_ENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: RESET_ENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable RESET. This function is enabled on pin PIO0_5."] #[inline] pub fn enable_reset_this_f(self) -> &'a mut W { self.variant(RESET_ENW::ENABLE_RESET_THIS_F) } #[doc = "Disable RESET. GPIO function PIO0_5 is selected on this pin. Any other movable function can be assigned to pin PIO0_5."] #[inline] pub fn disable_reset_gpio_(self) -> &'a mut W { self.variant(RESET_ENW::DISABLE_RESET_GPIO_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `CLKIN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLKINW { #[doc = "Enable CLKIN. This function is enabled on pin PIO0_1."] ENABLE_CLKIN_THIS_F, #[doc = "Disable CLKIN. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin CLKIN."] DISABLE_CLKIN_GPIO_, } impl CLKINW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { CLKINW::ENABLE_CLKIN_THIS_F => false, CLKINW::DISABLE_CLKIN_GPIO_ => true, } } } #[doc = r" Proxy"] pub struct _CLKINW<'a> { w: &'a mut W, } impl<'a> _CLKINW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: CLKINW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable CLKIN. This function is enabled on pin PIO0_1."] #[inline] pub fn enable_clkin_this_f(self) -> &'a mut W { self.variant(CLKINW::ENABLE_CLKIN_THIS_F) } #[doc = "Disable CLKIN. GPIO function PIO0_1 (default) or any other movable function can be assigned to pin CLKIN."] #[inline] pub fn disable_clkin_gpio_(self) -> &'a mut W { self.variant(CLKINW::DISABLE_CLKIN_GPIO_) } #[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 `VDDCMP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VDDCMPW { #[doc = "Enable VDDCMP. This function is enabled on pin PIO0_6."] ENABLE_VDDCMP_THIS_, #[doc = "Disable VDDCMP. GPIO function PIO0_6 (default) or any other movable function can be assigned to pin PIO0_6."] DISABLE_VDDCMP_GPIO, } impl VDDCMPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { VDDCMPW::ENABLE_VDDCMP_THIS_ => false, VDDCMPW::DISABLE_VDDCMP_GPIO => true, } } } #[doc = r" Proxy"] pub struct _VDDCMPW<'a> { w: &'a mut W, } impl<'a> _VDDCMPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: VDDCMPW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Enable VDDCMP. This function is enabled on pin PIO0_6."] #[inline] pub fn enable_vddcmp_this_(self) -> &'a mut W { self.variant(VDDCMPW::ENABLE_VDDCMP_THIS_) } #[doc = "Disable VDDCMP. GPIO function PIO0_6 (default) or any other movable function can be assigned to pin PIO0_6."] #[inline] pub fn disable_vddcmp_gpio(self) -> &'a mut W { self.variant(VDDCMPW::DISABLE_VDDCMP_GPIO) } #[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 } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn acmp_i1_en(&self) -> ACMP_I1_ENR { ACMP_I1_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed-pin function is deselected and GPIO is assigned to this pin. Functions CLKIN and ACMP_I2 are connected to the same pin PIO0_1. To use ACMP_I2, disable the CLKIN function in bit 7 of this register and enable ACMP_I2."] #[inline] pub fn acmp_i2_en(&self) -> ACMP_I2_ENR { ACMP_I2_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 2 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn swclk_en(&self) -> SWCLK_ENR { SWCLK_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn swdio_en(&self) -> SWDIO_ENR { SWDIO_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 4 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn xtalin_en(&self) -> XTALIN_ENR { XTALIN_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 5 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn xtalout_en(&self) -> XTALOUT_ENR { XTALOUT_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 6 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn reset_en(&self) -> RESET_ENR { RESET_ENR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 7 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed-pin function is deselected and GPIO is assigned to this pin. Functions CLKIN and ACMP_I2 are connected to the same pin PIO0_1. To use CLKIN, disable ACMP_I2 in bit 1 of this register and enable CLKIN."] #[inline] pub fn clkin(&self) -> CLKINR { CLKINR::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn vddcmp(&self) -> VDDCMPR { VDDCMPR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 435 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn acmp_i1_en(&mut self) -> _ACMP_I1_ENW { _ACMP_I1_ENW { w: self } } #[doc = "Bit 1 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed-pin function is deselected and GPIO is assigned to this pin. Functions CLKIN and ACMP_I2 are connected to the same pin PIO0_1. To use ACMP_I2, disable the CLKIN function in bit 7 of this register and enable ACMP_I2."] #[inline] pub fn acmp_i2_en(&mut self) -> _ACMP_I2_ENW { _ACMP_I2_ENW { w: self } } #[doc = "Bit 2 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn swclk_en(&mut self) -> _SWCLK_ENW { _SWCLK_ENW { w: self } } #[doc = "Bit 3 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn swdio_en(&mut self) -> _SWDIO_ENW { _SWDIO_ENW { w: self } } #[doc = "Bit 4 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn xtalin_en(&mut self) -> _XTALIN_ENW { _XTALIN_ENW { w: self } } #[doc = "Bit 5 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn xtalout_en(&mut self) -> _XTALOUT_ENW { _XTALOUT_ENW { w: self } } #[doc = "Bit 6 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. This function is selected by default."] #[inline] pub fn reset_en(&mut self) -> _RESET_ENW { _RESET_ENW { w: self } } #[doc = "Bit 7 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed-pin function is deselected and GPIO is assigned to this pin. Functions CLKIN and ACMP_I2 are connected to the same pin PIO0_1. To use CLKIN, disable ACMP_I2 in bit 1 of this register and enable CLKIN."] #[inline] pub fn clkin(&mut self) -> _CLKINW { _CLKINW { w: self } } #[doc = "Bit 8 - Enables fixed-pin function. Writing a 1 deselects the function and any movable function can be assigned to this pin. By default the fixed--pin function is deselected and GPIO is assigned to this pin."] #[inline] pub fn vddcmp(&mut self) -> _VDDCMPW { _VDDCMPW { w: self } } }
#[doc = "Reader of register CNT"] pub type R = crate::R<u32, super::CNT>; #[doc = "Writer for register CNT"] pub type W = crate::W<u32, super::CNT>; #[doc = "Register CNT `reset()`'s with value 0"] impl crate::ResetValue for super::CNT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CNT`"] pub type CNT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CNT`"] pub struct CNT_W<'a> { w: &'a mut W, } impl<'a> CNT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `CNTH`"] pub type CNTH_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CNTH`"] pub struct CNTH_W<'a> { w: &'a mut W, } impl<'a> CNTH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7fff << 16)) | (((value as u32) & 0x7fff) << 16); self.w } } #[doc = "Reader of field `CNT_or_UIFCPY`"] pub type CNT_OR_UIFCPY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CNT_or_UIFCPY`"] pub struct CNT_OR_UIFCPY_W<'a> { w: &'a mut W, } impl<'a> CNT_OR_UIFCPY_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:15 - Counter value"] #[inline(always)] pub fn cnt(&self) -> CNT_R { CNT_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:30 - High counter value"] #[inline(always)] pub fn cnth(&self) -> CNTH_R { CNTH_R::new(((self.bits >> 16) & 0x7fff) as u16) } #[doc = "Bit 31 - if IUFREMAP=0 than CNT with read write access else UIFCPY with read only access"] #[inline(always)] pub fn cnt_or_uifcpy(&self) -> CNT_OR_UIFCPY_R { CNT_OR_UIFCPY_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - Counter value"] #[inline(always)] pub fn cnt(&mut self) -> CNT_W { CNT_W { w: self } } #[doc = "Bits 16:30 - High counter value"] #[inline(always)] pub fn cnth(&mut self) -> CNTH_W { CNTH_W { w: self } } #[doc = "Bit 31 - if IUFREMAP=0 than CNT with read write access else UIFCPY with read only access"] #[inline(always)] pub fn cnt_or_uifcpy(&mut self) -> CNT_OR_UIFCPY_W { CNT_OR_UIFCPY_W { w: self } } }
use std::sync::Mutex; use std::thread; use std::sync::Arc; fn main() { let me = Arc::new(Mutex::new(0)); let mut handlers = vec![]; for _ in 0..10 { let new_me = Arc::clone(&me); let handle = thread::spawn(move || { let mut num = new_me.lock().unwrap(); *num +=1 }); handlers.push(handle); } for handler in handlers { handler.join().unwrap(); } println!("result = {}", *me.lock().unwrap()); println!("Hello, world!"); }
use common::comm::ClusterCommunicator; use common::network::{Message, MessageType}; use std::sync::mpsc::Sender; use std::collections::HashMap; use chrono::{DateTime, Utc}; use rand::Rng; use serde_cbor; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; // #[derive(Serialize, Deserialize, Debug)] // Can't serialize 'sender' pub struct ZmqNode { host_addr: String, // Unique ID gossip_fanout: u8, // Adjacent nodes updated each gossip cycle // node_comm_port: u16, // Node communication port node_comm_ctx: zmq::Context, // zmq context - ToDo: make generic for other comm libs _main_thread_sender: Sender<&'static str>, // Sender to main thread channel pub adjacent: Arc<Mutex<HashMap<String, DateTime<Utc>>>>, // Contains vector of ids to minimize storage delinquent: HashMap<String, DateTime<Utc>>, // Format is (host_addr, time_reported) removed: HashMap<String, DateTime<Utc>>, // Format is (host_addr, time_reported) } impl ClusterCommunicator for ZmqNode { fn send_message(&self, target: &str, msg: &Message) -> bool { const TIMEOUTPERIOD: i32 = 5000; // timeout in milliseconds let serialized_msg = serde_cbor::to_vec(msg).unwrap(); let requester = self.node_comm_ctx.socket(zmq::REQ).unwrap(); requester.set_sndtimeo(TIMEOUTPERIOD).unwrap(); requester.set_rcvtimeo(TIMEOUTPERIOD).unwrap(); let target_addr = format!("tcp://{}:5555", target); assert!(requester.connect(&target_addr).is_ok()); requester.send(&serialized_msg, 0).unwrap(); let mut ack: String = "".to_string(); match requester.recv_string(0) { Ok(v) => ack = v.unwrap(), Err(e) => println!("Error sending message to {}: {:?}", target, e), } assert!(requester.disconnect(&target_addr).is_ok()); if ack.len() > 0 { // TODO: Check that ack == "ACK" ? Or just message length > 0? return true; } else { return false; } } fn handle_message(&mut self, msg: &Message) { match &msg.msg_type { MessageType::Join => println!("Message Type Received: {:?}", &msg.msg_type), MessageType::Remove => println!("Message Type Received: {:?}", &msg.msg_type), MessageType::Gossip => { println!("Message Type Received: {:?}", &msg.msg_type); self.comm_recv_gossip(&msg.payload); } MessageType::Sync => println!("Message Type Received: {:?}", &msg.msg_type), MessageType::Ping => println!("Message Type Received: {:?}", &msg.msg_type), MessageType::Heartbeat => { println!("Message Type Received: {:?}", &msg.msg_type); // self.comm_recv_heartbeat(); // Currently handled in Node.run() by 'responder.send("ACK", 0).unwrap();' } } } fn comm_recv_gossip(&mut self, payload: &Vec<String>) { if payload.len() > 0 { for node_addr in payload { if let Ok(mut a) = self.adjacent.lock() { if !a.contains_key(node_addr) { a.insert(node_addr.to_string(), Utc::now()); } } } } } // fn comm_recv_heartbeat(&mut self) { // Currently handled in Node.run() by 'responder.send("ACK", 0).unwrap();' // println!("received heartbeat"); // } fn get_nghbr_sample(&self, a: &HashMap<String, DateTime<Utc>>) -> Vec<String> { let mut adj_node_sample: Vec<String> = Vec::new(); if (a.len() as u8) <= self.gossip_fanout { // Not sure about the 'as' conversion adj_node_sample = a.keys().map(|x| x.clone()).collect::<Vec<String>>(); } else { let adjacent_keys = a.keys().map(|x| x.clone()).collect::<Vec<String>>(); let adjacent_keys_len = adjacent_keys.len(); let mut rng = rand::thread_rng(); while (adj_node_sample.len() as u8) < self.gossip_fanout { let rand_index = rng.gen_range(0, adjacent_keys_len); if !adj_node_sample.contains(&adjacent_keys[rand_index]) { adj_node_sample.push(adjacent_keys[rand_index].to_string()); } } } adj_node_sample } fn update_neighbors(&mut self) { if let Ok(mut a) = self.adjacent.lock() { if a.len() > 0 { let nghbr_sample = self.get_nghbr_sample(&a); let adjacent_vec = a.keys().map(|x| x.clone()).collect::<Vec<String>>(); //println!("Sent update for {:?}", nghbr_sample); for nghbr in nghbr_sample { let msg = Message { target: &nghbr, sender: &self.host_addr, msg_type: MessageType::Gossip, payload: adjacent_vec.clone(), // ToDo: Fix to use a ref instead - https://matklad.github.io/2018/05/04/encapsulating-lifetime-of-the-field.html }; let result = self.send_message(&nghbr, &msg); // println!("Send result: {}", result); if !result { if !self.delinquent.contains_key(&nghbr) { self.delinquent.insert(nghbr.clone(), Utc::now()); } a.remove(&nghbr); } } } } } fn delinquent_node_check(&mut self) { const DELINQUENTPERIOD: u64 = 3600; // seconds let now = Utc::now(); let allowed_duration_delinquent = Duration::new(DELINQUENTPERIOD.into(), 0); println!("Checking delinquent nodes again..."); let delinquent_vec = self .delinquent .keys() .map(|x| x.clone()) .collect::<Vec<String>>(); for node in delinquent_vec { let msg = Message { target: &node, sender: &self.host_addr, msg_type: MessageType::Heartbeat, payload: Vec::new(), // ToDo: Fix to use a ref instead - https://matklad.github.io/2018/05/04/encapsulating-lifetime-of-the-field.html }; let result = self.send_message(&node, &msg); // If node responds to heartbeat, move back to adjacent node - implement heartbeat if result { if let Ok(mut a) = self.adjacent.lock() { a.insert(node.clone(), Utc::now()); self.delinquent.remove(&node); } } else { let node_delinquent_time = self.delinquent.get(&node).unwrap().clone(); // TODO: More clones, must eliminate... let time_difference = now .signed_duration_since(node_delinquent_time) .to_std() .unwrap(); // If node doesn not respond and timestamp does not exceed spec'd duration, continue // If timestamp exceeds some spec'd duration, remove node or add to a deleted_nodes field in Node if time_difference > allowed_duration_delinquent { self.removed.insert(node.clone(), Utc::now()); self.delinquent.remove(&node); } } } } } impl ZmqNode { pub fn new( mt_sender: Sender<&'static str>, host_addr: &str, init_nodes: Arc<Mutex<HashMap<String, DateTime<Utc>>>>, // listener_port: u16, ) -> ZmqNode { ZmqNode { host_addr: host_addr.to_string(), gossip_fanout: 3, // node_comm_port: listener_port, node_comm_ctx: zmq::Context::new(), _main_thread_sender: mt_sender, adjacent: init_nodes, //HashMap<&str, DateTime<UTC>>, delinquent: HashMap::new(), //HashMap<&str, DateTime>, removed: HashMap::new(), //HashMap<&str, DateTime>, } } pub fn run(&mut self) { // Server setup const GOSSIPPERIOD: u64 = 2; // seconds const DELCHECKPERIOD: u64 = 30; // seconds let responder = self.node_comm_ctx.socket(zmq::REP).unwrap(); assert!(responder.bind("tcp://*:5555").is_ok()); // Gossip let allowed_duration_gossip = Duration::new(GOSSIPPERIOD.into(), 0); let mut gossip_period_start_time = Instant::now(); // TODO: Switch to using chrono for time everywhere // Delinquent node check let allowed_duration_del_check = Duration::new(DELCHECKPERIOD.into(), 0); let mut del_check_period_start_time = Instant::now(); loop { // TODO: Examine if this loop is expensive if responder .poll(zmq::POLLIN, 10) .expect("client failed polling") > 0 { let message = responder.recv_msg(0).unwrap(); // ToDo: Incoming message should allow for different types of message // like "update", "join", "ping", "health", etc // deserialization examples: // let deserialized: HashMap<String, String> = serde_json::from_str(&message.as_str().unwrap()).unwrap(); // let deserialized: HashMap<String, String> = serde_cbor::from_slice(&message).unwrap(); let deserialized: Message = serde_cbor::from_slice(&message).unwrap(); responder.send("ACK", 0).unwrap(); self.handle_message(&deserialized); // TODO: Handle messages on green threads to prevent over-running gossip interval } // Check if heartbeat interval elapsed, send heartbeat/update message to peers if gossip_period_start_time.elapsed() > allowed_duration_gossip { // TODO: Debug print statements, remove later if let Ok(a) = self.adjacent.lock() { println!("Here's what my adjacent nodes are now: {:#?}", a); println!( "Here's what my delinquent nodes are now: {:#?}", self.delinquent ); } self.update_neighbors(); // TODO: Send messages on green threads to prevent over-running gossip interval gossip_period_start_time = Instant::now(); } // Check if heartbeat interval elapsed, send heartbeat/update message to peers if del_check_period_start_time.elapsed() > allowed_duration_del_check { self.delinquent_node_check(); // TODO: Send messages on green threads to prevent over-running gossip interval del_check_period_start_time = Instant::now(); } } } // TO BE IMPLEMENTED // fn join() // May not be needed - just start a node with known adjacent nodes // fn add_node() // This may belong in garyctl - just send a gossip message with new node }
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { h: usize, w: usize, a: [Chars; h], } let mut b = vec![vec!['#'; w + 2]; h + 2]; for i in 0..h { for j in 0..w { b[i + 1][j + 1] = a[i][j]; } } for row in b { for c in row { print!("{}", c); } println!(""); } }
fn main() { windows::core::build_legacy!( Windows::Foundation::{IClosable, IStringable}, Windows::Win32::System::Com::IClassFactory ); }
use chrono::Utc; use ed25519_dalek::{Keypair, PublicKey, Signature, Signer, Verifier}; use hex::ToHex; use log::{error, info}; use miniz_oxide::{deflate::compress_to_vec, inflate::decompress_to_vec}; use serde::{Deserialize, Serialize}; use serde_bytes::Bytes; use serde_json::{from_slice, to_string}; use std::convert::TryFrom; use std::io::stdin; use std::ops::AddAssign; use std::sync::{Arc, Mutex}; use std::thread; use std::{ io::{Read, Write}, net::{TcpListener, TcpStream}, }; use crate::block::{Block, DataPoint}; use crate::blockchain::Chain; const BUFFER_SIZE: usize = 65536 / 8; const COMPRESSION_LEVEL: u8 = 9; const TTL: usize = 3600; const VALIDATOR: bool = true; lazy_static! { static ref BOOT_NODES: Vec<String> = vec!["127.0.0.1:60000".to_string()]; } fn forward(contact_list: std::slice::Iter<String>, buf: &[u8]) { let compressed = compress_to_vec(buf, COMPRESSION_LEVEL); for peer in contact_list { match TcpStream::connect(&peer) { Ok(mut stream) => { stream.write(&compressed).unwrap(); } Err(e) => { error!("couldn't connect to {} with {}", peer, e); continue; } } } } fn validate_sig(pubkey: &Vec<u8>, msg: String, signed: &Vec<u8>) -> bool { let p = PublicKey::from_bytes(&pubkey).unwrap(); let r = p.verify(msg.as_bytes(), &Signature::try_from(&signed[..]).unwrap()); r.is_ok() } fn strip_trailing(buf: &[u8], trail: usize) -> &[u8] { for i in 0..buf.len() { if buf[i..i + 3] == [0, 0, 0] { return &buf[0..i + trail]; } } unreachable!(); } #[derive(Debug, Serialize, Deserialize)] struct Message { destiny: String, #[serde(with = "serde_bytes")] pubkey: Vec<u8>, #[serde(with = "serde_bytes")] signed: Vec<u8>, data: Vec<DataPoint>, blocks: Vec<Block>, contacts: Vec<String>, timestamp: i64, contact: String, } pub struct Client { contact_list: Arc<Mutex<Vec<String>>>, banned_list: Arc<Mutex<Vec<Vec<u8>>>>, chain: Arc<Mutex<Chain>>, keypair: Keypair, contact: Arc<Mutex<String>>, } impl Client { pub fn new(keypair: Keypair, boot_node: bool) -> Client { Client { contact_list: Arc::new(Mutex::new(if boot_node { vec![] } else { BOOT_NODES.clone() })), banned_list: Arc::new(Mutex::new(vec![])), keypair, chain: Arc::new(Mutex::new(Chain::new())), contact: Arc::new(Mutex::new(String::new())), } } pub fn main(&self) { let contacts = Arc::clone(&self.contact_list); let banned = Arc::clone(&self.banned_list); let chain = Arc::clone(&self.chain); let contact = Arc::clone(&self.contact); thread::spawn(move || { Listener::new(contacts, banned, chain, contact); }); println!( "Starting client with ID={}", self.keypair.public.encode_hex::<String>() ); loop { let mut input = String::new(); stdin().read_line(&mut input).unwrap(); let splitted: Vec<&str> = input.split_whitespace().collect(); match splitted[0] { "new-trans" => self.parse_transaction(&splitted[1..splitted.len()]), "get-chain" => self.get_chain(), "get-contacts" => self.get_contacts(), _ => eprintln!("invalid command: {}", splitted[0]), } } } fn parse_transaction(&self, splitted: &[&str]) { let mut amount = ""; let mut to = ""; for i in 0..splitted.len() { match splitted[i] { "amm" => amount = splitted[i + 1], "to" => to = splitted[i + 1], _ => continue, } } self.create_transaction(DataPoint::new( "".to_string(), to.to_string(), amount.parse().unwrap(), )) } fn create_transaction(&self, data: DataPoint) { let contact = self.contact.lock().unwrap().to_string(); let current_time = Utc::now().timestamp(); let msg = Message { destiny: "create-transaction".to_string(), pubkey: Bytes::new(&self.keypair.public.to_bytes()).to_vec(), signed: Bytes::new( &self .keypair .sign((data.to_string() + &current_time.to_string() + &contact).as_bytes()) .to_bytes(), ) .to_vec(), data: vec![data], blocks: vec![], contacts: vec![], timestamp: current_time, contact, }; self.send_all(to_string(&msg).unwrap().as_bytes()); } fn send_all(&self, buf: &[u8]) { forward(self.contact_list.lock().unwrap().iter(), buf) } fn get_chain(&self) { let current_time = Utc::now().timestamp(); let msg = Message { destiny: "get-chain".to_string(), pubkey: Bytes::new(&self.keypair.public.to_bytes()).to_vec(), signed: Bytes::new(b"NONE").to_vec(), data: vec![], blocks: vec![], contacts: vec![], timestamp: current_time, contact: self.contact.lock().unwrap().to_string(), }; self.send_all(to_string(&msg).unwrap().as_bytes()); } fn get_contacts(&self) { let current_time = Utc::now().timestamp(); let msg = Message { destiny: "get-contacts".to_string(), pubkey: Bytes::new(&self.keypair.public.to_bytes()).to_vec(), signed: Bytes::new(b"NONE").to_vec(), data: vec![], blocks: vec![], contacts: vec![], timestamp: current_time, contact: self.contact.lock().unwrap().to_string(), }; self.send_all(to_string(&msg).unwrap().as_bytes()); } } pub struct Listener { contact_list: Arc<Mutex<Vec<String>>>, banned_list: Arc<Mutex<Vec<Vec<u8>>>>, chain: Arc<Mutex<Chain>>, processed: Vec<Vec<u8>>, contact: Arc<Mutex<String>>, } impl Listener { pub fn new( contact_list: Arc<Mutex<Vec<String>>>, banned_list: Arc<Mutex<Vec<Vec<u8>>>>, chain: Arc<Mutex<Chain>>, contact: Arc<Mutex<String>>, ) { let mut l = Listener { contact_list, banned_list, processed: vec![], chain, contact, }; l.main() } fn main(&mut self) { use crate::config as cfg_reader; let cfg = cfg_reader::get_config(); let listener = TcpListener::bind(format!("127.0.0.1:{}", cfg.port)).unwrap(); let contact = listener.local_addr().unwrap().to_string(); self.contact.lock().unwrap().add_assign(contact.as_str()); info!("Listening on {}", contact); for stream in listener.incoming() { match stream { Ok(mut stream) => { let mut buf = [0; BUFFER_SIZE]; let stripped = self.get_message(&mut stream, &mut buf); let msg: Message = from_slice(&stripped).unwrap(); println!("{:?}", &msg); if self.banned(&msg.pubkey) || self.invalid_timestamp(msg.timestamp) { continue; } match msg.destiny.as_str() { "create-transaction" => { if !validate_sig( &msg.pubkey, msg.data[0].to_string() + &msg.timestamp.to_string() + &msg.contact, &msg.signed, ) || self.processed.contains(&msg.signed) { continue; } self.add_contact(msg.contact.to_string()); if !VALIDATOR { continue; } self .chain .lock() .unwrap() .add_data(msg.pubkey.encode_hex(), msg.data[0].to_owned()); self.forward(&stripped, msg.contact); } "get-chain" => { self.add_contact(msg.contact.to_string()); let blocks = self.chain.lock().unwrap().to_vec(); self.give_chain(blocks, contact.to_string()); } "give-chain" => { if !self.contact_list.lock().unwrap().contains(&msg.contact) { continue; } self.add_contact(msg.contact.to_string()); let new_chain = Chain::from_vec(msg.blocks); if new_chain.verify() { self.chain = Arc::new(Mutex::new(new_chain)); println!("chian chian {:?}", self.chain.lock().unwrap().to_string()); } else { self.ban(msg.pubkey); } } "get-contacts" => { self.add_contact(msg.contact.to_string()); let contacts = self.contact_list.lock().unwrap().to_vec(); self.give_contacts(contacts, contact.to_string()); } "give-contacts" => { self.add_contacts(msg.contacts); } _ => continue, } self.processed.push(msg.signed); self.cleanup(); } Err(e) => error!("connection failed with {}", e), } } } fn give_chain(&mut self, blocks: Vec<Block>, contact: String) { self.forward( to_string(&Message { destiny: "give-chain".to_string(), pubkey: "NONE".as_bytes().to_vec(), data: vec![], blocks, contacts: vec![], signed: "NONE".as_bytes().to_vec(), timestamp: Utc::now().timestamp(), contact: contact.clone(), }) .unwrap() .as_bytes(), contact, ); } fn give_contacts(&mut self, contacts: Vec<String>, contact: String) { self.forward( to_string(&Message { destiny: "give-contacts".to_string(), pubkey: "NONE".as_bytes().to_vec(), data: vec![], blocks: vec![], contacts, signed: "NONE".as_bytes().to_vec(), timestamp: Utc::now().timestamp(), contact: contact.clone(), }) .unwrap() .as_bytes(), contact, ); } fn add_contact(&mut self, contact: String) { if !self.contact_list.lock().unwrap().contains(&contact) { self.contact_list.lock().unwrap().push(contact); } } fn add_contacts(&mut self, contacts: Vec<String>) { let mycontact = self.contact.lock().unwrap().to_owned(); for c in contacts { if c != mycontact { self.add_contact(c); } } } fn banned(&mut self, pubkey: &Vec<u8>) -> bool { self.banned_list.lock().unwrap().contains(pubkey) } fn invalid_timestamp(&mut self, timestamp: i64) -> bool { timestamp + (TTL as i64) < Utc::now().timestamp() } fn ban(&mut self, pubkey: Vec<u8>) { self.banned_list.lock().unwrap().push(pubkey) } fn cleanup(&mut self) { while self.processed.len() > TTL { self.processed.remove(0); } } fn get_message(&mut self, stream: &mut TcpStream, buf: &mut [u8; BUFFER_SIZE]) -> Vec<u8> { stream.read(&mut buf[..]).unwrap(); let stripped = strip_trailing(buf, 0); // removing trailing zeros let mut d = decompress_to_vec(stripped); let mut trail: usize = 1; while d.is_err() { let stripped = strip_trailing(buf, trail); // removing trailing zeros d = decompress_to_vec(stripped); trail += 1; } d.unwrap() } fn forward(&mut self, buf: &[u8], contact: String) { let mut contacts = self.contact_list.lock().unwrap().clone(); if contacts.contains(&contact) { let index = contacts.iter().position(|x| *x == contact).unwrap(); contacts.remove(index); } forward(contacts.iter(), buf) } }
use crate::{ demos::{Chunk, Demo}, types::{Hitable, HitableList, Ray, Sphere, Vec3}, Camera, }; pub struct HitableSphere; impl Demo for HitableSphere { fn name(&self) -> &'static str { "sphere-using-hit-table" } fn world(&self) -> Option<HitableList> { Some(HitableList { list: vec![ Box::new(Sphere::new(Vec3::new(0.0, 0.0, -1.0), 0.5)), Box::new(Sphere::new(Vec3::new(0.0, -100.5, -1.0), 100.0)), ], }) } fn render_chunk( &self, chunk: &mut Chunk, _camera: Option<&Camera>, world: Option<&HitableList>, _samples: u8, ) { let &mut Chunk { x, y, nx, ny, start_x, start_y, ref mut buffer, } = chunk; let world = world.unwrap(); let lower_left_corner = Vec3::new(-2.0, -1.0, -1.0); let horizontal = Vec3::new(4.0, 0.0, 0.0); let vertical = Vec3::new(0.0, 2.0, 0.0); let origin = Vec3::new(0.0, 0.0, 0.0); let mut offset = 0; for j in start_y..start_y + ny { for i in start_x..start_x + nx { let u = i as f64 / x as f64; let v = j as f64 / y as f64; let ray = Ray::new(origin, lower_left_corner + horizontal * u + vertical * v); let color = calc_color(ray, &world); buffer[offset] = (255.99 * color.r()) as u8; buffer[offset + 1] = (255.99 * color.g()) as u8; buffer[offset + 2] = (255.99 * color.b()) as u8; offset += 4; } } } } fn calc_color(ray: Ray, world: &HitableList) -> Vec3 { if let Some(hit_rec) = world.hit(&ray, 0.0, std::f64::MAX) { // It's easier to visualise normals as unit vectors // So, This trick of adding 1 to each dimension and then halving // the resulting value shifts the normals from -1<->1 range to // 0<->1 range Vec3::new( hit_rec.normal.x() + 1.0, hit_rec.normal.y() + 1.0, hit_rec.normal.z() + 1.0, ) * 0.5 } else { let unit_direction = ray.direction().unit_vector(); let t = unit_direction.y() * 0.5 + 1.0; Vec3::new(1.0, 1.0, 1.0) * (1.0 - t) + Vec3::new(0.5, 0.7, 1.0) * t } }
use std::cmp::{max, min}; pub struct Input { pub text: String, pub mode: InputMode, idx: usize, } impl Input { pub fn idx(&self) -> &usize { &self.idx } } impl Default for Input { fn default() -> Input { Input { text: "".to_string(), mode: InputMode::Normal, idx: 0, } } } impl Editable for Input { fn left(&mut self) { match &self.idx { 0 => {} 1..=1000 => self.idx -= 1, _ => {} } () } fn right(&mut self) { self.idx = min(self.text.len(), self.idx + 1) } fn delete(&mut self) { match &self.idx { 0 => {} _ => { self.idx -= 1; self.text.remove(self.idx); } } } fn enter(&mut self) { todo!() } fn esc(&mut self) { todo!() } fn add(&mut self, c: char) { self.text.insert(self.idx, c); self.idx += 1; } fn home(&mut self) { self.idx = 0; } fn end(&mut self) { self.idx = self.text.len(); } fn next_boundary(&mut self) { let starting_point = min(self.text.len(), self.idx + 1); let substr = &self.text[starting_point..]; if let Some(boundary_idx) = substr.find(' ') { // we ignore one position earlier, need to add it back with + 1 self.idx += boundary_idx + 1; } else { self.idx = self.text.len(); } } fn previous_boundary(&mut self) { match self.idx { 0 => {} _ => { let substr = &self.text[..self.idx]; let substr: String = substr.chars().rev().collect(); if let Some(boundary_idx) = substr.find(' ') { // we ignore one position earlier, need to add it back with + 1 self.idx -= boundary_idx + 1; } else { self.idx = 0; } } } } } pub trait Editable { fn left(&mut self); fn right(&mut self); fn delete(&mut self); fn enter(&mut self); fn esc(&mut self); fn add(&mut self, c: char); fn home(&mut self); fn end(&mut self); fn next_boundary(&mut self); fn previous_boundary(&mut self); } pub enum InputMode { Normal, Editing, } #[cfg(test)] mod tests { use super::*; macro_rules! test_move { ($($input_func:ident: $func_name:ident: $value:expr,)*) => { $( #[test] fn $func_name() { // Given let (text, idx, expected_idx) = $value; let mut input = Input {text : text.to_string(), mode : InputMode::Normal, idx}; // When input.$input_func(); // Then assert_eq!(expected_idx, input.idx) } )* }; } test_move! { left : when_on_0_then_remain : ("", 0, 0), left : decrement_idx_by_1: ("hello", 3, 2), right: when_idx_equals_textlength_then_remain : ("hello", 5, 5), right: increment_idx_by_1 : ("hello", 3, 4), home: jump_to_idx_0 : ("hello", 3, 0), end: jump_to_end_of_input : ("hello", 3, 5), next_boundary: given_no_white_space_then_jump_to_end_of_input : ("hello", 1, 5), next_boundary: given_multiple_words_then_jump_to_end_of_current_word : ("hello world", 1, 5), next_boundary: given_already_at_end_then_remain : ("hello world", 11, 11), next_boundary: given_current_idx_is_boundary_then_choose_next_boundary_match : ("hello world", 5, 11), previous_boundary: given_no_white_space_then_jump_to_start_of_input : ("hello", 3, 0), previous_boundary: given_multiple_words_then_jump_to_start_of_current_word : ("hello world", 8, 5), previous_boundary: given_already_at_start_then_remain : ("hello world", 0, 0), previous_boundary: given_current_idx_is_boundary_then_choose_previous_boundary_match : ("hello world", 5, 0), previous_boundary: never_go_negative : ("hello world", 5, 0), } macro_rules! test_edit { ($($input_func:ident: $func_name:ident: $value:expr,)*) => { $( #[test] fn $func_name() { // Given let (text, idx, c, expected_idx, expected_text) = $value; let mut input = Input {text : text.to_string(), mode : InputMode::Normal, idx}; // When input.$input_func(c); // Then assert_eq!(expected_idx, input.idx); assert_eq!(expected_text, input.text); } )* }; } test_edit! { add : when_add_char_then_increment_idx_by_1 : ("bolloc", 6, 'k', 7, "bollock"), add : char_is_inserted_at_index : ("ollock", 0, 'b', 1, "bollock"), } #[test] fn delete_nothing_on_idx_0() { let mut input = Input { text: "bla".to_string(), mode: InputMode::Normal, idx: 0, }; input.delete(); assert_eq!("bla", &input.text); } #[test] fn delete_char_and_decrement_idx() { let mut input = Input { text: "bla".to_string(), mode: InputMode::Normal, idx: 2, }; input.delete(); assert_eq!(1, *input.idx()); assert_eq!("ba", &input.text); } }
use std::collections::HashSet; use std::env; use std::error; use std::fs; type Error = Box<dyn error::Error>; fn main() -> Result<(), Error> { for input_file in env::args().skip(1) { println!("{}", input_file); let input = groups(&fs::read_to_string(input_file)?); println!( "\tpart 1: sum over groups of number of questions that some member answered yes to" ); println!("\t{}", part1(&input)); println!( "\tpart 2: sum over groups of number of questions that all members answered yes to" ); println!("\t{}", part2(&input)); } Ok(()) } type Group = Vec<Member>; type Member = HashSet<Answer>; type Answer = char; fn groups(s: &str) -> Vec<Group> { s.split("\n\n") .map(|s| s.lines().map(|line| line.chars().collect()).collect()) .collect() } fn part1(gps: &Vec<Group>) -> usize { gps.iter() .map(|gp| { gp.iter() .fold(HashSet::new(), |acc, mem| acc.union(mem).cloned().collect()) .len() }) .sum() } fn part2(gps: &Vec<Group>) -> usize { gps.iter() .map(|gp| { gp.iter() .fold(None, |acc, mem| match acc { None => Some(mem.clone()), Some(acc) => Some(acc.intersection(mem).cloned().collect()), }) .unwrap_or_else(HashSet::new) .len() }) .sum() }
#[doc = "Reader of register MIS"] pub type R = crate::R<u32, super::MIS>; #[doc = "Reader of field `TATOMIS`"] pub type TATOMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `CAMMIS`"] pub type CAMMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `CAEMIS`"] pub type CAEMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `RTCMIS`"] pub type RTCMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `TAMMIS`"] pub type TAMMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `TBTOMIS`"] pub type TBTOMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `CBMMIS`"] pub type CBMMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `CBEMIS`"] pub type CBEMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `TBMMIS`"] pub type TBMMIS_R = crate::R<bool, bool>; #[doc = "Reader of field `WUEMIS`"] pub type WUEMIS_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - GPTM Timer A Time-Out Masked Interrupt"] #[inline(always)] pub fn tatomis(&self) -> TATOMIS_R { TATOMIS_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - GPTM Timer A Capture Mode Match Masked Interrupt"] #[inline(always)] pub fn cammis(&self) -> CAMMIS_R { CAMMIS_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - GPTM Timer A Capture Mode Event Masked Interrupt"] #[inline(always)] pub fn caemis(&self) -> CAEMIS_R { CAEMIS_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - GPTM RTC Masked Interrupt"] #[inline(always)] pub fn rtcmis(&self) -> RTCMIS_R { RTCMIS_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - GPTM Timer A Match Masked Interrupt"] #[inline(always)] pub fn tammis(&self) -> TAMMIS_R { TAMMIS_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 8 - GPTM Timer B Time-Out Masked Interrupt"] #[inline(always)] pub fn tbtomis(&self) -> TBTOMIS_R { TBTOMIS_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - GPTM Timer B Capture Mode Match Masked Interrupt"] #[inline(always)] pub fn cbmmis(&self) -> CBMMIS_R { CBMMIS_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - GPTM Timer B Capture Mode Event Masked Interrupt"] #[inline(always)] pub fn cbemis(&self) -> CBEMIS_R { CBEMIS_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - GPTM Timer B Match Masked Interrupt"] #[inline(always)] pub fn tbmmis(&self) -> TBMMIS_R { TBMMIS_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 16 - 32/64-Bit Wide GPTM Write Update Error Masked Interrupt Status"] #[inline(always)] pub fn wuemis(&self) -> WUEMIS_R { WUEMIS_R::new(((self.bits >> 16) & 0x01) != 0) } }
//! //! This crate was built to ease parsing files encoded in a Matroska container, such as [WebMs][webm] or [MKVs][mkv]. //! //! The main content provided by this crate is the [`MatroskaSpec`] enum. Otherwise, this crate simply provides type aliases in the form of [`WebmIterator`] and [`WebmWriter`]. //! //! [webm]: https://www.webmproject.org/ //! [mkv]: http://www.matroska.org/technical/specs/index.html //! //! //! # Example Usage //! //! The following examples show how to read, modify, and write webm files using this library. //! //! ## Example 1 //! The following example reads a media file into memory and decodes it. //! //! ``` //! use std::fs::File; //! use webm_iterable::WebmIterator; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let mut src = File::open("media/test.webm").unwrap(); //! let tag_iterator = WebmIterator::new(&mut src, &[]); //! //! for tag in tag_iterator { //! println!("[{:?}]", tag?.spec_tag); //! } //! //! Ok(()) //! } //! ``` //! //! ## Example 2 //! This next example does the same thing, but keeps track of the number of times each tag appears in the file. //! //! ``` //! use std::fs::File; //! use std::collections::HashMap; //! use webm_iterable::WebmIterator; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let mut src = File::open("media/test.webm").unwrap(); //! let tag_iterator = WebmIterator::new(&mut src, &[]); //! let mut tag_counts = HashMap::new(); //! //! for tag in tag_iterator { //! let count = tag_counts.entry(tag?.spec_tag).or_insert(0); //! *count += 1; //! } //! //! println!("{:?}", tag_counts); //! Ok(()) //! } //! ``` //! //! ## Example 3 //! This example grabs the audio from a webm and stores the result in a new file. The logic in this example is rather advanced - an explanation follows the code. //! //! ```no_run //! use std::fs::File; //! use std::convert::TryInto; //! //! use webm_iterable::{ //! WebmIterator, //! WebmWriter, //! matroska_spec::{MatroskaSpec, Block, EbmlSpecification}, //! tags::{TagPosition, TagData}, //! }; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! // 1 //! let mut src = File::open("media/audiosample.webm").unwrap(); //! let tag_iterator = WebmIterator::new(&mut src, &[MatroskaSpec::TrackEntry]); //! let mut dest = File::create("media/audioout.webm").unwrap(); //! let mut tag_writer = WebmWriter::new(&mut dest); //! let mut stripped_tracks = Vec::new(); //! //! // 2 //! for tag in tag_iterator { //! let mut tag = tag?; //! // 3 //! if let Some(MatroskaSpec::TrackEntry) = tag.spec_tag { //! if let TagPosition::FullTag(_id, data) = &mut tag.tag { //! if let TagData::Master(children) = data { //! let is_audio_track = |tag: &mut (u64, TagData)| { //! if MatroskaSpec::get_tag_id(&MatroskaSpec::TrackType) == tag.0 { //! if let TagData::UnsignedInt(val) = tag.1 { //! return val != 2; //! } //! } //! false //! }; //! //! if children.iter_mut().any(is_audio_track) { //! if let Some(track_number) = children.iter_mut().find(|c| c.0 == MatroskaSpec::get_tag_id(&MatroskaSpec::TrackNumber)) { //! if let TagData::UnsignedInt(val) = track_number.1 { //! stripped_tracks.push(val); //! continue; //! } //! } //! } //! } //! } //! // 4 //! } else if matches!(tag.spec_tag, Some(MatroskaSpec::Block)) || matches!(tag.spec_tag, Some(MatroskaSpec::SimpleBlock)) { //! if let TagPosition::FullTag(_id, tag) = tag.tag.clone() { //! let block: Block = tag.try_into()?; //! if stripped_tracks.iter().any(|t| *t == block.track) { //! continue; //! } //! } //! } //! // 5 //! tag_writer.write(tag.tag)?; //! } //! //! Ok(()) //! } //! ``` //! //! In the above example, we (1) build our iterator and writer based on local file paths and declare useful local variables, (2) iterate over the tags in the webm file, (3) identify any track numbers that are not audio, store them in the `stripped_tracks` variable, and prevent writing the "TrackEntry" out, (4) avoid writing any block data for any tracks that are not audio, and (5) write remaining tags to the output destination. //! //! __Notes__ //! * Notice the second parameter passed into the `WebmIterator::new()` function. This parameter tells the decoder which `Master` tags should be read as `TagPosition::FullTag` tags rather than the standard `TagPosition::StartTag` and `TagPosition::EndTag` variants. This greatly simplifies our iteration loop logic as we don't have to maintain an internal buffer for the "TrackEntry" tag that we are interested in processing. //! use ebml_iterable::{TagIterator, TagWriter}; pub mod tags { //! //! Re-export from [`ebml_iterable::tags`]. //! //! These types are exported from the [`ebml_iterable`] library as a convenience. They define the basic data structures that [`WebmIterator`][`super::WebmIterator`] and [`WebmWriter`][`super::WebmWriter`] understand. //! pub use ebml_iterable::tags::{TagPosition, TagData}; } mod errors; pub mod matroska_spec; use matroska_spec::MatroskaSpec; /// /// Alias for [`ebml_iterable::TagIterator`] using [`MatroskaSpec`] as the generic type. /// /// This implements Rust's standard [`Iterator`] trait. The struct can be created with the `new` function on any source that implements the [`std::io::Read`] trait. The iterator outputs `SpecTag` objects containing the type of Matroska tag and the tag data. See the [ebml-iterable](https://crates.io/crates/ebml_iterable) docs for more information if needed. /// /// Note: The `with_capacity` method can be used to construct a `WebmIterator` with a specified default buffer size. This is only useful as a microoptimization to memory management if you know the maximum tag size of the file you're reading. /// pub type WebmIterator<R> = TagIterator<R, MatroskaSpec>; /// /// Alias for [`ebml_iterable::TagWriter`]. /// /// This can be used to write webm files from tag data. This struct can be created with the `new` function on any source that implements the [`std::io::Write`] trait. See the [ebml-iterable](https://crates.io/crates/ebml_iterable) docs for more information if needed. /// pub type WebmWriter<W> = TagWriter<W>; #[cfg(test)] mod tests { use std::io::Cursor; use super::tags::{TagPosition, TagData}; use super::WebmWriter; use super::WebmIterator; #[test] fn basic_tag_stream_write_and_iterate() { let tags: Vec<TagPosition> = vec![ TagPosition::StartTag(0x1a45dfa3), TagPosition::StartTag(0x18538067), TagPosition::FullTag(0x83, TagData::UnsignedInt(0x01)), TagPosition::EndTag(0x18538067), TagPosition::FullTag(0x1f43b675, TagData::Master(vec![ (0x97, TagData::UnsignedInt(0x02)), ])), TagPosition::EndTag(0x1a45dfa3), ]; let mut dest = Cursor::new(Vec::new()); let mut writer = WebmWriter::new(&mut dest); for tag in tags { writer.write(tag).expect("Test shouldn't error"); } println!("dest {:?}", dest); let mut src = Cursor::new(dest.get_ref().to_vec()); let reader = WebmIterator::new(&mut src, &[]); let tags: Vec<TagPosition> = reader.map(|i| i.unwrap().tag).collect(); println!("tags {:?}", tags); assert_eq!(TagPosition::StartTag(0x1a45dfa3), tags[0]); assert_eq!(TagPosition::StartTag(0x18538067), tags[1]); assert_eq!(TagPosition::FullTag(0x83, TagData::UnsignedInt(0x01)), tags[2]); assert_eq!(TagPosition::EndTag(0x18538067), tags[3]); assert_eq!(TagPosition::StartTag(0x1f43b675), tags[4]); assert_eq!(TagPosition::FullTag(0x97, TagData::UnsignedInt(0x02)), tags[5]); assert_eq!(TagPosition::EndTag(0x1f43b675), tags[6]); assert_eq!(TagPosition::EndTag(0x1a45dfa3), tags[7]); } }
extern crate regex; use common; use self::regex::Regex; use std::collections::HashMap; #[derive(Clone, Debug)] struct Program { name: String, weight: i32, parent: Option<String>, children: Vec<String> } impl Program { pub fn from_line(line: &str) -> Self { lazy_static! { static ref RE: Regex = Regex::new(r#"([a-z]+) \((\d+)\)( -> ([a-z, ]+))?"#).unwrap(); } let captures = RE.captures(line).unwrap(); let name = captures.get(1).unwrap().as_str(); let weigth = captures.get(2).unwrap().as_str().parse::<i32>().unwrap(); let child_list = captures.get(4).map_or("", |m| m.as_str()); let child_names: Vec<String> = child_list .split(',') .map(|s| s.trim()) .filter(|s| s.len() > 0) .map(|s| String::from(s)) .collect(); Program { name: String::from(name), weight: weigth, parent: None, children: child_names } } } struct Tree { programs: HashMap<String, Program> } #[derive(Clone, Debug)] struct Correction { program: String, correction: i32 } fn create_map(programs: &Vec<Program>) -> HashMap<String, Program> { let mut result: HashMap<String, Program> = HashMap::new(); // Setting up dictionary for program in programs { result.insert(program.name.clone(), program.clone()); } result } fn find_outlier(weights: &Vec<i32>) -> (i32, i32) { let mut counts: HashMap<i32, i32> = HashMap::new(); for &weight in weights { let count = counts.entry(weight).or_insert(0).clone(); counts.insert(weight, count + 1); } let mut pairs: Vec<(&i32, &i32)> = counts.iter().collect(); pairs.sort_by_key(|&(_, &c)| -c); assert_eq!(pairs.len(), 2); let (wgood, _) = pairs[0]; let (wbad, _) = pairs[1]; (*wgood, *wbad) } impl Tree { pub fn from_programs(programs: &Vec<Program>) -> Self { let mut result = create_map(programs); // Setting parent references for program in programs { for child in program.children.iter() { match result.get_mut(&*child) { Some(child_program) => child_program.parent = Some(program.name.clone()), None => eprintln!("Could not find {}", child) } } } Tree { programs: result } } pub fn root(&self) -> Option<&Program> { match self.programs.iter().find(|&(_name, program)| program.parent.is_none()) { Some((_name, program)) => Some(program), None => None } } pub fn total_weight(&self, program: &Program) -> i32 { if program.children.is_empty() { program.weight } else { let child_weights: i32 = program.children.iter().map(|child| self.total_weight(self.programs.get(child).unwrap())).sum(); program.weight + child_weights } } pub fn find_correction(&self, program: &Program) -> Option<Correction> { if program.children.is_empty() { None } else { let weights: Vec<i32> = program.children.iter().map(|child| self.total_weight(self.programs.get(child).unwrap())).collect(); let children_corrections: Vec<Option<Correction>> = program.children.iter().map(|child| self.find_correction(self.programs.get(child).unwrap())).collect(); let children_balanced = children_corrections.iter().all(|c| c.is_none()); let weights_good = weights.iter().all(|w| *w == weights[0]); if children_balanced && weights_good { None } else { if children_balanced && !weights_good { for idx in 0..weights.len() { let child = self.programs.get(&program.children[idx]).unwrap(); let (good_weight, wrong_weight) = find_outlier(&weights); if weights[idx] == wrong_weight { let diff = wrong_weight - good_weight; return Some(Correction { program: child.name.clone(), correction: child.weight - diff }); } } None } else { let cs: Vec<Correction> = children_corrections .iter().filter(|c| c.is_some()) .map(|c| c.clone().unwrap().clone()).collect(); cs.first().map(|c| c.clone()) } } } } } pub fn run() { let input = common::read_data("day7.txt"); let programs: Vec<Program> = input.split('\n').map(Program::from_line).collect(); let tree = Tree::from_programs(&programs); let root = tree.root().unwrap(); println!("Day 7 result 1: {:?}", root); println!("Day 7 result 2: {:?}", tree.find_correction(root).map(|c| c.correction)); }
use num::traits::PrimInt; pub struct FibonacciIterator<Int> { a: Int, b: Int, } impl<Int> FibonacciIterator<Int> where Int: PrimInt, { pub fn new() -> Self { Self { a: Int::zero(), b: Int::one(), } } } impl<Int> Iterator for FibonacciIterator<Int> where Int: PrimInt, { type Item = Int; fn next(&mut self) -> Option<Self::Item> { let t = self.a + self.b; self.a = self.b; self.b = t; Some(t) } } pub struct FibonacciIteratorMod<Int> { a: Int, b: Int, m: Int, } impl<Int> FibonacciIteratorMod<Int> where Int: PrimInt, { pub fn new(m: Int) -> Self { Self { a: Int::zero(), b: Int::one(), m: m, } } } impl<Int> Iterator for FibonacciIteratorMod<Int> where Int: PrimInt, { type Item = Int; fn next(&mut self) -> Option<Self::Item> { let t = (self.a + self.b) % self.m; self.a = self.b; self.b = t; Some(t) } }
use crate::wallet::wallet::WalletType; use crate::base::crypto::signature::traits::signature::SignatureI; use crate::base::crypto::signature::guomi::SignatureGuomi; use crate::wallet::keypair::*; use crate::base::crypto::signature::sign::SignatureX; pub struct SignatureBuilder { signature: Box<dyn SignatureI>, } impl SignatureBuilder { pub fn new(key_type: WalletType, keypair: Keypair) -> Self { let signature = SignatureBuilder::build(key_type, keypair); SignatureBuilder { signature: signature, } } fn build(key_type: WalletType, keypair: Keypair) -> Box<dyn SignatureI> { match key_type { WalletType::ED25519 => { return Box::new(SignatureGuomi::new(keypair)); }, WalletType::SECP256K1 => { return Box::new(SignatureX::new(keypair)); }, WalletType::SM2P256V1 => { return Box::new(SignatureGuomi::new(keypair)); } } } } impl SignatureI for SignatureBuilder { fn sign(&self, message: &[u8]) -> String { self.signature.sign(&message) } fn verify(&self, message: &[u8], signature: &[u8], key: &[u8]) -> bool { self.signature.verify(&message, &signature, &key) } fn sign_txn_signature(&self, so: &Vec<u8>) -> String { self.signature.sign_txn_signature(&so) } }
pub use ssd1306::{prelude::*, *};
use std::{fmt::Debug, sync::Arc}; use async_trait::async_trait; use data_types::{NamespaceId, PartitionKey, TableId}; use parking_lot::Mutex; use crate::{ buffer_tree::{namespace::NamespaceName, partition::PartitionData, table::TableMetadata}, deferred_load::DeferredLoad, }; /// An infallible resolver of [`PartitionData`] for the specified table and /// partition key, returning an initialised [`PartitionData`] buffer for it. #[async_trait] pub(crate) trait PartitionProvider: Send + Sync + Debug { /// Return an initialised [`PartitionData`] for a given `(partition_key, /// table_id)` tuple. /// /// NOTE: the constructor for [`PartitionData`] is NOT `pub` and SHOULD NOT /// be `pub` so this trait is effectively sealed. async fn get_partition( &self, partition_key: PartitionKey, namespace_id: NamespaceId, namespace_name: Arc<DeferredLoad<NamespaceName>>, table_id: TableId, table: Arc<DeferredLoad<TableMetadata>>, ) -> Arc<Mutex<PartitionData>>; } #[async_trait] impl<T> PartitionProvider for Arc<T> where T: PartitionProvider, { async fn get_partition( &self, partition_key: PartitionKey, namespace_id: NamespaceId, namespace_name: Arc<DeferredLoad<NamespaceName>>, table_id: TableId, table: Arc<DeferredLoad<TableMetadata>>, ) -> Arc<Mutex<PartitionData>> { (**self) .get_partition(partition_key, namespace_id, namespace_name, table_id, table) .await } } #[cfg(test)] mod tests { use std::sync::Arc; use super::*; use crate::{ buffer_tree::partition::resolver::mock::MockPartitionProvider, test_util::{ defer_namespace_name_1_sec, defer_table_metadata_1_sec, PartitionDataBuilder, ARBITRARY_NAMESPACE_ID, ARBITRARY_PARTITION_KEY, ARBITRARY_TABLE_ID, ARBITRARY_TRANSITION_PARTITION_ID, }, }; #[tokio::test] async fn test_arc_impl() { let namespace_loader = defer_namespace_name_1_sec(); let table_loader = defer_table_metadata_1_sec(); let data = PartitionDataBuilder::new() .with_table_loader(Arc::clone(&table_loader)) .with_namespace_loader(Arc::clone(&namespace_loader)) .build(); let mock = Arc::new(MockPartitionProvider::default().with_partition(data)); let got = mock .get_partition( ARBITRARY_PARTITION_KEY.clone(), ARBITRARY_NAMESPACE_ID, Arc::clone(&namespace_loader), ARBITRARY_TABLE_ID, Arc::clone(&table_loader), ) .await; assert_eq!( got.lock().partition_id(), &*ARBITRARY_TRANSITION_PARTITION_ID ); assert_eq!(got.lock().namespace_id(), ARBITRARY_NAMESPACE_ID); assert_eq!( got.lock().namespace_name().to_string(), namespace_loader.to_string() ); assert_eq!(got.lock().table().to_string(), table_loader.to_string()); } }
use super::super::exec::frame::{ObjectBody, VariableType}; use super::super::exec::jit::{FuncJITExecInfo, LoopJITExecInfo}; use super::super::exec::objectheap::ObjectHeap; use super::super::gc::gc::GcType; use super::classfile::read::ClassFileReader; use super::classfile::{ classfile::ClassFile, constant::Constant, field::FieldInfo, method::MethodInfo, }; use super::classheap::ClassHeap; use rustc_hash::FxHashMap; #[derive(Debug, Clone)] pub struct JITInfoManager { loop_count: FxHashMap<usize, (usize, usize, Option<LoopJITExecInfo>)>, // loop (start, (end, count, exec_info) whole_method: (usize, Option<FuncJITExecInfo>), // count, function addr } #[derive(Debug, Clone)] pub struct Class { pub classfile: ClassFile, pub classheap: Option<GcType<ClassHeap>>, pub static_variables: FxHashMap<String, u64>, pub fields: FxHashMap<String, (usize, VariableType)>, pub jit_info_mgr: FxHashMap<(/*(name_index, descriptor_index)=*/ usize, usize), JITInfoManager>, } impl Class { pub fn new() -> Self { Class { classfile: ClassFile::new(), classheap: None, static_variables: FxHashMap::default(), fields: FxHashMap::default(), jit_info_mgr: FxHashMap::default(), } } pub fn get_static_variable(&self, name: &str) -> Option<u64> { self.static_variables .get(name) .and_then(|var| Some(var.clone())) } pub fn put_static_variable(&mut self, name: &str, val: u64) { self.static_variables.insert(name.to_string(), val); } pub fn load_classfile(&mut self, filename: &str) -> Option<()> { let mut cf_reader = ClassFileReader::new(filename)?; let cf = cf_reader.read()?; self.classfile = cf; self.number_fields(); Some(()) } pub fn get_name(&self) -> Option<&String> { let this_class = self.classfile.this_class as usize; let const_class = &self.classfile.constant_pool[this_class]; self.classfile.constant_pool[const_class.get_class_name_index()?].get_utf8() } pub fn get_super_class_name(&self) -> Option<&String> { let super_class = self.classfile.super_class as usize; let const_class = &self.classfile.constant_pool[super_class]; self.classfile.constant_pool[const_class.get_class_name_index()?].get_utf8() } pub fn get_utf8_from_const_pool(&self, index: usize) -> Option<&String> { self.classfile.constant_pool[index].get_utf8() } pub fn get_java_string_utf8_from_const_pool( &mut self, objectheap: GcType<ObjectHeap>, index: usize, ) -> Option<u64> { let (s, java_string) = match self.classfile.constant_pool[index] { Constant::Utf8 { ref s, ref mut java_string, } => (s, java_string), _ => return None, }; if let Some(java_string) = java_string { return Some(*java_string as u64); } let jstring = unsafe { &mut *objectheap }.create_string_object(s.clone(), self.classheap.unwrap()); *java_string = Some(jstring as GcType<ObjectBody>); Some(jstring) } pub fn get_method( &self, method_name: &str, method_descriptor: &str, ) -> Option<(GcType<Class>, MethodInfo)> { let mut cur_class_ptr = unsafe { &(*self.classheap.unwrap()) } .get_class(self.get_name().unwrap()) .unwrap(); loop { let cur_class = unsafe { &mut *cur_class_ptr }; for i in 0..cur_class.classfile.methods_count as usize { let name = cur_class.classfile.constant_pool [(cur_class.classfile.methods[i].name_index) as usize] .get_utf8() .unwrap(); if name != method_name { continue; } let descriptor = cur_class.classfile.constant_pool [(cur_class.classfile.methods[i].descriptor_index) as usize] .get_utf8() .unwrap(); if descriptor == method_descriptor { return Some((cur_class_ptr, cur_class.classfile.methods[i].clone())); } } if let Some(x) = cur_class.get_super_class() { cur_class_ptr = x; } else { break; } } None } pub fn get_field( &self, field_name: &str, field_descriptor: &str, ) -> Option<(GcType<Class>, FieldInfo)> { let mut cur_class_ptr = unsafe { &(*self.classheap.unwrap()) } .get_class(self.get_name().unwrap()) .unwrap(); loop { let cur_class = unsafe { &mut *cur_class_ptr }; for i in 0..cur_class.classfile.fields_count as usize { let name = cur_class.classfile.constant_pool [(cur_class.classfile.fields[i].name_index) as usize] .get_utf8() .unwrap(); if name != field_name { continue; } let descriptor = cur_class.classfile.constant_pool [(cur_class.classfile.fields[i].descriptor_index) as usize] .get_utf8() .unwrap(); if descriptor == field_descriptor { return Some((cur_class_ptr, cur_class.classfile.fields[i].clone())); } } if let Some(x) = cur_class.get_super_class() { cur_class_ptr = x; } else { break; } } None } pub fn get_numbered_field_info(&self, name: &str) -> Option<&(usize, VariableType)> { let mut class = self; loop { if let Some(info) = class.fields.get(name) { return Some(info); } if let Some(class_ptr) = class.get_super_class() { class = unsafe { &*class_ptr }; } else { return None; } } } fn number_fields(&mut self) { let init_count = self.count_super_class_fields(); for i in 0..self.classfile.fields_count as usize { let name = self.classfile.constant_pool[(self.classfile.fields[i].name_index) as usize] .get_utf8() .unwrap(); let descriptor = self.classfile.constant_pool [(self.classfile.fields[i].descriptor_index) as usize] .get_utf8() .unwrap(); self.fields.insert( name.clone(), ( init_count + i, VariableType::parse_type(descriptor).unwrap(), ), ); } } fn count_super_class_fields(&self) -> usize { if let Some(super_class_ptr) = self.get_super_class() { let super_class = unsafe { &*super_class_ptr }; return self.fields.len() + super_class.count_super_class_fields(); } 0 } pub fn get_super_class(&self) -> Option<GcType<Class>> { let name = self.get_super_class_name()?; unsafe { &(*self.classheap.unwrap()) }.get_class(name) } pub fn get_object_field_count(&self) -> usize { let mut count = self.classfile.fields_count as usize; if let Some(super_class) = self.get_super_class() { count += unsafe { &*super_class }.get_object_field_count(); } count } pub fn get_jit_info_mgr( &mut self, name_index: usize, descriptor_index: usize, ) -> &mut JITInfoManager { self.jit_info_mgr .entry((name_index, descriptor_index)) .or_insert(JITInfoManager::new()) } } impl JITInfoManager { pub fn new() -> Self { JITInfoManager { loop_count: FxHashMap::default(), whole_method: (0, None), } } pub fn inc_count_of_loop_exec(&mut self, start: usize, end: usize) { let (_, count, _) = self.loop_count.entry(start).or_insert((end, 0, None)); *count += 1; } pub fn inc_count_of_func_exec(&mut self) { let (count, _) = &mut self.whole_method; *count += 1; } pub fn loop_executed_enough_times(&self, start: usize) -> bool { let (_, count, _) = self.loop_count.get(&start).unwrap(); *count > 7 // false } pub fn func_executed_enough_times(&self) -> bool { let (count, _) = &self.whole_method; *count > 4 // false } pub fn get_jit_loop(&mut self, start: usize) -> &mut Option<LoopJITExecInfo> { &mut (*self.loop_count.get_mut(&start).unwrap()).2 } pub fn get_jit_func(&mut self) -> &mut Option<FuncJITExecInfo> { &mut self.whole_method.1 } }
#[doc = "Reader of register MTLTxQUR"] pub type R = crate::R<u32, super::MTLTXQUR>; #[doc = "Writer for register MTLTxQUR"] pub type W = crate::W<u32, super::MTLTXQUR>; #[doc = "Register MTLTxQUR `reset()`'s with value 0"] impl crate::ResetValue for super::MTLTXQUR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `UFCNTOVF`"] pub type UFCNTOVF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UFCNTOVF`"] pub struct UFCNTOVF_W<'a> { w: &'a mut W, } impl<'a> UFCNTOVF_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `UFFRMCNT`"] pub type UFFRMCNT_R = crate::R<u16, u16>; #[doc = "Write proxy for field `UFFRMCNT`"] pub struct UFFRMCNT_W<'a> { w: &'a mut W, } impl<'a> UFFRMCNT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x07ff) | ((value as u32) & 0x07ff); self.w } } impl R { #[doc = "Bit 11 - Overflow Bit for Underflow Packet Counter"] #[inline(always)] pub fn ufcntovf(&self) -> UFCNTOVF_R { UFCNTOVF_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bits 0:10 - Underflow Packet Counter"] #[inline(always)] pub fn uffrmcnt(&self) -> UFFRMCNT_R { UFFRMCNT_R::new((self.bits & 0x07ff) as u16) } } impl W { #[doc = "Bit 11 - Overflow Bit for Underflow Packet Counter"] #[inline(always)] pub fn ufcntovf(&mut self) -> UFCNTOVF_W { UFCNTOVF_W { w: self } } #[doc = "Bits 0:10 - Underflow Packet Counter"] #[inline(always)] pub fn uffrmcnt(&mut self) -> UFFRMCNT_W { UFFRMCNT_W { w: self } } }
use std::net::IpAddr; use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::Mutex; use std::thread; use std::time::Duration; use num_cpus; use super::super::dummy; use super::super::dummy_keypair; use super::super::tests::make_packet; use super::super::udp::*; use super::KeyPair; use super::SIZE_MESSAGE_PREFIX; use super::{Callbacks, Device}; extern crate test; const SIZE_KEEPALIVE: usize = 32; #[cfg(test)] mod tests { use super::*; use env_logger; use log::debug; use std::sync::atomic::AtomicUsize; use test::Bencher; // type for tracking events inside the router module struct Flags { send: Mutex<Vec<(usize, bool)>>, recv: Mutex<Vec<(usize, bool)>>, need_key: Mutex<Vec<()>>, key_confirmed: Mutex<Vec<()>>, } #[derive(Clone)] struct Opaque(Arc<Flags>); struct TestCallbacks(); impl Opaque { fn new() -> Opaque { Opaque(Arc::new(Flags { send: Mutex::new(vec![]), recv: Mutex::new(vec![]), need_key: Mutex::new(vec![]), key_confirmed: Mutex::new(vec![]), })) } #[allow(dead_code)] fn reset(&self) { self.0.send.lock().unwrap().clear(); self.0.recv.lock().unwrap().clear(); self.0.need_key.lock().unwrap().clear(); self.0.key_confirmed.lock().unwrap().clear(); } fn send(&self) -> Option<(usize, bool)> { self.0.send.lock().unwrap().pop() } fn recv(&self) -> Option<(usize, bool)> { self.0.recv.lock().unwrap().pop() } fn need_key(&self) -> Option<()> { self.0.need_key.lock().unwrap().pop() } fn key_confirmed(&self) -> Option<()> { self.0.key_confirmed.lock().unwrap().pop() } // has all events been accounted for by assertions? fn is_empty(&self) -> bool { let send = self.0.send.lock().unwrap(); let recv = self.0.recv.lock().unwrap(); let need_key = self.0.need_key.lock().unwrap(); let key_confirmed = self.0.key_confirmed.lock().unwrap(); send.is_empty() && recv.is_empty() && need_key.is_empty() & key_confirmed.is_empty() } } impl Callbacks for TestCallbacks { type Opaque = Opaque; fn send(t: &Self::Opaque, size: usize, sent: bool, _keypair: &Arc<KeyPair>, _counter: u64) { t.0.send.lock().unwrap().push((size, sent)) } fn recv(t: &Self::Opaque, size: usize, sent: bool, _keypair: &Arc<KeyPair>) { t.0.recv.lock().unwrap().push((size, sent)) } fn need_key(t: &Self::Opaque) { t.0.need_key.lock().unwrap().push(()); } fn key_confirmed(t: &Self::Opaque) { t.0.key_confirmed.lock().unwrap().push(()); } } // wait for scheduling (VERY conservative) fn wait() { thread::sleep(Duration::from_millis(30)); } fn init() { let _ = env_logger::builder().is_test(true).try_init(); } fn make_packet_padded(size: usize, src: IpAddr, dst: IpAddr, id: u64) -> Vec<u8> { let p = make_packet(size, src, dst, id); let mut o = vec![0; p.len() + SIZE_MESSAGE_PREFIX]; o[SIZE_MESSAGE_PREFIX..SIZE_MESSAGE_PREFIX + p.len()].copy_from_slice(&p[..]); o } #[bench] fn bench_outbound(b: &mut Bencher) { struct BencherCallbacks {} impl Callbacks for BencherCallbacks { type Opaque = Arc<AtomicUsize>; fn send( t: &Self::Opaque, size: usize, _sent: bool, _keypair: &Arc<KeyPair>, _counter: u64, ) { t.fetch_add(size, Ordering::SeqCst); } fn recv(_: &Self::Opaque, _size: usize, _sent: bool, _keypair: &Arc<KeyPair>) {} fn need_key(_: &Self::Opaque) {} fn key_confirmed(_: &Self::Opaque) {} } // create device let (_fake, _reader, tun_writer, _mtu) = dummy::TunTest::create(false); let router: Device<_, BencherCallbacks, dummy::TunWriter, dummy::VoidBind> = Device::new(num_cpus::get(), tun_writer); // add new peer let opaque = Arc::new(AtomicUsize::new(0)); let peer = router.new_peer(opaque.clone()); peer.add_keypair(dummy_keypair(true)); // add subnet to peer let (mask, len, dst) = ("192.168.1.0", 24, "192.168.1.20"); let mask: IpAddr = mask.parse().unwrap(); peer.add_allowed_ip(mask, len); // create "IP packet" let dst = dst.parse().unwrap(); let src = match dst { IpAddr::V4(_) => "127.0.0.1".parse().unwrap(), IpAddr::V6(_) => "::1".parse().unwrap(), }; let msg = make_packet_padded(1024, src, dst, 0); // every iteration sends 10 GB b.iter(|| { opaque.store(0, Ordering::SeqCst); while opaque.load(Ordering::Acquire) < 10 * 1024 * 1024 { router.send(msg.to_vec()).unwrap(); } }); } #[test] fn test_outbound() { init(); // create device let (_fake, _reader, tun_writer, _mtu) = dummy::TunTest::create(false); let router: Device<_, TestCallbacks, _, _> = Device::new(1, tun_writer); router.set_outbound_writer(dummy::VoidBind::new()); let tests = vec![ ("192.168.1.0", 24, "192.168.1.20", true), ("172.133.133.133", 32, "172.133.133.133", true), ("172.133.133.133", 32, "172.133.133.132", false), ( "2001:db8::ff00:42:0000", 112, "2001:db8::ff00:42:3242", true, ), ( "2001:db8::ff00:42:8000", 113, "2001:db8::ff00:42:0660", false, ), ( "2001:db8::ff00:42:8000", 113, "2001:db8::ff00:42:ffff", true, ), ]; for (num, (mask, len, dst, okay)) in tests.iter().enumerate() { println!( "Check: {} {} {}/{}", dst, if *okay { "\\in" } else { "\\notin" }, mask, len ); for set_key in vec![true, false] { debug!("index = {}, set_key = {}", num, set_key); // add new peer let opaque = Opaque::new(); let peer = router.new_peer(opaque.clone()); let mask: IpAddr = mask.parse().unwrap(); if set_key { peer.add_keypair(dummy_keypair(true)); } // map subnet to peer peer.add_allowed_ip(mask, *len); // create "IP packet" let dst = dst.parse().unwrap(); let src = match dst { IpAddr::V4(_) => "127.0.0.1".parse().unwrap(), IpAddr::V6(_) => "::1".parse().unwrap(), }; let msg = make_packet_padded(1024, src, dst, 0); // cryptkey route the IP packet let res = router.send(msg); // allow some scheduling wait(); if *okay { // cryptkey routing succeeded assert!(res.is_ok(), "crypt-key routing should succeed: {:?}", res); assert_eq!( opaque.need_key().is_some(), !set_key, "should have requested a new key, if no encryption state was set" ); assert_eq!( opaque.send().is_some(), set_key, "transmission should have been attempted" ); assert!( opaque.recv().is_none(), "no messages should have been marked as received" ); } else { // no such cryptkey route assert!(res.is_err(), "crypt-key routing should fail"); assert!( opaque.need_key().is_none(), "should not request a new-key if crypt-key routing failed" ); assert_eq!( opaque.send(), if set_key { Some((SIZE_KEEPALIVE, false)) } else { None }, "transmission should only happen if key was set (keepalive)", ); assert!( opaque.recv().is_none(), "no messages should have been marked as received", ); } } } println!("Test complete, drop device"); } #[test] fn test_bidirectional() { init(); let tests = [ ( ("192.168.1.0", 24, "192.168.1.20", true), ("172.133.133.133", 32, "172.133.133.133", true), ), ( ("192.168.1.0", 24, "192.168.1.20", true), ("172.133.133.133", 32, "172.133.133.133", true), ), ( ( "2001:db8::ff00:42:8000", 113, "2001:db8::ff00:42:ffff", true, ), ( "2001:db8::ff40:42:8000", 113, "2001:db8::ff40:42:ffff", true, ), ), ( ( "2001:db8::ff00:42:8000", 113, "2001:db8::ff00:42:ffff", true, ), ( "2001:db8::ff40:42:8000", 113, "2001:db8::ff40:42:ffff", true, ), ), ]; for stage in vec![true, false] { for (p1, p2) in tests.iter() { let ((bind_reader1, bind_writer1), (bind_reader2, bind_writer2)) = dummy::PairBind::pair(); // create matching device let (_fake, _, tun_writer1, _) = dummy::TunTest::create(false); let (_fake, _, tun_writer2, _) = dummy::TunTest::create(false); let router1: Device<_, TestCallbacks, _, _> = Device::new(1, tun_writer1); router1.set_outbound_writer(bind_writer1); let router2: Device<_, TestCallbacks, _, _> = Device::new(1, tun_writer2); router2.set_outbound_writer(bind_writer2); // prepare opaque values for tracing callbacks let opaque1 = Opaque::new(); let opaque2 = Opaque::new(); // create peers with matching keypairs and assign subnets let peer1 = router1.new_peer(opaque1.clone()); let peer2 = router2.new_peer(opaque2.clone()); { let (mask, len, _ip, _okay) = p1; let mask: IpAddr = mask.parse().unwrap(); peer1.add_allowed_ip(mask, *len); peer1.add_keypair(dummy_keypair(false)); } { let (mask, len, _ip, _okay) = p2; let mask: IpAddr = mask.parse().unwrap(); peer2.add_allowed_ip(mask, *len); peer2.set_endpoint(dummy::UnitEndpoint::new()); } if stage { println!("confirm using staged packet"); // create IP packet let (_mask, _len, ip1, _okay) = p1; let (_mask, _len, ip2, _okay) = p2; let msg = make_packet_padded( 1024, ip1.parse().unwrap(), // src ip2.parse().unwrap(), // dst 0, ); // stage packet for sending router2.send(msg).expect("failed to sent staged packet"); wait(); // validate events assert!(opaque2.recv().is_none()); assert!( opaque2.send().is_none(), "sending should fail as not key is set" ); assert!( opaque2.need_key().is_some(), "a new key should be requested since a packet was attempted transmitted" ); assert!(opaque2.is_empty(), "callbacks should only run once"); } // this should cause a key-confirmation packet (keepalive or staged packet) // this also causes peer1 to learn the "endpoint" for peer2 assert!(peer1.get_endpoint().is_none()); peer2.add_keypair(dummy_keypair(true)); wait(); assert!(opaque2.send().is_some()); assert!(opaque2.is_empty(), "events on peer2 should be 'send'"); assert!(opaque1.is_empty(), "nothing should happened on peer1"); // read confirming message received by the other end ("across the internet") let mut buf = vec![0u8; 2048]; let (len, from) = bind_reader1.read(&mut buf).unwrap(); buf.truncate(len); router1.recv(from, buf).unwrap(); wait(); assert!(opaque1.recv().is_some()); assert!(opaque1.key_confirmed().is_some()); assert!( opaque1.is_empty(), "events on peer1 should be 'recv' and 'key_confirmed'" ); assert!(peer1.get_endpoint().is_some()); assert!(opaque2.is_empty(), "nothing should happened on peer2"); // now that peer1 has an endpoint // route packets : peer1 -> peer2 for id in 1..11 { println!("round: {}", id); assert!( opaque1.is_empty(), "we should have asserted a value for every callback on peer1" ); assert!( opaque2.is_empty(), "we should have asserted a value for every callback on peer2" ); // pass IP packet to router let (_mask, _len, ip1, _okay) = p1; let (_mask, _len, ip2, _okay) = p2; let msg = make_packet_padded( 1024, ip2.parse().unwrap(), // src ip1.parse().unwrap(), // dst id, ); router1.send(msg).unwrap(); wait(); assert!(opaque1.send().is_some(), "encryption should succeed"); assert!( opaque1.recv().is_none(), "receiving callback should not be called" ); assert!(opaque1.need_key().is_none()); // receive ("across the internet") on the other end let mut buf = vec![0u8; 2048]; let (len, from) = bind_reader2.read(&mut buf).unwrap(); buf.truncate(len); router2.recv(from, buf).unwrap(); wait(); assert!( opaque2.send().is_none(), "sending callback should not be called" ); assert!( opaque2.recv().is_some(), "decryption and routing should succeed" ); assert!(opaque2.need_key().is_none()); } } } } }
pub fn raindrops(number: i64) -> String { let mut result = "" . to_string(); if number % 3 == 0 { result.push_str("Pling"); } if number % 5 == 0 { result.push_str("Plang"); } if number % 7 == 0 { result.push_str("Plong"); } if result.is_empty() { result = number.to_string(); } return result }
// Copyright 2021 Datafuse Labs. // // 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 std::alloc::Allocator; use super::table0::Entry; type Ent<V> = Entry<[u8; 0], V>; pub struct TableEmpty<V, A: Allocator + Clone> { pub(crate) has_zero: bool, pub(crate) slice: Box<[Entry<[u8; 0], V>; 1], A>, pub(crate) allocator: A, } impl<V, A: Allocator + Clone + Default> Default for TableEmpty<V, A> { fn default() -> Self { Self::new_in(A::default()) } } impl<V, A: Allocator + Clone> TableEmpty<V, A> { pub fn new_in(allocator: A) -> Self { Self { has_zero: false, allocator: allocator.clone(), slice: unsafe { Box::<[Ent<V>; 1], A>::new_zeroed_in(allocator).assume_init() }, } } pub fn capacity(&self) -> usize { 1 } pub fn len(&self) -> usize { usize::from(self.has_zero) } pub fn heap_bytes(&self) -> usize { std::mem::size_of::<Ent<V>>() } pub fn get(&self) -> Option<&Ent<V>> { if self.has_zero { Some(&self.slice[0]) } else { None } } pub fn get_mut(&mut self) -> Option<&mut Ent<V>> { if self.has_zero { Some(&mut self.slice[0]) } else { None } } /// # Safety /// /// The resulted `MaybeUninit` should be initialized immedidately. pub fn insert(&mut self) -> Result<&mut Ent<V>, &mut Ent<V>> { if !self.has_zero { self.has_zero = true; Ok(&mut self.slice[0]) } else { Err(&mut self.slice[0]) } } pub fn iter(&self) -> TableEmptyIter<'_, V> { TableEmptyIter { slice: self.slice.as_ref(), i: usize::from(!self.has_zero), } } pub fn clear(&mut self) { unsafe { self.has_zero = false; let allocator = self.allocator.clone(); self.slice = Box::<[Ent<V>; 1], A>::new_zeroed_in(allocator).assume_init(); } } } impl<V, A: Allocator + Clone> Drop for TableEmpty<V, A> { fn drop(&mut self) { if std::mem::needs_drop::<V>() && self.has_zero { unsafe { self.slice[0].val.assume_init_drop(); } } } } pub struct TableEmptyIter<'a, V> { slice: &'a [Ent<V>; 1], i: usize, } impl<'a, V> Iterator for TableEmptyIter<'a, V> { type Item = &'a Ent<V>; fn next(&mut self) -> Option<Self::Item> { if self.i > 0 { None } else { self.i += 1; Some(&self.slice[0]) } } fn size_hint(&self) -> (usize, Option<usize>) { let len = if self.i > 0 { 0 } else { 1 }; (len, Some(len)) } } pub struct TableEmptyIterMut<'a, V> { slice: &'a mut [Ent<V>; 1], i: usize, } impl<'a, V> Iterator for TableEmptyIterMut<'a, V> { type Item = &'a mut Ent<V>; fn next(&mut self) -> Option<Self::Item> { if self.i > 0 { None } else { let res = unsafe { &mut *(self.slice.as_ptr().add(self.i) as *mut _) }; self.i += 1; Some(res) } } }
pub struct Solution; impl Solution { pub fn can_finish(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool { let mut checker = LoopChecker::new(num_courses as usize); for prerequisite in prerequisites { checker.add_edge(prerequisite[0] as usize, prerequisite[1] as usize); } !checker.has_loop() } } #[derive(Clone)] enum State { Unchecked, Checking, Checked, } struct LoopChecker { num_vertices: usize, nexts: Vec<Vec<usize>>, states: Vec<State>, } impl LoopChecker { fn new(num_vertices: usize) -> LoopChecker { let nexts = vec![Vec::new(); num_vertices]; let states = vec![State::Unchecked; num_vertices]; LoopChecker { num_vertices, nexts, states, } } fn add_edge(&mut self, from: usize, to: usize) { self.nexts[from].push(to); } fn has_loop(&mut self) -> bool { for i in 0..self.num_vertices { if self.check(i) { return true; } } false } fn check(&mut self, i: usize) -> bool { match self.states[i] { State::Unchecked => { self.states[i] = State::Checking; for j in 0..self.nexts[i].len() { if self.check(self.nexts[i][j]) { return true; } } self.states[i] = State::Checked; false } State::Checking => true, State::Checked => false, } } } #[test] fn test0207() { fn case(num_courses: i32, prerequisites: Vec<Vec<i32>>, want: bool) { let got = Solution::can_finish(num_courses, prerequisites); assert_eq!(got, want); } case(2, vec![vec![1, 0]], true); case(2, vec![vec![1, 0], vec![0, 1]], false); }
use crate::extensions::srgb8::*; use nannou::prelude::*; pub fn soft_white() -> Hsl { // srgb8(249, 248, 245).into_hsl() hsl(0.12466522, 0.34505126, 0.9302026) } pub fn soft_black() -> Hsl { srgb8(26, 26, 22).into_hsl() }
impl Solution { pub fn is_valid(s: String) -> bool { let mut stack = Vec::new(); for c in s.chars() { if c == '(' || c == '[' || c == '{' { stack.push(c); continue; } match stack.pop() { Some(prev) => { if prev == '(' && c == ')' || prev == '[' && c == ']' || prev == '{' && c == '}' { continue; } stack.push(prev); stack.push(c); } None => stack.push(c) } } stack.is_empty() } } struct Solution {} #[cfg(test)] mod tests { use crate::Solution; fn test(s: String, expected: bool) { assert_eq!(Solution::is_valid(s), expected); } #[test] fn example1() { test("()".to_string(), true); } #[test] fn example2() { test("()[]{}".to_string(), true); } #[test] fn example3() { test("(]".to_string(), false); } #[test] fn example4() { test("([)]".to_string(), false); } #[test] fn example5() { test("{[]}".to_string(), true); } #[test] fn case89() { test("([}}])".to_string(), false); } }
use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(day5)] fn generator(input: &str) -> Vec<i16> { let mut passes = input .lines() .map(|pass| seat_id(pass)) .collect::<Vec<i16>>(); passes.sort(); passes } fn splitter(pgm: &str, low: char, high: char, from: i16, to: i16) -> i16 { let (mut a, mut b) = (from, to); for c in pgm.chars() { if c == low { b = a + (b - a) / 2 } else if c == high { a = a + (b - a) / 2 + 1 } else { panic!("Unexpected char {}", c) }; } assert_eq!(a, b); a } fn seat_id(pgm: &str) -> i16 { (splitter(&pgm[0..7], 'F', 'B', 0, 127) * 8) + splitter(&pgm[7..10], 'L', 'R', 0, 7) } #[aoc(day5, part1)] fn solve_part1(seats: &Vec<i16>) -> i16 { *seats.iter().max().unwrap() } #[aoc(day5, part2)] fn solve_part2(seats: &Vec<i16>) -> i16 { *seats .iter() .find(|s| seats.contains(&(*s + 2)) && !seats.contains(&(*s + 1))) .unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_splitter() { assert_eq!(splitter("FBFBBFF", 'F', 'B', 0, 127), 44); assert_eq!(splitter("RLR", 'L', 'R', 0, 7), 5); } #[test] fn test_seat_id() { assert_eq!(seat_id("BFFFBBFRRR"), 567); assert_eq!(seat_id("FFFBBBFRRR"), 119); assert_eq!(seat_id("BBFFBBFRLL"), 820); } }
fn main() { let input: Vec<i32> = include_str!("../input") .replace("\n", "") .split(',') .map(|num| num.parse().unwrap()) .collect(); println!("Part 1: {}", part1(&input)); println!("Part 2: {}", part2(&input)); } fn part1(input: &Vec<i32>) -> i32 { let mut result = i32::MAX; let min = *input.iter().min().unwrap(); let max = *input.iter().max().unwrap(); for target in min..max { let sum = input.iter().map(|x| (x - target).abs()).sum(); result = std::cmp::min(result, sum); } result } fn part2(input: &Vec<i32>) -> i32 { let mut result = i32::MAX; let min = *input.iter().min().unwrap(); let max = *input.iter().max().unwrap(); for target in min..max { let sum = input .iter() .map(|x| { let distance = (x - target).abs(); distance * (distance + 1) / 2 }) .sum(); result = std::cmp::min(result, sum); } result }
//! Helper to simplify implementation of widget decorators. use crate::{ geometry::{measurement::MeasureSpec, BoundingBox, Position}, input::{controller::InputContext, event::InputEvent}, state::WidgetState, widgets::Widget, }; pub trait WidgetDecorator { type Widget: Widget; fn attach(&mut self, parent: usize, self_index: usize) { debug_assert!(self_index == 0 || parent != self_index); self.widget_mut().attach(parent, self_index); } fn bounding_box(&self) -> BoundingBox { self.widget().bounding_box() } fn bounding_box_mut(&mut self) -> &mut BoundingBox { self.widget_mut().bounding_box_mut() } fn measure(&mut self, measure_spec: MeasureSpec) { self.widget_mut().measure(measure_spec); } fn arrange(&mut self, position: Position) { self.widget_mut().arrange(position); } fn children(&self) -> usize { 1 + self.widget().children() } fn get_child(&self, idx: usize) -> &dyn Widget { if idx == 0 { self.widget() } else { self.widget().get_child(idx - 1) } } fn get_mut_child(&mut self, idx: usize) -> &mut dyn Widget { if idx == 0 { self.widget_mut() } else { self.widget_mut().get_mut_child(idx - 1) } } fn parent_index(&self) -> usize { self.widget().parent_index() } fn update(&mut self) { self.widget_mut().update(); } fn on_state_changed(&mut self, state: WidgetState) { self.fire_on_state_changed(state); self.widget_mut().on_state_changed(state); } fn fire_on_state_changed(&mut self, _state: WidgetState) {} fn set_parent(&mut self, _index: usize) { // TODO this doesn't belong in the Widget interface } fn test_input(&mut self, event: InputEvent) -> Option<usize> { self.widget_mut().test_input(event).map(|i| i + 1) } fn handle_input(&mut self, ctxt: InputContext, event: InputEvent) -> bool { self.widget_mut().handle_input(ctxt, event) } fn is_selectable(&self) -> bool { self.widget().is_selectable() } fn widget(&self) -> &Self::Widget; fn widget_mut(&mut self) -> &mut Self::Widget; } impl<T> Widget for T where T: WidgetDecorator, { fn attach(&mut self, parent: usize, self_index: usize) { WidgetDecorator::attach(self, parent, self_index); } fn bounding_box(&self) -> BoundingBox { WidgetDecorator::bounding_box(self) } fn bounding_box_mut(&mut self) -> &mut BoundingBox { WidgetDecorator::bounding_box_mut(self) } fn children(&self) -> usize { WidgetDecorator::children(self) } fn get_child(&self, idx: usize) -> &dyn Widget { WidgetDecorator::get_child(self, idx) } fn get_mut_child(&mut self, idx: usize) -> &mut dyn Widget { WidgetDecorator::get_mut_child(self, idx) } fn measure(&mut self, measure_spec: MeasureSpec) { WidgetDecorator::measure(self, measure_spec); } fn arrange(&mut self, position: Position) { WidgetDecorator::arrange(self, position); } fn update(&mut self) { WidgetDecorator::update(self); } fn parent_index(&self) -> usize { WidgetDecorator::parent_index(self) } fn set_parent(&mut self, index: usize) { // TODO this doesn't belong in the Widget interface WidgetDecorator::set_parent(self, index); } fn test_input(&mut self, event: InputEvent) -> Option<usize> { WidgetDecorator::test_input(self, event) } fn handle_input(&mut self, ctxt: InputContext, event: InputEvent) -> bool { WidgetDecorator::handle_input(self, ctxt, event) } fn on_state_changed(&mut self, state: WidgetState) { WidgetDecorator::on_state_changed(self, state); } fn is_selectable(&self) -> bool { WidgetDecorator::is_selectable(self) } }
use crate::mod_definition::{MappedModDefinition, ModDefinition}; use crate::mod_line_scanner::ASSUMED_FIRST_MONSTER_ID; use crate::{replace_use, LazyString}; use lazy_static::lazy_static; use maplit::btreeset; use regex::Captures; use std::cell::RefCell; use std::collections::{BTreeSet, HashMap}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::rc::Rc; use std::str::FromStr; lazy_static! { static ref KNOWN_SUMMON_COPYSPELL_IDS: BTreeSet<u32> = { btreeset![721, 724, 733, 795, 805, 813, 818, 847, 875, 893, 900, 920, 1091] }; static ref KNOWN_SUMMON_COPYSPELL_NAMES: BTreeSet<String> = { btreeset![ "animate skeleton".to_owned(), "horde of skeletons".to_owned(), "raise skeletons".to_owned(), "reanimation".to_owned(), "pale riders".to_owned(), "revive lictor".to_owned(), "living mercury".to_owned(), "king of elemental earth".to_owned(), "summon fire elemental".to_owned(), "pack of wolves".to_owned(), "contact forest giant".to_owned(), "infernal disease".to_owned(), "hannya pact".to_owned(), "swarm".to_owned(), "creeping doom".to_owned(), ] }; } pub fn remap_ids( mod_definitions: &HashMap<String, ModDefinition>, ) -> HashMap<String, MappedModDefinition> { let mut weapons_implicit_definition_count = 0; let mut armours_implicit_definition_count = 0; let mut monsters_implicit_definition_count = 0; let mut name_types_implicit_definition_count = 0; let mut spells_implicit_definition_count = 0; let mut items_implicit_definition_count = 0; let mut sites_implicit_definition_count = 0; let mut nations_implicit_definition_count = 0; // let mut events_implicit_definition_count = 0; // I think we don't remap events let mut poptype_implicit_definition_count = 0; let mut montags_implicit_definition_count = 0; let mut event_codes_implicit_definition_count = 0; let mut restricted_items_implicit_definition_count = 0; let mut enchantments_implicit_definition_count = 0; for mod_definition in mod_definitions.values() { weapons_implicit_definition_count += mod_definition.weapons.implicit_definitions; armours_implicit_definition_count += mod_definition.armours.implicit_definitions; monsters_implicit_definition_count += mod_definition.monsters.implicit_definitions; name_types_implicit_definition_count += mod_definition.name_types.implicit_definitions; spells_implicit_definition_count += mod_definition.spells.implicit_definitions; nations_implicit_definition_count += mod_definition.nations.implicit_definitions; // events_implicit_definition_count += mod_definition.events.implicit_definitions; poptype_implicit_definition_count += mod_definition.poptype.implicit_definitions; montags_implicit_definition_count += mod_definition.montags.implicit_definitions; event_codes_implicit_definition_count += mod_definition.event_codes.implicit_definitions; restricted_items_implicit_definition_count += mod_definition.restricted_items.implicit_definitions; items_implicit_definition_count += mod_definition.items.implicit_definitions; sites_implicit_definition_count += mod_definition.sites.implicit_definitions; } let mut first_available_weapon_id = crate::ASSUMED_FIRST_WEAPON_ID + weapons_implicit_definition_count; let mut first_available_armour_id = 31 + crate::ASSUMED_FIRST_ARMOUR_ID + armours_implicit_definition_count; let mut first_available_monster_id = 105 + crate::ASSUMED_FIRST_MONSTER_ID + monsters_implicit_definition_count; // println!("first available monster ID: {}", first_available_monster_id); let mut first_available_name_type_id = crate::ASSUMED_FIRST_NAMETYPE_ID + name_types_implicit_definition_count; let mut first_available_spell_id = crate::ASSUMED_FIRST_SPELL_ID + spells_implicit_definition_count; // This has been really annoying let's just add a safety net let mut first_available_nations_id = 20 + crate::ASSUMED_FIRST_NATION_ID + nations_implicit_definition_count; let mut first_available_montags_id = crate::ASSUMED_FIRST_MONTAG_ID + montags_implicit_definition_count; let mut first_available_event_codes_id = crate::ASSUMED_FIRST_EVENTCODE_ID + event_codes_implicit_definition_count; let mut first_available_restricted_items_id = crate::ASSUMED_FIRST_RESTRICTED_ITEM_ID + restricted_items_implicit_definition_count; let mut first_available_enchantment_id = 200; let mut first_available_item_id = crate::ASSUMED_FIRST_ITEM_ID + items_implicit_definition_count; let mut first_available_site_id = crate::ASSUMED_FIRST_SITE_ID + sites_implicit_definition_count; let mut mapped_mods = HashMap::new(); for (mod_name, mod_definition) in mod_definitions.into_iter() { let mapped_mod = MappedModDefinition { weapons: remap_particular_ids( &mut first_available_weapon_id, &mod_definition.weapons.defined_ids, ), armours: remap_particular_ids( &mut first_available_armour_id, &mod_definition.armours.defined_ids, ), monsters: remap_particular_ids( &mut first_available_monster_id, &mod_definition.monsters.defined_ids, ), name_types: remap_particular_ids( &mut first_available_name_type_id, &mod_definition.name_types.defined_ids, ), spells: remap_particular_ids( &mut first_available_spell_id, &mod_definition.spells.defined_ids, ), nations: remap_particular_ids( &mut first_available_nations_id, &mod_definition.nations.defined_ids, ), montags: remap_particular_ids( &mut first_available_montags_id, &mod_definition.montags.defined_ids, ), event_codes: remap_particular_ids( &mut first_available_event_codes_id, &mod_definition.event_codes.defined_ids, ), restricted_items: remap_particular_ids( &mut first_available_restricted_items_id, &mod_definition.restricted_items.defined_ids, ), enchantments: remap_particular_ids( &mut first_available_enchantment_id, &mod_definition.enchantments, ), items: remap_particular_ids( &mut first_available_item_id, &mod_definition.items.defined_ids, ), sites: remap_particular_ids( &mut first_available_site_id, &mod_definition.sites.defined_ids, ), // poptype: unimplemented!(), FIXME: is this an issue or not? }; // Clone doesn't seem to be needed if we consume self mapped_mods.insert(mod_name.clone(), mapped_mod); } mapped_mods } fn remap_particular_ids( first_available_id: &mut u32, mod_definitions: &BTreeSet<u32>, ) -> HashMap<u32, u32> { let mut mapped_ids = HashMap::new(); for mod_definition_id in mod_definitions { mapped_ids.insert(*mod_definition_id, *first_available_id); *first_available_id += 1; } mapped_ids } struct ParsedSpellBlock { copyspell: Option<String>, selectspell: Option<String>, effect: Option<u64>, damage: Option<i64>, } // When parsing a spell, we can't know what to map it's #damage line to until // we've seen the whole thing. So we keep its lines here (as well as a ref to // where we will put the damage line) struct SpellBlock { start_line: String, lines: Vec<String>, eventual_damage_line: Rc<RefCell<Option<String>>>, } impl SpellBlock { pub fn new(start_line: String) -> Self { Self { start_line, lines: Vec::new(), eventual_damage_line: Rc::new(RefCell::new(None)), } } // If we find a #damage line, then we don't know what to map it to until later // So we set it to get its value from the ref later. fn process_damage_line(&mut self, line: &str) -> LazyString { { let mut b = self.eventual_damage_line.borrow_mut(); *b = Some(line.to_owned()); } let new_rc = Rc::clone(&self.eventual_damage_line); crate::LazyString::Thunk(Box::new(move || { let b = new_rc.borrow(); let st: &String = b .as_ref() .expect("Tried to map a #damage line but nobody set what to map to"); st.clone() })) } // TODO: we're scanning for damage a few times now fn parse_spell(&self) -> ParsedSpellBlock { let mut option_effect = None; let mut option_copyspell_line = None; let mut option_damage = None; let mut option_selectspell_line = None; let iter = std::iter::once(&self.start_line).chain(self.lines.iter()); for spell_line in iter { if let Some(effect_capture) = crate::SPELL_EFFECT.captures(spell_line) { let found_id = u64::from_str(effect_capture.name("id").unwrap().as_str()).unwrap(); option_effect = Some(found_id) } else if crate::SPELL_COPY_ID.is_match(spell_line) || crate::SPELL_COPY_NAME.is_match(spell_line) { option_copyspell_line = Some(spell_line.clone()) } else if let Some(damage_capture) = crate::SPELL_DAMAGE.captures(spell_line) { let found_id = i64::from_str(damage_capture.name("id").unwrap().as_str()).unwrap(); option_damage = Some(found_id) } else if crate::SPELL_SELECT_ID.is_match(spell_line) || crate::SPELL_SELECT_NAME.is_match(spell_line) { option_selectspell_line = Some(spell_line.clone()) } } ParsedSpellBlock { copyspell: option_copyspell_line, damage: option_damage, effect: option_effect, selectspell: option_selectspell_line, } } // Map the damage line, given that it's an effect fn map_enchantment_damage_line(&mut self, mapped_definition: &MappedModDefinition) { let mut b = self.eventual_damage_line.borrow_mut(); if let Some(damage_line) = b.as_ref() { if let Some(damage_capture) = crate::SPELL_DAMAGE.captures(damage_line) { let found_id = u64::from_str(damage_capture.name("id").unwrap().as_str()).unwrap() as u32; if found_id >= crate::ASSUMED_FIRST_ENCHANTMENT_ID { if let Some(new_id) = mapped_definition.enchantments.get(&found_id) { let new_string = crate::SPELL_DAMAGE .replace(damage_line, |ref captures: &Captures| -> String { format!("{}{}{}", &captures["prefix"], new_id, &captures["suffix"]) }) .to_string(); *b = Some(new_string); } } } } } fn map_summoning_damage_line(&mut self, mapped_definition: &MappedModDefinition) { // TODO: don't actually need to scan the regex twice let mut b = self.eventual_damage_line.borrow_mut(); if let Some(damage_line) = b.as_ref() { if let Some(damage_capture) = crate::SPELL_DAMAGE.captures(damage_line) { let found_id = i64::from_str(damage_capture.name("id").unwrap().as_str()).unwrap(); if found_id > 0 { // lookup in monsters if let Some(new_id) = mapped_definition.monsters.get(&(found_id as u32)) { let new_string = crate::SPELL_DAMAGE .replace(damage_line, |ref captures: &Captures| -> String { format!("{}{}{}", &captures["prefix"], new_id, &captures["suffix"]) }) .to_string(); *b = Some(new_string); } } else { // lookup in montags. Found_id is negative if let Some(new_id) = mapped_definition.montags.get(&(-found_id as u32)) { let new_montag_id = -(*new_id as i32); let new_string = crate::SPELL_DAMAGE .replace(damage_line, |ref captures: &Captures| -> String { format!( "{}{}{}", &captures["prefix"], new_montag_id, &captures["suffix"] ) }) .to_string(); *b = Some(new_string); } } } } } // For each line in a spell, map it, returning true if we reached the end pub fn map_line_until_end( &mut self, line: &str, lines: &mut Vec<LazyString>, mapped_definition: &MappedModDefinition, ) -> bool { self.lines.push(line.to_owned()); if crate::SPELL_DAMAGE.is_match(&line) { lines.push(self.process_damage_line(line)); // help we have a #damage and we don't know how to map it yet false } else if crate::END.is_match(&line) { // URGH going to need some lookahead on this let parsed_spell = self.parse_spell(); if let Some(effect) = parsed_spell.effect { if crate::ENCHANTMENT_EFFECTS.contains(&effect) { self.map_enchantment_damage_line(mapped_definition); } else if crate::SUMMONING_EFFECTS.contains(&effect) { self.map_summoning_damage_line(mapped_definition); } } else { // Do we have a copyspell? if let Some(copyspell_line) = parsed_spell.copyspell { // We know it's a summon spell if is_known_summoning_copyspell(&copyspell_line) { // println!("{} is a known copyspell line", copyspell_line); self.map_summoning_damage_line(mapped_definition); } else if let Some(damage) = parsed_spell.damage { // does the damage match a monster, montag, or ench? // println!("{} is NOT a known copyspell line", copyspell_line); if damage > 0 { if let Some(new_id) = mapped_definition.monsters.get(&(damage as u32)) { if (damage as u32) >= ASSUMED_FIRST_MONSTER_ID { println!( "WARNING! '{}' found for a potential monster ID \ which might need to be manually mapped from {} to {}", copyspell_line, damage, new_id ); } } else if let Some(new_id) = mapped_definition.enchantments.get(&(damage as u32)) { println!( "WARNING! '{}' found for a potential enchantment ID \ which might need to be manually mapped from {} to {}", copyspell_line, damage, new_id ); } } else { if let Some(new_id) = mapped_definition.montags.get(&(-damage as u32)) { println!( "WARNING! '{}' found for a potential montag ID \ which might need to be manually mapped from {} to {}", copyspell_line, -damage, new_id ); } } } // god this code is really messy } else if let Some(selectspell) = parsed_spell.selectspell { if is_known_summoning_selectspell(&selectspell) { self.map_summoning_damage_line(mapped_definition); } else if let Some(damage) = parsed_spell.damage { // does the damage match a monster, montag, or ench? if damage > 0 { if let Some(new_id) = mapped_definition.monsters.get(&(damage as u32)) { if (damage as u32) >= ASSUMED_FIRST_MONSTER_ID { println!( "WARNING! '{}' found for a potential monster ID \ which might need to be manually mapped from {} to {}", selectspell, damage, new_id ); } } else if let Some(new_id) = mapped_definition.enchantments.get(&(damage as u32)) { println!( "WARNING! '{}' found for a potential enchantment ID \ which might need to be manually mapped from {} to {}", selectspell, damage, new_id ); } } else { if let Some(new_id) = mapped_definition.montags.get(&(-damage as u32)) { println!( "WARNING! '{}' found for a potential montag ID \ which might need to be manually mapped from {} to {}", selectspell, -damage, new_id ); } } } } else { println!("Found a spell which has no damage, no copyspell, and no selectspell. Please report this to the author.") } } true } else { false } } } fn is_known_summoning_copyspell(copyspell: &String) -> bool { if let Some(name_capture) = crate::SPELL_COPY_NAME.captures(copyspell) { // println!("copyspell name {:?}", name_capture); let found_name = name_capture.name("name").unwrap().as_str(); KNOWN_SUMMON_COPYSPELL_NAMES.contains(&found_name.to_lowercase()) } else if let Some(id_capture) = crate::SPELL_COPY_ID.captures(copyspell) { // println!("copyspell id {:?}", id_capture); let found_id = u32::from_str(id_capture.name("id").unwrap().as_str()).unwrap(); KNOWN_SUMMON_COPYSPELL_IDS.contains(&found_id) } else { false } } fn is_known_summoning_selectspell(selectspell: &String) -> bool { if let Some(name_capture) = crate::SPELL_SELECT_NAME.captures(selectspell) { let found_name = name_capture.name("name").unwrap().as_str(); KNOWN_SUMMON_COPYSPELL_NAMES.contains(&found_name.to_lowercase()) } else if let Some(id_capture) = crate::SPELL_SELECT_ID.captures(selectspell) { let found_id = u32::from_str(id_capture.name("id").unwrap().as_str()).unwrap(); KNOWN_SUMMON_COPYSPELL_IDS.contains(&found_id) } else { false } } pub fn apply_remapped_ids( lines: &mut Vec<LazyString>, remapped_ids: &HashMap<String, MappedModDefinition>, ) { use LazyString::*; for (path, mapped_definition) in remapped_ids { let file = File::open(path).unwrap(); let file_buff = BufReader::new(file); let line_iter = file_buff.lines().map(|result| result.unwrap()); let mut option_spell_block: Option<SpellBlock> = None; let mut is_in_description = false; for line in line_iter { if is_in_description { if crate::MOD_DESCRIPTION_STOP.is_match(&line) { // End of description, ditch this line and then continue as normal is_in_description = false; continue; } else { // Throw away a description line continue; } } else { if let Some(current_spell_block) = &mut option_spell_block { let is_end_block = current_spell_block.map_line_until_end(&line, lines, &mapped_definition); if is_end_block { option_spell_block = None; } // FIXME: this is real bad but we can't put control flow in `map_line_until_end` soooo if crate::SPELL_DAMAGE.is_match(&line) { continue; } } else if crate::SPELL_BLOCK_START.is_match(&line) { // If we find a #newspell or a #selectspell, start recording lines option_spell_block = Some(SpellBlock::new(line.clone())); } } if crate::MOD_NAME_LINE.is_match(&line) || crate::MOD_DESCRIPTION_LINE.is_match(&line) || crate::MOD_ICON_LINE.is_match(&line) || crate::MOD_VERSION_LINE.is_match(&line) || crate::MOD_DOMVERSION_LINE.is_match(&line) { // ditch the mod info continue; } else if crate::MOD_DESCRIPTION_START.is_match(&line) { // Description has started, ditch the line is_in_description = true; continue; } else { let new_line = replace_use( &line, &mapped_definition.weapons, &crate::mod_line_scanner::USE_NUMBERED_WEAPON ).or_else(|| replace_use( &line, &mapped_definition.armours, &crate::mod_line_scanner::USE_NUMBERED_ARMOUR) ).or_else(|| { if let Some(capture) = crate::mod_line_scanner::USE_MONSTER.captures(&line) { let found_id = i32::from_str(capture.name("id").unwrap().as_str()).unwrap(); if found_id > 0 { if let Some(new_id) = mapped_definition.monsters.get(&(found_id as u32)) { let new_line: String = crate::mod_line_scanner::USE_MONSTER.replace(&line, |ref captures: &Captures| -> String { format!("{}{}{}", &captures["prefix"], new_id, &captures["suffix"]) }).to_string(); Some(new_line) } else { Some(line.clone()) } } else { // it's a montag! if let Some(new_id) = mapped_definition.montags.get(&(-found_id as u32)) { let new_line: String = crate::mod_line_scanner::USE_MONSTER.replace(&line, |ref captures: &Captures| -> String { format!("{}-{}{}", &captures["prefix"], new_id, &captures["suffix"]) }).to_string(); Some(new_line) } else { Some(line.clone()) } } } else { None } }).or_else(|| replace_use(&line, &mapped_definition.name_types, &crate::mod_line_scanner::USE_NAMETYPE) ).or_else(|| replace_use(&line, &mapped_definition.spells, &crate::mod_line_scanner::USE_NUMBERED_SPELL) ).or_else(|| replace_use(&line, &mapped_definition.nations, &crate::mod_line_scanner::USE_NUMBERED_NATION) ).or_else(|| // n.b.: some of the montags have been mapped in the monsters step above replace_use(&line, &mapped_definition.montags, &crate::mod_line_scanner::USE_NUMBERED_MONTAG) ).or_else(|| replace_use(&line, &mapped_definition.event_codes, &crate::mod_line_scanner::USE_NUMBERED_EVENTCODE) ).or_else(|| replace_use(&line, &mapped_definition.restricted_items, &crate::mod_line_scanner::USE_NUMBERED_RESTRICTED_ITEM) ).or_else(|| replace_use(&line, &mapped_definition.items, &crate::mod_line_scanner::USE_NUMBERED_ITEM) ).or_else(|| replace_use(&line, &mapped_definition.sites, &crate::mod_line_scanner::USE_NUMBERED_SITE) ) .or_else(|| replace_use(&line, &mapped_definition.enchantments, &crate::mod_line_scanner::USE_GLOBAL_ENCHANTMENT) ) .or_else(|| Some(line.clone())); if let Some(some_new_line) = new_line { lines.push(S(some_new_line)); } } } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "Foundation_Collections")] pub mod Collections; #[cfg(feature = "Foundation_Diagnostics")] pub mod Diagnostics; #[cfg(feature = "Foundation_Metadata")] pub mod Metadata; #[cfg(feature = "Foundation_Numerics")] pub mod Numerics; #[link(name = "windows")] extern "system" {} pub type AsyncActionCompletedHandler = *mut ::core::ffi::c_void; pub type AsyncActionProgressHandler = *mut ::core::ffi::c_void; pub type AsyncActionWithProgressCompletedHandler = *mut ::core::ffi::c_void; pub type AsyncOperationCompletedHandler = *mut ::core::ffi::c_void; pub type AsyncOperationProgressHandler = *mut ::core::ffi::c_void; pub type AsyncOperationWithProgressCompletedHandler = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct AsyncStatus(pub i32); impl AsyncStatus { pub const Canceled: Self = Self(2i32); pub const Completed: Self = Self(1i32); pub const Error: Self = Self(3i32); pub const Started: Self = Self(0i32); } impl ::core::marker::Copy for AsyncStatus {} impl ::core::clone::Clone for AsyncStatus { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DateTime { pub UniversalTime: i64, } impl ::core::marker::Copy for DateTime {} impl ::core::clone::Clone for DateTime { fn clone(&self) -> Self { *self } } pub type Deferral = *mut ::core::ffi::c_void; pub type DeferralCompletedHandler = *mut ::core::ffi::c_void; pub type EventHandler = *mut ::core::ffi::c_void; #[repr(C)] pub struct EventRegistrationToken { pub Value: i64, } impl ::core::marker::Copy for EventRegistrationToken {} impl ::core::clone::Clone for EventRegistrationToken { fn clone(&self) -> Self { *self } } pub type IAsyncAction = *mut ::core::ffi::c_void; pub type IAsyncActionWithProgress = *mut ::core::ffi::c_void; pub type IAsyncInfo = *mut ::core::ffi::c_void; pub type IAsyncOperation = *mut ::core::ffi::c_void; pub type IAsyncOperationWithProgress = *mut ::core::ffi::c_void; pub type IClosable = *mut ::core::ffi::c_void; pub type IGetActivationFactory = *mut ::core::ffi::c_void; pub type IMemoryBuffer = *mut ::core::ffi::c_void; pub type IMemoryBufferReference = *mut ::core::ffi::c_void; pub type IPropertyValue = *mut ::core::ffi::c_void; pub type IReference = *mut ::core::ffi::c_void; pub type IReferenceArray = *mut ::core::ffi::c_void; pub type IStringable = *mut ::core::ffi::c_void; pub type IWwwFormUrlDecoderEntry = *mut ::core::ffi::c_void; pub type MemoryBuffer = *mut ::core::ffi::c_void; #[repr(C)] pub struct Point { pub X: f32, pub Y: f32, } impl ::core::marker::Copy for Point {} impl ::core::clone::Clone for Point { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct PropertyType(pub i32); impl PropertyType { pub const Empty: Self = Self(0i32); pub const UInt8: Self = Self(1i32); pub const Int16: Self = Self(2i32); pub const UInt16: Self = Self(3i32); pub const Int32: Self = Self(4i32); pub const UInt32: Self = Self(5i32); pub const Int64: Self = Self(6i32); pub const UInt64: Self = Self(7i32); pub const Single: Self = Self(8i32); pub const Double: Self = Self(9i32); pub const Char16: Self = Self(10i32); pub const Boolean: Self = Self(11i32); pub const String: Self = Self(12i32); pub const Inspectable: Self = Self(13i32); pub const DateTime: Self = Self(14i32); pub const TimeSpan: Self = Self(15i32); pub const Guid: Self = Self(16i32); pub const Point: Self = Self(17i32); pub const Size: Self = Self(18i32); pub const Rect: Self = Self(19i32); pub const OtherType: Self = Self(20i32); pub const UInt8Array: Self = Self(1025i32); pub const Int16Array: Self = Self(1026i32); pub const UInt16Array: Self = Self(1027i32); pub const Int32Array: Self = Self(1028i32); pub const UInt32Array: Self = Self(1029i32); pub const Int64Array: Self = Self(1030i32); pub const UInt64Array: Self = Self(1031i32); pub const SingleArray: Self = Self(1032i32); pub const DoubleArray: Self = Self(1033i32); pub const Char16Array: Self = Self(1034i32); pub const BooleanArray: Self = Self(1035i32); pub const StringArray: Self = Self(1036i32); pub const InspectableArray: Self = Self(1037i32); pub const DateTimeArray: Self = Self(1038i32); pub const TimeSpanArray: Self = Self(1039i32); pub const GuidArray: Self = Self(1040i32); pub const PointArray: Self = Self(1041i32); pub const SizeArray: Self = Self(1042i32); pub const RectArray: Self = Self(1043i32); pub const OtherTypeArray: Self = Self(1044i32); } impl ::core::marker::Copy for PropertyType {} impl ::core::clone::Clone for PropertyType { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct Rect { pub X: f32, pub Y: f32, pub Width: f32, pub Height: f32, } impl ::core::marker::Copy for Rect {} impl ::core::clone::Clone for Rect { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct Size { pub Width: f32, pub Height: f32, } impl ::core::marker::Copy for Size {} impl ::core::clone::Clone for Size { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct TimeSpan { pub Duration: i64, } impl ::core::marker::Copy for TimeSpan {} impl ::core::clone::Clone for TimeSpan { fn clone(&self) -> Self { *self } } pub type TypedEventHandler = *mut ::core::ffi::c_void; pub type Uri = *mut ::core::ffi::c_void; pub type WwwFormUrlDecoder = *mut ::core::ffi::c_void; pub type WwwFormUrlDecoderEntry = *mut ::core::ffi::c_void;