text
stringlengths
8
4.13M
use futures::executor::block_on; use futures::{stream, StreamExt}; // 0.3.5 use reqwest::Client; // 0.10.6 const CONCURRENT_REQUESTS: usize = 2; #[derive(Debug)] pub struct Parser { pub tickers: Vec<String>, } impl Parser { pub fn parse(&self) { println!("hello1 {:#?}", self); for x in &self.tickers { println!("c = {:#?}", x); } } } async fn info(tickers: &Vec<String>) { let client = Client::new(); let urls = tickers.into_iter().map(|t| format!("https://query1.finance.yahoo.com/v8/finance/chart/{}?region=GB&lang=en-GB&includePrePost=false&interval=2m&range=1d&corsDomain=uk.finance.yahoo.com&.tsrc=finance", t)); let c = urls.len(); println!("urls = {:#?}", urls); println!("c = {:#?}", c); stream::iter(urls) .map(|url| { let client = &client; async move { let resp = client.get(&url).send().await?; resp.bytes().await } }) .buffer_unordered(c) .for_each(|b| async { match b { Ok(b) => 1, Err(e) => 2, } }) .await; }
use std::fmt; use std::str::FromStr; use crate::errors::ParseError; /// Represents an RGB color. #[derive(Copy, Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Color { /// red from 0-255 pub red: u8, /// blue from 0-255 pub green: u8, /// green from 0-255 pub blue: u8, } impl Color { /// Create a new color from the respective parts pub fn new(red: u8, green: u8, blue: u8) -> Self { Color { red, green, blue } } } impl FromStr for Color { type Err = ParseError; fn from_str(line: &str) -> Result<Color, Self::Err> { let mut s = line.split(" : "); s.next().ok_or(ParseError::MissingColorComponent)?; let s = s.next().ok_or(ParseError::MissingColorComponent)?; let s = s.split(',').collect::<Vec<_>>(); let red = s[0].parse::<u8>()?; let green = s[1].parse::<u8>()?; let blue = s[2].parse::<u8>()?; Ok(Color { red, green, blue }) } } impl fmt::Display for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{},{},{}", self.red, self.green, self.blue) } }
use super::*; prelude_macros::implement_constructors! { [i8, u8, i16, u16 , i32, u32, i64, u64, f16, f32], { Vec2 => { (all: Num), (x: Num, y: Num), (fr: Vec2), }, Vec3 => { (all: Num), (x: Num, y: Num, z: Num), (x: Num, b: Vec2), (a: Vec2, z: Num), (fr: Vec3), }, Vec4 => { (all: Num), (x: Num, y: Num, z: Num, w: Num), (a: Vec2, b: Vec2), (a: Vec2, z: Num, w: Num), (x: Num, y: Num, c: Vec2), (x: Num, b: Vec2, c: Num), (a: Vec3, w: Num), (x: Num, b: Vec3), (fr: Vec4), }, } } #[test] fn test_constructors() { 1.0.vec3(); (1.0, 2.0, 3.0).vec3(); (1.0.vec2(), 3.0).vec3(); 1.vec3i32(); (1, 2, 3).vec3i32(); (1.vec2i32(), 3).vec3i32(); } // TODO: All constructors pub fn mat2(val: f32) -> Mat2 { Mat2::broadcast_diagonal(val) }
#[doc = "Reader of register CLKCTL"] pub type R = crate::R<u32, super::CLKCTL>; #[doc = "Writer for register CLKCTL"] pub type W = crate::W<u32, super::CLKCTL>; #[doc = "Register CLKCTL `reset()`'s with value 0"] impl crate::ResetValue for super::CLKCTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DIV_8`"] pub type DIV_8_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DIV_8`"] pub struct DIV_8_W<'a> { w: &'a mut W, } impl<'a> DIV_8_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 } } #[doc = "Reader of field `HWCLKEN`"] pub type HWCLKEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HWCLKEN`"] pub struct HWCLKEN_W<'a> { w: &'a mut W, } impl<'a> HWCLKEN_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 `CLKEDGE`"] pub type CLKEDGE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CLKEDGE`"] pub struct CLKEDGE_W<'a> { w: &'a mut W, } impl<'a> CLKEDGE_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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `BUSMODE`"] pub type BUSMODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BUSMODE`"] pub struct BUSMODE_W<'a> { w: &'a mut W, } impl<'a> BUSMODE_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 & !(0x03 << 11)) | (((value as u32) & 0x03) << 11); self.w } } #[doc = "Reader of field `CLKBYP`"] pub type CLKBYP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CLKBYP`"] pub struct CLKBYP_W<'a> { w: &'a mut W, } impl<'a> CLKBYP_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `CLKPWRSAV`"] pub type CLKPWRSAV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CLKPWRSAV`"] pub struct CLKPWRSAV_W<'a> { w: &'a mut W, } impl<'a> CLKPWRSAV_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `CLKEN`"] pub type CLKEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CLKEN`"] pub struct CLKEN_W<'a> { w: &'a mut W, } impl<'a> CLKEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `DIV_0_7`"] pub type DIV_0_7_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DIV_0_7`"] pub struct DIV_0_7_W<'a> { w: &'a mut W, } impl<'a> DIV_0_7_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } impl R { #[doc = "Bit 31 - MSB of Clock division"] #[inline(always)] pub fn div_8(&self) -> DIV_8_R { DIV_8_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 14 - Hardware Clock Control enable bit"] #[inline(always)] pub fn hwclken(&self) -> HWCLKEN_R { HWCLKEN_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - SDIO_CLK clock edge selection bit"] #[inline(always)] pub fn clkedge(&self) -> CLKEDGE_R { CLKEDGE_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bits 11:12 - SDIO card bus mode control bit"] #[inline(always)] pub fn busmode(&self) -> BUSMODE_R { BUSMODE_R::new(((self.bits >> 11) & 0x03) as u8) } #[doc = "Bit 10 - Clock bypass enable bit"] #[inline(always)] pub fn clkbyp(&self) -> CLKBYP_R { CLKBYP_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - SDIO_CLK clock dynamic switch on/off for power saving"] #[inline(always)] pub fn clkpwrsav(&self) -> CLKPWRSAV_R { CLKPWRSAV_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - SDIO_CLK clock output enable bit"] #[inline(always)] pub fn clken(&self) -> CLKEN_R { CLKEN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bits 0:7 - Clock division"] #[inline(always)] pub fn div_0_7(&self) -> DIV_0_7_R { DIV_0_7_R::new((self.bits & 0xff) as u8) } } impl W { #[doc = "Bit 31 - MSB of Clock division"] #[inline(always)] pub fn div_8(&mut self) -> DIV_8_W { DIV_8_W { w: self } } #[doc = "Bit 14 - Hardware Clock Control enable bit"] #[inline(always)] pub fn hwclken(&mut self) -> HWCLKEN_W { HWCLKEN_W { w: self } } #[doc = "Bit 13 - SDIO_CLK clock edge selection bit"] #[inline(always)] pub fn clkedge(&mut self) -> CLKEDGE_W { CLKEDGE_W { w: self } } #[doc = "Bits 11:12 - SDIO card bus mode control bit"] #[inline(always)] pub fn busmode(&mut self) -> BUSMODE_W { BUSMODE_W { w: self } } #[doc = "Bit 10 - Clock bypass enable bit"] #[inline(always)] pub fn clkbyp(&mut self) -> CLKBYP_W { CLKBYP_W { w: self } } #[doc = "Bit 9 - SDIO_CLK clock dynamic switch on/off for power saving"] #[inline(always)] pub fn clkpwrsav(&mut self) -> CLKPWRSAV_W { CLKPWRSAV_W { w: self } } #[doc = "Bit 8 - SDIO_CLK clock output enable bit"] #[inline(always)] pub fn clken(&mut self) -> CLKEN_W { CLKEN_W { w: self } } #[doc = "Bits 0:7 - Clock division"] #[inline(always)] pub fn div_0_7(&mut self) -> DIV_0_7_W { DIV_0_7_W { w: self } } }
use std::ops::MulAssign; use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; use matrix::Position; use crate::ruleset::board_type::BoardType; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct Coordinate { pub row: i16, pub column: i16, } impl Coordinate { pub fn new(row: i16, column: i16) -> Self { Self { row, column } } } impl Position for Coordinate { fn row(&self) -> usize { self.row as usize } fn column(&self) -> usize { self.column as usize } fn coordinates(&self) -> (usize, usize) { (self.row as usize, self.column as usize) } } impl Add for Coordinate { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self::new(self.row + rhs.row, self.column) } } impl AddAssign for Coordinate { fn add_assign(&mut self, rhs: Self) { self.row += rhs.row; self.column += rhs.column; } } impl Sub for Coordinate { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { Self::new(self.row - rhs.row, self.column - rhs.column) } } impl SubAssign for Coordinate { fn sub_assign(&mut self, rhs: Self) { self.row -= rhs.row; self.column -= rhs.column; } } impl Mul<i16> for Coordinate { type Output = Self; fn mul(self, rhs: i16) -> Self::Output { Self::new(self.row * rhs, self.column * rhs) } } impl MulAssign<i16> for Coordinate { fn mul_assign(&mut self, rhs: i16) { self.row *= rhs; self.column *= rhs; } } pub fn flip_coordinate(board: &BoardType, coordinate: Coordinate) -> Coordinate { Coordinate::new(board.rows() as i16 - coordinate.row - 1, coordinate.column) } pub fn rotate_coordinate(board: &BoardType, coordinate: Coordinate) -> Coordinate { Coordinate::new( board.rows() as i16 - coordinate.row - 1, board.columns() as i16 - coordinate.column - 1, ) }
use rand::prelude::*; use std::io; /// Prompts the user to guess a number given in `secret` as attempt # `attempt`. /// /// # Returns /// `true` if the user was right, `false` otherwise. pub fn guess(secret: u32, attempt: usize) -> bool { println!("Guess a number between 0 and 9 (attempt {}/3) > ", attempt); let mut line = String::new(); io::stdin().read_line(&mut line).unwrap(); let guess: u32 = match line.trim().parse() { Ok(n) => n, Err(e) => { println!("Failed to recognize number: {}", e); return false; } }; if guess > secret { println!("Too low!"); false } else if guess < secret { println!("Too high!"); false } else { println!("Correct!"); true } } fn main() { let secret = rand::thread_rng().gen_range(0, 10); for i in 1..4 { if guess(secret, i) { return; } } println!("GAME OVER") }
use std::{cmp::Ordering, iter}; use rosu_v2::prelude::{Score, User}; use crate::{ embeds::{Author, EmbedBuilder, EmbedData, Footer}, util::{ numbers::{with_comma_float, with_comma_int}, osu::{approx_more_pp, pp_missing, ExtractablePp, PpListUtil}, }, }; pub struct PPMissingEmbed { author: Author, description: String, footer: Option<Footer>, thumbnail: String, title: String, } impl PPMissingEmbed { pub fn new( user: User, scores: &mut [Score], goal_pp: f32, rank: Option<usize>, each: Option<f32>, ) -> Self { let stats_pp = user.statistics.as_ref().unwrap().pp; let title = format!( "What scores is {name} missing to reach {goal_pp}pp?", name = user.username, goal_pp = with_comma_float(goal_pp), ); let description = match (scores.last().and_then(|s| s.pp), each) { // No top scores (None, _) => "No top scores found".to_owned(), // Total pp already above goal _ if stats_pp > goal_pp => format!( "{name} has {pp_raw}pp which is already more than {pp_given}pp.", name = user.username, pp_raw = with_comma_float(stats_pp), pp_given = with_comma_float(goal_pp), ), // Reach goal with only one score (Some(_), None) => { let (required, idx) = if scores.len() == 100 { let mut pps = scores.extract_pp(); approx_more_pp(&mut pps, 50); pp_missing(stats_pp, goal_pp, pps.as_slice()) } else { pp_missing(stats_pp, goal_pp, &*scores) }; format!( "To reach {pp}pp with one additional score, {user} needs to perform \ a **{required}pp** score which would be the top {approx}#{idx}", pp = with_comma_float(goal_pp), user = user.username, required = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } // Given score pp is below last top 100 score pp (Some(last_pp), Some(each)) if each < last_pp => { format!( "New top100 scores require at least **{last_pp}pp** for {user} \ so {pp} total pp can't be reached with {each}pp scores.", pp = with_comma_float(goal_pp), last_pp = with_comma_float(last_pp), each = with_comma_float(each), user = user.username, ) } // Given score pp would be in top 100 (Some(_), Some(each)) => { let mut pps = scores.extract_pp(); let (required, idx) = if scores.len() == 100 { approx_more_pp(&mut pps, 50); pp_missing(stats_pp, goal_pp, pps.as_slice()) } else { pp_missing(stats_pp, goal_pp, &*scores) }; if required < each { format!( "To reach {pp}pp with one additional score, {user} needs to perform \ a **{required}pp** score which would be the top {approx}#{idx}", pp = with_comma_float(goal_pp), user = user.username, required = with_comma_float(required), approx = if idx >= 100 { "~" } else { "" }, idx = idx + 1, ) } else { let idx = pps .iter() .position(|&pp| pp < each) .unwrap_or_else(|| scores.len()); let mut iter = pps .iter() .copied() .zip(0..) .map(|(pp, i)| pp * 0.95_f32.powi(i)); let mut top: f32 = (&mut iter).take(idx).sum(); let bot: f32 = iter.sum(); let bonus_pp = (stats_pp - (top + bot)).max(0.0); top += bonus_pp; let len = pps.len(); let mut n_each = len; for i in idx..len { let bot = pps[idx..] .iter() .copied() .zip(i as i32 + 1..) .fold(0.0, |sum, (pp, i)| sum + pp * 0.95_f32.powi(i)); let factor = 0.95_f32.powi(i as i32); if top + factor * each + bot >= goal_pp { // requires n_each many new scores of `each` many pp and one additional score n_each = i - idx; break; } top += factor * each; } if n_each == len { format!( "Filling up {user}'{genitiv} top scores with {amount} new {each}pp score{plural} \ would only lead to {approx}**{top}pp** which is still less than {pp}pp.", amount = len - idx, each = with_comma_float(each), plural = if len - idx != 1 { "s" } else { "" }, genitiv = if idx != 1 { "s" } else { "" }, pp = with_comma_float(goal_pp), approx = if idx >= 100 { "roughly " } else { "" }, top = with_comma_float(top), user = user.username, ) } else { pps.extend(iter::repeat(each).take(n_each)); pps.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap_or(Ordering::Equal)); let accum = pps.accum_weighted(); // Calculate the pp of the missing score after adding `n_each` many `each` pp scores let total = accum + bonus_pp; let (required, _) = pp_missing(total, goal_pp, pps.as_slice()); format!( "To reach {pp}pp, {user} needs to perform **{n_each}** more \ {each}pp score{plural} and one **{required}pp** score.", each = with_comma_float(each), plural = if n_each != 1 { "s" } else { "" }, pp = with_comma_float(goal_pp), user = user.username, required = with_comma_float(required), ) } } } }; let footer = rank.map(|rank| { Footer::new(format!( "The current rank for {pp}pp is #{rank}", pp = with_comma_float(goal_pp), rank = with_comma_int(rank), )) }); Self { author: author!(user), description, footer, thumbnail: user.avatar_url, title, } } } impl EmbedData for PPMissingEmbed { fn into_builder(self) -> EmbedBuilder { let builder = EmbedBuilder::new() .author(self.author) .description(self.description) .thumbnail(self.thumbnail) .title(self.title); if let Some(footer) = self.footer { builder.footer(footer) } else { builder } } }
//! # postgrest-rs //! //! [PostgREST][postgrest] client-side library. //! //! This library is a thin wrapper that brings an ORM-like interface to //! PostgREST. //! //! ## Usage //! //! Simple example: //! ``` //! use postgrest::Postgrest; //! //! # async fn run() -> Result<(), Box<dyn std::error::Error>> { //! let client = Postgrest::new("https://your.postgrest.endpoint"); //! let resp = client //! .from("your_table") //! .select("*") //! .execute() //! .await?; //! let body = resp //! .text() //! .await?; //! # Ok(()) //! # } //! ``` //! //! Using filters: //! ``` //! # use postgrest::Postgrest; //! # async fn run() -> Result<(), Box<dyn std::error::Error>> { //! # let client = Postgrest::new("https://your.postgrest.endpoint"); //! let resp = client //! .from("countries") //! .eq("name", "Germany") //! .gte("id", "20") //! .select("*") //! .execute() //! .await?; //! # Ok(()) //! # } //! ``` //! //! Updating a table: //! ``` //! # use postgrest::Postgrest; //! # async fn run() -> Result<(), Box<dyn std::error::Error>> { //! # let client = Postgrest::new("https://your.postgrest.endpoint"); //! let resp = client //! .from("users") //! .eq("username", "soedirgo") //! .update("{\"organization\": \"supabase\"}") //! .execute() //! .await?; //! # Ok(()) //! # } //! ``` //! //! Executing stored procedures: //! ``` //! # use postgrest::Postgrest; //! # async fn run() -> Result<(), Box<dyn std::error::Error>> { //! # let client = Postgrest::new("https://your.postgrest.endpoint"); //! let resp = client //! .rpc("add", r#"{"a": 1, "b": 2}"#) //! .execute() //! .await?; //! # Ok(()) //! # } //! ``` //! //! Check out the [README][readme] for more info. //! //! [postgrest]: https://postgrest.org //! [readme]: https://github.com/supabase/postgrest-rs mod builder; mod filter; pub use builder::Builder; use reqwest::header::{HeaderMap, HeaderValue, IntoHeaderName}; use reqwest::Client; pub struct Postgrest { url: String, schema: Option<String>, headers: HeaderMap, client: Client, } impl Postgrest { /// Creates a Postgrest client. /// /// # Example /// /// ``` /// use postgrest::Postgrest; /// /// let client = Postgrest::new("http://your.postgrest.endpoint"); /// ``` pub fn new<T>(url: T) -> Self where T: Into<String>, { Postgrest { url: url.into(), schema: None, headers: HeaderMap::new(), client: Client::new(), } } /// Switches the schema. /// /// # Note /// /// You can only switch schemas before you call `from` or `rpc`. /// /// # Example /// /// ``` /// use postgrest::Postgrest; /// /// let client = Postgrest::new("http://your.postgrest.endpoint"); /// client.schema("private"); /// ``` pub fn schema<T>(mut self, schema: T) -> Self where T: Into<String>, { self.schema = Some(schema.into()); self } /// Add arbitrary headers to the request. For instance when you may want to connect /// through an API gateway that needs an API key header. /// /// # Example /// /// ``` /// use postgrest::Postgrest; /// /// let client = Postgrest::new("https://your.postgrest.endpoint") /// .insert_header("apikey", "super.secret.key") /// .from("table"); /// ``` pub fn insert_header( mut self, header_name: impl IntoHeaderName, header_value: impl AsRef<str>, ) -> Self { self.headers.insert( header_name, HeaderValue::from_str(header_value.as_ref()).expect("Invalid header value."), ); self } /// Perform a table operation. /// /// # Example /// /// ``` /// use postgrest::Postgrest; /// /// let client = Postgrest::new("http://your.postgrest.endpoint"); /// client.from("table"); /// ``` pub fn from<T>(&self, table: T) -> Builder where T: AsRef<str>, { let url = format!("{}/{}", self.url, table.as_ref()); Builder::new( url, self.schema.clone(), self.headers.clone(), self.client.clone(), ) } /// Perform a stored procedure call. /// /// # Example /// /// ``` /// use postgrest::Postgrest; /// /// let client = Postgrest::new("http://your.postgrest.endpoint"); /// client.rpc("multiply", r#"{"a": 1, "b": 2}"#); /// ``` pub fn rpc<T, U>(&self, function: T, params: U) -> Builder where T: AsRef<str>, U: Into<String>, { let url = format!("{}/rpc/{}", self.url, function.as_ref()); Builder::new( url, self.schema.clone(), self.headers.clone(), self.client.clone(), ) .rpc(params) } } #[cfg(test)] mod tests { use super::*; const REST_URL: &str = "http://localhost:3000"; #[test] fn initialize() { assert_eq!(Postgrest::new(REST_URL).url, REST_URL); } #[test] fn switch_schema() { assert_eq!( Postgrest::new(REST_URL).schema("private").schema, Some("private".to_string()) ); } #[test] fn with_insert_header() { assert_eq!( Postgrest::new(REST_URL) .insert_header("apikey", "super.secret.key") .headers .get("apikey") .unwrap(), "super.secret.key" ); } }
// Test that both states must have the same ObjectState. // edition:2018 extern crate async_trait; extern crate krator; extern crate anyhow; extern crate k8s_openapi; use k8s_openapi::apimachinery::pkg::apis::meta::v1::Status; use k8s_openapi::api::core::v1::Pod; use krator::state::test::Stub; use krator::{TransitionTo, ObjectState, State, SharedState, Manifest, Transition}; #[derive(Debug, TransitionTo)] #[transition_to(OtherState)] struct TestState; struct PodState; struct ProviderState; #[async_trait::async_trait] impl ObjectState for PodState { type Manifest = Pod; type Status = Status; type SharedState = ProviderState; async fn async_drop(self, _provider_state: &mut ProviderState) { } } #[derive(Debug)] struct OtherState; struct OtherPodState; #[async_trait::async_trait] impl ObjectState for OtherPodState { type Manifest = Pod; type Status = Status; type SharedState = ProviderState; async fn async_drop(self, _provider_state: &mut ProviderState) { } } #[async_trait::async_trait] impl State<PodState> for TestState { async fn next( self: Box<Self>, _provider_state: SharedState<ProviderState>, _state: &mut PodState, _pod: Manifest<Pod>, ) -> Transition<PodState> { // This fails because `OtherState` is `State<OtherPodState, PodStatus>` Transition::next(self, OtherState) } async fn status( &self, _state: &mut PodState, _pod: &Pod, ) -> anyhow::Result<Status> { Ok(Default::default()) } } #[async_trait::async_trait] impl State<OtherPodState> for OtherState { async fn next( self: Box<Self>, _provider_state: SharedState<ProviderState>, _state: &mut OtherPodState, _pod: Manifest<Pod>, ) -> Transition<OtherPodState> { Transition::Complete(Ok(())) } async fn status( &self, _state: &mut OtherPodState, _pod: &Pod, ) -> anyhow::Result<Status> { Ok(Default::default()) } } fn main() {}
#![no_main] mod common; use highway::{HighwayHash, PortableHash}; libfuzzer_sys::fuzz_target!(|input: common::FuzzKey| { let (key, data) = (input.key, &input.data); let hash1 = PortableHash::new(key).hash64(data); let hash2 = PortableHash::new(key).hash64(data); assert_eq!(hash1, hash2); PortableHash::new(key).hash128(data); PortableHash::new(key).hash256(data); });
use super::{common_loan_args, parse_common_loan_args}; use clap::{App, Arg, ArgMatches, SubCommand}; pub const SUB_LOAN_INFO_AT: &str = "info-at"; const ARG_N_PERIOD: &str = "n-period"; /// Returns the loan info-at sub command pub fn loan_info_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(SUB_LOAN_INFO_AT) .about("compute loans info for a point in time") .arg( Arg::with_name(ARG_N_PERIOD) .takes_value(true) .required(true) .index(1), ).args(common_loan_args().as_slice()) } /// Execute the work and print results for the info-at sub command /// /// # Arguments /// * `matches` - The command matches to retrieve the paramters pub fn execute_loan_info_at<'a>(matches: &ArgMatches<'a>) { let loan = parse_common_loan_args(matches); let at = matches .value_of(ARG_N_PERIOD) .unwrap() .parse::<u32>() .unwrap(); println!( "*** Information for a loan of {} during {} years with period of {} at {}% ***\n", loan.capital, loan.years, loan.period, loan.interest_rate_year * 100_f32 ); let years_round = format!("{:.1}", at as f32 / loan.period as f32); let mut loan_table = table!(["title", "at (periods)", "at (~years)", "value"]); loan_table.add_row(row!["term price", "NONE", "NONE", loan.term_price()]); loan_table.add_row(row!["capital paid", at, years_round, loan.capital_at(at)]); loan_table.add_row(row!["paid", at, years_round, loan.paid(at)]); loan_table.add_row(row!["interest paid", at, years_round, loan.interest_at(at)]); loan_table.printstd(); }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use proc_macro2::TokenStream; use quote::quote; use syn::punctuated::Punctuated; use syn::{parse_quote, Error, ItemFn, Result}; #[derive(Copy, Clone, PartialEq)] pub enum Mode { Main, Test, CompatTest, } pub fn expand(mode: Mode, mut function: ItemFn) -> Result<TokenStream> { if function.sig.inputs.len() > 1 { return Err(Error::new_spanned( function.sig, "expected one argument of type fbinit::FacebookInit", )); } if mode == Mode::Main && function.sig.ident != "main" { return Err(Error::new_spanned( function.sig, "#[fbinit::main] must be used on the main function", )); } let guard = match mode { Mode::Main => Some(quote! { if module_path!().contains("::") { panic!("fbinit must be performed in the crate root on the main function"); } }), Mode::Test | Mode::CompatTest => None, }; let assignment = function.sig.inputs.first().map(|arg| quote!(let #arg =)); function.sig.inputs = Punctuated::new(); let block = function.block; let body = match (function.sig.asyncness.is_some(), mode) { (true, Mode::CompatTest) => quote! { tokio_compat::runtime::current_thread::Runtime::new() .unwrap() .block_on_std(async #block) }, (true, Mode::Test) => quote! { tokio::runtime::Builder::new() .basic_scheduler() .enable_all() .build() .unwrap() .block_on(async #block) }, (true, Mode::Main) => quote! { tokio::runtime::Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap() .block_on(async #block) }, (false, Mode::CompatTest) => { return Err(Error::new_spanned( function.sig, "#[fbinit::compat_test] should be used only on async functions", )); } (false, _) => { let stmts = block.stmts; quote! { #(#stmts)* } } }; function.block = parse_quote!({ #guard #assignment unsafe { fbinit::r#impl::perform_init() }; let destroy_guard = unsafe { fbinit::r#impl::DestroyGuard::new() }; #body }); function.sig.asyncness = None; if mode == Mode::Test || mode == Mode::CompatTest { function.attrs.push(parse_quote!(#[test])); } Ok(quote!(#function)) }
// Copyright (c) 2016 Anatoly Ikorsky // // 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. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. pub use mysql_common::named_params; use mysql_common::{ constants::DEFAULT_MAX_ALLOWED_PACKET, crypto, packets::{ parse_auth_switch_request, parse_handshake_packet, AuthPlugin, AuthSwitchRequest, HandshakeResponse, SslRequest, }, }; use std::{ fmt, future::Future, mem, pin::Pin, str::FromStr, sync::Arc, time::{Duration, Instant}, }; use crate::{ conn::{pool::Pool, stmt_cache::StmtCache}, connection_like::{streamless::Streamless, ConnectionLike, StmtCacheResult}, consts::{self, CapabilityFlags}, error::*, io::Stream, local_infile_handler::LocalInfileHandler, opts::Opts, queryable::{query_result, BinaryProtocol, Queryable, TextProtocol}, Column, OptsBuilder, }; pub mod pool; pub mod stmt_cache; /// Helper that asynchronously disconnects connection on the default tokio executor. fn disconnect(mut conn: Conn) { let disconnected = conn.inner.disconnected; // Mark conn as disconnected. conn.inner.disconnected = true; if !disconnected { // We shouldn't call tokio::spawn if unwinding if std::thread::panicking() { return; } // Server will report broken connection if spawn fails. // this might fail if, say, the runtime is shutting down, but we've done what we could tokio::spawn(async move { if let Ok(conn) = conn.cleanup().await { let _ = conn.disconnect().await; } }); } } /// Mysql connection struct ConnInner { stream: Option<Stream>, id: u32, version: (u16, u16, u16), max_allowed_packet: usize, socket: Option<String>, capabilities: consts::CapabilityFlags, status: consts::StatusFlags, last_insert_id: u64, affected_rows: u64, warnings: u16, pool: Option<Pool>, has_result: Option<(Arc<Vec<Column>>, Option<StmtCacheResult>)>, in_transaction: bool, opts: Opts, last_io: Instant, wait_timeout: Duration, stmt_cache: StmtCache, nonce: Vec<u8>, auth_plugin: AuthPlugin<'static>, auth_switched: bool, /// Connection is already disconnected. disconnected: bool, } impl fmt::Debug for ConnInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Conn") .field("connection id", &self.id) .field("server version", &self.version) .field("pool", &self.pool) .field("has result", &self.has_result.is_some()) .field("in transaction", &self.in_transaction) .field("stream", &self.stream) .field("options", &self.opts) .finish() } } impl ConnInner { /// Constructs an empty connection. fn empty(opts: Opts) -> ConnInner { ConnInner { capabilities: opts.get_capabilities(), status: consts::StatusFlags::empty(), last_insert_id: 0, affected_rows: 0, stream: None, max_allowed_packet: DEFAULT_MAX_ALLOWED_PACKET, warnings: 0, version: (0, 0, 0), id: 0, has_result: None, pool: None, in_transaction: false, last_io: Instant::now(), wait_timeout: Duration::from_secs(0), stmt_cache: StmtCache::new(opts.get_stmt_cache_size()), socket: opts.get_socket().map(Into::into), opts, nonce: Vec::default(), auth_plugin: AuthPlugin::MysqlNativePassword, auth_switched: false, disconnected: false, } } } #[derive(Debug)] pub struct Conn { inner: Box<ConnInner>, } impl Conn { /// Returns the ID generated by a query (usually `INSERT`) on a table with a column having the /// `AUTO_INCREMENT` attribute. Returns `None` if there was no previous query on the connection /// or if the query did not update an AUTO_INCREMENT value. pub fn last_insert_id(&self) -> Option<u64> { self.get_last_insert_id() } /// Returns the number of rows affected by the last `INSERT`, `UPDATE`, `REPLACE` or `DELETE` /// query. pub fn affected_rows(&self) -> u64 { self.get_affected_rows() } async fn close(mut self) -> Result<()> { self.inner.disconnected = true; self.cleanup().await?.disconnect().await } fn is_secure(&self) -> bool { if let Some(ref stream) = self.inner.stream { stream.is_secure() } else { false } } /// Hacky way to move connection through &mut. `self` becomes unusable. fn take(&mut self) -> Conn { let inner = mem::replace(&mut *self.inner, ConnInner::empty(Default::default())); Conn { inner: Box::new(inner), } } fn empty(opts: Opts) -> Self { Self { inner: Box::new(ConnInner::empty(opts)), } } fn setup_stream(mut self) -> Result<Conn> { if let Some(stream) = self.inner.stream.take() { stream.set_keepalive_ms(self.inner.opts.get_tcp_keepalive())?; stream.set_tcp_nodelay(self.inner.opts.get_tcp_nodelay())?; self.inner.stream = Some(stream); Ok(self) } else { unreachable!(); } } async fn handle_handshake(self) -> Result<Conn> { let (mut conn, packet) = self.read_packet().await?; let handshake = parse_handshake_packet(&*packet)?; conn.inner.nonce = { let mut nonce = Vec::from(handshake.scramble_1_ref()); nonce.extend_from_slice(handshake.scramble_2_ref().unwrap_or(&[][..])); nonce }; conn.inner.capabilities = handshake.capabilities() & conn.inner.opts.get_capabilities(); conn.inner.version = handshake.server_version_parsed().unwrap_or((0, 0, 0)); conn.inner.id = handshake.connection_id(); conn.inner.status = handshake.status_flags(); conn.inner.auth_plugin = match handshake.auth_plugin() { Some(AuthPlugin::MysqlNativePassword) => AuthPlugin::MysqlNativePassword, Some(AuthPlugin::CachingSha2Password) => AuthPlugin::CachingSha2Password, Some(AuthPlugin::Other(ref name)) => { let name = String::from_utf8_lossy(name).into(); return Err(DriverError::UnknownAuthPlugin { name }.into()); } None => AuthPlugin::MysqlNativePassword, }; Ok(conn) } async fn switch_to_ssl_if_needed(self) -> Result<Conn> { if self .inner .opts .get_capabilities() .contains(CapabilityFlags::CLIENT_SSL) { let ssl_request = SslRequest::new(self.inner.capabilities); let conn = self.write_packet(ssl_request.as_ref()).await?; let ssl_opts = conn .get_opts() .get_ssl_opts() .cloned() .expect("unreachable"); let domain = conn.get_opts().get_ip_or_hostname().into(); let (streamless, stream) = conn.take_stream(); let stream = stream.make_secure(domain, ssl_opts).await?; Ok(streamless.return_stream(stream)) } else { Ok(self) } } async fn do_handshake_response(self) -> Result<Conn> { let auth_data = self .inner .auth_plugin .gen_data(self.inner.opts.get_pass(), &*self.inner.nonce); let handshake_response = HandshakeResponse::new( &auth_data, self.inner.version, self.inner.opts.get_user(), self.inner.opts.get_db_name(), &self.inner.auth_plugin, self.get_capabilities(), &Default::default(), // TODO: Add support ); self.write_packet(handshake_response.as_ref()).await } async fn perform_auth_switch( mut self, auth_switch_request: AuthSwitchRequest<'_>, ) -> Result<Conn> { if !self.inner.auth_switched { self.inner.auth_switched = true; self.inner.nonce = auth_switch_request.plugin_data().into(); self.inner.auth_plugin = auth_switch_request.auth_plugin().clone().into_owned(); let plugin_data = self .inner .auth_plugin .gen_data(self.inner.opts.get_pass(), &*self.inner.nonce) .unwrap_or_else(Vec::new); self.write_packet(plugin_data).await?.continue_auth().await } else { unreachable!("auth_switched flag should be checked by caller") } } fn continue_auth(self) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send>> { // NOTE: we need to box this since it may recurse // see https://github.com/rust-lang/rust/issues/46415#issuecomment-528099782 Box::pin(async move { match self.inner.auth_plugin { AuthPlugin::MysqlNativePassword => self.continue_mysql_native_password_auth().await, AuthPlugin::CachingSha2Password => self.continue_caching_sha2_password_auth().await, AuthPlugin::Other(ref name) => Err(DriverError::UnknownAuthPlugin { name: String::from_utf8_lossy(name.as_ref()).to_string(), })?, } }) } fn switch_to_compression(mut self) -> Result<Conn> { if self .get_capabilities() .contains(CapabilityFlags::CLIENT_COMPRESS) { if let Some(compression) = self.inner.opts.get_compression() { if let Some(stream) = self.inner.stream.as_mut() { stream.compress(compression); } } } Ok(self) } async fn continue_caching_sha2_password_auth(self) -> Result<Conn> { let (conn, packet) = self.read_packet().await?; match packet.get(0) { Some(0x00) => { // ok packet for empty password Ok(conn) } Some(0x01) => match packet.get(1) { Some(0x03) => { // auth ok conn.drop_packet().await } Some(0x04) => { let mut pass = conn .inner .opts .get_pass() .map(Vec::from) .unwrap_or_default(); pass.push(0); let conn = if conn.is_secure() { conn.write_packet(&*pass).await? } else { let conn = conn.write_packet(&[0x02][..]).await?; let (conn, packet) = conn.read_packet().await?; let key = &packet[1..]; for (i, byte) in pass.iter_mut().enumerate() { *byte ^= conn.inner.nonce[i % conn.inner.nonce.len()]; } let encrypted_pass = crypto::encrypt(&*pass, key); conn.write_packet(&*encrypted_pass).await? }; conn.drop_packet().await } _ => Err(DriverError::UnexpectedPacket { payload: packet.into(), } .into()), }, Some(0xfe) if !conn.inner.auth_switched => { let auth_switch_request = parse_auth_switch_request(&*packet)?.into_owned(); conn.perform_auth_switch(auth_switch_request).await } _ => Err(DriverError::UnexpectedPacket { payload: packet.into(), } .into()), } } async fn continue_mysql_native_password_auth(self) -> Result<Conn> { let (this, packet) = self.read_packet().await?; match packet.get(0) { Some(0x00) => Ok(this), Some(0xfe) if !this.inner.auth_switched => { let auth_switch_request = parse_auth_switch_request(packet.as_ref())?.into_owned(); this.perform_auth_switch(auth_switch_request).await } _ => Err(DriverError::UnexpectedPacket { payload: packet }.into()), } } async fn drop_packet(self) -> Result<Conn> { Ok(self.read_packet().await?.0) } async fn run_init_commands(self) -> Result<Conn> { let mut init: Vec<_> = self.inner.opts.get_init().iter().cloned().collect(); let mut conn = self; while let Some(query) = init.pop() { conn = conn.drop_query(query).await?; } Ok(conn) } /// Returns future that resolves to [`Conn`]. pub async fn new<T: Into<Opts>>(opts: T) -> Result<Conn> { let opts = opts.into(); let mut conn = Conn::empty(opts.clone()); let stream = if let Some(path) = opts.get_socket() { Stream::connect_socket(path.to_owned()).await? } else { Stream::connect_tcp((opts.get_ip_or_hostname(), opts.get_tcp_port())).await? }; conn.inner.stream = Some(stream); conn.setup_stream()? .handle_handshake() .await? .switch_to_ssl_if_needed() .await? .do_handshake_response() .await? .continue_auth() .await? .switch_to_compression()? .read_socket() .await? .reconnect_via_socket_if_needed() .await? .read_max_allowed_packet() .await? .read_wait_timeout() .await? .run_init_commands() .await } /// Returns future that resolves to [`Conn`]. pub async fn from_url<T: AsRef<str>>(url: T) -> Result<Conn> { Conn::new(Opts::from_str(url.as_ref())?).await } /// Will try to connect via socket using socket address in `self.inner.socket`. /// /// Returns new connection on success or self on error. /// /// Won't try to reconnect if socket connection is already enforced in [`Opts`]. fn reconnect_via_socket_if_needed(self) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send>> { // NOTE: we need to box this since it may recurse // see https://github.com/rust-lang/rust/issues/46415#issuecomment-528099782 Box::pin(async move { if let Some(socket) = self.inner.socket.as_ref() { let opts = self.inner.opts.clone(); if opts.get_socket().is_none() { let mut builder = OptsBuilder::from_opts(opts); builder.socket(Some(&**socket)); match Conn::new(builder).await { Ok(conn) => return Ok(conn), Err(_) => return Ok(self), } } } Ok(self) }) } /// Returns future that resolves to [`Conn`] with socket address stored in it. /// /// Do nothing if socket address is already in [`Opts`] or if `prefer_socket` is `false`. async fn read_socket(self) -> Result<Self> { if self.inner.opts.get_prefer_socket() && self.inner.socket.is_none() { let (mut this, row_opt) = self.first("SELECT @@socket").await?; this.inner.socket = row_opt.unwrap_or((None,)).0; Ok(this) } else { Ok(self) } } /// Returns future that resolves to [`Conn`] with `max_allowed_packet` stored in it. async fn read_max_allowed_packet(self) -> Result<Self> { let (mut this, row_opt): (Self, _) = self.first("SELECT @@max_allowed_packet").await?; if let Some(stream) = this.inner.stream.as_mut() { stream.set_max_allowed_packet(row_opt.unwrap_or((DEFAULT_MAX_ALLOWED_PACKET,)).0); } Ok(this) } /// Returns future that resolves to [`Conn`] with `wait_timeout` stored in it. async fn read_wait_timeout(self) -> Result<Self> { let (mut this, row_opt) = self.first("SELECT @@wait_timeout").await?; let wait_timeout_secs = row_opt.unwrap_or((28800,)).0; this.inner.wait_timeout = Duration::from_secs(wait_timeout_secs); Ok(this) } /// Returns true if time since last io exceeds wait_timeout (or conn_ttl if specified in opts). fn expired(&self) -> bool { let ttl = self .inner .opts .get_conn_ttl() .unwrap_or(self.inner.wait_timeout); self.idling() > ttl } /// Returns duration since last io. fn idling(&self) -> Duration { self.inner.last_io.elapsed() } /// Returns future that resolves to a [`Conn`] with `COM_RESET_CONNECTION` executed on it. pub async fn reset(self) -> Result<Conn> { let pool = self.inner.pool.clone(); let mut conn = if self.inner.version > (5, 7, 2) { self.write_command_data(consts::Command::COM_RESET_CONNECTION, &[]) .await? .read_packet() .await? .0 } else { Conn::new(self.inner.opts.clone()).await? }; conn.inner.stmt_cache.clear(); conn.inner.pool = pool; Ok(conn) } async fn rollback_transaction(mut self) -> Result<Self> { assert!(self.inner.in_transaction); self.inner.in_transaction = false; self.drop_query("ROLLBACK").await } async fn drop_result(mut self) -> Result<Conn> { match self.inner.has_result.take() { Some((columns, None)) => { query_result::assemble::<_, TextProtocol>(self, Some(columns), None) .drop_result() .await } Some((columns, cached)) => { query_result::assemble::<_, BinaryProtocol>(self, Some(columns), cached) .drop_result() .await } None => Ok(self), } } fn cleanup(self) -> Pin<Box<dyn Future<Output = Result<Conn>> + Send>> { // NOTE: we need to box this since it may recurse // see https://github.com/rust-lang/rust/issues/46415#issuecomment-528099782 Box::pin(async move { if self.inner.has_result.is_some() { self.drop_result().await?.cleanup().await } else if self.inner.in_transaction { self.rollback_transaction().await?.cleanup().await } else { Ok(self) } }) } } impl ConnectionLike for Conn { fn take_stream(mut self) -> (Streamless<Self>, Stream) { let stream = self.inner.stream.take().expect("Logic error: stream taken"); (Streamless::new(self), stream) } fn return_stream(&mut self, stream: Stream) { self.inner.stream = Some(stream); } fn stmt_cache_ref(&self) -> &StmtCache { &self.inner.stmt_cache } fn stmt_cache_mut(&mut self) -> &mut StmtCache { &mut self.inner.stmt_cache } fn get_affected_rows(&self) -> u64 { self.inner.affected_rows } fn get_capabilities(&self) -> consts::CapabilityFlags { self.inner.capabilities } fn get_in_transaction(&self) -> bool { self.inner.in_transaction } fn get_last_insert_id(&self) -> Option<u64> { match self.inner.last_insert_id { 0 => None, x => Some(x), } } fn get_local_infile_handler(&self) -> Option<Arc<dyn LocalInfileHandler>> { self.inner.opts.get_local_infile_handler() } fn get_max_allowed_packet(&self) -> usize { self.inner.max_allowed_packet } fn get_opts(&self) -> &Opts { &self.inner.opts } fn get_pending_result(&self) -> Option<&(Arc<Vec<Column>>, Option<StmtCacheResult>)> { self.inner.has_result.as_ref() } fn get_server_version(&self) -> (u16, u16, u16) { self.inner.version } fn get_status(&self) -> consts::StatusFlags { self.inner.status } fn set_affected_rows(&mut self, affected_rows: u64) { self.inner.affected_rows = affected_rows; } fn set_in_transaction(&mut self, in_transaction: bool) { self.inner.in_transaction = in_transaction; } fn set_last_insert_id(&mut self, last_insert_id: u64) { self.inner.last_insert_id = last_insert_id; } fn set_pending_result(&mut self, meta: Option<(Arc<Vec<Column>>, Option<StmtCacheResult>)>) { self.inner.has_result = meta; } fn set_status(&mut self, status: consts::StatusFlags) { self.inner.status = status; } fn set_warnings(&mut self, warnings: u16) { self.inner.warnings = warnings; } fn reset_seq_id(&mut self) { if let Some(stream) = self.inner.stream.as_mut() { stream.reset_seq_id(); } } fn sync_seq_id(&mut self) { if let Some(stream) = self.inner.stream.as_mut() { stream.sync_seq_id(); } } fn touch(&mut self) { self.inner.last_io = Instant::now(); } fn on_disconnect(&mut self) { self.inner.disconnected = true; } } #[cfg(test)] mod test { use crate::{ from_row, params, prelude::*, test_misc::get_opts, Conn, OptsBuilder, TransactionOptions, WhiteListFsLocalInfileHandler, }; #[test] fn opts_should_satisfy_send_and_sync() { struct A<T: Sync + Send>(T); A(get_opts()); } #[tokio::test] async fn should_connect_without_database() -> super::Result<()> { let mut opts = get_opts(); // no database name opts.db_name(None::<String>); let conn: Conn = Conn::new(opts.clone()).await?.ping().await?; conn.disconnect().await?; // empty database name opts.db_name(Some("")); let conn: Conn = Conn::new(opts).await?.ping().await?; conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_connect() -> super::Result<()> { let conn: Conn = Conn::new(get_opts()).await?.ping().await?; let (mut conn, plugins): (Conn, _) = conn .query("SHOW PLUGINS") .await? .map_and_drop(|mut row| row.take::<String, _>("Name").unwrap()) .await?; // Should connect with any combination of supported plugin and empty-nonempty password. let variants = vec![ ("caching_sha2_password", 2, "non-empty"), ("caching_sha2_password", 2, ""), ("mysql_native_password", 0, "non-empty"), ("mysql_native_password", 0, ""), ] .into_iter() .filter(|variant| plugins.iter().any(|p| p == variant.0)); for (plug, val, pass) in variants { let query = format!("CREATE USER 'test_user'@'%' IDENTIFIED WITH {}", plug); conn = conn.drop_query(query).await.unwrap(); conn = if (8, 0, 11) <= conn.inner.version && conn.inner.version <= (9, 0, 0) { conn.drop_query(format!("SET PASSWORD FOR 'test_user'@'%' = '{}'", pass)) .await .unwrap() } else { conn = conn .drop_query(format!("SET old_passwords = {}", val)) .await .unwrap(); conn.drop_query(format!( "SET PASSWORD FOR 'test_user'@'%' = PASSWORD('{}')", pass )) .await .unwrap() }; let mut opts = get_opts(); opts.user(Some("test_user")) .pass(Some(pass)) .db_name(None::<String>); let result = Conn::new(opts).await; conn = conn.drop_query("DROP USER 'test_user'@'%'").await.unwrap(); result?.disconnect().await?; } if crate::test_misc::test_compression() { assert!(format!("{:?}", conn).contains("Compression")); } if crate::test_misc::test_ssl() { assert!(format!("{:?}", conn).contains("Tls")); } conn.disconnect().await?; Ok(()) } #[test] fn should_not_panic_if_dropped_without_tokio_runtime() { let fut = Conn::new(get_opts()); let mut runtime = tokio::runtime::Runtime::new().unwrap(); runtime.block_on(async { fut.await.unwrap(); }); // connection will drop here } #[tokio::test] async fn should_execute_init_queries_on_new_connection() -> super::Result<()> { let mut opts_builder = OptsBuilder::from_opts(get_opts()); opts_builder.init(vec!["SET @a = 42", "SET @b = 'foo'"]); let (conn, result) = Conn::new(opts_builder) .await? .query("SELECT @a, @b") .await? .collect_and_drop::<(u8, String)>() .await?; conn.disconnect().await?; assert_eq!(result, vec![(42, "foo".into())]); Ok(()) } #[tokio::test] async fn should_reset_the_connection() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let conn = conn.drop_exec("SELECT ?", (1,)).await?; let conn = conn.reset().await?; let conn = conn.drop_exec("SELECT ?", (1,)).await?; conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_not_cache_statements_if_stmt_cache_size_is_zero() -> super::Result<()> { let mut opts = OptsBuilder::from_opts(get_opts()); opts.stmt_cache_size(0); let conn = Conn::new(opts).await?; let conn = conn.drop_exec("DO ?", (1,)).await?; let stmt = conn.prepare("DO 2").await?; let (stmt, _) = stmt.first::<_, (crate::Value,)>(()).await?; let (stmt, _) = stmt.first::<_, (crate::Value,)>(()).await?; let conn = stmt.close().await?; let conn = conn.prep_exec("DO 3", ()).await?.drop_result().await?; let conn = conn.batch_exec("DO 4", vec![(), ()]).await?; let (conn, _) = conn.first_exec::<_, _, (u8,)>("DO 5", ()).await?; let (conn, row) = conn .first("SHOW SESSION STATUS LIKE 'Com_stmt_close';") .await?; assert_eq!(from_row::<(String, usize)>(row.unwrap()).1, 5); conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_hold_stmt_cache_size_bound() -> super::Result<()> { use crate::connection_like::ConnectionLike; let mut opts = OptsBuilder::from_opts(get_opts()); opts.stmt_cache_size(3); let conn = Conn::new(opts) .await? .drop_exec("DO 1", ()) .await? .drop_exec("DO 2", ()) .await? .drop_exec("DO 3", ()) .await? .drop_exec("DO 1", ()) .await? .drop_exec("DO 4", ()) .await? .drop_exec("DO 3", ()) .await? .drop_exec("DO 5", ()) .await? .drop_exec("DO 6", ()) .await?; let (conn, row_opt) = conn .first("SHOW SESSION STATUS LIKE 'Com_stmt_close';") .await?; let (_, count): (String, usize) = row_opt.unwrap(); assert_eq!(count, 3); let order = conn .stmt_cache_ref() .iter() .map(Clone::clone) .collect::<Vec<String>>(); assert_eq!(order, &["DO 3", "DO 5", "DO 6"]); conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_perform_queries() -> super::Result<()> { let long_string = ::std::iter::repeat('A') .take(18 * 1024 * 1024) .collect::<String>(); let conn = Conn::new(get_opts()).await?; let result = conn .query(format!(r"SELECT '{}', 231", long_string)) .await?; let (conn, result) = result .reduce_and_drop(vec![], move |mut acc, row| { acc.push(from_row(row)); acc }) .await?; conn.disconnect().await?; assert_eq!((long_string, 231), result[0]); Ok(()) } #[tokio::test] async fn should_drop_query() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let (conn, result) = conn .drop_query("CREATE TEMPORARY TABLE tmp (id int DEFAULT 10, name text)") .await? .drop_query("INSERT INTO tmp VALUES (1, 'foo')") .await? .first::<_, (u8,)>("SELECT COUNT(*) FROM tmp") .await?; conn.disconnect().await?; assert_eq!(result, Some((1,))); Ok(()) } #[tokio::test] async fn should_try_collect() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let result = conn .query( r"SELECT 'hello', 123 UNION ALL SELECT 'world', 'bar' UNION ALL SELECT 'hello', 123 ", ) .await?; let (result, mut rows) = result.try_collect::<(String, u8)>().await?; assert!(rows.pop().unwrap().is_ok()); assert!(rows.pop().unwrap().is_err()); assert!(rows.pop().unwrap().is_ok()); let conn = result.drop_result().await?; conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_try_collect_and_drop() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let (conn, mut rows) = conn .query( r"SELECT 'hello', 123 UNION ALL SELECT 'world', 'bar' UNION ALL SELECT 'hello', 123; SELECT 'foo', 255; ", ) .await? .try_collect_and_drop::<(String, u8)>() .await?; assert!(rows.pop().unwrap().is_ok()); assert!(rows.pop().unwrap().is_err()); assert!(rows.pop().unwrap().is_ok()); conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_handle_mutliresult_set() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let result = conn .query( r"SELECT 'hello', 123 UNION ALL SELECT 'world', 231; SELECT 'foo', 255; ", ) .await?; let (result, rows_1) = result.collect::<(String, u8)>().await?; let (conn, rows_2) = result.collect_and_drop().await?; conn.disconnect().await?; assert_eq!((String::from("hello"), 123), rows_1[0]); assert_eq!((String::from("world"), 231), rows_1[1]); assert_eq!((String::from("foo"), 255), rows_2[0]); Ok(()) } #[tokio::test] async fn should_map_resultset() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let result = conn .query( r" SELECT 'hello', 123 UNION ALL SELECT 'world', 231; SELECT 'foo', 255; ", ) .await?; let (result, rows_1) = result.map(|row| from_row::<(String, u8)>(row)).await?; let (conn, rows_2) = result.map_and_drop(from_row).await?; conn.disconnect().await?; assert_eq!((String::from("hello"), 123), rows_1[0]); assert_eq!((String::from("world"), 231), rows_1[1]); assert_eq!((String::from("foo"), 255), rows_2[0]); Ok(()) } #[tokio::test] async fn should_reduce_resultset() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let result = conn .query( r"SELECT 5 UNION ALL SELECT 6; SELECT 7;", ) .await?; let (result, reduced) = result .reduce(0, |mut acc, row| { acc += from_row::<i32>(row); acc }) .await?; let (conn, rows_2) = result.collect_and_drop::<i32>().await?; conn.disconnect().await?; assert_eq!(11, reduced); assert_eq!(7, rows_2[0]); Ok(()) } #[tokio::test] async fn should_handle_multi_result_sets_where_some_results_have_no_output() -> super::Result<()> { const QUERY: &str = r"SELECT 1; UPDATE time_zone SET Time_zone_id = 1 WHERE Time_zone_id = 1; SELECT 2; SELECT 3; UPDATE time_zone SET Time_zone_id = 1 WHERE Time_zone_id = 1; UPDATE time_zone SET Time_zone_id = 1 WHERE Time_zone_id = 1; SELECT 4;"; let c = Conn::new(get_opts()).await?; let c = c .drop_query("CREATE TEMPORARY TABLE time_zone (Time_zone_id INT)") .await .unwrap(); let t = c.start_transaction(TransactionOptions::new()).await?; let t = t.drop_query(QUERY).await?; let r = t.query(QUERY).await?; let (t, out) = r.collect_and_drop::<u8>().await?; assert_eq!(vec![1], out); let r = t.query(QUERY).await?; let t = r .for_each_and_drop(|x| assert_eq!(from_row::<u8>(x), 1)) .await?; let r = t.query(QUERY).await?; let (t, out) = r.map_and_drop(|row| from_row::<u8>(row)).await?; assert_eq!(vec![1], out); let r = t.query(QUERY).await?; let (t, out) = r .reduce_and_drop(0u8, |acc, x| acc + from_row::<u8>(x)) .await?; assert_eq!(1, out); let t = t.query(QUERY).await?.drop_result().await?; let c = t.commit().await?; let (c, result) = c.first_exec::<_, _, u8>("SELECT 1", ()).await?; c.disconnect().await?; assert_eq!(result, Some(1)); Ok(()) } #[tokio::test] async fn should_iterate_over_resultset() -> super::Result<()> { use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; let acc = Arc::new(AtomicUsize::new(0)); let conn = Conn::new(get_opts()).await?; let result = conn .query( r"SELECT 2 UNION ALL SELECT 3; SELECT 5;", ) .await?; let result = result .for_each({ let acc = acc.clone(); move |row| { acc.fetch_add(from_row::<usize>(row), Ordering::SeqCst); } }) .await?; let conn = result .for_each_and_drop({ let acc = acc.clone(); move |row| { acc.fetch_add(from_row::<usize>(row), Ordering::SeqCst); } }) .await?; conn.disconnect().await?; assert_eq!(acc.load(Ordering::SeqCst), 10); Ok(()) } #[tokio::test] async fn should_prepare_statement() -> super::Result<()> { Conn::new(get_opts()) .await? .prepare(r"SELECT ?") .await? .close() .await? .disconnect() .await?; Conn::new(get_opts()) .await? .prepare(r"SELECT :foo") .await? .close() .await? .disconnect() .await?; Ok(()) } #[tokio::test] async fn should_execute_statement() -> super::Result<()> { let long_string = ::std::iter::repeat('A') .take(18 * 1024 * 1024) .collect::<String>(); let conn = Conn::new(get_opts()).await?; let stmt = conn.prepare(r"SELECT ?").await?; let result = stmt.execute((&long_string,)).await?; let (stmt, mut mapped) = result .map_and_drop(|row| from_row::<(String,)>(row)) .await?; assert_eq!(mapped.len(), 1); assert_eq!(mapped.pop(), Some((long_string,))); let result = stmt.execute((42,)).await?; let (stmt, collected) = result.collect_and_drop::<(u8,)>().await?; assert_eq!(collected, vec![(42u8,)]); let result = stmt.execute((8,)).await?; let (stmt, reduced) = result .reduce_and_drop(2, |mut acc, row| { acc += from_row::<i32>(row); acc }) .await?; stmt.close().await?.disconnect().await?; assert_eq!(reduced, 10); let conn = Conn::new(get_opts()).await?; let stmt = conn.prepare(r"SELECT :foo, :bar, :foo, 3").await?; let result = stmt .execute(params! { "foo" => "quux", "bar" => "baz" }) .await?; let (stmt, mut mapped) = result .map_and_drop(|row| from_row::<(String, String, String, u8)>(row)) .await?; assert_eq!(mapped.len(), 1); assert_eq!( mapped.pop(), Some(("quux".into(), "baz".into(), "quux".into(), 3)) ); let result = stmt.execute(params! { "foo" => 2, "bar" => 3 }).await?; let (stmt, collected) = result.collect_and_drop::<(u8, u8, u8, u8)>().await?; assert_eq!(collected, vec![(2, 3, 2, 3)]); let result = stmt.execute(params! { "foo" => 2, "bar" => 3 }).await?; let (stmt, reduced) = result .reduce_and_drop(0, |acc, row| { let (a, b, c, d): (u8, u8, u8, u8) = from_row(row); acc + a + b + c + d }) .await?; stmt.close().await?.disconnect().await?; assert_eq!(reduced, 10); Ok(()) } #[tokio::test] async fn should_prep_exec_statement() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let result = conn .prep_exec(r"SELECT :a, :b, :a", params! { "a" => 2, "b" => 3 }) .await?; let (conn, output) = result .map_and_drop(|row| { let (a, b, c): (u8, u8, u8) = from_row(row); a * b * c }) .await?; conn.disconnect().await?; assert_eq!(output[0], 12u8); Ok(()) } #[tokio::test] async fn should_first_exec_statement() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let (conn, output): (_, Option<(u8,)>) = conn .first_exec( r"SELECT :a UNION ALL SELECT :b", params! { "a" => 2, "b" => 3 }, ) .await?; conn.disconnect().await?; assert_eq!(output.unwrap(), (2u8,)); Ok(()) } #[tokio::test] async fn should_run_transactions() -> super::Result<()> { let conn = Conn::new(get_opts()).await?; let conn = conn .drop_query("CREATE TEMPORARY TABLE tmp (id INT, name TEXT)") .await?; let transaction = conn.start_transaction(Default::default()).await?; let conn = transaction .drop_query("INSERT INTO tmp VALUES (1, 'foo'), (2, 'bar')") .await? .commit() .await?; let (conn, output_opt) = conn.first("SELECT COUNT(*) FROM tmp").await?; assert_eq!(output_opt, Some((2u8,))); let transaction = conn.start_transaction(Default::default()).await?; let transaction = transaction .drop_query("INSERT INTO tmp VALUES (3, 'baz'), (4, 'quux')") .await?; let (t, output_opt) = transaction .first_exec("SELECT COUNT(*) FROM tmp", ()) .await?; assert_eq!(output_opt, Some((4u8,))); let conn = t.rollback().await?; let (conn, output_opt) = conn.first("SELECT COUNT(*) FROM tmp").await?; assert_eq!(output_opt, Some((2u8,))); conn.disconnect().await?; Ok(()) } #[tokio::test] async fn should_handle_local_infile() -> super::Result<()> { use std::{io::Write, path::Path}; let file_path = tempfile::Builder::new().tempfile_in("").unwrap(); let file_path = file_path.path(); let file_name = Path::new(file_path.file_name().unwrap()); let mut opts = OptsBuilder::from_opts(get_opts()); opts.local_infile_handler(Some(WhiteListFsLocalInfileHandler::new(&[file_name][..]))); let conn = Conn::new(opts).await.unwrap(); let conn = conn .drop_query("CREATE TEMPORARY TABLE tmp (a TEXT);") .await .unwrap(); let mut file = ::std::fs::File::create(file_name).unwrap(); let _ = file.write(b"AAAAAA\n"); let _ = file.write(b"BBBBBB\n"); let _ = file.write(b"CCCCCC\n"); let conn = match conn .drop_query(dbg!(format!( r#"LOAD DATA LOCAL INFILE "{}" INTO TABLE tmp;"#, file_name.display() ))) .await { Ok(conn) => conn, Err(super::Error::Server(ref err)) if err.code == 1148 => { // The used command is not allowed with this MySQL version return Ok(()); } e @ Err(_) => e.unwrap(), }; let (conn, result) = conn .prep_exec("SELECT * FROM tmp;", ()) .await .unwrap() .map_and_drop(|row| from_row::<(String,)>(row).0) .await .unwrap(); assert_eq!(result.len(), 3); assert_eq!(result[0], "AAAAAA"); assert_eq!(result[1], "BBBBBB"); assert_eq!(result[2], "CCCCCC"); let result = conn.disconnect().await; if let Err(crate::error::Error::Server(ref err)) = result { if err.code == 1148 { // The used command is not allowed with this MySQL version return Ok(()); } } result.unwrap(); Ok(()) } #[cfg(feature = "nightly")] mod bench { use futures_util::try_future::TryFutureExt; use crate::{conn::Conn, queryable::Queryable, test_misc::get_opts}; #[bench] fn simple_exec(bencher: &mut test::Bencher) { let runtime = tokio::runtime::Runtime::new().unwrap(); let mut conn_opt = Some(runtime.block_on(Conn::new(get_opts())).unwrap()); bencher.iter(|| { let conn = conn_opt.take().unwrap(); conn_opt = Some(runtime.block_on(conn.drop_query("DO 1")).unwrap()); }); runtime .block_on(conn_opt.take().unwrap().disconnect()) .unwrap(); runtime.shutdown_on_idle(); } #[bench] fn select_large_string(bencher: &mut test::Bencher) { let runtime = tokio::runtime::Runtime::new().unwrap(); let mut conn_opt = Some(runtime.block_on(Conn::new(get_opts())).unwrap()); bencher.iter(|| { let conn = conn_opt.take().unwrap(); conn_opt = Some( runtime .block_on(conn.drop_query("SELECT REPEAT('A', 10000)")) .unwrap(), ); }); runtime .block_on(conn_opt.take().unwrap().disconnect()) .unwrap(); runtime.shutdown_on_idle(); } #[bench] fn prepared_exec(bencher: &mut test::Bencher) { let runtime = tokio::runtime::Runtime::new().unwrap(); let mut stmt_opt = Some( runtime .block_on(Conn::new(get_opts()).and_then(|conn| conn.prepare("DO 1"))) .unwrap(), ); bencher.iter(|| { let stmt = stmt_opt.take().unwrap(); stmt_opt = Some( runtime .block_on(stmt.execute(()).and_then(|result| result.drop_result())) .unwrap(), ); }); runtime .block_on( stmt_opt .take() .unwrap() .close() .and_then(|conn| conn.disconnect()), ) .unwrap(); runtime.shutdown_on_idle(); } #[bench] fn prepare_and_exec(bencher: &mut test::Bencher) { let runtime = tokio::runtime::Runtime::new().unwrap(); let mut conn_opt = Some(runtime.block_on(Conn::new(get_opts())).unwrap()); bencher.iter(|| { let conn = conn_opt.take().unwrap(); conn_opt = Some( runtime .block_on( conn.prepare("SELECT ?") .and_then(|stmt| stmt.execute((0,))) .and_then(|result| result.drop_result()) .and_then(|stmt| stmt.close()), ) .unwrap(), ); }); runtime .block_on(conn_opt.take().unwrap().disconnect()) .unwrap(); runtime.shutdown_on_idle(); } } }
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! List interface example. // For explanation of lint checks, run `rustc -W help` or see // https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid( bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings )] #![deny( deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true )] #![warn( trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![allow( box_pointers, missing_copy_implementations, missing_debug_implementations, variant_size_differences )] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", deny(clippy, clippy_pedantic))] extern crate get_if_addrs; fn main() { let ifaces = get_if_addrs::get_if_addrs().unwrap(); println!("Got list of interfaces"); println!("{:#?}", ifaces); }
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct UserInfo { pub email: String, pub token: String, pub username: String, pub bio: Option<String>, pub image: Option<String>, }
#[doc = "Register `OTG_HCTSIZ14` reader"] pub type R = crate::R<OTG_HCTSIZ14_SPEC>; #[doc = "Register `OTG_HCTSIZ14` writer"] pub type W = crate::W<OTG_HCTSIZ14_SPEC>; #[doc = "Field `XFRSIZ` reader - XFRSIZ"] pub type XFRSIZ_R = crate::FieldReader<u32>; #[doc = "Field `XFRSIZ` writer - XFRSIZ"] pub type XFRSIZ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 19, O, u32>; #[doc = "Field `PKTCNT` reader - PKTCNT"] pub type PKTCNT_R = crate::FieldReader<u16>; #[doc = "Field `PKTCNT` writer - PKTCNT"] pub type PKTCNT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 10, O, u16>; #[doc = "Field `DPID` reader - DPID"] pub type DPID_R = crate::FieldReader; #[doc = "Field `DPID` writer - DPID"] pub type DPID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:18 - XFRSIZ"] #[inline(always)] pub fn xfrsiz(&self) -> XFRSIZ_R { XFRSIZ_R::new(self.bits & 0x0007_ffff) } #[doc = "Bits 19:28 - PKTCNT"] #[inline(always)] pub fn pktcnt(&self) -> PKTCNT_R { PKTCNT_R::new(((self.bits >> 19) & 0x03ff) as u16) } #[doc = "Bits 29:30 - DPID"] #[inline(always)] pub fn dpid(&self) -> DPID_R { DPID_R::new(((self.bits >> 29) & 3) as u8) } } impl W { #[doc = "Bits 0:18 - XFRSIZ"] #[inline(always)] #[must_use] pub fn xfrsiz(&mut self) -> XFRSIZ_W<OTG_HCTSIZ14_SPEC, 0> { XFRSIZ_W::new(self) } #[doc = "Bits 19:28 - PKTCNT"] #[inline(always)] #[must_use] pub fn pktcnt(&mut self) -> PKTCNT_W<OTG_HCTSIZ14_SPEC, 19> { PKTCNT_W::new(self) } #[doc = "Bits 29:30 - DPID"] #[inline(always)] #[must_use] pub fn dpid(&mut self) -> DPID_W<OTG_HCTSIZ14_SPEC, 29> { DPID_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "OTG host channel 14 transfer size register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otg_hctsiz14::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`otg_hctsiz14::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct OTG_HCTSIZ14_SPEC; impl crate::RegisterSpec for OTG_HCTSIZ14_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`otg_hctsiz14::R`](R) reader structure"] impl crate::Readable for OTG_HCTSIZ14_SPEC {} #[doc = "`write(|w| ..)` method takes [`otg_hctsiz14::W`](W) writer structure"] impl crate::Writable for OTG_HCTSIZ14_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets OTG_HCTSIZ14 to value 0"] impl crate::Resettable for OTG_HCTSIZ14_SPEC { const RESET_VALUE: Self::Ux = 0; }
mod chapter_01; mod chapter_16; pub mod chapter_17; fn main() { println!("Done"); }
#[cfg(windows)] const LINE_ENDING: &'static str = "\r\n"; #[cfg(not(windows))] const LINE_ENDING: &'static str = "\n"; #[derive(Debug, PartialEq, Clone)] pub struct GCode { pub command: String, pub x: f32, pub y: f32, pub z: f32 // Including a Z because some slicers will map a lift as a raising of the Z axis rather than using the lift command. - Austin Haskell } impl GCode { pub fn deserialize(raw: &String) -> Vec<GCode> { let mut parsed_values: Vec<GCode> = Vec::new(); for line in raw.split(LINE_ENDING) { if line.len() < 1 || (!line.starts_with('G') && !line.starts_with('M')) { continue; } let parsed_line: Vec<&str> = filter_out_invalids(line.split(' ').collect()); match GCode::construct_gcode_from_line(parsed_line) { Ok(code) => parsed_values.push(code), Err(_) => continue } } parsed_values } pub fn construct_gcode_from_line(line: Vec<&str>) -> Result<GCode, &str> { let mut code = GCode { x: 0.0, y: 0.0, z: 0.0, command: String::from("") }; let supported_g_codes: Vec<&str> = vec!["G0", "G1", "G10"]; for parsed_command in line { let first_letter = parsed_command.chars().next().unwrap_or_default(); match first_letter { 'X' => code.x = ignore_letter_and_parse(parsed_command), 'Y' => code.y = ignore_letter_and_parse(parsed_command), 'Z' => code.z = ignore_letter_and_parse(parsed_command), 'G' => { if !supported_g_codes.contains(&parsed_command) { return Err("GCode command not supported"); } code.command = parsed_command.to_string(); }, 'M' => return Err("Command has no implementation"), // TODO: Figure out which M commands we should support - Austin Haskell _ => continue } } Ok(code) } } fn filter_out_invalids(line: Vec<&str>) -> Vec<&str> { let mut cleaned_line: Vec<&str> = Vec::new(); for parsed_command in line { if parsed_command.is_empty() { continue; } let first_letter = parsed_command.chars().next().unwrap_or_default(); match first_letter { ' ' => continue, ';' => break, // Once we hit a comment, just stop - Austin Haskell _ => cleaned_line.push(parsed_command) } } cleaned_line } fn ignore_letter_and_parse(val: &str) -> f32 { if val.len() < 1 { return 0.0; } (&val[1..]).parse::<f32>().unwrap_or_default() } #[test] fn ignore_letter_and_parse_zero_length_defaults() { assert_eq!(ignore_letter_and_parse(""), 0.0); } #[test] fn ignore_letter_and_parse_parses() { assert_eq!(ignore_letter_and_parse("X-189.1"), -189.1); assert_eq!(ignore_letter_and_parse("X1"), 1.0); } #[test] fn deserialize_unknown_type_ignored_deserializes() { let result = GCode::deserialize(&String::from("J1 X1.1422 Y-1.0178 F1016")); assert_eq!(result.len(), 0); } #[test] fn deserialize_comments_ignored_deserializes() { let result = GCode::deserialize(&String::from(";G1 X1.1422 Y-1.0178 F1016")); assert_eq!(result.len(), 0); } #[test] fn deserialize_commands_without_xyz_deserializes() { let result = GCode::deserialize(&String::from( "G1")); assert_eq!(result.len(), 1); }
pub mod draw_context; pub mod std_shaders; pub mod object; use self::draw_context::DrawContext; use glium; use glium::{glutin, Display}; use glium::glutin::{ContextBuilder, EventsLoop, WindowBuilder}; use glium::glutin::Event; use std::collections::hash_map::HashMap; use support::font_loader::FontEngine; use camera::Camera; use gui::Gui; #[derive(Copy, Clone)] pub struct Vertex { pub position: [f32; 3], pub normal: [f32; 3], pub tex_coords: [f32; 2] } implement_vertex!(Vertex, position, normal, tex_coords); #[derive(Copy, Clone)] pub struct Vertex2D { pub coords: [f32; 2], } implement_vertex!(Vertex2D, coords); pub struct Mouse{ pub position: (i32, i32), pub releative: (i32, i32) } pub struct Window{ pub events_loop: EventsLoop, pub draw_context: DrawContext, pub events: Vec<Event>, pub focused: bool, pub res: (u32, u32), pub mouse: Mouse, pub font_engine: FontEngine, pub gui_manager: Gui } impl Mouse{ pub fn new() -> Mouse{ Mouse{ position: (0, 0), releative: (0, 0) } } pub fn update(&mut self, new_pos: (i32, i32)){ self.releative.0 = self.position.0 - new_pos.0; self.releative.1 = self.position.1 - new_pos.1; self.position = new_pos; } } #[allow(dead_code)] impl Window { pub fn new(sizex: u32, sizey: u32, title: &'static str) -> Window{ let events_loop = glutin::EventsLoop::new(); let window = WindowBuilder::new() .with_dimensions(sizex, sizey) .with_title(title); let context = ContextBuilder::new() .with_depth_buffer(24); let display = Display::new(window, context, &events_loop).unwrap(); let _ = display.gl_window().window().set_cursor_state(glutin::CursorState::Hide); let camera = Camera::new(sizex, sizey); let gui_mngr = Gui{buttons: vec![]}; Window{ events_loop: events_loop, draw_context: DrawContext{ display, render_buffer: draw_context::RenderBuffer{ shaders: HashMap::new() }, render_data: HashMap::new(), camera: camera, scr_res: (sizex, sizey) }, events: vec![], focused: true, res: (sizex, sizey), mouse: Mouse::new(), font_engine: FontEngine::new(), gui_manager: gui_mngr } } pub fn get_display(&mut self) -> (&mut DrawContext, &mut EventsLoop){ (&mut self.draw_context, &mut self.events_loop) } pub fn set_mouse_pos(&mut self, x: i32, y: i32){ let _ = self.draw_context.display.gl_window().window().set_cursor_position(x, y); } pub fn update(&mut self){ use glium::glutin::Event::WindowEvent; use glium::glutin; let mut events = vec![]; let mut mouse_pos = self.mouse.position; let mut focused = None; self.events_loop.poll_events(|ev| { events.push(ev.clone()); match ev{ WindowEvent { ref event, .. } => match event{ &glutin::WindowEvent::CursorMoved{position, ..} => { mouse_pos = (position.0 as i32, position.1 as i32); }, &glutin::WindowEvent::Focused(focus) => { focused = Some(focus); }, _ => {} }, _ => {} } }); if focused.is_some(){ self.focused = focused.unwrap(); } if mouse_pos != (-1, -1){ self.mouse.update((mouse_pos.0 as i32, mouse_pos.1 as i32)); } self.events = events; } } pub fn get_params() -> glium::DrawParameters<'static>{ glium::DrawParameters { depth: glium::Depth { test: glium::DepthTest::IfLess, write: true, .. Default::default() }, backface_culling: glium::draw_parameters::BackfaceCullingMode::CullClockwise, blend: glium::draw_parameters::Blend::alpha_blending(), .. Default::default() } }
use serenity::{model::channel::Message, prelude::*}; use super::super::bot; use super::super::bot::ContestData; use super::super::dictionary; use super::super::sort::Sorted; use indexmap::IndexMap; use crate::try_say; use std::fs::File; use std::io::{BufWriter, Write}; use std::str::from_utf8; pub(crate) fn prob(ctx: &mut Context, msg: &Message, lang: bot::Lang) -> String { let dic = match lang { bot::Lang::En => &*dictionary::ENGLISH, bot::Lang::Ja => &*dictionary::JAPANESE, bot::Lang::Fr => &*dictionary::FRENCH, bot::Lang::De => &*dictionary::GERMAN, bot::Lang::It => &*dictionary::ITALIAN, bot::Lang::Ru => &*dictionary::RUSSIAN, bot::Lang::Eo => &*dictionary::ESPERANTO, }; let ans = dic.get(&mut rand::thread_rng()); let sorted = ans.sorted(); try_say!( ctx, msg, format!( "ソートなぞなぞ ソート前の {as_str} な〜んだ?\n`{prob}`", as_str = lang.as_symbol(), prob = sorted ) ); println!("called prob: [{}, {}]", ans, sorted); ans.clone() } pub(crate) fn kick(ctx: &mut Context, msg: &Message) -> std::io::Result<()> { use std::process::Command; let mut src = BufWriter::new(File::create("/tmp/main.rs")?); let code = format!( r#"fn kick() {{ println!("ヒィンw"); }} fn main() {{ {} }} "#, &msg.content ); println!("{}", code); src.write_all(code.as_bytes())?; src.flush()?; match Command::new("rustc").arg("/tmp/main.rs").output() { Ok(output) => { if output.status.success() { try_say!(ctx, msg, "ヒィンw"); } else { try_say!(ctx, msg, from_utf8(output.stderr.as_slice()).unwrap()); } } Err(e) => { try_say!(ctx, msg, format!("{:?}", e)); } } Ok(()) } pub(crate) fn answer_check(ctx: &mut Context, msg: &Message) { if let Ok(mut quiz_guard) = bot::QUIZ.lock() { let elapsed = quiz_guard.elapsed(); match quiz_guard.answer_check(&msg.content) { bot::CheckResult::WA => { // includes the case that bot is standing by. return; } bot::CheckResult::Assumed(_ans) => { if quiz_guard.is_holding() { try_say!( ctx, msg, format!( "{} さん、正解です!\n正解は\"{}\"でした! [{:.3} sec]", &msg.author.name, quiz_guard.ans().unwrap(), elapsed.unwrap(), ) ); *quiz_guard = bot::Status::StandingBy; return; } else if quiz_guard.is_contesting() { try_say!( ctx, msg, format!( "{} さん、正解です!\n正解は\"{}\"でした! [{:.3} sec]", &msg.author.name, quiz_guard.ans().unwrap(), elapsed.unwrap(), ) ); let contest_result = &mut *bot::CONTEST_RESULT.lock().unwrap(); *contest_result .entry(msg.author.name.clone()) .or_insert(ContestData::default()) += elapsed.unwrap(); let (_, num) = quiz_guard.get_contest_num().unwrap(); if quiz_guard.is_contest_end() { try_say!( ctx, msg, format!( "{num}問連続のコンテストが終了しました。\n{result}", num = num, result = bot::aggregates(dbg!(&*contest_result)) ) ); *contest_result = IndexMap::new(); *quiz_guard = bot::Status::StandingBy; } else { quiz_guard.contest_continue(ctx, msg); } } } bot::CheckResult::Anagram(ans) => { if quiz_guard.is_contesting() { *bot::CONTEST_RESULT .lock() .unwrap() .entry(msg.author.name.clone()) .or_insert(ContestData::default()) += elapsed.unwrap(); } try_say!( ctx, msg, format!( "{} さん、{} は非想定解ですが正解です!", &msg.author.name, ans.to_lowercase() ) ); } bot::CheckResult::Full(ans) => { if quiz_guard.is_contesting() { *bot::CONTEST_RESULT .lock() .unwrap() .entry(msg.author.name.clone()) .or_insert(ContestData::default()) += elapsed.unwrap(); } try_say!( ctx, msg, format!( "{} さん、{} は出題辞書にない非想定解ですが正解です!", &msg.author.name, ans.to_lowercase() ) ); } } } }
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use crate::{client::Client, core::session::URLPart, event_source::parser::EventParser, TypeState}; use futures_util::{Stream, StreamExt}; use reqwest::header::{HeaderValue, ACCEPT, CONTENT_TYPE}; use super::Changes; impl Client { pub async fn event_source( &self, mut types: Option<impl IntoIterator<Item = TypeState>>, close_after_state: bool, ping: Option<u32>, last_event_id: Option<&str>, ) -> crate::Result<impl Stream<Item = crate::Result<Changes>> + Unpin> { let mut event_source_url = String::with_capacity(self.session().event_source_url().len()); for part in self.event_source_url() { match part { URLPart::Value(value) => { event_source_url.push_str(value); } URLPart::Parameter(param) => match param { super::URLParameter::Types => { if let Some(types) = Option::take(&mut types) { event_source_url.push_str( &types .into_iter() .map(|state| state.to_string()) .collect::<Vec<_>>() .join(","), ); } else { event_source_url.push('*'); } } super::URLParameter::CloseAfter => { event_source_url.push_str(if close_after_state { "state" } else { "no" }); } super::URLParameter::Ping => { if let Some(ping) = ping { event_source_url.push_str(&ping.to_string()); } else { event_source_url.push('0'); } } }, } } // Add headers let mut headers = self.headers().clone(); headers.remove(CONTENT_TYPE); headers.insert(ACCEPT, HeaderValue::from_static("text/event-stream")); if let Some(last_event_id) = last_event_id { headers.insert( "Last-Event-ID", HeaderValue::from_str(last_event_id).unwrap(), ); } let mut stream = Client::handle_error( reqwest::Client::builder() .connect_timeout(self.timeout()) .danger_accept_invalid_certs(self.accept_invalid_certs) .redirect(self.redirect_policy()) .default_headers(headers) .build()? .get(event_source_url) .send() .await?, ) .await? .bytes_stream(); let mut parser = EventParser::default(); Ok(Box::pin(async_stream::stream! { loop { if let Some(changes) = parser.filter_state() { yield changes; continue; } if let Some(result) = stream.next().await { match result { Ok(bytes) => { parser.push_bytes(bytes.to_vec()); continue; } Err(err) => { yield Err(err.into()); break; } } } else { break; } } })) } }
use core::{ fmt, hash::{Hash, Hasher}, }; pub enum EitherBoth<A, B> { Left(A), Right(B), Both(A, B), } impl<A, B> fmt::Debug for EitherBoth<A, B> where A: fmt::Debug, B: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use EitherBoth::*; match self { Left(a) => write!(f, "Left({:?})", a), Right(b) => write!(f, "Right({:?})", b), Both(a, b) => write!(f, "Both({:?}, {:?})", a, b), } } } impl<A, B> Clone for EitherBoth<A, B> where A: Clone, B: Clone, { fn clone(&self) -> Self { use EitherBoth::*; match self { Left(a) => Left(a.clone()), Right(b) => Right(b.clone()), Both(a, b) => Both(a.clone(), b.clone()), } } } impl<A, B> Copy for EitherBoth<A, B> where A: Copy, B: Copy, { } impl<A, B> PartialEq for EitherBoth<A, B> where A: PartialEq, B: PartialEq, { fn eq(&self, other: &Self) -> bool { use EitherBoth::*; match (self, other) { (Left(a), Left(other_a)) => a == other_a, (Right(b), Right(other_b)) => b == other_b, (Both(a, b), Both(other_a, other_b)) => (a == other_a) && (b == other_b), _ => false, } } } impl<A, B> Eq for EitherBoth<A, B> where A: Eq, B: Eq, { } impl<A, B> Hash for EitherBoth<A, B> where A: Hash, B: Hash, { fn hash<H: Hasher>(&self, state: &mut H) { use EitherBoth::*; match self { Left(a) => a.hash(state), Right(b) => b.hash(state), Both(a, b) => { a.hash(state); b.hash(state) }, } } }
use hydroflow_datalog_core::{gen_hydroflow_graph, hydroflow_graph_to_program}; use proc_macro2::Span; use quote::{quote, ToTokens}; /// Generate a Hydroflow instance from [Datalog](https://en.wikipedia.org/wiki/Datalog) code. /// /// This uses a variant of Datalog that is similar to [Dedalus](https://www2.eecs.berkeley.edu/Pubs/TechRpts/2009/EECS-2009-173.pdf). /// /// For examples, see [the datalog tests in the Hydroflow repo](https://github.com/hydro-project/hydroflow/blob/main/hydroflow/tests/datalog_frontend.rs). // TODO(mingwei): rustdoc examples inline. #[proc_macro] pub fn datalog(item: proc_macro::TokenStream) -> proc_macro::TokenStream { let item = proc_macro2::TokenStream::from(item); let literal: proc_macro2::Literal = syn::parse_quote! { #item }; let hydroflow_crate = proc_macro_crate::crate_name("hydroflow") .expect("hydroflow should be present in `Cargo.toml`"); let root = match hydroflow_crate { proc_macro_crate::FoundCrate::Itself => quote! { hydroflow }, proc_macro_crate::FoundCrate::Name(name) => { let ident = syn::Ident::new(&name, Span::call_site()); quote! { #ident } } }; match gen_hydroflow_graph(literal) { Ok(graph) => { let program = hydroflow_graph_to_program(graph, root); program.to_token_stream().into() } Err(diagnostics) => { for diagnostic in diagnostics { diagnostic.emit(); } proc_macro::TokenStream::from(quote!(hydroflow::scheduled::graph::Hydroflow::new())) } } }
use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct ResponseErr { pub msg: String } #[derive(Debug, Serialize, Deserialize)] pub struct Header{ pub method: String, pub token: String, pub user: User } #[derive(Debug, Serialize, Deserialize)] pub struct Community { pub id: i32, pub name: String, pub description: String, pub public: bool, } #[derive(Serialize, Deserialize)] pub struct NoIdCommunity { pub name: String, pub description: String, pub public: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct User { pub id: i32, pub name: String, pub email: String, pub uid: String, pub icon: String, } #[derive(Debug, Serialize, Deserialize)] pub struct NoIdUser { pub name: String, pub email: String, pub uid: String, pub icon: String, } #[derive(Debug, Serialize, Deserialize)] pub struct ShowUser { pub id: i32, pub name: String, pub icon: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Member{ pub id: i32, pub user_id: i32, pub community_id: i32, } #[derive(Debug, Serialize, Deserialize)] pub struct NoIdMember{ pub user_id: i32, pub community_id: i32, } #[derive(Debug, Serialize, Deserialize)] pub struct Restaurant{ pub id: i32, pub vendor: i32, pub place_id: String, pub name: String, pub addr: String, pub lat: f64, pub lng: f64, } #[derive(Debug, Serialize, Deserialize)] pub struct NoIdRestaurant{ pub place_id: String, pub vendor: i32, pub name: String, pub addr: String, pub lat: f64, pub lng: f64, } #[derive(Debug, Serialize, Deserialize)] pub struct Pin{ pub id: i32, pub restaurant_id: i32, pub community_id: i32 } #[derive(Debug, Serialize, Deserialize)] pub struct NoIdPin{ pub restaurant_id: i32, pub community_id: i32 } #[derive(Debug, Serialize, Deserialize)] pub struct NoIdReview{ pub pin_id: i32, pub member_id: i32, pub good: bool, pub comment: Option<String> } #[derive(Debug, Serialize, Deserialize)] pub struct PostedReview{ pub pin_id: i32, pub good: bool, pub comment: Option<String> }
use std::collections::HashSet; use aoc_lib::Solver; #[derive(Debug)] pub struct Day9 { head_positions: Vec<Coord>, tail_positions: HashSet<Coord>, current_tail_position: Coord, } #[derive(Hash, PartialEq, Eq, Debug, Default, Clone, Copy, PartialOrd, Ord)] struct Coord(i32, i32); impl Solver for Day9 { fn solution_part1(input: aoc_lib::Input) -> Option<Self::OutputPart1> { let mut d = Day9::default(); let instrs = input.lines.iter().map(MotionInstruction::from); instrs.for_each(|x| { for _ in 1..=x.distance() { d.move_rope(x).adjust_tail(); } }); Some(d.tail_positions.len()) } fn solution_part2(input: aoc_lib::Input) -> Option<Self::OutputPart2> { let mut d = Day9::default(); let instrs = input.lines.iter().map(MotionInstruction::from); let mut tails = [Coord::default()].repeat(9); instrs.for_each(|x| { for _ in 1..=x.distance() { d.move_rope(x); let new_head_pos = d.head_positions.last().expect("head position"); tails[0] = d.get_new_tail_position(*new_head_pos, tails[0]); for i in 1..=8 { tails[i] = d.get_new_tail_position(tails[i - 1], tails[i]); } d.tail_positions.insert(tails[8]); } }); Some(d.tail_positions.len()) } fn day() -> u8 { 9 } type OutputPart1 = usize; type OutputPart2 = usize; } impl Default for Day9 { fn default() -> Self { Day9 { head_positions: vec![Coord::default()], tail_positions: HashSet::from([Coord::default()]), current_tail_position: Coord::default(), } } } fn move_closer(dest: i32, src: i32) -> i32 { if dest.abs_diff(src) <= 1 { src } else if src > dest { move_closer(dest, src - 1) } else { move_closer(dest, src + 1) } } impl Day9 { fn move_rope(&mut self, instr: MotionInstruction) -> &mut Self { let curr_head_pos = self .head_positions .last() .expect("head positions should not be empty"); self.head_positions .push(self.get_new_head_position(instr, *curr_head_pos)); self } fn get_new_head_position( &self, instr: MotionInstruction, Coord(curr_x, curr_y): Coord, ) -> Coord { match instr { MotionInstruction::Right(_) => Coord(curr_x + 1_i32, curr_y), MotionInstruction::Left(_) => Coord(curr_x - 1_i32, curr_y), MotionInstruction::Up(_) => Coord(curr_x, curr_y + 1_i32), MotionInstruction::Down(_) => Coord(curr_x, curr_y - 1_i32), } } fn get_new_tail_position( &self, Coord(curr_h_x, curr_h_y): Coord, Coord(curr_t_x, curr_t_y): Coord, ) -> Coord { let (mod_t_x, mod_t_y) = { if (curr_h_y == curr_t_y && curr_h_x.abs_diff(curr_t_x) > 1) || (curr_h_x == curr_t_x && curr_h_y.abs_diff(curr_t_y) > 1) { if curr_h_y == curr_t_y { (move_closer(curr_h_x, curr_t_x), curr_t_y) } else { (curr_t_x, move_closer(curr_h_y, curr_t_y)) } } else if (curr_h_x.abs_diff(curr_t_x) > 1 && curr_h_y.abs_diff(curr_t_y) == 1) || (curr_h_y.abs_diff(curr_t_y) > 1 && curr_h_x.abs_diff(curr_t_x) == 1) { if curr_h_y.abs_diff(curr_t_y) == 1 { (move_closer(curr_h_x, curr_t_x), curr_h_y) } else { (curr_h_x, move_closer(curr_h_y, curr_t_y)) } } else { ( move_closer(curr_h_x, curr_t_x), move_closer(curr_h_y, curr_t_y), ) } }; Coord(mod_t_x, mod_t_y) } fn adjust_tail(&mut self) -> &mut Self { let curr_head_position = self .head_positions .last() .expect("head positions should not be empty"); let Coord(mod_t_x, mod_t_y) = self.get_new_tail_position(*curr_head_position, self.current_tail_position); self.tail_positions.insert(Coord(mod_t_x, mod_t_y)); self.current_tail_position = Coord(mod_t_x, mod_t_y); self } } #[derive(Debug, Clone, Copy)] enum MotionInstruction { Right(usize), Left(usize), Up(usize), Down(usize), } impl MotionInstruction { fn distance(&self) -> usize { match self { MotionInstruction::Right(x) => *x, MotionInstruction::Left(x) => *x, MotionInstruction::Up(x) => *x, MotionInstruction::Down(x) => *x, } } } impl From<&String> for MotionInstruction { fn from(s: &String) -> Self { let xs = s.split(' ').collect::<Vec<_>>(); let dist = xs.get(1).map(|n| n.parse::<usize>().expect("")).expect(""); match *xs.first().expect("there should be some character") { "R" => MotionInstruction::Right(dist), "L" => MotionInstruction::Left(dist), "U" => MotionInstruction::Up(dist), "D" => MotionInstruction::Down(dist), _ => panic!("not possible"), } } }
use crate::get_attr_val; use proc_macro as pm; pub(crate) fn rewrite(attr: syn::AttributeArgs, mut item: syn::ItemFn) -> pm::TokenStream { let unmangled = get_attr_val("unmangled", &attr); if unmangled != item.sig.ident { let tys = item.sig.inputs.iter().map(|arg| { if let syn::FnArg::Typed(p) = arg { &p.ty } else { unreachable!() } }); item.sig.abi = None; item.sig.inputs = syn::parse_quote!(x: (#(#tys,)*), ctx: Context); item.block = syn::parse_quote!({ #unmangled(x, ctx) }); quote::quote!(#item).into() } else { quote::quote!().into() } }
// Traits are similar to a feature often called interfaces in other languages, although with some differences. pub trait Summary { fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("(Read more from {}...)", self.summarize_author()) }} // Trait implementation pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize_author(&self) -> String { String::from("") } fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize_author(&self) -> String { format!("@{}", self.username) } fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } fn example() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, }; println!("1 new tweet: {}", tweet.summarize()); } // this method accept every type that implements the summary trait pub fn notify(item: &impl Summary) { println!("Breaking news! {}", item.summarize()); } // this method accept every type that implements both Summary and Display pub fn notify2(item: &(impl Summary + Display)) { println!("Breaking news! {}", item.summarize()); } // the return type is generic but it has to implement the Summary trait fn returns_summarizable() -> impl Summary { Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, } }
use std::cmp::Eq; use std::fmt::Display; use std::hash::Hash; pub trait Logic: Hash + Eq + Display + Clone { type Manager: Clone; fn is_false(&self) -> bool; fn is_true(&self) -> bool; fn negated(&self) -> Self; fn and(&self, other: Self) -> Self; } use smtlib; impl Logic for smtlib::Term { type Manager = smtlib::Instance; fn is_false(&self) -> bool { self.is_false() } fn is_true(&self) -> bool { self.is_true() } fn negated(&self) -> Self { self.negated() } fn and(&self, other: Self) -> Self { smtlib::Term::new_appl(smtlib::Identifier::AND, vec![self.clone(), other]) } }
//! Massage and work the auzten file to make sure we can deal with real data. extern crate las; macro_rules! autzen { ($name:ident, $major:expr, $minor:expr) => { mod $name { use las::{Builder, Read, Reader, Version, Write, Writer}; use std::io::Cursor; #[test] fn read_write() { let mut reader = Reader::from_path("tests/data/autzen.las").unwrap(); let mut builder = Builder::from(reader.header().clone()); builder.version = Version::new($major, $minor); let mut writer = Writer::new(Cursor::new(Vec::new()), builder.into_header().unwrap()).unwrap(); for point in reader.points() { writer.write(point.unwrap()).unwrap(); } writer.close().unwrap(); } } }; } autzen!(las_1_0, 1, 0); autzen!(las_1_1, 1, 1); autzen!(las_1_2, 1, 2); autzen!(las_1_3, 1, 3); autzen!(las_1_4, 1, 4); fn test_seek_0_works_on(path: &str) { use las::{Read, Reader}; let mut reader = Reader::from_path(path).unwrap(); let _p1 = reader.read().unwrap().unwrap(); reader.seek(0).unwrap(); let _p3 = reader.read().unwrap().unwrap(); } fn test_seek_to_last_point_works_on(path: &str) { use las::{Read, Reader}; let mut reader = Reader::from_path(path).unwrap(); let _p1 = reader.read().unwrap().unwrap(); reader.seek(reader.header().number_of_points() - 1).unwrap(); let res = reader.read(); assert!(res.is_some()); assert!(res.unwrap().is_ok()); } fn test_seek_past_last_point_works_on(path: &str) { use las::{Read, Reader}; let mut reader = Reader::from_path(path).unwrap(); let _p1 = reader.read().unwrap().unwrap(); reader.seek(reader.header().number_of_points()).unwrap(); let res = reader.read(); assert!(res.is_none()); } #[test] fn test_seek_past_last_point_works_on_las() { test_seek_past_last_point_works_on("tests/data/autzen.las"); } #[cfg(feature = "laz")] #[test] fn test_seek_past_last_point_works_on_laz() { test_seek_past_last_point_works_on("tests/data/autzen.laz"); } #[test] fn test_seek_to_last_point_works_on_las() { test_seek_to_last_point_works_on("tests/data/autzen.las"); } #[cfg(feature = "laz")] #[test] fn test_seek_to_last_point_works_on_laz() { test_seek_to_last_point_works_on("tests/data/autzen.laz"); } #[test] fn test_seek_0_works_on_las() { test_seek_0_works_on("tests/data/autzen.las"); } #[cfg(feature = "laz")] #[test] fn test_seek_0_works_on_laz() { test_seek_0_works_on("tests/data/autzen.laz"); }
#[doc = "Register `RCC_ADCCKSELR` reader"] pub type R = crate::R<RCC_ADCCKSELR_SPEC>; #[doc = "Register `RCC_ADCCKSELR` writer"] pub type W = crate::W<RCC_ADCCKSELR_SPEC>; #[doc = "Field `ADCSRC` reader - ADCSRC"] pub type ADCSRC_R = crate::FieldReader; #[doc = "Field `ADCSRC` writer - ADCSRC"] pub type ADCSRC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:1 - ADCSRC"] #[inline(always)] pub fn adcsrc(&self) -> ADCSRC_R { ADCSRC_R::new((self.bits & 3) as u8) } } impl W { #[doc = "Bits 0:1 - ADCSRC"] #[inline(always)] #[must_use] pub fn adcsrc(&mut self) -> ADCSRC_W<RCC_ADCCKSELR_SPEC, 0> { ADCSRC_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to control the selection of the kernel clock for the ADC block.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_adcckselr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_adcckselr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_ADCCKSELR_SPEC; impl crate::RegisterSpec for RCC_ADCCKSELR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_adcckselr::R`](R) reader structure"] impl crate::Readable for RCC_ADCCKSELR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_adcckselr::W`](W) writer structure"] impl crate::Writable for RCC_ADCCKSELR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_ADCCKSELR to value 0"] impl crate::Resettable for RCC_ADCCKSELR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::{ os::unix::prelude::CommandExt, path::PathBuf, process::Command, time::{Duration, SystemTime}, }; /// Update the local nix-index database. pub fn update_database() { eprintln!("Updating nix-index database, takes around 5 minutes."); Command::new("nix-index").exec(); } /// Prints a warning if the nix-index database is non-existent pub fn check_database_exists() { let database_file = get_database_file(); if !database_file.exists() { eprintln!("Warning: Nix-index database does not exist, either obtain a prebuilt database from https://github.com/Mic92/nix-index-database or try updating with `nix run 'nixpkgs#nix-index' --extra-experimental-features 'nix-command flakes'`."); } } /// Prints a warning if the nix-index database is out of date. pub fn check_database_updated() { let database_file = get_database_file(); if is_database_old(database_file) { eprintln!( "Warning: Nix-index database is older than 30 days, either obtain a prebuilt database from https://github.com/Mic92/nix-index-database or try updating with `nix run 'nixpkgs#nix-index' --extra-experimental-features 'nix-command flakes'`." ); } } /// Get the location of the nix-index database file fn get_database_file() -> PathBuf { let base = xdg::BaseDirectories::with_prefix("nix-index").unwrap(); let cache_dir = base.get_cache_home(); cache_dir.join("files") } /// Test whether the database is more than 30 days old fn is_database_old(database_file: std::path::PathBuf) -> bool { let metadata = match database_file.metadata() { Ok(metadata) => metadata, Err(_) => return false, }; let time_since_modified = metadata .modified() .unwrap_or_else(|_| SystemTime::now()) .elapsed() .unwrap_or(Duration::new(0, 0)); time_since_modified > Duration::from_secs(30 * 24 * 60 * 60) && !metadata.permissions().readonly() }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use super::{StarkDomain, TracePolyTable, TraceTable}; use air::{Air, EvaluationFrame, TraceInfo}; use math::{fft, log2, polynom, StarkField}; use utils::{collections::Vec, iter_mut, uninit_vector}; #[cfg(not(feature = "concurrent"))] use utils::collections::vec; #[cfg(feature = "concurrent")] use utils::{iterators::*, rayon}; // CONSTANTS // ================================================================================================ const MIN_FRAGMENT_LENGTH: usize = 2; // TRACE TABLE // ================================================================================================ /// An execution trace of a computation. /// /// Execution trace is a two-dimensional matrix in which each row represents the state of a /// computation at a single point in time and each column corresponds to an algebraic register /// tracked over all steps of the computation. /// /// There are two ways to create an execution trace. /// /// First, you can use the [ExecutionTrace::init()] function which takes a set of vectors as a /// parameter, where each vector contains values for a given column of the trace. This approach /// allows you to build an execution trace as you see fit, as long as it meets a basic set of /// requirements. These requirements are: /// /// 1. Lengths of all columns in the execution trace must be the same. /// 2. The length of the columns must be some power of two. /// /// The other approach is to use [ExecutionTrace::new()] function, which takes trace width and /// length as parameters. This function will allocate memory for the trace, but will not fill it /// with data. To fill the execution trace, you can use the [fill()](ExecutionTrace::fill) method, /// which takes two closures as parameters: /// /// 1. The first closure is responsible for initializing the first state of the computation /// (the first row of the execution trace). /// 2. The second closure receives the previous state of the execution trace as input, and must /// update it to the next state of the computation. /// /// You can also use [ExecutionTrace::with_meta()] function to create a blank execution trace. /// This function work just like [ExecutionTrace::new()] function, but also takes a metadata /// parameter which can be an arbitrary sequence of bytes up to 64KB in size. /// /// # Concurrent trace generation /// For computations which consist of many small independent computations, we can generate the /// execution trace of the entire computation by building fragments of the trace in parallel, /// and then joining these fragments together. /// /// For this purpose, `ExecutionTrace` struct exposes [fragments()](ExecutionTrace::fragments) /// method, which takes fragment length as a parameter, breaks the execution trace into equally /// sized fragments, and returns an iterator over these fragments. You can then use fragment's /// [fill()](ExecutionTraceFragment::fill) method to fill all fragments with data in parallel. /// The semantics of the fragment's [ExecutionTraceFragment::fill()] method are identical to the /// semantics of the [ExecutionTrace::fill()] method. pub struct ExecutionTrace<B: StarkField> { trace: Vec<Vec<B>>, meta: Vec<u8>, } impl<B: StarkField> ExecutionTrace<B> { // CONSTRUCTORS // -------------------------------------------------------------------------------------------- /// Creates a new execution trace of the specified width and length. /// /// This allocates all the required memory for the trace, but does not initialize it. It is /// expected that the trace will be filled using one of the data mutator methods. /// /// # Panics /// Panics if: /// * `width` is zero or greater than 255. /// * `length` is smaller than 8, greater than biggest multiplicative subgroup in the field /// `B`, or is not a power of two. pub fn new(width: usize, length: usize) -> Self { Self::with_meta(width, length, vec![]) } /// Creates a new execution trace of the specified width and length, and with the specified /// metadata. /// /// This allocates all the required memory for the trace, but does not initialize it. It is /// expected that the trace will be filled using one of the data mutator methods. /// /// # Panics /// Panics if: /// * `width` is zero or greater than 255. /// * `length` is smaller than 8, greater than the biggest multiplicative subgroup in the /// field `B`, or is not a power of two. /// * Length of `meta` is greater than 65535; pub fn with_meta(width: usize, length: usize, meta: Vec<u8>) -> Self { assert!( width > 0, "execution trace must consist of at least one register" ); assert!( width <= TraceInfo::MAX_TRACE_WIDTH, "execution trace width cannot be greater than {}, but was {}", TraceInfo::MAX_TRACE_WIDTH, width ); assert!( length >= TraceInfo::MIN_TRACE_LENGTH, "execution trace must be at lest {} steps long, but was {}", TraceInfo::MIN_TRACE_LENGTH, length ); assert!( length.is_power_of_two(), "execution trace length must be a power of 2" ); assert!( log2(length) as u32 <= B::TWO_ADICITY, "execution trace length cannot exceed 2^{} steps, but was 2^{}", B::TWO_ADICITY, log2(length) ); assert!( meta.len() <= TraceInfo::MAX_META_LENGTH, "number of metadata bytes cannot be greater than {}, but was {}", TraceInfo::MAX_META_LENGTH, meta.len() ); let registers = unsafe { (0..width).map(|_| uninit_vector(length)).collect() }; ExecutionTrace { trace: registers, meta, } } /// Creates a new execution trace from a list of provided register traces. /// /// The provides `registers` vector is expected to contain register traces. /// /// # Panics /// Panics if: /// * The `registers` vector is empty or has over 255 registers. /// * Number of elements in any of the registers is smaller than 8, greater than the biggest /// multiplicative subgroup in the field `B`, or is not a power of two. /// * Number of elements is not identical for all registers. pub fn init(registers: Vec<Vec<B>>) -> Self { assert!( !registers.is_empty(), "execution trace must consist of at least one register" ); assert!( registers.len() <= TraceInfo::MAX_TRACE_WIDTH, "execution trace width cannot be greater than {}, but was {}", TraceInfo::MAX_TRACE_WIDTH, registers.len() ); let trace_length = registers[0].len(); assert!( trace_length >= TraceInfo::MIN_TRACE_LENGTH, "execution trace must be at lest {} steps long, but was {}", TraceInfo::MIN_TRACE_LENGTH, trace_length ); assert!( trace_length.is_power_of_two(), "execution trace length must be a power of 2" ); assert!( log2(trace_length) as u32 <= B::TWO_ADICITY, "execution trace length cannot exceed 2^{} steps, but was 2^{}", B::TWO_ADICITY, log2(trace_length) ); for register in registers.iter() { assert_eq!( register.len(), trace_length, "all register traces must have the same length" ); } ExecutionTrace { trace: registers, meta: vec![], } } // DATA MUTATORS // -------------------------------------------------------------------------------------------- /// Updates a value in a single cell of the execution trace. /// /// Specifically, the value in the specified `register` and the specified `step` is set to the /// provide `value`. /// /// # Panics /// Panics if either `register` or `step` are out of bounds for this execution trace. pub fn set(&mut self, register: usize, step: usize, value: B) { self.trace[register][step] = value; } /// Updates metadata for this execution trace to the specified vector of bytes. /// /// # Panics /// Panics if the length of `meta` is greater than 65535; pub fn set_meta(&mut self, meta: Vec<u8>) { assert!( meta.len() <= TraceInfo::MAX_META_LENGTH, "number of metadata bytes cannot be greater than {}, but was {}", TraceInfo::MAX_META_LENGTH, meta.len() ); self.meta = meta } /// Fill all rows in the execution trace. /// /// The rows are filled by executing the provided closures as follows: /// - `init` closure is used to initialize the first row of the trace; it receives a mutable /// reference to the first state initialized to all zeros. The contents of the state are /// copied into the first row of the trace after the closure returns. /// - `update` closure is used to populate all subsequent rows of the trace; it receives two /// parameters: /// - index of the last updated row (starting with 0). /// - a mutable reference to the last updated state; the contents of the state are copied /// into the next row of the trace after the closure returns. pub fn fill<I, U>(&mut self, init: I, update: U) where I: Fn(&mut [B]), U: Fn(usize, &mut [B]), { let mut state = vec![B::ZERO; self.width()]; init(&mut state); self.update_row(0, &state); for i in 0..self.length() - 1 { update(i, &mut state); self.update_row(i + 1, &state); } } /// Updates a single row in the execution trace with provided data. pub fn update_row(&mut self, step: usize, state: &[B]) { for (register, &value) in self.trace.iter_mut().zip(state) { register[step] = value; } } // FRAGMENTS // -------------------------------------------------------------------------------------------- /// Breaks the execution trace into mutable fragments. /// /// The number of rows in each fragment will be equal to `fragment_length` parameter. The /// returned fragments can be used to update data in the trace from multiple threads. /// /// # Panics /// Panics if `fragment_length` is smaller than 2, greater than the length of the trace, /// or is not a power of two. #[cfg(not(feature = "concurrent"))] pub fn fragments( &mut self, fragment_length: usize, ) -> vec::IntoIter<ExecutionTraceFragment<B>> { self.build_fragments(fragment_length).into_iter() } /// Breaks the execution trace into mutable fragments. /// /// The number of rows in each fragment will be equal to `fragment_length` parameter. The /// returned fragments can be used to update data in the trace from multiple threads. /// /// # Panics /// Panics if `fragment_length` is smaller than 2, greater than the length of the trace, /// or is not a power of two. #[cfg(feature = "concurrent")] pub fn fragments( &mut self, fragment_length: usize, ) -> rayon::vec::IntoIter<ExecutionTraceFragment<B>> { self.build_fragments(fragment_length).into_par_iter() } /// Returns a vector of trace fragments each covering the number of steps specified by the /// `fragment_length` parameter. fn build_fragments(&mut self, fragment_length: usize) -> Vec<ExecutionTraceFragment<B>> { assert!( fragment_length >= MIN_FRAGMENT_LENGTH, "fragment length must be at least {}, but was {}", MIN_FRAGMENT_LENGTH, fragment_length ); assert!( fragment_length <= self.length(), "length of a fragment cannot exceed {}, but was {}", self.length(), fragment_length ); assert!( fragment_length.is_power_of_two(), "fragment length must be a power of 2" ); let num_fragments = self.length() / fragment_length; let mut fragment_data = (0..num_fragments).map(|_| Vec::new()).collect::<Vec<_>>(); self.trace.iter_mut().for_each(|column| { for (i, fragment) in column.chunks_mut(fragment_length).enumerate() { fragment_data[i].push(fragment); } }); fragment_data .into_iter() .enumerate() .map(|(i, data)| ExecutionTraceFragment { index: i, offset: i * fragment_length, data, }) .collect() } // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- /// Returns trace info for this execution trace. pub fn get_info(&self) -> TraceInfo { TraceInfo::with_meta(self.width(), self.length(), self.meta.clone()) } /// Returns number of registers in the trace table. pub fn width(&self) -> usize { self.trace.len() } /// Returns the number of states in this trace table. pub fn length(&self) -> usize { self.trace[0].len() } /// Returns value of the cell the specified `register` at the specified `step`. pub fn get(&self, register: usize, step: usize) -> B { self.trace[register][step] } /// Returns the entire register trace for the register at the specified index. pub fn get_register(&self, idx: usize) -> &[B] { &self.trace[idx] } /// Reads a single row of this trace at the specified `step` into the specified `target`. pub fn read_row_into(&self, step: usize, target: &mut [B]) { for (i, register) in self.trace.iter().enumerate() { target[i] = register[step]; } } /// Returns metadata associated with this execution trace. pub fn get_meta(&self) -> &[u8] { &self.meta } // VALIDATION // -------------------------------------------------------------------------------------------- /// Checks if this execution trace is valid against the specified AIR, and panics if not. /// /// NOTE: this is a very expensive operation and is intended for use only in debug mode. pub fn validate<A: Air<BaseElement = B>>(&self, air: &A) { // TODO: eventually, this should return errors instead of panicking // make sure the width align; if they don't something went terribly wrong assert_eq!( self.width(), air.trace_width(), "inconsistent trace width: expected {}, but was {}", self.width(), air.trace_width() ); // --- 1. make sure the assertions are valid ---------------------------------------------- for assertion in air.get_assertions() { assertion.apply(self.length(), |step, value| { assert!( value == self.get(assertion.register(), step), "trace does not satisfy assertion trace({}, {}) == {}", assertion.register(), step, value ); }); } // --- 2. make sure this trace satisfies all transition constraints ----------------------- // collect the info needed to build periodic values for a specific step let g = air.trace_domain_generator(); let periodic_values_polys = air.get_periodic_column_polys(); let mut periodic_values = vec![B::ZERO; periodic_values_polys.len()]; // initialize buffers to hold evaluation frames and results of constraint evaluations let mut x = B::ONE; let mut ev_frame = EvaluationFrame::new(self.width()); let mut evaluations = vec![B::ZERO; air.num_transition_constraints()]; for step in 0..self.length() - 1 { // build periodic values for (p, v) in periodic_values_polys.iter().zip(periodic_values.iter_mut()) { let num_cycles = air.trace_length() / p.len(); let x = x.exp((num_cycles as u32).into()); *v = polynom::eval(p, x); } // build evaluation frame self.read_row_into(step, ev_frame.current_mut()); self.read_row_into(step + 1, ev_frame.next_mut()); // evaluate transition constraints air.evaluate_transition(&ev_frame, &periodic_values, &mut evaluations); // make sure all constraints evaluated to ZERO for (i, &evaluation) in evaluations.iter().enumerate() { assert!( evaluation == B::ZERO, "transition constraint {} did not evaluate to ZERO at step {}", i, step ); } // update x coordinate of the domain x *= g; } } // LOW-DEGREE EXTENSION // -------------------------------------------------------------------------------------------- /// Extends all registers of the trace table to the length of the LDE domain. /// /// The extension is done by first interpolating each register into a polynomial over the /// trace domain, and then evaluating the polynomial over the LDE domain. pub fn extend(mut self, domain: &StarkDomain<B>) -> (TraceTable<B>, TracePolyTable<B>) { assert_eq!( self.length(), domain.trace_length(), "inconsistent trace length" ); // build and cache trace twiddles for FFT interpolation; we do it here so that we // don't have to rebuild these twiddles for every register. let inv_twiddles = fft::get_inv_twiddles::<B>(domain.trace_length()); // extend all registers; the extension procedure first interpolates register traces into // polynomials (in-place), then evaluates these polynomials over a larger domain, and // then returns extended evaluations. let extended_trace = iter_mut!(self.trace) .map(|register_trace| extend_register(register_trace, domain, &inv_twiddles)) .collect(); ( TraceTable::new(extended_trace, domain.trace_to_lde_blowup()), TracePolyTable::new(self.trace), ) } } // TRACE FRAGMENTS // ================================================================================================ /// A set of consecutive rows of an execution trace. /// /// An execution trace fragment is a "view" into the specific execution trace. Updating data in /// the fragment, directly updates the data in the underlying execution trace. /// /// A fragment cannot be instantiated directly but is created by executing /// [ExecutionTrace::fragments()] method. /// /// A fragment always contains contiguous rows, and the number of rows is guaranteed to be a power /// of two. pub struct ExecutionTraceFragment<'a, B: StarkField> { index: usize, offset: usize, data: Vec<&'a mut [B]>, } impl<'a, B: StarkField> ExecutionTraceFragment<'a, B> { // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- /// Returns the index of this fragment. pub fn index(&self) -> usize { self.index } /// Returns the step at which the fragment starts in the context of the original execution /// trace. pub fn offset(&self) -> usize { self.offset } /// Returns the number of rows in this execution trace fragment. pub fn length(&self) -> usize { self.data[0].len() } /// Returns the width of the fragment (same as the width of the underlying execution trace). pub fn width(&self) -> usize { self.data.len() } // DATA MUTATORS // -------------------------------------------------------------------------------------------- /// Fills all rows in the fragment. /// /// The rows are filled by executing the provided closures as follows: /// - `init` closure is used to initialize the first row of the fragment; it receives a /// mutable reference to the first state initialized to all zeros. Contents of the state are /// copied into the first row of the fragment after the closure returns. /// - `update` closure is used to populate all subsequent rows of the fragment; it receives two /// parameters: /// - index of the last updated row (starting with 0). /// - a mutable reference to the last updated state; the contents of the state are copied /// into the next row of the fragment after the closure returns. pub fn fill<I, T>(&mut self, init_state: I, update_state: T) where I: Fn(&mut [B]), T: Fn(usize, &mut [B]), { let mut state = vec![B::ZERO; self.width()]; init_state(&mut state); self.update_row(0, &state); for i in 0..self.length() - 1 { update_state(i, &mut state); self.update_row(i + 1, &state); } } /// Updates a single row in the fragment with provided data. pub fn update_row(&mut self, row_idx: usize, row_data: &[B]) { for (column, &value) in self.data.iter_mut().zip(row_data) { column[row_idx] = value; } } } // HELPER FUNCTIONS // ================================================================================================ #[inline(always)] fn extend_register<B: StarkField>( trace: &mut [B], domain: &StarkDomain<B>, inv_twiddles: &[B], ) -> Vec<B> { let domain_offset = domain.offset(); let twiddles = domain.trace_twiddles(); let blowup_factor = domain.trace_to_lde_blowup(); // interpolate register trace into a polynomial; we do this over the un-shifted trace_domain fft::interpolate_poly(trace, inv_twiddles); // evaluate the polynomial over extended domain; the domain may be shifted by the // domain_offset fft::evaluate_poly_with_offset(trace, twiddles, domain_offset, blowup_factor) }
macro_rules! add_from { ($ctor:ident, $type:ty) => { impl From<$type> for $crate::defaults::SudoDefault { fn from(value: $type) -> Self { $crate::defaults::SudoDefault::$ctor(value.into()) } } }; ($ctor:ident, $type:ty, negatable$(, $vetting_function:expr)?) => { impl From<$type> for $crate::defaults::SudoDefault { fn from(value: $type) -> Self { $crate::defaults::SudoDefault::$ctor(OptTuple { default: value.into(), negated: None, }$(, $vetting_function)?) } } impl From<($type, $type)> for $crate::defaults::SudoDefault { fn from((value, neg): ($type, $type)) -> Self { $crate::defaults::SudoDefault::$ctor(OptTuple { default: value.into(), negated: Some(neg.into()), }$(, $vetting_function)?) } } }; } macro_rules! sliceify { ([$($value:tt),*]) => { &[$($value),*][..] }; ($value:tt) => { ($value) }; } macro_rules! tupleify { ($fst:expr, $snd:expr) => { ($fst, $snd) }; ($value:tt) => { $value }; } macro_rules! optional { () => { |x| x }; ($block: block) => { $block }; } macro_rules! defaults { ($($name:ident = $value:tt $((!= $negate:tt))? $([$($key:ident),*])? $([$first:literal ..= $last:literal$(; radix: $radix: expr)?])? $({$fn: expr})?)*) => { pub const ALL_PARAMS: &'static [&'static str] = &[ $(stringify!($name)),* ]; // because of the nature of radix and ranges, 'let mut result' is not always necessary, and // a radix of 10 can also not always be avoided (and for uniformity, I would also not avoid this // if this was hand-written code. #[allow(unused_mut)] #[allow(clippy::from_str_radix_10)] pub fn sudo_default(var: &str) -> Option<SudoDefault> { add_from!(Flag, bool); add_from!(Integer, i64, negatable, |text| i64::from_str_radix(text, 10).ok()); add_from!(Text, &'static str, negatable); add_from!(Text, Option<&'static str>, negatable); add_from!(List, &'static [&'static str]); add_from!(Enum, StrEnum<'static>, negatable); Some( match var { $(stringify!($name) => { let restrict = optional![$({ let keys = &[$(stringify!($key)),*]; |key: &'static str| StrEnum::new(key, keys).unwrap_or_else(|| unreachable!()) })?]; let datum = restrict(sliceify!($value)); let mut result = tupleify!(datum$(, restrict($negate))?).into(); $( if let SudoDefault::Integer(_, ref mut checker) = &mut result { *checker = |text| i64::from_str_radix(text, 10$(*0 + $radix)?).ok().filter(|val| ($first ..= $last).contains(val)); } )? $( if let SudoDefault::Integer(_, ref mut checker) = &mut result { *checker = $fn } )? result }, )* _ => return None } ) } }; } pub(super) use add_from; pub(super) use defaults; pub(super) use optional; pub(super) use sliceify; pub(super) use tupleify;
mod engine; mod fuel_tank; pub mod player; pub use self::{engine::Engine, fuel_tank::FuelTank}; use amethyst::ecs::prelude::{Component, VecStorage}; /// This component is meant for player entities. #[derive(Debug, Clone, Copy)] pub struct PlayerBase { pub id: usize, } impl Component for PlayerBase { type Storage = VecStorage<Self,>; } /// This component is meant for npc entities. #[derive(Debug, Clone, Copy)] pub struct NPCBase { pub id: usize, } impl Component for NPCBase { type Storage = VecStorage<Self,>; } /// A resource to generate new player and NPC tags with correct, unique IDs. /// Can run out of IDs, since no tracking regarding freed NPC or Player IDs happens. /// The lowest valid ID is `1`, `0` is an invalid ID. #[derive(Debug, Default)] pub struct TagGenerator { player_count: usize, npc_count: usize, } impl TagGenerator { pub fn new_player_tag(&mut self) -> PlayerBase { self.player_count += 1; PlayerBase { id: self.player_count, } } /// TODO: Use when NPC's introduced #[allow(dead_code)] pub fn new_npc_tag(&mut self) -> NPCBase { self.npc_count += 1; NPCBase { id: self.npc_count, } } }
fn scope_stuff() { println!("OUTER --"); let outer = 15; println!("outer = {}", outer); { println!("-- INNER --"); let inner = 134; let outer = 136.5555_f32; // <-- Shadows other binding println!("-- inner = {}", inner); println!("-- outer = {}", outer); } println!("OUTER --"); println!("outer = {}", outer); let outer = "some_string"; println!("outer = {}", outer); // <-- Shadows other binding } fn declaration() { let binding; { let x = 15; binding = x * x; } println!("First binding: {}", binding); // Use of uninitialized bindings won't compile. let _another; } fn main() { scope_stuff(); declaration(); }
import std::{str, map, uint, int, option}; import std::map::hashmap; import std::option::{none, some}; import syntax::ast; import ast::{ty, pat, lit, path}; import syntax::codemap::{codemap, span}; import syntax::visit; import std::io::{stdout, str_writer, string_writer}; import syntax::print; import print::pprust::{print_block, print_item, print_expr, print_path, print_decl, print_fn, print_type, print_literal}; import print::pp::mk_printer; type flag = hashmap<str, ()>; fn def_eq(a: ast::def_id, b: ast::def_id) -> bool { ret a.crate == b.crate && a.node == b.node; } fn hash_def(d: ast::def_id) -> uint { let h = 5381u; h = (h << 5u) + h ^ (d.crate as uint); h = (h << 5u) + h ^ (d.node as uint); ret h; } fn new_def_hash<@V>() -> std::map::hashmap<ast::def_id, V> { let hasher: std::map::hashfn<ast::def_id> = hash_def; let eqer: std::map::eqfn<ast::def_id> = def_eq; ret std::map::mk_hashmap::<ast::def_id, V>(hasher, eqer); } fn field_expr(f: ast::field) -> @ast::expr { ret f.node.expr; } fn field_exprs(fields: [ast::field]) -> [@ast::expr] { let es = []; for f: ast::field in fields { es += [f.node.expr]; } ret es; } fn log_expr(e: ast::expr) { log print::pprust::expr_to_str(@e); } fn log_expr_err(e: ast::expr) { log_err print::pprust::expr_to_str(@e); } fn log_ty_err(t: @ty) { log_err print::pprust::ty_to_str(t); } fn log_pat_err(p: @pat) { log_err print::pprust::pat_to_str(p); } fn log_block(b: ast::blk) { log print::pprust::block_to_str(b); } fn log_block_err(b: ast::blk) { log_err print::pprust::block_to_str(b); } fn log_item_err(i: @ast::item) { log_err print::pprust::item_to_str(i); } fn log_fn(f: ast::_fn, name: ast::ident, params: [ast::ty_param]) { log print::pprust::fun_to_str(f, name, params); } fn log_fn_err(f: ast::_fn, name: ast::ident, params: [ast::ty_param]) { log_err print::pprust::fun_to_str(f, name, params); } fn log_stmt(st: ast::stmt) { log print::pprust::stmt_to_str(st); } fn log_stmt_err(st: ast::stmt) { log_err print::pprust::stmt_to_str(st); } fn has_nonlocal_exits(b: ast::blk) -> bool { let has_exits = @mutable false; fn visit_expr(flag: @mutable bool, e: @ast::expr) { alt e.node { ast::expr_break. { *flag = true; } ast::expr_cont. { *flag = true; } _ { } } } let v = visit::mk_simple_visitor(@{visit_expr: bind visit_expr(has_exits, _) with *visit::default_simple_visitor()}); visit::visit_block(b, (), v); ret *has_exits; } fn local_rhs_span(l: @ast::local, def: span) -> span { alt l.node.init { some(i) { ret i.expr.span; } _ { ret def; } } } fn lit_eq(l: @ast::lit, m: @ast::lit) -> bool { alt l.node { ast::lit_str(s) { alt m.node { ast::lit_str(t) { ret s == t } _ { ret false; } } } ast::lit_char(c) { alt m.node { ast::lit_char(d) { ret c == d; } _ { ret false; } } } ast::lit_int(i) { alt m.node { ast::lit_int(j) { ret i == j; } _ { ret false; } } } ast::lit_uint(i) { alt m.node { ast::lit_uint(j) { ret i == j; } _ { ret false; } } } ast::lit_mach_int(_, i) { alt m.node { ast::lit_mach_int(_, j) { ret i == j; } _ { ret false; } } } ast::lit_float(s) { alt m.node { ast::lit_float(t) { ret s == t; } _ { ret false; } } } ast::lit_mach_float(_, s) { alt m.node { ast::lit_mach_float(_, t) { ret s == t; } _ { ret false; } } } ast::lit_nil. { alt m.node { ast::lit_nil. { ret true; } _ { ret false; } } } ast::lit_bool(b) { alt m.node { ast::lit_bool(c) { ret b == c; } _ { ret false; } } } } } tag call_kind { kind_call; kind_spawn; kind_bind; kind_for_each; } fn call_kind_str(c: call_kind) -> str { alt c { kind_call. { "Call" } kind_spawn. { "Spawn" } kind_bind. { "Bind" } kind_for_each. { "For-Each" } } } fn is_main_name(path: [ast::ident]) -> bool { str::eq(option::get(std::vec::last(path)), "main") } // FIXME mode this to std::float when editing the stdlib no longer // requires a snapshot fn float_to_str(num: float, digits: uint) -> str { let accum = if num < 0.0 { num = -num; "-" } else { "" }; let trunc = num as uint; let frac = num - (trunc as float); accum += uint::str(trunc); if frac == 0.0 || digits == 0u { ret accum; } accum += "."; while digits > 0u && frac > 0.0 { frac *= 10.0; let digit = frac as uint; accum += uint::str(digit); frac -= digit as float; digits -= 1u; } ret accum; } // // Local Variables: // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: //
#[doc = "Reader of register LE_PING_TIMER_ADDR"] pub type R = crate::R<u32, super::LE_PING_TIMER_ADDR>; #[doc = "Writer for register LE_PING_TIMER_ADDR"] pub type W = crate::W<u32, super::LE_PING_TIMER_ADDR>; #[doc = "Register LE_PING_TIMER_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::LE_PING_TIMER_ADDR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CONN_PING_TIMER_ADDR`"] pub type CONN_PING_TIMER_ADDR_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CONN_PING_TIMER_ADDR`"] pub struct CONN_PING_TIMER_ADDR_W<'a> { w: &'a mut W, } impl<'a> CONN_PING_TIMER_ADDR_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 & !0xffff) | ((value as u32) & 0xffff); self.w } } impl R { #[doc = "Bits 0:15 - The register used to configure the LE Au-thenticated payload Timeout (LE APTO) which is the Maximum amount of time specified between packets authenticated by a MIC. This value of ping timer is in the order of 10ms, valid range 0x1 ~ 0xFFFF"] #[inline(always)] pub fn conn_ping_timer_addr(&self) -> CONN_PING_TIMER_ADDR_R { CONN_PING_TIMER_ADDR_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - The register used to configure the LE Au-thenticated payload Timeout (LE APTO) which is the Maximum amount of time specified between packets authenticated by a MIC. This value of ping timer is in the order of 10ms, valid range 0x1 ~ 0xFFFF"] #[inline(always)] pub fn conn_ping_timer_addr(&mut self) -> CONN_PING_TIMER_ADDR_W { CONN_PING_TIMER_ADDR_W { w: self } } }
#![cfg_attr(feature = "strict", deny(warnings))] #![warn( clippy::print_stderr, clippy::print_stdout, clippy::unwrap_used, clippy::wildcard_imports )] mod completion; mod composition; mod diagnostics; mod lang; mod lsp; mod server; mod visitors; #[cfg(feature = "wasm")] mod wasm; #[cfg(test)] #[macro_use] extern crate pretty_assertions; pub use server::LspServer; #[macro_export] macro_rules! walk_ast_package { ($visitor:expr, $package:expr) => {{ let mut visitor = $visitor; flux::ast::walk::walk( &mut visitor, flux::ast::walk::Node::Package(&$package), ); visitor }}; } #[macro_export] macro_rules! walk_semantic_package { ($visitor:expr, $package:ident) => {{ let mut visitor_instance = $visitor; flux::semantic::walk::walk( &mut visitor_instance, flux::semantic::walk::Node::Package(&$package), ); visitor_instance }}; }
use std::{sync::Arc, time::Duration}; use bson::doc; use crate::{ error::Result, event::{ cmap::{CmapEvent, CmapEventHandler, ConnectionCheckoutFailedReason}, command::CommandEventHandler, }, runtime, runtime::AsyncJoinHandle, test::{ log_uncaptured, spec::{unified_runner::run_unified_tests, v2_runner::run_v2_tests}, Event, EventHandler, FailCommandOptions, FailPoint, FailPointMode, TestClient, CLIENT_OPTIONS, }, }; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_legacy() { run_v2_tests(&["retryable-reads", "legacy"]).await; } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_unified() { run_unified_tests(&["retryable-reads", "unified"]).await; } /// Test ensures that the connection used in the first attempt of a retry is released back into the /// pool before the second attempt. #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn retry_releases_connection() { let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.hosts.drain(1..); client_options.retry_reads = Some(true); client_options.max_pool_size = Some(1); let client = TestClient::with_options(Some(client_options)).await; if !client.supports_fail_command() { log_uncaptured("skipping retry_releases_connection due to failCommand not being supported"); return; } let collection = client .database("retry_releases_connection") .collection("retry_releases_connection"); collection.insert_one(doc! { "x": 1 }, None).await.unwrap(); // Use a connection error to ensure streaming monitor checks get cancelled. Otherwise, we'd have // to wait for the entire heartbeatFrequencyMS before the find succeeds. let options = FailCommandOptions::builder().close_connection(true).build(); let failpoint = FailPoint::fail_command(&["find"], FailPointMode::Times(1), Some(options)); let _fp_guard = client.enable_failpoint(failpoint, None).await.unwrap(); runtime::timeout(Duration::from_secs(1), collection.find_one(doc! {}, None)) .await .expect("operation should not time out") .expect("find should succeed"); } /// Prose test from retryable reads spec verifying that PoolClearedErrors are retried. #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn retry_read_pool_cleared() { let handler = Arc::new(EventHandler::new()); let mut client_options = CLIENT_OPTIONS.get().await.clone(); client_options.retry_reads = Some(true); client_options.max_pool_size = Some(1); client_options.cmap_event_handler = Some(handler.clone() as Arc<dyn CmapEventHandler>); client_options.command_event_handler = Some(handler.clone() as Arc<dyn CommandEventHandler>); // on sharded clusters, ensure only a single mongos is used if client_options.repl_set_name.is_none() { client_options.hosts.drain(1..); } let client = TestClient::with_options(Some(client_options.clone())).await; if !client.supports_block_connection() { log_uncaptured( "skipping retry_read_pool_cleared due to blockConnection not being supported", ); return; } if client.is_load_balanced() { log_uncaptured("skipping retry_read_pool_cleared due to load-balanced topology"); return; } let collection = client .database("retry_read_pool_cleared") .collection("retry_read_pool_cleared"); collection.insert_one(doc! { "x": 1 }, None).await.unwrap(); let options = FailCommandOptions::builder() .error_code(91) .block_connection(Duration::from_secs(1)) .build(); let failpoint = FailPoint::fail_command(&["find"], FailPointMode::Times(1), Some(options)); let _fp_guard = client.enable_failpoint(failpoint, None).await.unwrap(); let mut subscriber = handler.subscribe(); let mut tasks: Vec<AsyncJoinHandle<_>> = Vec::new(); for _ in 0..2 { let coll = collection.clone(); let task = runtime::spawn(async move { coll.find_one(doc! {}, None).await }); tasks.push(task); } futures::future::join_all(tasks) .await .into_iter() .collect::<Result<Vec<_>>>() .expect("all should succeed"); let _ = subscriber .wait_for_event(Duration::from_millis(500), |event| { matches!(event, Event::Cmap(CmapEvent::ConnectionCheckedOut(_))) }) .await .expect("first checkout should succeed"); let _ = subscriber .wait_for_event(Duration::from_millis(500), |event| { matches!(event, Event::Cmap(CmapEvent::PoolCleared(_))) }) .await .expect("pool clear should occur"); let next_cmap_events = subscriber .collect_events(Duration::from_millis(1000), |event| match event { Event::Cmap(_) => true, _ => false, }) .await; if !next_cmap_events.iter().any(|event| match event { Event::Cmap(CmapEvent::ConnectionCheckoutFailed(e)) => { matches!(e.reason, ConnectionCheckoutFailedReason::ConnectionError) } _ => false, }) { panic!( "Expected second checkout to fail, but no ConnectionCheckoutFailed event observed. \ CMAP events:\n{:?}", next_cmap_events ); } assert_eq!(handler.get_command_started_events(&["find"]).len(), 3); }
// cargo-deps: rand // A simple allocator built using an implicit free list. // (See also: stjepang/vec-arena) // // Compile this using either "rustc --test" or "cargo script". #[cfg(not(test))] extern crate rand; #[derive(Clone, Debug)] pub struct Pool<T> { pub slots: Vec<Result<T, usize>>, pub len: usize, pub next: usize, } impl<T> Default for Pool<T> { fn default() -> Self { Self { slots: Default::default(), len: Default::default(), next: Default::default(), } } } impl<T> Pool<T> { pub fn len(&self) -> usize { self.len } pub fn capacity(&self) -> usize { self.slots.len() } pub fn get(&self, index: usize) -> Option<&T> { match self.slots.get(index) { Some(&Ok(ref item)) => Some(item), _ => None, } } pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { match self.slots.get_mut(index) { Some(&mut Ok(ref mut item)) => Some(item), _ => None, } } pub fn insert(&mut self, item: T) -> usize { let idx = self.next; loop { match self.slots.get_mut(idx) { None => {} Some(slot) => match std::mem::replace(slot, Ok(item)) { Err(next) => { self.next = next; break; }, Ok(_) => unreachable!(), } } let len = self.slots.len(); self.slots.push(Err(len + 1)); } self.len += 1; idx } pub fn remove(&mut self, index: usize) -> Option<T> { match self.slots.get_mut(index) { None => None, Some(slot) => { if let Err(_) = *slot { return None; } let empty = Err(self.next); self.next = index; self.len -= 1; std::mem::replace(slot, empty).ok() } } } } #[test] fn test() { let mut pool = Pool::default(); println!("{:?}", pool); assert_eq!(pool.insert(":3"), 0); println!("{:?}", pool); assert_eq!(pool.insert(":D"), 1); println!("{:?}", pool); assert_eq!(pool.remove(0), Some(":3")); println!("{:?}", pool); assert_eq!(pool.remove(1), Some(":D")); println!("{:?}", pool); assert_eq!(pool.insert(":o"), 1); println!("{:?}", pool); assert_eq!(pool.insert(":P"), 0); println!("{:?}", pool); } #[cfg(not(test))] fn main() { use rand::Rng; let mut rng = rand::thread_rng(); let mut pool = Pool::default(); let mut decimate = false; // every so often, decimate the entire pool loop { let mut changed = false; if rng.gen_range(0, pool.capacity() + 10) == 0 { decimate = true; } if !decimate && rng.gen_range(0, 2) == 0 { pool.insert(""); changed = true; } else if pool.len() == 0 { decimate = false; } else { let i = rng.gen_range(0, pool.capacity()); if pool.remove(i).is_some() { changed = true; } } if changed { if decimate { print!("- ") } else { print!("+ ") } print!("({:02}) ", pool.next); for slot in &pool.slots { match *slot { Ok(_) => print!(" . "), Err(i) => print!("{:02} ", i), } } println!(""); // std::thread::sleep(std::time::Duration::from_millis(100)); } } } // rustc -C llvm-args=-x86-asm-syntax=intel --emit asm -O pool.rs // // extern fn pool_remove(p: &mut Pool<*mut u8>, i: usize, r: &mut Option<*mut u8>) { // *r = p.remove(i) // } // // extern { fn register(cb: extern fn(p: &mut Pool<*mut u8>, i: usize, r: &mut Option<*mut u8>)); } // // fn main() { // unsafe { register(pool_remove) } // }
#[doc = "Reader of register INTR_CAUSE2"] pub type R = crate::R<u32, super::INTR_CAUSE2>; #[doc = "Reader of field `PORT_INT`"] pub type PORT_INT_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Each IO port has an associated bit field in this register. The bit field reflects the IO port's interrupt line (bit field i reflects 'gpio_interrupts\\[i\\]' for IO port i). The register is used when the system uses a combined interrupt line 'gpio_interrupt'. The software ISR reads the register to deternine which IO port(s) is responsible for the combined interrupt line. Once, the IO port(s) is determined, the IO port's GPIO_PORT_INTR register is read to determine the IO pin(s) in the IO port that caused the interrupt. '0': Port has no pending interrupt '1': Port has pending interrupt"] #[inline(always)] pub fn port_int(&self) -> PORT_INT_R { PORT_INT_R::new((self.bits & 0xffff_ffff) as u32) } }
// just a one element tuple, wrapper around List // this is whats called a tuple struct pub struct IntoIter<T>(List<T>); pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } pub struct IterMut<'a, T> { next: Option<&'a mut Node<T>>, } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { // have to do take() because a mutable reference isnt copyable, unline a normal reference // this takes out the value form self.next and puts it in x and then make self.next = // x.next and returns a mutable ref to x.elem self.next.take().map(|x| { self.next = x.next.as_deref_mut(); &mut x.elem }) } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.next.map(|x| { // as_deref wiil give access to reference to the type of option I guess , self.next is // Option<&'a Node<T>> , map will change &'a Node<T> to // something else, it gets changes to &x.elem and also // next ptr is updated to x.next self.next = x.next.as_deref(); // // Another way of doing the same thing // self.next = x.next.as_ref().map(|y| &**y); // // another way is with turbofish, rust can insert as many // *'s as it wants to make the types match // self.next = x.next.as_ref().map::<&Node<T>, _>(|y| &y); // &x.elem }) } } pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { let new_node = Box::new(Node { elem, next: self.head.take(), }); self.head = Some(new_node); } pub fn pop(&mut self) -> Option<T> { match self.head.take() { None => None, Some(node) => { self.head = node.next; Some(node.elem) } } } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|x| &x.elem) } pub fn peek_mut(&mut self) -> Option<&mut T> { self.head.as_mut().map(|x| &mut x.elem) } pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } // no need for lifetimes here, as it has only one reference as input and one reference as // output, so the compiler itself adds the lifetime here, // it's implicit // if it had more than one reference as input, it would require lifetime annotations, if the // compiler got confused that is pub fn iter<'a>(&'a self) -> Iter<'a, T> { Iter { // // next: self.head.as_deref(), // the below match does the same exact thing as this next: match &(self.head) { // or self.head.as_ref() Some(x) => Some(&**x), None => None, }, } } pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { IterMut { next: self.head.as_deref_mut(), } } } impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } impl<T> Drop for List<T> { fn drop(&mut self) { let mut cur_link = self.head.take(); while let Some(mut node) = cur_link { // cur_link = node.next and the current value will go // out of scope cur_link = node.next.take(); } } } #[cfg(test)] mod test { use std::str::FromStr; use super::List; #[test] fn basics() { let mut list = List::new(); assert_eq!(list.pop(), None); // Push some more just to make sure nothing's corrupted list.push(4); list.push(5); // Check normal removal assert_eq!(list.pop(), Some(5)); assert_eq!(list.pop(), Some(4)); // Check exhaustion assert_eq!(list.pop(), None); } #[test] fn peek() { let mut list = List::new(); assert_eq!(list.peek(), None); list.push(10); assert_eq!(list.peek(), Some(&10)); list.push(11); assert_eq!(list.peek(), Some(&11)); assert_eq!(list.peek_mut(), Some(&mut 11)); let x = list.peek_mut(); drop(x); list.peek_mut().map(|x| *x = 10); assert_eq!(list.peek(), Some(&10)); list.push(100); } #[test] fn into_iter() { let mut list = List::new(); list.push(1); list.push(2); let mut x = list.into_iter(); assert_eq!(x.next(), Some(2)); assert_eq!(x.next(), Some(1)); let mut list2 = List::new(); list2.push(String::from_str("Hi").unwrap()); list2.push(String::from_str("Hello").unwrap()); let mut y = list2.into_iter(); assert_eq!(y.next().as_deref(), Some("Hello")); assert_eq!(y.next().as_deref(), Some("Hi")); } #[test] fn iter() { let mut list = List::new(); list.push(1); list.push(2); let mut x = list.iter(); assert_eq!(x.next(), Some(&2)); assert_eq!(x.next(), Some(&1)); let mut list2 = List::new(); list2.push(String::from_str("Hi").unwrap()); list2.push(String::from_str("Hello").unwrap()); let mut y = list2.iter(); assert_eq!(y.next().map(|x| x.as_ref()), Some("Hello")); assert_eq!(y.next().map(|x| x.as_ref()), Some("Hi")); } #[test] fn iter_mut() { let mut list = List::new(); list.push(1); list.push(2); let mut x = list.iter_mut(); assert_eq!(x.next(), Some(&mut 2)); assert_eq!(x.next(), Some(&mut 1)); let mut list2 = List::new(); list2.push(String::from_str("Hi").unwrap()); list2.push(String::from_str("Hello").unwrap()); let mut y = list2.iter_mut(); assert_eq!(y.next(), Some(&mut String::from_str("Hello").unwrap())); assert_eq!(y.next(), Some(&mut String::from_str("Hi").unwrap())); } }
//! Provides utility functions for generating data sequences use crate::euclid::Modulus; use std::f64::consts; /// Generates a base 10 log spaced vector of the given length between the /// specified decade exponents (inclusive). Equivalent to MATLAB logspace /// /// # Examples /// /// ``` /// use statrs::generate; /// /// let x = generate::log_spaced(5, 0.0, 4.0); /// assert_eq!(x, [1.0, 10.0, 100.0, 1000.0, 10000.0]); /// ``` pub fn log_spaced(length: usize, start_exp: f64, stop_exp: f64) -> Vec<f64> { match length { 0 => Vec::new(), 1 => vec![10f64.powf(stop_exp)], _ => { let step = (stop_exp - start_exp) / (length - 1) as f64; let mut vec = (0..length) .map(|x| 10f64.powf(start_exp + (x as f64) * step)) .collect::<Vec<f64>>(); vec[length - 1] = 10f64.powf(stop_exp); vec } } } /// Infinite iterator returning floats that form a periodic wave pub struct InfinitePeriodic { amplitude: f64, step: f64, phase: f64, k: f64, } impl InfinitePeriodic { /// Constructs a new infinite periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfinitePeriodic; /// /// let x = InfinitePeriodic::new(8.0, 2.0, 10.0, 1.0, /// 2).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, [6.0, 8.5, 1.0, 3.5, 6.0, 8.5, 1.0, 3.5, 6.0, 8.5]); /// ``` pub fn new( sampling_rate: f64, frequency: f64, amplitude: f64, phase: f64, delay: i64, ) -> InfinitePeriodic { let step = frequency / sampling_rate * amplitude; InfinitePeriodic { amplitude, step, phase: (phase - delay as f64 * step).modulus(amplitude), k: 0.0, } } /// Constructs a default infinite periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfinitePeriodic; /// /// let x = InfinitePeriodic::default(8.0, /// 2.0).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, [0.0, 0.25, 0.5, 0.75, 0.0, 0.25, 0.5, 0.75, 0.0, 0.25]); /// ``` pub fn default(sampling_rate: f64, frequency: f64) -> InfinitePeriodic { Self::new(sampling_rate, frequency, 1.0, 0.0, 0) } } impl Iterator for InfinitePeriodic { type Item = f64; fn next(&mut self) -> Option<f64> { let mut x = self.phase + self.k * self.step; if x >= self.amplitude { x %= self.amplitude; self.phase = x; self.k = 0.0; } self.k += 1.0; Some(x) } } /// Infinite iterator returning floats that form a sinusoidal wave pub struct InfiniteSinusoidal { amplitude: f64, mean: f64, step: f64, phase: f64, i: usize, } impl InfiniteSinusoidal { /// Constructs a new infinite sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSinusoidal; /// /// let x = InfiniteSinusoidal::new(8.0, 2.0, 1.0, 5.0, 2.0, /// 1).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, /// [5.416146836547142, 5.909297426825682, 4.583853163452858, /// 4.090702573174318, 5.416146836547142, 5.909297426825682, /// 4.583853163452858, 4.090702573174318, 5.416146836547142, /// 5.909297426825682]); /// ``` pub fn new( sampling_rate: f64, frequency: f64, amplitude: f64, mean: f64, phase: f64, delay: i64, ) -> InfiniteSinusoidal { let pi2 = consts::PI * 2.0; let step = frequency / sampling_rate * pi2; InfiniteSinusoidal { amplitude, mean, step, phase: (phase - delay as f64 * step) % pi2, i: 0, } } /// Constructs a default infinite sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSinusoidal; /// /// let x = InfiniteSinusoidal::default(8.0, 2.0, /// 1.0).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, /// [0.0, 1.0, 0.00000000000000012246467991473532, /// -1.0, -0.00000000000000024492935982947064, 1.0, /// 0.00000000000000036739403974420594, -1.0, /// -0.0000000000000004898587196589413, 1.0]); /// ``` pub fn default(sampling_rate: f64, frequency: f64, amplitude: f64) -> InfiniteSinusoidal { Self::new(sampling_rate, frequency, amplitude, 0.0, 0.0, 0) } } impl Iterator for InfiniteSinusoidal { type Item = f64; fn next(&mut self) -> Option<f64> { let x = self.mean + self.amplitude * (self.phase + self.i as f64 * self.step).sin(); self.i += 1; if self.i == 1000 { self.i = 0; self.phase = (self.phase + 1000.0 * self.step) % (consts::PI * 2.0); } Some(x) } } /// Infinite iterator returning floats forming a square wave starting /// with the high phase pub struct InfiniteSquare { periodic: InfinitePeriodic, high_duration: f64, high_value: f64, low_value: f64, } impl InfiniteSquare { /// Constructs a new infinite square wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSquare; /// /// let x = InfiniteSquare::new(3, 7, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// assert_eq!(x, [-1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, /// -1.0, 1.0]) /// ``` pub fn new( high_duration: i64, low_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> InfiniteSquare { let duration = (high_duration + low_duration) as f64; InfiniteSquare { periodic: InfinitePeriodic::new(1.0, 1.0 / duration, duration, 0.0, delay), high_duration: high_duration as f64, high_value, low_value, } } } impl Iterator for InfiniteSquare { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().map(|x| { if x < self.high_duration { self.high_value } else { self.low_value } }) } } /// Infinite iterator returning floats forming a triangle wave starting with /// the raise phase from the lowest sample pub struct InfiniteTriangle { periodic: InfinitePeriodic, raise_duration: f64, raise: f64, fall: f64, high_value: f64, low_value: f64, } impl InfiniteTriangle { /// Constructs a new infinite triangle wave generator /// /// # Examples /// /// ``` /// #[macro_use] /// extern crate statrs; /// /// use statrs::generate::InfiniteTriangle; /// /// # fn main() { /// let x = InfiniteTriangle::new(4, 7, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// let expected: [f64; 12] = [-0.714, -1.0, -0.5, 0.0, 0.5, 1.0, 0.714, /// 0.429, 0.143, -0.143, -0.429, -0.714]; /// for (&left, &right) in x.iter().zip(expected.iter()) { /// assert_almost_eq!(left, right, 1e-3); /// } /// # } /// ``` pub fn new( raise_duration: i64, fall_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> InfiniteTriangle { let duration = (raise_duration + fall_duration) as f64; let height = high_value - low_value; InfiniteTriangle { periodic: InfinitePeriodic::new(1.0, 1.0 / duration, duration, 0.0, delay), raise_duration: raise_duration as f64, raise: height / raise_duration as f64, fall: height / fall_duration as f64, high_value, low_value, } } } impl Iterator for InfiniteTriangle { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().map(|x| { if x < self.raise_duration { self.low_value + x * self.raise } else { self.high_value - (x - self.raise_duration) * self.fall } }) } } /// Infinite iterator returning floats forming a sawtooth wave /// starting with the lowest sample pub struct InfiniteSawtooth { periodic: InfinitePeriodic, low_value: f64, } impl InfiniteSawtooth { /// Constructs a new infinite sawtooth wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSawtooth; /// /// let x = InfiniteSawtooth::new(5, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// assert_eq!(x, [1.0, -1.0, -0.5, 0.0, 0.5, 1.0, -1.0, -0.5, 0.0, 0.5, /// 1.0, -1.0]); /// ``` pub fn new(period: i64, high_value: f64, low_value: f64, delay: i64) -> InfiniteSawtooth { let height = high_value - low_value; let period = period as f64; InfiniteSawtooth { periodic: InfinitePeriodic::new( 1.0, 1.0 / period, height * period / (period - 1.0), 0.0, delay, ), low_value: low_value as f64, } } } impl Iterator for InfiniteSawtooth { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().map(|x| x + self.low_value) } }
extern crate libc; extern crate rsnl; use libc::{c_int, c_void}; use rsnl::message::{NetlinkMessage, nl_msg, nlmsghdr}; use rsnl::message::expose::{nl_msg_ptr, nlmsghdr_ptr}; #[repr(C)] struct genlmsghdr; #[link(name="nl-genl-3")] extern "C" { fn genlmsg_valid_hdr(hdr: *const nlmsghdr, hdrlen: c_int) -> i32; fn genlmsg_hdr(hdr: *const nlmsghdr) -> *const genlmsghdr; fn genlmsg_put(msg: *const nl_msg, port: u32, seq: u32, family: c_int, hdrlen: c_int, flags: c_int, cmd: u8, version: u8) -> *const c_void; } // leaky! pub struct GenlHeader { ptr: *const genlmsghdr, } pub fn valid_hdr(msg: &NetlinkMessage, hdrlen: i32) -> i32 { let hdrptr = nlmsghdr_ptr(msg); unsafe { genlmsg_valid_hdr(hdrptr, hdrlen) } } pub fn hdr(msg: &NetlinkMessage) -> GenlHeader { GenlHeader { ptr: unsafe { genlmsg_hdr(nlmsghdr_ptr(msg)) } } } pub fn put(msg: &mut NetlinkMessage, port: u32, seq: u32, family: i32, hdrlen: i32, flags: i32, cmd: u8, version: u8) { unsafe { genlmsg_put(nl_msg_ptr(msg), port, seq, family, hdrlen, flags, cmd, version); } }
// Copyright 2019 The xi-editor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Utilities, macOS specific. use cocoa::base::{id, nil, BOOL, YES}; use cocoa::foundation::{NSAutoreleasePool, NSString}; pub fn init() {} /// Panic if not on the main thread.assert_main_thread() /// /// Many Cocoa operations are only valid on the main thread, and (I think) /// undefined behavior is possible if invoked from other threads. If so, /// failing on non main thread is necessary for safety. pub fn assert_main_thread() { unsafe { let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); assert_eq!(is_main_thread, YES); } } /// Create a new NSString from a &str. pub(crate) fn make_nsstring(s: &str) -> id { unsafe { NSString::alloc(nil).init_str(s).autorelease() } } pub(crate) fn from_nsstring(s: id) -> String { unsafe { let slice = std::slice::from_raw_parts(s.UTF8String() as *const _, s.len()); let result = std::str::from_utf8_unchecked(slice); result.into() } } /// Returns the current locale string. /// /// This should a [Unicode language identifier]. /// /// [Unicode language identifier]: https://unicode.org/reports/tr35/#Unicode_language_identifier pub fn get_locale() -> String { unsafe { let nslocale_class = class!(NSLocale); let locale: id = msg_send![nslocale_class, currentLocale]; let ident: id = msg_send![locale, localeIdentifier]; let mut locale = from_nsstring(ident); if let Some(idx) = locale.chars().position(|c| c == '@') { locale.truncate(idx); } locale } }
use std::fs; use regex::Regex; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Instruction { operation: String, argument: isize, } impl Instruction { pub fn new(operation: String, argument: isize) -> Instruction { Instruction { operation, argument } } pub fn parse(line: &str) -> Instruction { // ex "acc +6" lazy_static! { static ref INSTR: Regex = Regex::new(r"^(nop|acc|jmp) ([\-\+]\d+)$").unwrap(); } assert!(INSTR.is_match(&line)); let caps = INSTR.captures(line).unwrap(); let operation = caps.get(1).unwrap().as_str().to_string(); let argument = caps.get(2).unwrap().as_str().parse::<isize>().unwrap(); Instruction { operation, argument } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Program { pc: usize, acc: isize, code: Vec<Instruction>, run_count: Vec<usize> } impl Program { pub fn new(code: Vec<Instruction>) -> Program { let count = code.len(); Program { pc: 0, acc: 0, code: code, run_count: vec![0; count] } } // run program, returning the acc result pub fn run(&mut self) -> isize { loop { self.run_count[self.pc] += 1; //increment instuction's run count let i = &self.code[self.pc]; //println!("pc: {} - acc: {} - {:?} ", self.pc, self.acc, i); match i.operation.as_str() { "nop" => { self.pc += 1; }, "acc" => { self.acc += i.argument; self.pc += 1; }, "jmp" => { self.pc = (self.pc as isize + i.argument) as usize; }, _ => unreachable!("Invalid instruction: {:?}", i) } if self.complete() || self.looping() { break; } } self.acc } pub fn looping(&self) -> bool { self.run_count[self.pc] > 0 } pub fn complete(&self) -> bool { self.pc >= self.code.len() } pub fn corrupt_instruction(&mut self, index: usize) { let mut i = &mut self.code[index]; match i.operation.as_str() { "nop" => { i.operation = String::from("jmp") }, "jmp" => { i.operation = String::from("nop") }, _ => unreachable!("Invalid corruption: {:?}", i) } } } pub fn day8(args: &[String]) -> i32 { println!("Day 8"); if args.len() != 1 { println!("Missing input file"); return -1; } let filename = &args[0]; println!("In file {}", filename); let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); let code: Vec<Instruction> = contents.lines().map(|l| Instruction::parse(l)).collect(); //println!("{:?}", code); let mut program = Program::new(code.clone()); println!("Part 1: {:?}", program.run()); println!("Part 2: {:?}", part2(Program::new(code.clone()))); 0 } pub fn part2(program: Program) -> isize { let corrupt_locations = program.code.iter().enumerate() .filter(|(_i, c)| c.operation == "jmp" || c.operation == "nop") .map(|(i, _c)| i) .collect::<Vec<usize>>(); for loc in corrupt_locations { //println!("Corrupting location {}", loc); let mut corrupt = program.clone(); corrupt.corrupt_instruction(loc); let acc = corrupt.run(); if corrupt.complete() { return acc; } } 0 }
use crate::object::*; use crate::object::text::Text; use crate::surface; use surface::{ Object, Surface }; use super::*; use elements::Svg; use elements::shape; fn point(l: &shape::Line) -> Point { Point::new(l.x1, l.y1) } fn line(l: &shape::Line) -> Line { line![ (l.x1, l.y1), (l.x2 - l.x1, l.y2 - l.y1) ] } fn rect(r: &shape::Rect) -> Rect { Rect::new(match (r.x, r.y) { (None, None) => (0, 0), (Some(x), None) => (x, 0), (None, Some(y)) => (0, y), (Some(x), Some(y)) => (x, y) }, r.width, r.height) } fn text(t: &shape::Text) -> Text { Text::new((t.x, t.y), &t.text) } pub fn svg(s: &Svg) -> Surface { let mut v = Vec::new(); use shape::Shape; use surface::Primitive::*; use Object::*; for s in &s.shapes { v.push( match s { Shape::Line(l) => { if l.x1 == l.x2 && l.y1 == l.y2 { continue; } else if (l.x1 - l.x2).abs() == 1 && (l.y1 - l.y2).abs() == 1 { Primitive(Point(point(l))) } else { Primitive(Line(line(l))) } }, Shape::Rect(r) => { Primitive(Rect(rect(r))) }, Shape::Text(t) => { Primitive(Text(text(t))) } } ); } Surface::from(v) } #[cfg(test)] mod tests { extern crate serde; extern crate serde_xml_rs as serde_xml; use serde_xml_rs::from_str as from; use super::*; #[test] fn point_test() { let svg = r#" <line x1="4" y1="8" x2="4" y2="8" /> "#; let p = point(&from(svg).unwrap()); assert_eq!(p, Point::new(4, 8)); } #[test] fn line_test() { let svg = r#" <line x1="0" y1="0" x2="3" y2="3" /> "#; let l = line(&from(svg).unwrap()); assert_eq!(l, line![(0, 0), (3, 3)]); } #[test] fn rect_test() { let svg = r#" <rect x="3" y="6" width="300" height="200" /> "#; let r = rect(&from(svg).unwrap()); assert_eq!(r, Rect::new((3, 6), 300, 200)); } }
use actix::prelude::*; mod client; mod codec; pub use self::client::AdsClient as Client; use std::process; use futures::{future, Future}; use std::net::ToSocketAddrs; use tokio_codec::FramedRead; use tokio_io::AsyncRead; use tokio_tcp::TcpStream; pub use self::client::*; pub use self::codec::types::*; pub use self::codec::*; pub trait ToPlcConn { fn as_plc_conn(&self) -> [u8; 8]; } impl<T> ToPlcConn for (T, u16) where T: AsRef<str>, { fn as_plc_conn(&self) -> [u8; 8] { let net_id: Vec<_> = self .0 .as_ref() .split('.') .map(|x| u8::from_str_radix(x, 10).unwrap()) .collect(); let mut d = [0u8; 8]; d[..6].clone_from_slice(&net_id[..6]); d[7] = ((self.1 >> 8) & 0xff) as u8; d[6] = (self.1 & 0xff) as u8; d } } impl ToPlcConn for [u8; 8] { fn as_plc_conn(&self) -> [u8; 8] { *self } } pub fn create_client<T: ToSocketAddrs>( addr: T, target: &impl ToPlcConn, source: &impl ToPlcConn, ) -> impl Future<Item = Addr<Client>, Error = ()> { let target = target.as_plc_conn(); let source = source.as_plc_conn(); TcpStream::connect(&addr.to_socket_addrs().unwrap().next().unwrap()) .and_then(move |stream| { future::ok(Client::create(move |ctx| { let (r, w) = stream.split(); ctx.add_stream(FramedRead::new(r, codec::AdsClientCodec)); Client::new( actix::io::FramedWrite::new(w, codec::AdsClientCodec, ctx), source, target, ) })) }) .map_err(|e| { println!("Can not connect to server: {}", e); process::exit(1) }) }
use crate::codes::*; use crate::error::*; use crate::file::*; use crate::flags::*; use crate::helpers::*; use crate::signatures::*; macro_rules! table { ($name:ident) => { #[derive(Debug, Copy, Clone, Eq)] pub struct $name<'a> { pub(crate) row: RowData<'a>, } impl<'a> Row<'a> for $name<'a> { fn new(table: &Table<'a>, index: u32) -> Self { Self { row: RowData { table: *table, index } } } } impl<'a> PartialEq for $name<'a> { fn eq(&self, other: &Self) -> bool { self.row.index == other.row.index && self.row.table.file == other.row.table.file } } }; } table!(Constant); table!(CustomAttribute); table!(Field); table!(GenericParam); table!(InterfaceImpl); table!(MemberRef); table!(MethodDef); table!(Param); table!(TypeDef); table!(TypeRef); table!(TypeSpec); #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ConstantValue { I32(i32), U32(u32), } impl std::fmt::Display for ConstantValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ConstantValue::U32(value) => write!(f, "{}", value), ConstantValue::I32(value) => write!(f, "{}", value), } } } impl<'a> Constant<'a> { pub fn value(&self) -> ParseResult<ConstantValue> { match self.row.u32(0)? { 0x08 => Ok(ConstantValue::I32(*self.row.blob_as::<i32>(2)?)), 0x09 => Ok(ConstantValue::U32(*self.row.blob_as::<u32>(2)?)), _ => Err(ParseError::InvalidFile), } } } impl<'a> CustomAttribute<'a> { pub fn parent(&self) -> ParseResult<HasCustomAttribute> { Ok(HasCustomAttribute::decode(&self.row.table, self.row.u32(0)?)?) } pub fn constructor(&self) -> ParseResult<CustomAttributeType> { Ok(CustomAttributeType::decode(&self.row.table, self.row.u32(1)?)?) } pub fn arguments(&'a self) -> ParseResult<Vec<(&'a str, ArgumentSig)>> { Ok(match self.constructor()? { CustomAttributeType::MethodDef(value) => ArgumentSig::new(&self.row.table, value.row.blob(4)?, self.row.blob(2)?)?, CustomAttributeType::MemberRef(value) => ArgumentSig::new(&self.row.table, value.row.blob(2)?, self.row.blob(2)?)?, }) } pub fn has_name(&self, name: &str) -> ParseResult<bool> { let (namespace, name) = split_type_name(name)?; Ok(match self.constructor()? { CustomAttributeType::MethodDef(value) => { let parent = value.parent()?; name == parent.name()? && namespace == parent.namespace()? } CustomAttributeType::MemberRef(value) => match value.parent()? { MemberRefParent::TypeDef(value) => name == value.name()? && namespace == value.namespace()?, MemberRefParent::TypeRef(value) => name == value.name()? && namespace == value.namespace()?, _ => false, }, }) } } impl<'a> Field<'a> { pub fn name(&self) -> ParseResult<&str> { self.row.str(1) } pub fn constants(&self) -> ParseResult<RowIterator<'a, Constant<'a>>> { self.row.table.file.constant(self.row.table.reader).equal_range(1, HasConstant::Field(*self).encode()) } pub fn signature(&self) -> ParseResult<TypeSig> { field_sig(self) } } impl<'a> MemberRef<'a> { pub fn parent(&self) -> ParseResult<MemberRefParent> { Ok(MemberRefParent::decode(&self.row.table, self.row.u32(0)?)?) } pub fn name(&self) -> ParseResult<&str> { self.row.str(1) } } impl<'a> MethodDef<'a> { pub fn flags(&self) -> ParseResult<MethodAttributes> { Ok(MethodAttributes(self.row.u32(2)?)) } pub fn abi_name(&self) -> ParseResult<&str> { self.row.str(3) } pub(crate) fn params(&self) -> ParseResult<RowIterator<'a, Param<'a>>> { self.row.list(5, &self.row.table.file.param(self.row.table.reader)) } pub fn parent(&self) -> ParseResult<TypeDef> { self.row.table.file.type_def(self.row.table.reader).upper_bound(6, self.row.index) } pub fn signature(&self) -> ParseResult<MethodSig> { MethodSig::new(self) } pub fn name(&self) -> ParseResult<String> { // TODO: need to account for OverloadAttribute considering that Rust doesn't support overloads. let mut source = self.abi_name()?; let mut result = String::with_capacity(source.len() + 2); if self.flags()?.special() { if source.starts_with("get_") || source.starts_with("add_") { source = &source[4..]; } else if source.starts_with("put_") { result.push_str("set_"); source = &source[4..]; } else if source.starts_with("remove_") { result.push_str("revoke_"); source = &source[7..]; } } for c in source.chars() { if c.is_uppercase() { if !result.is_empty() { result.push('_'); } for c in c.to_lowercase() { result.push(c); } } else { result.push(c); } } if result.starts_with("get_") { result.replace_range(0..4, ""); } Ok(result) } } impl<'a> Param<'a> { pub fn sequence(&self) -> ParseResult<u32> { self.row.u32(1) } pub fn name(&self) -> ParseResult<&str> { self.row.str(2) } } impl<'a> TypeDef<'a> { pub fn flags(&self) -> ParseResult<TypeAttributes> { Ok(TypeAttributes(self.row.u32(0)?)) } pub fn name(&self) -> ParseResult<&str> { self.row.str(1) } pub fn namespace(&self) -> ParseResult<&str> { self.row.str(2) } pub fn extends(&self) -> ParseResult<TypeDefOrRef> { Ok(TypeDefOrRef::decode(&self.row.table, self.row.u32(3)?)?) } pub fn fields(&self) -> ParseResult<RowIterator<'a, Field<'a>>> { self.row.list(4, &self.row.table.file.field(self.row.table.reader)) } pub fn methods(&self) -> ParseResult<RowIterator<'a, MethodDef<'a>>> { self.row.list(5, &self.row.table.file.method_def(self.row.table.reader)) } pub fn attributes(&self) -> ParseResult<RowIterator<'a, CustomAttribute<'a>>> { self.row.table.file.custom_attribute(self.row.table.reader).equal_range(0, HasCustomAttribute::TypeDef(*self).encode()) } pub fn has_attribute(&self, name: &str) -> ParseResult<bool> { for attribute in self.attributes()? { if attribute.has_name(name)? { return Ok(true); } } Ok(false) } pub fn find_attribute(&self, name: &str) -> ParseResult<CustomAttribute<'a>> { for attribute in self.attributes()? { if attribute.has_name(name)? { return Ok(attribute); } } Err(ParseError::MissingAttribute) } } impl<'a> TypeRef<'a> { pub fn name(&self) -> ParseResult<&str> { self.row.str(1) } pub fn namespace(&self) -> ParseResult<&str> { self.row.str(2) } }
#[allow(unused_imports)] use packed_simd::{ f32x16, f32x2, f32x4, f32x8, f64x2, f64x4, f64x8, i128x1, i128x2, i128x4, i16x16, i16x2, i16x32, i16x4, i16x8, i32x16, i32x2, i32x4, i32x8, i64x2, i64x4, i64x8, i8x16, i8x2, i8x32, i8x4, i8x64, i8x8, isizex2, isizex4, isizex8, m128x1, m128x2, m128x4, m16x16, m16x2, m16x32, m16x4, m16x8, m32x16, m32x2, m32x4, m32x8, m64x2, m64x4, m64x8, m8x16, m8x2, m8x32, m8x4, m8x64, m8x8, msizex2, msizex4, msizex8, u128x1, u128x2, u128x4, u16x16, u16x2, u16x32, u16x4, u16x8, u32x16, u32x2, u32x4, u32x8, u64x2, u64x4, u64x8, u8x16, u8x2, u8x32, u8x4, u8x64, u8x8, usizex2, usizex4, usizex8, }; use crate::num::single::Scalar; pub trait SimdScalar: sealed::SimdOps { const LANES: usize; type Single: Scalar<Simd = Self>; type Mask: SimdMask; fn from_array(data: [Self::Single; Self::LANES]) -> Self; fn from_single(single: Self::Single) -> Self; fn load_unaligned(slice: &[Self::Single]) -> Self; unsafe fn load_unaligned_unchecked(slice: &[Self::Single]) -> Self; fn load_aligned(slice: &[Self::Single]) -> Self; unsafe fn load_aligned_unchecked(slice: &[Self::Single]) -> Self; fn store_unaligned(self, slice: &mut [Self::Single]); unsafe fn store_unaligned_unchecked(self, slice: &mut [Self::Single]); fn store_aligned(self, slice: &mut [Self::Single]); unsafe fn store_aligned_unchecked(self, slice: &mut [Self::Single]); fn extract(self, index: usize) -> Self::Single; unsafe fn extract_unchecked(self, index: usize) -> Self::Single; fn replace(self, index: usize, new: Self::Single) -> Self; unsafe fn replace_unchecked(self, index: usize, new: Self::Single) -> Self; fn min(self, other: Self) -> Self; fn max(self, other: Self) -> Self; fn max_element(self) -> Self::Single; fn min_element(self) -> Self::Single; fn element_sum(self) -> Self::Single; fn element_product(self) -> Self::Single; fn eq(self, other: Self) -> Self::Mask; fn ne(self, other: Self) -> Self::Mask; fn ge(self, other: Self) -> Self::Mask; fn le(self, other: Self) -> Self::Mask; fn gt(self, other: Self) -> Self::Mask; fn lt(self, other: Self) -> Self::Mask; fn select_from(self, other: Self, mask: Self::Mask) -> Self; } pub trait SimdMask { const LANES: usize; fn from_value(v: bool) -> Self; fn extract(self, index: usize) -> bool; unsafe fn extract_unchecked(self, index: usize) -> bool; fn replace(self, index: usize, new: bool) -> Self; unsafe fn replace_unchecked(self, index: usize, new: bool) -> Self; fn element_and(self) -> bool; fn element_or(self) -> bool; fn element_xor(self) -> bool; fn all(self) -> bool; fn any(self) -> bool; fn none(self) -> bool; fn eq(self, other: Self) -> Self; fn ne(self, other: Self) -> Self; fn ge(self, other: Self) -> Self; fn le(self, other: Self) -> Self; fn gt(self, other: Self) -> Self; fn lt(self, other: Self) -> Self; fn select<S: SimdScalar<Mask = Self>>(self, a: S, b: S) -> S; } macro_rules! create_and_impl_simd_scalars { ($($scalar:tt, $name:tt, $packed:tt, $mask:tt, $lanes:expr, $sum:ident, $prod:ident, enabled = [$($feat:expr),*], disabled = [$($not_feat:expr),*]);*$(;)?) => { $( #[allow(non_camel_case_types)] #[cfg(all($(target_feature = $feat,)* not($(target_feature = $not_feat,)*)))] pub type $name = $packed; #[cfg(all($(target_feature = $feat,)* not($(target_feature = $not_feat,)*)))] impl $crate::num::simd::SimdScalar for $name { const LANES: usize = $lanes; type Single = $scalar; type Mask = $mask; fn from_array(data: [Self::Single; Self::LANES]) -> Self { // SAFETY: Self::LANES is always equal to $packed::lanes(), therefore // the slice is always exactly as long as it needs to be. We use an // unaligned load because we can not be certain that the `data` array // is aligned properly. unsafe { $packed::from_slice_unaligned_unchecked(&data[..]) } } fn from_single(single: Self::Single) -> Self { $packed::splat(single) } fn load_unaligned(slice: &[Self::Single]) -> Self { $packed::from_slice_unaligned(slice) } unsafe fn load_unaligned_unchecked(slice: &[Self::Single]) -> Self { $packed::from_slice_unaligned_unchecked(slice) } fn load_aligned(slice: &[Self::Single]) -> Self { $packed::from_slice_aligned(slice) } unsafe fn load_aligned_unchecked(slice: &[Self::Single]) -> Self { $packed::from_slice_aligned_unchecked(slice) } fn store_unaligned(self, slice: &mut [Self::Single]) { <$packed>::write_to_slice_unaligned(self, slice) } unsafe fn store_unaligned_unchecked(self, slice: &mut [Self::Single]) { <$packed>::write_to_slice_unaligned_unchecked(self, slice) } fn store_aligned(self, slice: &mut [Self::Single]) { <$packed>::write_to_slice_aligned(self, slice) } unsafe fn store_aligned_unchecked(self, slice: &mut [Self::Single]) { <$packed>::write_to_slice_aligned_unchecked(self, slice) } fn extract(self, index: usize) -> Self::Single { <$packed>::extract(self, index) } unsafe fn extract_unchecked(self, index: usize) -> Self::Single { <$packed>::extract_unchecked(self, index) } fn replace(self, index: usize, new: Self::Single) -> Self { <$packed>::replace(self, index, new) } unsafe fn replace_unchecked(self, index: usize, new: Self::Single) -> Self { <$packed>::replace_unchecked(self, index, new) } fn min(self, other: Self) -> Self { <$packed>::min(self, other) } fn max(self, other: Self) -> Self { <$packed>::max(self, other) } fn max_element(self) -> Self::Single { <$packed>::max_element(self) } fn min_element(self) -> Self::Single { <$packed>::min_element(self) } fn element_sum(self) -> Self::Single { <$packed>::$sum(self) } fn element_product(self) -> Self::Single { <$packed>::$prod(self) } fn eq(self, other: Self) -> Self::Mask { <$packed>::eq(self, other) } fn ne(self, other: Self) -> Self::Mask { <$packed>::ne(self, other) } fn ge(self, other: Self) -> Self::Mask { <$packed>::ge(self, other) } fn le(self, other: Self) -> Self::Mask { <$packed>::le(self, other) } fn gt(self, other: Self) -> Self::Mask { <$packed>::gt(self, other) } fn lt(self, other: Self) -> Self::Mask { <$packed>::lt(self, other) } fn select_from(self, other: Self, mask: Self::Mask) -> Self { <$mask>::select(mask, self, other) } } )* }; } macro_rules! create_and_impl_simd_masks { ($($name:tt, $packed:tt, $lanes:expr, enabled = [$($feat:expr),*], disabled = [$($not_feat:expr),*]);*$(;)?) => { $( #[allow(non_camel_case_types)] #[cfg(all($(target_feature = $feat,)* not($(target_feature = $not_feat,)*)))] type $name = $packed; #[cfg(all($(target_feature = $feat,)* not($(target_feature = $not_feat,)*)))] impl $crate::num::simd::SimdMask for $name { const LANES: usize = $lanes; fn from_value(v: bool) -> Self { $packed::splat(v) } fn extract(self, index: usize) -> bool { <$packed>::extract(self, index) } unsafe fn extract_unchecked(self, index: usize) -> bool { <$packed>::extract_unchecked(self, index) } fn replace(self, index: usize, new: bool) -> Self { <$packed>::replace(self, index, new) } unsafe fn replace_unchecked(self, index: usize, new: bool) -> Self { <$packed>::replace_unchecked(self, index, new) } fn element_and(self) -> bool { <$packed>::and(self) } fn element_or(self) -> bool { <$packed>::or(self) } fn element_xor(self) -> bool { <$packed>::xor(self) } fn all(self) -> bool { <$packed>::all(self) } fn any(self) -> bool { <$packed>::any(self) } fn none(self) -> bool { <$packed>::none(self) } fn eq(self, other: Self) -> Self { <$packed>::eq(self, other) } fn ne(self, other: Self) -> Self { <$packed>::ne(self, other) } fn ge(self, other: Self) -> Self { <$packed>::ge(self, other) } fn le(self, other: Self) -> Self { <$packed>::le(self, other) } fn gt(self, other: Self) -> Self { <$packed>::gt(self, other) } fn lt(self, other: Self) -> Self { <$packed>::lt(self, other) } fn select<S: $crate::num::simd::SimdScalar<Mask = Self>>(self, a: S, b: S) -> S { S::select_from(a, b, self) } } )* }; } create_and_impl_simd_scalars! { // i8 on x86 i8, i8s, i8x8, m8x8, 8, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; i8, i8s, i8x16, m8x16, 16, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; i8, i8s, i8x32, m8x32, 32, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; i8, i8s, i8x64, m8x64, 64, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // u8 on x86 u8, u8s, u8x8, m8x8, 8, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; u8, u8s, u8x16, m8x16, 16, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; u8, u8s, u8x32, m8x32, 32, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; u8, u8s, u8x64, m8x64, 64, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // i16 on x86 i16, i16s, i16x4, m16x4, 4, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; i16, i16s, i16x8, m16x8, 8, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; i16, i16s, i16x16, m16x16, 16, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; i16, i16s, i16x32, m16x32, 32, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // u16 on x86 u16, u16s, u16x4, m16x4, 4, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; u16, u16s, u16x8, m16x8, 8, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; u16, u16s, u16x16, m16x16, 16, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; u16, u16s, u16x32, m16x32, 32, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // i32 on x86 i32, i32s, i32x2, m32x2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; i32, i32s, i32x4, m32x4, 4, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; i32, i32s, i32x8, m32x8, 8, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; i32, i32s, i32x16, m32x16, 16, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // u32 on x86 u32, u32s, u32x2, m32x2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; u32, u32s, u32x4, m32x4, 4, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; u32, u32s, u32x8, m32x8, 8, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; u32, u32s, u32x16, m32x16, 16, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // i64 on x86 i64, i64s, i64x2, m64x2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; i64, i64s, i64x2, m64x2, 2, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; i64, i64s, i64x4, m64x4, 4, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; i64, i64s, i64x8, m64x8, 8, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // u64 on x86 u64, u64s, u64x2, m64x2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; u64, u64s, u64x2, m64x2, 2, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; u64, u64s, u64x4, m64x4, 4, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; u64, u64s, u64x8, m64x8, 8, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // i128 on x86 i128, i128s, i128x1, m128x1, 1, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; i128, i128s, i128x1, m128x1, 1, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; i128, i128s, i128x2, m128x2, 2, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; i128, i128s, i128x4, m128x4, 4, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // u128 on x86 u128, u128s, u128x1, m128x1, 1, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; u128, u128s, u128x1, m128x1, 1, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; u128, u128s, u128x2, m128x2, 2, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; u128, u128s, u128x4, m128x4, 4, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // isize on x86 isize, isizes, isizex2, msizex2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; isize, isizes, isizex2, msizex2, 2, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; isize, isizes, isizex4, msizex4, 4, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; isize, isizes, isizex8, msizex8, 8, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // usize on x86 usize, usizes, usizex2, msizex2, 2, wrapping_sum, wrapping_product, enabled = [], disabled = ["avx"]; usize, usizes, usizex2, msizex2, 2, wrapping_sum, wrapping_product, enabled = ["avx"], disabled = ["avx2"]; usize, usizes, usizex4, msizex4, 4, wrapping_sum, wrapping_product, enabled = ["avx2"], disabled = ["avx512"]; usize, usizes, usizex8, msizex8, 8, wrapping_sum, wrapping_product, enabled = ["avx512"], disabled = []; // f32 on x86 f32, f32s, f32x2, m32x2, 2, sum, product, enabled = [], disabled = ["avx"]; f32, f32s, f32x8, m32x8, 8, sum, product, enabled = ["avx"], disabled = ["avx2"]; f32, f32s, f32x8, m32x8, 8, sum, product, enabled = ["avx2"], disabled = ["avx512"]; f32, f32s, f32x16, m32x16, 16, sum, product, enabled = ["avx512"], disabled = []; // f64 on x86 f64, f64s, f64x2, m64x2, 2, sum, product, enabled = [], disabled = ["avx"]; f64, f64s, f64x4, m64x4, 4, sum, product, enabled = ["avx"], disabled = ["avx2"]; f64, f64s, f64x4, m64x4, 4, sum, product, enabled = ["avx2"], disabled = ["avx512"]; f64, f64s, f64x8, m64x8, 8, sum, product, enabled = ["avx512"], disabled = []; } create_and_impl_simd_masks! { // m8 on x86 m8s, m8x8, 8, enabled = [], disabled = ["avx"]; m8s, m8x16, 16, enabled = ["avx"], disabled = ["avx2"]; m8s, m8x32, 32, enabled = ["avx2"], disabled = ["avx512"]; m8s, m8x64, 64, enabled = ["avx512"], disabled = []; // m16 on x86 m16s, m16x4, 4, enabled = [], disabled = ["avx"]; m16s, m16x8, 8, enabled = ["avx"], disabled = ["avx2"]; m16s, m16x16, 16, enabled = ["avx2"], disabled = ["avx512"]; m16s, m16x32, 32, enabled = ["avx512"], disabled = []; // m32 on x86 m32s, m32x2, 2, enabled = [], disabled = ["avx"]; m32s, m32x4, 4, enabled = ["avx"], disabled = ["avx2"]; m32s, m32x8, 8, enabled = ["avx2"], disabled = ["avx512"]; m32s, m32x16, 16, enabled = ["avx512"], disabled = []; // m32f on x86 for AVX (Special case for floating point with AVX) // Floating point with AVX has operations that require a 256 bit // mask, but usually only 128 bit masks are generated for AVX // (Unless AVX2 is supported). Ugh. m32fs, m32x8, 8, enabled = ["avx"], disabled = ["avx2"]; // m64 on x86 m64s, m64x2, 2, enabled = [], disabled = ["avx"]; m64s, m64x2, 2, enabled = ["avx"], disabled = ["avx2"]; m64s, m64x4, 4, enabled = ["avx2"], disabled = ["avx512"]; m64s, m64x8, 8, enabled = ["avx512"], disabled = []; // m64f on x86 for AVX (Special case for floating point with AVX) // Floating point with AVX has operations that require a 256 bit // mask, but usually only 128 bit masks are generated for AVX // (Unless AVX2 is supported). Ugh. m64fs, m64x4, 4, enabled = ["avx"], disabled = ["avx2"]; // m128 on x86 m128s, m128x1, 1, enabled = [], disabled = ["avx"]; m128s, m128x1, 1, enabled = ["avx"], disabled = ["avx2"]; m128s, m128x2, 2, enabled = ["avx2"], disabled = ["avx512"]; m128s, m128x4, 4, enabled = ["avx512"], disabled = []; // msize on x86 msizes, msizex2, 2, enabled = [], disabled = ["avx"]; msizes, msizex2, 2, enabled = ["avx"], disabled = ["avx2"]; msizes, msizex4, 4, enabled = ["avx2"], disabled = ["avx512"]; msizes, msizex8, 8, enabled = ["avx512"], disabled = []; } mod sealed { use std::{ fmt::Debug, ops::{ Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Sub, SubAssign, }, }; use packed_simd::{ f32x16, f32x2, f32x4, f32x8, f64x2, f64x4, f64x8, i128x1, i128x2, i128x4, i16x16, i16x2, i16x32, i16x4, i16x8, i32x16, i32x2, i32x4, i32x8, i64x2, i64x4, i64x8, i8x16, i8x2, i8x32, i8x4, i8x64, i8x8, isizex2, isizex4, isizex8, m128x1, m128x2, m128x4, m16x16, m16x2, m16x32, m16x4, m16x8, m32x16, m32x2, m32x4, m32x8, m64x2, m64x4, m64x8, m8x16, m8x2, m8x32, m8x4, m8x64, m8x8, msizex2, msizex4, msizex8, u128x1, u128x2, u128x4, u16x16, u16x2, u16x32, u16x4, u16x8, u32x16, u32x2, u32x4, u32x8, u64x2, u64x4, u64x8, u8x16, u8x2, u8x32, u8x4, u8x64, u8x8, usizex2, usizex4, usizex8, }; pub trait SimdOps: Copy + Clone + Debug + Add<Output = Self> + AddAssign + Div<Output = Self> + DivAssign + Mul<Output = Self> + MulAssign + Rem<Output = Self> + RemAssign + Sub<Output = Self> + SubAssign { } pub trait SimdMaskOps: Copy + Clone + Debug + BitAnd<Output = Self> + BitAndAssign + BitOr<Output = Self> + BitOrAssign + BitXor<Output = Self> + BitXorAssign + Not { } macro_rules! impl_simd_ops { ($($t:ty),*$(,)?) => { $( impl $crate::num::simd::sealed::SimdOps for $t {} )* }; } impl_simd_ops! { i8x2, i8x4, i8x8, i8x16, i8x32, i8x64, u8x2, u8x4, u8x8, u8x16, u8x32, u8x64, i16x2, i16x4, i16x8, i16x16, i16x32, u16x2, u16x4, u16x8, u16x16, u16x32, i32x2, i32x4, i32x8, i32x16, u32x2, u32x4, u32x8, u32x16, i64x2, i64x4, i64x8, u64x2, u64x4, u64x8, i128x1, i128x2, i128x4, u128x1, u128x2, u128x4, isizex2, isizex4, isizex8, usizex2, usizex4, usizex8, f32x2, f32x4, f32x8, f32x16, f64x2, f64x4, f64x8, } macro_rules! impl_simd_mask_ops { ($($t:ty),*$(,)?) => { $( impl $crate::num::simd::sealed::SimdMaskOps for $t {} )* } } impl_simd_mask_ops! { m8x2, m8x4, m8x8, m8x16, m8x32, m8x64, m16x2, m16x4, m16x8, m16x16, m16x32, m32x2, m32x4, m32x8, m32x16, m64x2, m64x4, m64x8, m128x1, m128x2, m128x4, msizex2, msizex4, msizex8, } }
#[derive(Debug)] enum Option<T>{ some(T), none, } fn main() { let number=Option::some(13); let st=Option::some(String::from("Mehran")); // let n:Option<T>=Option::none; println!("{:#?}",number); println!("{:#?}",st); // println!("{:#?}",n); }
fn main() { proconio::input! { n: i32, k: i32, } let mut ans = 1; let mut n = n; while n >= k { ans += 1; n = n / k; } println!("{}", ans); }
//! Riddle crate containing providing the common API to which riddle renderers abide. This allows //! secondary libraries to be defined in terms of the traits and structs defined in this crate //! without needing to encode knowledge of any specific renderers. mod renderer; mod sprite; mod sprite_font; pub mod vertex; pub use renderer::*; pub use sprite::*; pub use sprite_font::*; use riddle_common::Color; use riddle_image::Image; use riddle_math::{Rect, Vector2};
//! The so-called specification is unclear //! on the matter of alternatives of compound types. //! For now, we'll do the simpler thing. use super::super::messages::WriteGTP; use super::*; use std::io; #[derive(Debug)] pub struct Value(simple_entity::Value); impl From<simple_entity::Value> for Value { fn from(v: simple_entity::Value) -> Self { Value(v) } } impl WriteGTP for Value { fn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> { self.0.write_gtp(f) } } #[derive(Clone, Debug)] pub struct Type { first: simple_entity::Type, second: simple_entity::Type, } impl From<(simple_entity::Type, simple_entity::Type)> for Type { fn from(pair: (simple_entity::Type, simple_entity::Type)) -> Self { let (first, second) = pair; Type { first, second } } } impl HasType<Type> for Value { fn has_type(&self, t: &Type) -> bool { let Value(v) = self; v.has_type(&t.first) | v.has_type(&t.second) } } impl Data for Value { type Type = Type; fn parse<'a, I: Input<'a>>(i: I, t: &Self::Type) -> IResult<I, Self> { map!( i, alt!(parse_gtp!(&t.first) | parse_gtp!(&t.second)), From::<simple_entity::Value>::from ) } }
use super::{ declaration::Declaration, definition::Definition, foreign_declaration::ForeignDeclaration, foreign_definition::ForeignDefinition, type_definition::TypeDefinition, }; #[derive(Clone, Debug, PartialEq)] pub struct Module { type_definitions: Vec<TypeDefinition>, foreign_declarations: Vec<ForeignDeclaration>, foreign_definitions: Vec<ForeignDefinition>, declarations: Vec<Declaration>, definitions: Vec<Definition>, } impl Module { pub fn new( type_definitions: Vec<TypeDefinition>, foreign_declarations: Vec<ForeignDeclaration>, foreign_definitions: Vec<ForeignDefinition>, declarations: Vec<Declaration>, definitions: Vec<Definition>, ) -> Self { Self { type_definitions, foreign_declarations, foreign_definitions, declarations, definitions, } } pub fn type_definitions(&self) -> &[TypeDefinition] { &self.type_definitions } pub fn foreign_declarations(&self) -> &[ForeignDeclaration] { &self.foreign_declarations } pub fn foreign_definitions(&self) -> &[ForeignDefinition] { &self.foreign_definitions } pub fn declarations(&self) -> &[Declaration] { &self.declarations } pub fn definitions(&self) -> &[Definition] { &self.definitions } }
use parity_wasm::{deserialize_buffer, elements::Module}; use std::fs::read; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt( name = "kontrolleuer", about = "Inspecting what assumptions a wasm binary has about its environment" )] struct Options { /// Input file #[structopt()] file: String, /// Verbose output #[structopt(long = "verbose")] verbose: bool, } fn main() { let options = Options::from_args(); let contents = read(options.file).expect("Failed to read file"); let module = deserialize_buffer::<Module>(&contents).unwrap(); let import_section = module.import_section(); let mut assumptions = Assumptions::new(); let entries = import_section.map(|s| s.entries()); if let Some(entries) = entries { for import in entries { match import.module() { "wasi_unstable" => assumptions.add_wasi(import.field()), _ => assumptions.add_unknown(import.field()), } } } report(assumptions, options.verbose); } struct WasiAssumptions<'a> { file_system: Vec<&'a str>, environment: Vec<&'a str>, process: Vec<&'a str>, network: Vec<&'a str>, unknown: Vec<&'a str>, } impl<'a> WasiAssumptions<'a> { fn new() -> WasiAssumptions<'a> { WasiAssumptions { file_system: Vec::new(), environment: Vec::new(), process: Vec::new(), network: Vec::new(), unknown: Vec::new(), } } fn add(&mut self, name: &'a str) { match name { "args_get" | "args_sizes_get" | "clock_res_get" | "clock_time_get" | "random_get" | "environ_get" | "environ_sizes_get" => self.environment.push(name), "fd_advise" | "fd_close" | "fd_datasync" | "fd_fdstat_get" | "fd_fdstat_set_flags" | "fd_fdstat_set_rights" | "fd_filestat_get" | "fd_filestat_set_size" | "fd_filestat_set_times" | "fd_pread" | "fd_prestat_get" | "fd_prestat_dir_name" | "fd_pwrite" | "fd_read" | "fd_readdir" | "fd_renumber" | "fd_seek" | "fd_sync" | "fd_tell" | "fd_write" | "path_create_directory" | "path_filestat_get" | "path_filestat_set_times" | "path_link" | "path_open" | "path_readlink" | "path_remove_directory" | "path_rename" | "path_symlink" | "path_unlink_file" | "poll_oneoff" => self.file_system.push(name), "proc_exit" | "proc_raise" | "sched_yield" => self.process.push(name), "sock_recv" | "sock_send" | "sock_shutdown" => self.network.push(name), _ => self.unknown.push(name), } } fn count(&self) -> usize { self.file_system.len() + self.process.len() + self.environment.len() + self.network.len() + self.unknown.len() } } struct Assumptions<'a> { wasi: WasiAssumptions<'a>, unknown: Vec<&'a str>, } impl<'a> Assumptions<'a> { fn new() -> Assumptions<'a> { Assumptions { wasi: WasiAssumptions::new(), unknown: Vec::new(), } } fn add_wasi(&mut self, name: &'a str) { self.wasi.add(name) } fn add_unknown(&mut self, name: &'a str) { self.unknown.push(name) } fn count(&self) -> usize { self.unknown.len() + self.wasi.count() } } fn report<'a>(assumptions: Assumptions<'a>, verbose: bool) { let total_count = assumptions.count(); println!( "There {} {} total external API call{}.", correct_to_be_form(total_count), total_count, optional_s(total_count) ); let wasi = assumptions.wasi; let wasi_count = wasi.count(); if wasi_count > 0 { println!("This binary is expecting a WASI compliant runtime."); println!( "\tThe binary uses {} WASI call{}", wasi_count, optional_s(wasi_count) ); println!("\tThe following system resource types are used:"); let mut types = Vec::new(); if wasi.file_system.len() > 0 { types.push("file system"); } if wasi.environment.len() > 0 { types.push("environment"); } if wasi.process.len() > 0 { types.push("process"); } println!("\t\t{}", types.join(", ")); if verbose { if wasi.file_system.len() > 0 { println!("\tFile system calls:"); for call in wasi.file_system { println!("\t\t{}", call); } } if wasi.environment.len() > 0 { println!("\tEnivronent system calls:"); for call in wasi.environment { println!("\t\t{}", call); } } if wasi.process.len() > 0 { println!("\tProcess system calls:"); for call in wasi.process { println!("\t\t{}", call); } } } let unknown = wasi.unknown; let unknown_count = unknown.len(); if unknown_count > 0 { println!( "There {} {} unknown wasi sys call{}:", correct_to_be_form(unknown_count), unknown_count, optional_s(unknown_count) ); for call in unknown { println!("\t{}", call); } } } if assumptions.unknown.len() > 0 { println!("Unknown imports:"); for unknown in assumptions.unknown { println!("\t{}", unknown); } } } fn correct_to_be_form(count: usize) -> &'static str { if count == 1 { "is" } else { "are" } } fn optional_s(count: usize) -> &'static str { if count == 1 { "" } else { "s" } }
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Register `SR` writer"] pub type W = crate::W<SR_SPEC>; #[doc = "Field `AWD` reader - Analog watchdog flag"] pub type AWD_R = crate::BitReader; #[doc = "Field `AWD` writer - Analog watchdog flag"] pub type AWD_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `EOC` reader - Regular channel end of conversion"] pub type EOC_R = crate::BitReader; #[doc = "Field `EOC` writer - Regular channel end of conversion"] pub type EOC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `JEOC` reader - Injected channel end of conversion"] pub type JEOC_R = crate::BitReader; #[doc = "Field `JEOC` writer - Injected channel end of conversion"] pub type JEOC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `JSTRT` reader - Injected channel start flag"] pub type JSTRT_R = crate::BitReader; #[doc = "Field `JSTRT` writer - Injected channel start flag"] pub type JSTRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `STRT` reader - Regular channel start flag"] pub type STRT_R = crate::BitReader; #[doc = "Field `STRT` writer - Regular channel start flag"] pub type STRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `OVR` reader - Overrun"] pub type OVR_R = crate::BitReader; #[doc = "Field `OVR` writer - Overrun"] pub type OVR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADONS` reader - ADC ON status"] pub type ADONS_R = crate::BitReader; #[doc = "Field `RCNR` reader - Regular channel not ready"] pub type RCNR_R = crate::BitReader; #[doc = "Field `JCNR` reader - Injected channel not ready"] pub type JCNR_R = crate::BitReader; impl R { #[doc = "Bit 0 - Analog watchdog flag"] #[inline(always)] pub fn awd(&self) -> AWD_R { AWD_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Regular channel end of conversion"] #[inline(always)] pub fn eoc(&self) -> EOC_R { EOC_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Injected channel end of conversion"] #[inline(always)] pub fn jeoc(&self) -> JEOC_R { JEOC_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Injected channel start flag"] #[inline(always)] pub fn jstrt(&self) -> JSTRT_R { JSTRT_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Regular channel start flag"] #[inline(always)] pub fn strt(&self) -> STRT_R { STRT_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Overrun"] #[inline(always)] pub fn ovr(&self) -> OVR_R { OVR_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - ADC ON status"] #[inline(always)] pub fn adons(&self) -> ADONS_R { ADONS_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 8 - Regular channel not ready"] #[inline(always)] pub fn rcnr(&self) -> RCNR_R { RCNR_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Injected channel not ready"] #[inline(always)] pub fn jcnr(&self) -> JCNR_R { JCNR_R::new(((self.bits >> 9) & 1) != 0) } } impl W { #[doc = "Bit 0 - Analog watchdog flag"] #[inline(always)] #[must_use] pub fn awd(&mut self) -> AWD_W<SR_SPEC, 0> { AWD_W::new(self) } #[doc = "Bit 1 - Regular channel end of conversion"] #[inline(always)] #[must_use] pub fn eoc(&mut self) -> EOC_W<SR_SPEC, 1> { EOC_W::new(self) } #[doc = "Bit 2 - Injected channel end of conversion"] #[inline(always)] #[must_use] pub fn jeoc(&mut self) -> JEOC_W<SR_SPEC, 2> { JEOC_W::new(self) } #[doc = "Bit 3 - Injected channel start flag"] #[inline(always)] #[must_use] pub fn jstrt(&mut self) -> JSTRT_W<SR_SPEC, 3> { JSTRT_W::new(self) } #[doc = "Bit 4 - Regular channel start flag"] #[inline(always)] #[must_use] pub fn strt(&mut self) -> STRT_W<SR_SPEC, 4> { STRT_W::new(self) } #[doc = "Bit 5 - Overrun"] #[inline(always)] #[must_use] pub fn ovr(&mut self) -> OVR_W<SR_SPEC, 5> { OVR_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SR_SPEC; impl crate::RegisterSpec for SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`sr::R`](R) reader structure"] impl crate::Readable for SR_SPEC {} #[doc = "`write(|w| ..)` method takes [`sr::W`](W) writer structure"] impl crate::Writable for SR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SR to value 0"] impl crate::Resettable for SR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use alloc::boxed::Box; use core::{marker::PhantomData, num::NonZeroU32}; use necsim_core::{ cogs::{Backup, Habitat}, intrinsics::{ceil, log2}, landscape::{LandscapeExtent, Location}, }; use crate::decomposition::Decomposition; mod area; mod weight; #[cfg(test)] mod test; #[allow(clippy::module_name_repetitions)] #[derive(Debug)] pub struct EqualDecomposition<H: Habitat> { rank: u32, partitions: NonZeroU32, extent: LandscapeExtent, morton: (u8, u8), indices: Box<[u64]>, _marker: PhantomData<H>, } #[contract_trait] impl<H: Habitat> Backup for EqualDecomposition<H> { unsafe fn backup_unchecked(&self) -> Self { Self { rank: self.rank, partitions: self.partitions, extent: self.extent.clone(), morton: self.morton, indices: self.indices.clone(), _marker: PhantomData::<H>, } } } #[contract_trait] impl<H: Habitat> Decomposition<H> for EqualDecomposition<H> { fn get_subdomain_rank(&self) -> u32 { self.rank } fn get_number_of_subdomains(&self) -> NonZeroU32 { self.partitions } #[debug_requires( habitat.get_extent() == &self.extent, "habitat has a matching extent" )] fn map_location_to_subdomain_rank(&self, location: &Location, habitat: &H) -> u32 { let mut dx = location.x() - self.extent.x(); let mut dy = location.y() - self.extent.y(); let morton_index = Self::map_x_y_to_morton(self.morton.0, self.morton.1, dx, dy); #[allow(clippy::cast_possible_truncation)] match self.indices.binary_search(&morton_index) { Ok(index) => (index + 1) as u32, Err(index) => index as u32, } } } impl<H: Habitat> EqualDecomposition<H> { fn next_log2(coord: u32) -> u8 { #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] if coord > 1 { ceil(log2(f64::from(coord))) as u8 } else { 0 } } fn map_x_y_to_morton(mut morton_x: u8, mut morton_y: u8, mut dx: u32, mut dy: u32) -> u64 { let mut morton_index = 0_u64; let morton = morton_x.min(morton_y); for m in 0..morton { morton_index |= u64::from(dx & 0x1_u32) << (m * 2); dx >>= 1; morton_index |= u64::from(dy & 0x1_u32) << (m * 2 + 1); dy >>= 1; } morton_x -= morton; morton_y -= morton; if morton_x > 0 { morton_index |= u64::from(dx) << (morton * 2); } if morton_y > 0 { morton_index |= u64::from(dy) << (morton * 2 + morton_x); } morton_index } }
mod common; use cached::cached; use proptest::prelude::*; use valis_automata::{ dfa::{standard::StandardDFA, DFA}, range_set::Range, }; use valis_ds::{ops::Intersection, set::SetBase}; cached! { THREE_OR_LESS_TRUE_THREE_OR_MORE_FALSE; fn three_or_less_true_three_or_more_false() -> StandardDFA<bool, u8> = { let states: Range<u8> = (0..=7).into(); let accept_states = [7].into_iter().cloned().collect(); let dead_state = Some(4); let start_state = 0; let transitions = vec![ 5, // 0, false 1, // 0, true 5, // 1, false 2, // 1, true 5, // 2, false 3, // 2, true 5, // 3, false 4, // 3, true 4, // 4, false 4, // 4, true 6, // 5, false 4, // 5, true 7, // 6, false 4, // 6, true 7, // 7, false 4, // 7, true ] .into_boxed_slice(); assert_eq!(transitions.len(), states.size() * 2); let dfa = StandardDFA::<bool, u8>::new(states, transitions, accept_states, start_state, dead_state); common::render_dfa_to_file("three_or_less_true_three_or_more_false.dot", &dfa); dfa } } cached! { THREE_OR_MORE_TRUE_THREE_OR_LESS_FALSE; fn three_or_more_true_three_or_less_false() -> StandardDFA<bool, u8> = { let states: Range<u8> = (0..=7).into(); let accept_states = [3, 5, 6, 7].into_iter().cloned().collect(); let dead_state = Some(4); let start_state = 0; let transitions = vec![ 4, // 0, false 1, // 0, true 4, // 1, false 2, // 1, true 4, // 2, false 3, // 2, true 5, // 3, false 3, // 3, true 4, // 4, false 4, // 4, true 6, // 5, false 4, // 5, true 7, // 6, false 4, // 6, true 4, // 7, false 4, // 7, true ] .into_boxed_slice(); assert_eq!(transitions.len(), states.size() * 2); let dfa = StandardDFA::<bool, u8>::new(states, transitions, accept_states, start_state, dead_state); common::render_dfa_to_file("three_or_more_true_three_or_less_false.dot", &dfa); dfa } } cached! { THREE_TRUE_THREE_FALSE; fn three_true_three_false() -> StandardDFA<bool, u8> = { let dfa_2 = three_or_less_true_three_or_more_false(); let dfa_3 = three_or_more_true_three_or_less_false(); let dfa = (&dfa_2).intersection(&dfa_3); common::render_dfa_to_file("three_true_three_false.dot", &dfa); dfa } } #[test] fn accept_three_or_less_true_three_or_more_false() { let dfa_2 = three_or_less_true_three_or_more_false(); assert!(dfa_2.accept(vec![true, true, true, false, false, false])); assert!(dfa_2.accept(vec![ true, true, true, false, false, false, false, false, false, false ])); assert!(dfa_2.accept(vec![true, false, false, false, false, false])); assert!(dfa_2.accept(vec![false, false, false, false, false])); assert!(dfa_2.accept(vec![false, false, false])); assert!(!dfa_2.accept(vec![false, false])); assert!(!dfa_2.accept(vec![])); assert!(!dfa_2.accept(vec![true, true, true, true, false, false, false])); assert!(!dfa_2.accept(vec![true, true, true, false, false])); assert!(!dfa_2.accept(vec![true, true, true])); } #[test] fn accept_three_or_more_true_three_or_less_false() { let dfa_3 = three_or_more_true_three_or_less_false(); assert!(dfa_3.accept(vec![true, true, true, false, false, false])); assert!(dfa_3.accept(vec![ true, true, true, true, true, true, false, false, false ])); assert!(dfa_3.accept(vec![true, true, true, true, false, false])); assert!(dfa_3.accept(vec![true, true, true, true])); assert!(dfa_3.accept(vec![true, true, true])); assert!(!dfa_3.accept(vec![false, false])); assert!(!dfa_3.accept(vec![])); assert!(!dfa_3.accept(vec![true, true, true, true, false, false, false, false])); assert!(!dfa_3.accept(vec![true, true, false, false])); assert!(!dfa_3.accept(vec![true, true])); } #[test] fn accept_three_true_three_false() { let dfa_inter = three_true_three_false(); assert!(dfa_inter.accept(vec![true, true, true, false, false, false])); assert!(!dfa_inter.accept(vec![true, true])); assert!(!dfa_inter.accept(vec![true, true, true])); assert!(!dfa_inter.accept(vec![true, true, true, true])); assert!(!dfa_inter.accept(vec![ true, true, true, true, true, true, false, false, false ])); assert!(!dfa_inter.accept(vec![true, true, true, true, false, false])); assert!(!dfa_inter.accept(vec![true, true, true, true, false, false, false])); assert!(!dfa_inter.accept(vec![true, true, true, true, false, false, false, false])); assert!(!dfa_inter.accept(vec![true, true, true, false, false])); assert!(!dfa_inter.accept(vec![ true, true, true, false, false, false, false, false, false, false ])); assert!(!dfa_inter.accept(vec![true, true, false, false])); assert!(!dfa_inter.accept(vec![true, false, false, false, false, false])); assert!(!dfa_inter.accept(vec![false, false])); assert!(!dfa_inter.accept(vec![false, false, false])); assert!(!dfa_inter.accept(vec![false, false, false, false, false])); assert!(!dfa_inter.accept(vec![])); } proptest! { #[test] fn not_accept_three_true_three_false_random(s in r"(?x) (1?1?0?0?) | (1?1?0{4,}) | (1{4,}0?0?) | (1{4,}0{4,}) ") { let dfa_1 = three_true_three_false(); let string = common::convert_string(s, common::binary_converter()); prop_assert!(!dfa_1.accept(string)); } #[test] fn accept_three_or_more_true_three_or_less_false_random(s in r"1{3,}0?0?0?") { let dfa_1 = three_or_more_true_three_or_less_false(); let string = common::convert_string(s, common::binary_converter()); prop_assert!(dfa_1.accept(string)); } #[test] fn accept_three_or_less_true_three_or_more_false_random(s in r"1?1?1?0{3,}") { let dfa_1 = three_or_less_true_three_or_more_false(); let string = common::convert_string(s, common::binary_converter()); prop_assert!(dfa_1.accept(string)); } }
#[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::AUX3 { #[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 `TMRB3EN23`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRB3EN23R { #[doc = "Disable enhanced functions. value."] DIS, #[doc = "Enable enhanced functions. value."] EN, } impl TMRB3EN23R { #[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 { TMRB3EN23R::DIS => true, TMRB3EN23R::EN => false, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRB3EN23R { match value { true => TMRB3EN23R::DIS, false => TMRB3EN23R::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRB3EN23R::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == TMRB3EN23R::EN } } #[doc = "Possible values of the field `TMRB3POL23`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRB3POL23R { #[doc = "Upper output normal polarity value."] NORM, #[doc = "Upper output inverted polarity. value."] INV, } impl TMRB3POL23R { #[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 { TMRB3POL23R::NORM => false, TMRB3POL23R::INV => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRB3POL23R { match value { false => TMRB3POL23R::NORM, true => TMRB3POL23R::INV, } } #[doc = "Checks if the value of the field is `NORM`"] #[inline] pub fn is_norm(&self) -> bool { *self == TMRB3POL23R::NORM } #[doc = "Checks if the value of the field is `INV`"] #[inline] pub fn is_inv(&self) -> bool { *self == TMRB3POL23R::INV } } #[doc = "Possible values of the field `TMRB3TINV`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRB3TINVR { #[doc = "Disable invert on trigger value."] DIS, #[doc = "Enable invert on trigger value."] EN, } impl TMRB3TINVR { #[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 { TMRB3TINVR::DIS => false, TMRB3TINVR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRB3TINVR { match value { false => TMRB3TINVR::DIS, true => TMRB3TINVR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRB3TINVR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == TMRB3TINVR::EN } } #[doc = "Possible values of the field `TMRB3NOSYNC`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRB3NOSYNCR { #[doc = "Synchronization on source clock value."] DIS, #[doc = "No synchronization on source clock value."] NOSYNC, } impl TMRB3NOSYNCR { #[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 { TMRB3NOSYNCR::DIS => false, TMRB3NOSYNCR::NOSYNC => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRB3NOSYNCR { match value { false => TMRB3NOSYNCR::DIS, true => TMRB3NOSYNCR::NOSYNC, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRB3NOSYNCR::DIS } #[doc = "Checks if the value of the field is `NOSYNC`"] #[inline] pub fn is_nosync(&self) -> bool { *self == TMRB3NOSYNCR::NOSYNC } } #[doc = "Possible values of the field `TMRB3TRIG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRB3TRIGR { #[doc = "Trigger source is disabled. value."] DIS, #[doc = "Trigger source is CTIMERA3 OUT. value."] A3OUT, #[doc = "Trigger source is CTIMERB2 OUT. value."] B2OUT, #[doc = "Trigger source is CTIMERA2 OUT. value."] A2OUT, #[doc = "Trigger source is CTIMERA4 OUT. value."] A4OUT, #[doc = "Trigger source is CTIMERB4 OUT. value."] B4OUT, #[doc = "Trigger source is CTIMERA6 OUT. value."] A6OUT, #[doc = "Trigger source is CTIMERB6 OUT. value."] B6OUT, #[doc = "Trigger source is CTIMERB5 OUT2. value."] B5OUT2, #[doc = "Trigger source is CTIMERA5 OUT2. value."] A5OUT2, #[doc = "Trigger source is CTIMERA1 OUT2. value."] A1OUT2, #[doc = "Trigger source is CTIMERB1 OUT2. value."] B1OUT2, #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] A6OUT2DUAL, #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] A7OUT2DUAL, #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] B2OUT2DUAL, #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] A2OUT2DUAL, } impl TMRB3TRIGR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { TMRB3TRIGR::DIS => 0, TMRB3TRIGR::A3OUT => 1, TMRB3TRIGR::B2OUT => 2, TMRB3TRIGR::A2OUT => 3, TMRB3TRIGR::A4OUT => 4, TMRB3TRIGR::B4OUT => 5, TMRB3TRIGR::A6OUT => 6, TMRB3TRIGR::B6OUT => 7, TMRB3TRIGR::B5OUT2 => 8, TMRB3TRIGR::A5OUT2 => 9, TMRB3TRIGR::A1OUT2 => 10, TMRB3TRIGR::B1OUT2 => 11, TMRB3TRIGR::A6OUT2DUAL => 12, TMRB3TRIGR::A7OUT2DUAL => 13, TMRB3TRIGR::B2OUT2DUAL => 14, TMRB3TRIGR::A2OUT2DUAL => 15, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> TMRB3TRIGR { match value { 0 => TMRB3TRIGR::DIS, 1 => TMRB3TRIGR::A3OUT, 2 => TMRB3TRIGR::B2OUT, 3 => TMRB3TRIGR::A2OUT, 4 => TMRB3TRIGR::A4OUT, 5 => TMRB3TRIGR::B4OUT, 6 => TMRB3TRIGR::A6OUT, 7 => TMRB3TRIGR::B6OUT, 8 => TMRB3TRIGR::B5OUT2, 9 => TMRB3TRIGR::A5OUT2, 10 => TMRB3TRIGR::A1OUT2, 11 => TMRB3TRIGR::B1OUT2, 12 => TMRB3TRIGR::A6OUT2DUAL, 13 => TMRB3TRIGR::A7OUT2DUAL, 14 => TMRB3TRIGR::B2OUT2DUAL, 15 => TMRB3TRIGR::A2OUT2DUAL, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRB3TRIGR::DIS } #[doc = "Checks if the value of the field is `A3OUT`"] #[inline] pub fn is_a3out(&self) -> bool { *self == TMRB3TRIGR::A3OUT } #[doc = "Checks if the value of the field is `B2OUT`"] #[inline] pub fn is_b2out(&self) -> bool { *self == TMRB3TRIGR::B2OUT } #[doc = "Checks if the value of the field is `A2OUT`"] #[inline] pub fn is_a2out(&self) -> bool { *self == TMRB3TRIGR::A2OUT } #[doc = "Checks if the value of the field is `A4OUT`"] #[inline] pub fn is_a4out(&self) -> bool { *self == TMRB3TRIGR::A4OUT } #[doc = "Checks if the value of the field is `B4OUT`"] #[inline] pub fn is_b4out(&self) -> bool { *self == TMRB3TRIGR::B4OUT } #[doc = "Checks if the value of the field is `A6OUT`"] #[inline] pub fn is_a6out(&self) -> bool { *self == TMRB3TRIGR::A6OUT } #[doc = "Checks if the value of the field is `B6OUT`"] #[inline] pub fn is_b6out(&self) -> bool { *self == TMRB3TRIGR::B6OUT } #[doc = "Checks if the value of the field is `B5OUT2`"] #[inline] pub fn is_b5out2(&self) -> bool { *self == TMRB3TRIGR::B5OUT2 } #[doc = "Checks if the value of the field is `A5OUT2`"] #[inline] pub fn is_a5out2(&self) -> bool { *self == TMRB3TRIGR::A5OUT2 } #[doc = "Checks if the value of the field is `A1OUT2`"] #[inline] pub fn is_a1out2(&self) -> bool { *self == TMRB3TRIGR::A1OUT2 } #[doc = "Checks if the value of the field is `B1OUT2`"] #[inline] pub fn is_b1out2(&self) -> bool { *self == TMRB3TRIGR::B1OUT2 } #[doc = "Checks if the value of the field is `A6OUT2DUAL`"] #[inline] pub fn is_a6out2dual(&self) -> bool { *self == TMRB3TRIGR::A6OUT2DUAL } #[doc = "Checks if the value of the field is `A7OUT2DUAL`"] #[inline] pub fn is_a7out2dual(&self) -> bool { *self == TMRB3TRIGR::A7OUT2DUAL } #[doc = "Checks if the value of the field is `B2OUT2DUAL`"] #[inline] pub fn is_b2out2dual(&self) -> bool { *self == TMRB3TRIGR::B2OUT2DUAL } #[doc = "Checks if the value of the field is `A2OUT2DUAL`"] #[inline] pub fn is_a2out2dual(&self) -> bool { *self == TMRB3TRIGR::A2OUT2DUAL } } #[doc = r" Value of the field"] pub struct TMRB3LMTR { bits: u8, } impl TMRB3LMTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Possible values of the field `TMRA3EN23`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRA3EN23R { #[doc = "Disable enhanced functions. value."] DIS, #[doc = "Enable enhanced functions. value."] EN, } impl TMRA3EN23R { #[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 { TMRA3EN23R::DIS => true, TMRA3EN23R::EN => false, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRA3EN23R { match value { true => TMRA3EN23R::DIS, false => TMRA3EN23R::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRA3EN23R::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == TMRA3EN23R::EN } } #[doc = "Possible values of the field `TMRA3POL23`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRA3POL23R { #[doc = "Upper output normal polarity value."] NORM, #[doc = "Upper output inverted polarity. value."] INV, } impl TMRA3POL23R { #[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 { TMRA3POL23R::NORM => false, TMRA3POL23R::INV => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRA3POL23R { match value { false => TMRA3POL23R::NORM, true => TMRA3POL23R::INV, } } #[doc = "Checks if the value of the field is `NORM`"] #[inline] pub fn is_norm(&self) -> bool { *self == TMRA3POL23R::NORM } #[doc = "Checks if the value of the field is `INV`"] #[inline] pub fn is_inv(&self) -> bool { *self == TMRA3POL23R::INV } } #[doc = "Possible values of the field `TMRA3TINV`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRA3TINVR { #[doc = "Disable invert on trigger value."] DIS, #[doc = "Enable invert on trigger value."] EN, } impl TMRA3TINVR { #[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 { TMRA3TINVR::DIS => false, TMRA3TINVR::EN => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRA3TINVR { match value { false => TMRA3TINVR::DIS, true => TMRA3TINVR::EN, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRA3TINVR::DIS } #[doc = "Checks if the value of the field is `EN`"] #[inline] pub fn is_en(&self) -> bool { *self == TMRA3TINVR::EN } } #[doc = "Possible values of the field `TMRA3NOSYNC`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRA3NOSYNCR { #[doc = "Synchronization on source clock value."] DIS, #[doc = "No synchronization on source clock value."] NOSYNC, } impl TMRA3NOSYNCR { #[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 { TMRA3NOSYNCR::DIS => false, TMRA3NOSYNCR::NOSYNC => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> TMRA3NOSYNCR { match value { false => TMRA3NOSYNCR::DIS, true => TMRA3NOSYNCR::NOSYNC, } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRA3NOSYNCR::DIS } #[doc = "Checks if the value of the field is `NOSYNC`"] #[inline] pub fn is_nosync(&self) -> bool { *self == TMRA3NOSYNCR::NOSYNC } } #[doc = "Possible values of the field `TMRA3TRIG`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMRA3TRIGR { #[doc = "Trigger source is disabled. value."] DIS, #[doc = "Trigger source is CTIMERB3 OUT. value."] B3OUT, #[doc = "Trigger source is CTIMERB2 OUT. value."] B2OUT, #[doc = "Trigger source is CTIMERA2 OUT. value."] A2OUT, #[doc = "Trigger source is CTIMERA4 OUT. value."] A4OUT, #[doc = "Trigger source is CTIMERB4 OUT. value."] B4OUT, #[doc = "Trigger source is CTIMERA7 OUT. value."] A7OUT, #[doc = "Trigger source is CTIMERB7 OUT. value."] B7OUT, #[doc = "Trigger source is CTIMERB5 OUT2. value."] B5OUT2, #[doc = "Trigger source is CTIMERA5 OUT2. value."] A5OUT2, #[doc = "Trigger source is CTIMERA1 OUT2. value."] A1OUT2, #[doc = "Trigger source is CTIMERB1 OUT2. value."] B1OUT2, #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] A6OUT2DUAL, #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] A7OUT2DUAL, #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] B2OUT2DUAL, #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] A2OUT2DUAL, } impl TMRA3TRIGR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { TMRA3TRIGR::DIS => 0, TMRA3TRIGR::B3OUT => 1, TMRA3TRIGR::B2OUT => 2, TMRA3TRIGR::A2OUT => 3, TMRA3TRIGR::A4OUT => 4, TMRA3TRIGR::B4OUT => 5, TMRA3TRIGR::A7OUT => 6, TMRA3TRIGR::B7OUT => 7, TMRA3TRIGR::B5OUT2 => 8, TMRA3TRIGR::A5OUT2 => 9, TMRA3TRIGR::A1OUT2 => 10, TMRA3TRIGR::B1OUT2 => 11, TMRA3TRIGR::A6OUT2DUAL => 12, TMRA3TRIGR::A7OUT2DUAL => 13, TMRA3TRIGR::B2OUT2DUAL => 14, TMRA3TRIGR::A2OUT2DUAL => 15, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> TMRA3TRIGR { match value { 0 => TMRA3TRIGR::DIS, 1 => TMRA3TRIGR::B3OUT, 2 => TMRA3TRIGR::B2OUT, 3 => TMRA3TRIGR::A2OUT, 4 => TMRA3TRIGR::A4OUT, 5 => TMRA3TRIGR::B4OUT, 6 => TMRA3TRIGR::A7OUT, 7 => TMRA3TRIGR::B7OUT, 8 => TMRA3TRIGR::B5OUT2, 9 => TMRA3TRIGR::A5OUT2, 10 => TMRA3TRIGR::A1OUT2, 11 => TMRA3TRIGR::B1OUT2, 12 => TMRA3TRIGR::A6OUT2DUAL, 13 => TMRA3TRIGR::A7OUT2DUAL, 14 => TMRA3TRIGR::B2OUT2DUAL, 15 => TMRA3TRIGR::A2OUT2DUAL, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIS`"] #[inline] pub fn is_dis(&self) -> bool { *self == TMRA3TRIGR::DIS } #[doc = "Checks if the value of the field is `B3OUT`"] #[inline] pub fn is_b3out(&self) -> bool { *self == TMRA3TRIGR::B3OUT } #[doc = "Checks if the value of the field is `B2OUT`"] #[inline] pub fn is_b2out(&self) -> bool { *self == TMRA3TRIGR::B2OUT } #[doc = "Checks if the value of the field is `A2OUT`"] #[inline] pub fn is_a2out(&self) -> bool { *self == TMRA3TRIGR::A2OUT } #[doc = "Checks if the value of the field is `A4OUT`"] #[inline] pub fn is_a4out(&self) -> bool { *self == TMRA3TRIGR::A4OUT } #[doc = "Checks if the value of the field is `B4OUT`"] #[inline] pub fn is_b4out(&self) -> bool { *self == TMRA3TRIGR::B4OUT } #[doc = "Checks if the value of the field is `A7OUT`"] #[inline] pub fn is_a7out(&self) -> bool { *self == TMRA3TRIGR::A7OUT } #[doc = "Checks if the value of the field is `B7OUT`"] #[inline] pub fn is_b7out(&self) -> bool { *self == TMRA3TRIGR::B7OUT } #[doc = "Checks if the value of the field is `B5OUT2`"] #[inline] pub fn is_b5out2(&self) -> bool { *self == TMRA3TRIGR::B5OUT2 } #[doc = "Checks if the value of the field is `A5OUT2`"] #[inline] pub fn is_a5out2(&self) -> bool { *self == TMRA3TRIGR::A5OUT2 } #[doc = "Checks if the value of the field is `A1OUT2`"] #[inline] pub fn is_a1out2(&self) -> bool { *self == TMRA3TRIGR::A1OUT2 } #[doc = "Checks if the value of the field is `B1OUT2`"] #[inline] pub fn is_b1out2(&self) -> bool { *self == TMRA3TRIGR::B1OUT2 } #[doc = "Checks if the value of the field is `A6OUT2DUAL`"] #[inline] pub fn is_a6out2dual(&self) -> bool { *self == TMRA3TRIGR::A6OUT2DUAL } #[doc = "Checks if the value of the field is `A7OUT2DUAL`"] #[inline] pub fn is_a7out2dual(&self) -> bool { *self == TMRA3TRIGR::A7OUT2DUAL } #[doc = "Checks if the value of the field is `B2OUT2DUAL`"] #[inline] pub fn is_b2out2dual(&self) -> bool { *self == TMRA3TRIGR::B2OUT2DUAL } #[doc = "Checks if the value of the field is `A2OUT2DUAL`"] #[inline] pub fn is_a2out2dual(&self) -> bool { *self == TMRA3TRIGR::A2OUT2DUAL } } #[doc = r" Value of the field"] pub struct TMRA3LMTR { bits: u8, } impl TMRA3LMTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Values that can be written to the field `TMRB3EN23`"] pub enum TMRB3EN23W { #[doc = "Disable enhanced functions. value."] DIS, #[doc = "Enable enhanced functions. value."] EN, } impl TMRB3EN23W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRB3EN23W::DIS => true, TMRB3EN23W::EN => false, } } } #[doc = r" Proxy"] pub struct _TMRB3EN23W<'a> { w: &'a mut W, } impl<'a> _TMRB3EN23W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRB3EN23W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable enhanced functions. value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRB3EN23W::DIS) } #[doc = "Enable enhanced functions. value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(TMRB3EN23W::EN) } #[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 = 30; 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 `TMRB3POL23`"] pub enum TMRB3POL23W { #[doc = "Upper output normal polarity value."] NORM, #[doc = "Upper output inverted polarity. value."] INV, } impl TMRB3POL23W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRB3POL23W::NORM => false, TMRB3POL23W::INV => true, } } } #[doc = r" Proxy"] pub struct _TMRB3POL23W<'a> { w: &'a mut W, } impl<'a> _TMRB3POL23W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRB3POL23W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Upper output normal polarity value."] #[inline] pub fn norm(self) -> &'a mut W { self.variant(TMRB3POL23W::NORM) } #[doc = "Upper output inverted polarity. value."] #[inline] pub fn inv(self) -> &'a mut W { self.variant(TMRB3POL23W::INV) } #[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 = 29; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRB3TINV`"] pub enum TMRB3TINVW { #[doc = "Disable invert on trigger value."] DIS, #[doc = "Enable invert on trigger value."] EN, } impl TMRB3TINVW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRB3TINVW::DIS => false, TMRB3TINVW::EN => true, } } } #[doc = r" Proxy"] pub struct _TMRB3TINVW<'a> { w: &'a mut W, } impl<'a> _TMRB3TINVW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRB3TINVW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable invert on trigger value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRB3TINVW::DIS) } #[doc = "Enable invert on trigger value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(TMRB3TINVW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRB3NOSYNC`"] pub enum TMRB3NOSYNCW { #[doc = "Synchronization on source clock value."] DIS, #[doc = "No synchronization on source clock value."] NOSYNC, } impl TMRB3NOSYNCW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRB3NOSYNCW::DIS => false, TMRB3NOSYNCW::NOSYNC => true, } } } #[doc = r" Proxy"] pub struct _TMRB3NOSYNCW<'a> { w: &'a mut W, } impl<'a> _TMRB3NOSYNCW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRB3NOSYNCW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Synchronization on source clock value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRB3NOSYNCW::DIS) } #[doc = "No synchronization on source clock value."] #[inline] pub fn nosync(self) -> &'a mut W { self.variant(TMRB3NOSYNCW::NOSYNC) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 27; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRB3TRIG`"] pub enum TMRB3TRIGW { #[doc = "Trigger source is disabled. value."] DIS, #[doc = "Trigger source is CTIMERA3 OUT. value."] A3OUT, #[doc = "Trigger source is CTIMERB2 OUT. value."] B2OUT, #[doc = "Trigger source is CTIMERA2 OUT. value."] A2OUT, #[doc = "Trigger source is CTIMERA4 OUT. value."] A4OUT, #[doc = "Trigger source is CTIMERB4 OUT. value."] B4OUT, #[doc = "Trigger source is CTIMERA6 OUT. value."] A6OUT, #[doc = "Trigger source is CTIMERB6 OUT. value."] B6OUT, #[doc = "Trigger source is CTIMERB5 OUT2. value."] B5OUT2, #[doc = "Trigger source is CTIMERA5 OUT2. value."] A5OUT2, #[doc = "Trigger source is CTIMERA1 OUT2. value."] A1OUT2, #[doc = "Trigger source is CTIMERB1 OUT2. value."] B1OUT2, #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] A6OUT2DUAL, #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] A7OUT2DUAL, #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] B2OUT2DUAL, #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] A2OUT2DUAL, } impl TMRB3TRIGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { TMRB3TRIGW::DIS => 0, TMRB3TRIGW::A3OUT => 1, TMRB3TRIGW::B2OUT => 2, TMRB3TRIGW::A2OUT => 3, TMRB3TRIGW::A4OUT => 4, TMRB3TRIGW::B4OUT => 5, TMRB3TRIGW::A6OUT => 6, TMRB3TRIGW::B6OUT => 7, TMRB3TRIGW::B5OUT2 => 8, TMRB3TRIGW::A5OUT2 => 9, TMRB3TRIGW::A1OUT2 => 10, TMRB3TRIGW::B1OUT2 => 11, TMRB3TRIGW::A6OUT2DUAL => 12, TMRB3TRIGW::A7OUT2DUAL => 13, TMRB3TRIGW::B2OUT2DUAL => 14, TMRB3TRIGW::A2OUT2DUAL => 15, } } } #[doc = r" Proxy"] pub struct _TMRB3TRIGW<'a> { w: &'a mut W, } impl<'a> _TMRB3TRIGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRB3TRIGW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Trigger source is disabled. value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRB3TRIGW::DIS) } #[doc = "Trigger source is CTIMERA3 OUT. value."] #[inline] pub fn a3out(self) -> &'a mut W { self.variant(TMRB3TRIGW::A3OUT) } #[doc = "Trigger source is CTIMERB2 OUT. value."] #[inline] pub fn b2out(self) -> &'a mut W { self.variant(TMRB3TRIGW::B2OUT) } #[doc = "Trigger source is CTIMERA2 OUT. value."] #[inline] pub fn a2out(self) -> &'a mut W { self.variant(TMRB3TRIGW::A2OUT) } #[doc = "Trigger source is CTIMERA4 OUT. value."] #[inline] pub fn a4out(self) -> &'a mut W { self.variant(TMRB3TRIGW::A4OUT) } #[doc = "Trigger source is CTIMERB4 OUT. value."] #[inline] pub fn b4out(self) -> &'a mut W { self.variant(TMRB3TRIGW::B4OUT) } #[doc = "Trigger source is CTIMERA6 OUT. value."] #[inline] pub fn a6out(self) -> &'a mut W { self.variant(TMRB3TRIGW::A6OUT) } #[doc = "Trigger source is CTIMERB6 OUT. value."] #[inline] pub fn b6out(self) -> &'a mut W { self.variant(TMRB3TRIGW::B6OUT) } #[doc = "Trigger source is CTIMERB5 OUT2. value."] #[inline] pub fn b5out2(self) -> &'a mut W { self.variant(TMRB3TRIGW::B5OUT2) } #[doc = "Trigger source is CTIMERA5 OUT2. value."] #[inline] pub fn a5out2(self) -> &'a mut W { self.variant(TMRB3TRIGW::A5OUT2) } #[doc = "Trigger source is CTIMERA1 OUT2. value."] #[inline] pub fn a1out2(self) -> &'a mut W { self.variant(TMRB3TRIGW::A1OUT2) } #[doc = "Trigger source is CTIMERB1 OUT2. value."] #[inline] pub fn b1out2(self) -> &'a mut W { self.variant(TMRB3TRIGW::B1OUT2) } #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] #[inline] pub fn a6out2dual(self) -> &'a mut W { self.variant(TMRB3TRIGW::A6OUT2DUAL) } #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] #[inline] pub fn a7out2dual(self) -> &'a mut W { self.variant(TMRB3TRIGW::A7OUT2DUAL) } #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] #[inline] pub fn b2out2dual(self) -> &'a mut W { self.variant(TMRB3TRIGW::B2OUT2DUAL) } #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] #[inline] pub fn a2out2dual(self) -> &'a mut W { self.variant(TMRB3TRIGW::A2OUT2DUAL) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _TMRB3LMTW<'a> { w: &'a mut W, } impl<'a> _TMRB3LMTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 63; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRA3EN23`"] pub enum TMRA3EN23W { #[doc = "Disable enhanced functions. value."] DIS, #[doc = "Enable enhanced functions. value."] EN, } impl TMRA3EN23W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRA3EN23W::DIS => true, TMRA3EN23W::EN => false, } } } #[doc = r" Proxy"] pub struct _TMRA3EN23W<'a> { w: &'a mut W, } impl<'a> _TMRA3EN23W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRA3EN23W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable enhanced functions. value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRA3EN23W::DIS) } #[doc = "Enable enhanced functions. value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(TMRA3EN23W::EN) } #[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 = 14; 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 `TMRA3POL23`"] pub enum TMRA3POL23W { #[doc = "Upper output normal polarity value."] NORM, #[doc = "Upper output inverted polarity. value."] INV, } impl TMRA3POL23W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRA3POL23W::NORM => false, TMRA3POL23W::INV => true, } } } #[doc = r" Proxy"] pub struct _TMRA3POL23W<'a> { w: &'a mut W, } impl<'a> _TMRA3POL23W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRA3POL23W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Upper output normal polarity value."] #[inline] pub fn norm(self) -> &'a mut W { self.variant(TMRA3POL23W::NORM) } #[doc = "Upper output inverted polarity. value."] #[inline] pub fn inv(self) -> &'a mut W { self.variant(TMRA3POL23W::INV) } #[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 = 13; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRA3TINV`"] pub enum TMRA3TINVW { #[doc = "Disable invert on trigger value."] DIS, #[doc = "Enable invert on trigger value."] EN, } impl TMRA3TINVW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRA3TINVW::DIS => false, TMRA3TINVW::EN => true, } } } #[doc = r" Proxy"] pub struct _TMRA3TINVW<'a> { w: &'a mut W, } impl<'a> _TMRA3TINVW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRA3TINVW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable invert on trigger value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRA3TINVW::DIS) } #[doc = "Enable invert on trigger value."] #[inline] pub fn en(self) -> &'a mut W { self.variant(TMRA3TINVW::EN) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRA3NOSYNC`"] pub enum TMRA3NOSYNCW { #[doc = "Synchronization on source clock value."] DIS, #[doc = "No synchronization on source clock value."] NOSYNC, } impl TMRA3NOSYNCW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { TMRA3NOSYNCW::DIS => false, TMRA3NOSYNCW::NOSYNC => true, } } } #[doc = r" Proxy"] pub struct _TMRA3NOSYNCW<'a> { w: &'a mut W, } impl<'a> _TMRA3NOSYNCW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRA3NOSYNCW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Synchronization on source clock value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRA3NOSYNCW::DIS) } #[doc = "No synchronization on source clock value."] #[inline] pub fn nosync(self) -> &'a mut W { self.variant(TMRA3NOSYNCW::NOSYNC) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `TMRA3TRIG`"] pub enum TMRA3TRIGW { #[doc = "Trigger source is disabled. value."] DIS, #[doc = "Trigger source is CTIMERB3 OUT. value."] B3OUT, #[doc = "Trigger source is CTIMERB2 OUT. value."] B2OUT, #[doc = "Trigger source is CTIMERA2 OUT. value."] A2OUT, #[doc = "Trigger source is CTIMERA4 OUT. value."] A4OUT, #[doc = "Trigger source is CTIMERB4 OUT. value."] B4OUT, #[doc = "Trigger source is CTIMERA7 OUT. value."] A7OUT, #[doc = "Trigger source is CTIMERB7 OUT. value."] B7OUT, #[doc = "Trigger source is CTIMERB5 OUT2. value."] B5OUT2, #[doc = "Trigger source is CTIMERA5 OUT2. value."] A5OUT2, #[doc = "Trigger source is CTIMERA1 OUT2. value."] A1OUT2, #[doc = "Trigger source is CTIMERB1 OUT2. value."] B1OUT2, #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] A6OUT2DUAL, #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] A7OUT2DUAL, #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] B2OUT2DUAL, #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] A2OUT2DUAL, } impl TMRA3TRIGW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { TMRA3TRIGW::DIS => 0, TMRA3TRIGW::B3OUT => 1, TMRA3TRIGW::B2OUT => 2, TMRA3TRIGW::A2OUT => 3, TMRA3TRIGW::A4OUT => 4, TMRA3TRIGW::B4OUT => 5, TMRA3TRIGW::A7OUT => 6, TMRA3TRIGW::B7OUT => 7, TMRA3TRIGW::B5OUT2 => 8, TMRA3TRIGW::A5OUT2 => 9, TMRA3TRIGW::A1OUT2 => 10, TMRA3TRIGW::B1OUT2 => 11, TMRA3TRIGW::A6OUT2DUAL => 12, TMRA3TRIGW::A7OUT2DUAL => 13, TMRA3TRIGW::B2OUT2DUAL => 14, TMRA3TRIGW::A2OUT2DUAL => 15, } } } #[doc = r" Proxy"] pub struct _TMRA3TRIGW<'a> { w: &'a mut W, } impl<'a> _TMRA3TRIGW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: TMRA3TRIGW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Trigger source is disabled. value."] #[inline] pub fn dis(self) -> &'a mut W { self.variant(TMRA3TRIGW::DIS) } #[doc = "Trigger source is CTIMERB3 OUT. value."] #[inline] pub fn b3out(self) -> &'a mut W { self.variant(TMRA3TRIGW::B3OUT) } #[doc = "Trigger source is CTIMERB2 OUT. value."] #[inline] pub fn b2out(self) -> &'a mut W { self.variant(TMRA3TRIGW::B2OUT) } #[doc = "Trigger source is CTIMERA2 OUT. value."] #[inline] pub fn a2out(self) -> &'a mut W { self.variant(TMRA3TRIGW::A2OUT) } #[doc = "Trigger source is CTIMERA4 OUT. value."] #[inline] pub fn a4out(self) -> &'a mut W { self.variant(TMRA3TRIGW::A4OUT) } #[doc = "Trigger source is CTIMERB4 OUT. value."] #[inline] pub fn b4out(self) -> &'a mut W { self.variant(TMRA3TRIGW::B4OUT) } #[doc = "Trigger source is CTIMERA7 OUT. value."] #[inline] pub fn a7out(self) -> &'a mut W { self.variant(TMRA3TRIGW::A7OUT) } #[doc = "Trigger source is CTIMERB7 OUT. value."] #[inline] pub fn b7out(self) -> &'a mut W { self.variant(TMRA3TRIGW::B7OUT) } #[doc = "Trigger source is CTIMERB5 OUT2. value."] #[inline] pub fn b5out2(self) -> &'a mut W { self.variant(TMRA3TRIGW::B5OUT2) } #[doc = "Trigger source is CTIMERA5 OUT2. value."] #[inline] pub fn a5out2(self) -> &'a mut W { self.variant(TMRA3TRIGW::A5OUT2) } #[doc = "Trigger source is CTIMERA1 OUT2. value."] #[inline] pub fn a1out2(self) -> &'a mut W { self.variant(TMRA3TRIGW::A1OUT2) } #[doc = "Trigger source is CTIMERB1 OUT2. value."] #[inline] pub fn b1out2(self) -> &'a mut W { self.variant(TMRA3TRIGW::B1OUT2) } #[doc = "Trigger source is CTIMERA6 OUT2, dual edge. value."] #[inline] pub fn a6out2dual(self) -> &'a mut W { self.variant(TMRA3TRIGW::A6OUT2DUAL) } #[doc = "Trigger source is CTIMERA7 OUT2, dual edge. value."] #[inline] pub fn a7out2dual(self) -> &'a mut W { self.variant(TMRA3TRIGW::A7OUT2DUAL) } #[doc = "Trigger source is CTIMERB2 OUT2, dual edge. value."] #[inline] pub fn b2out2dual(self) -> &'a mut W { self.variant(TMRA3TRIGW::B2OUT2DUAL) } #[doc = "Trigger source is CTIMERA2 OUT2, dual edge. value."] #[inline] pub fn a2out2dual(self) -> &'a mut W { self.variant(TMRA3TRIGW::A2OUT2DUAL) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _TMRA3LMTW<'a> { w: &'a mut W, } impl<'a> _TMRA3LMTW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 127; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 30 - Counter/Timer B3 Upper compare enable."] #[inline] pub fn tmrb3en23(&self) -> TMRB3EN23R { TMRB3EN23R::_from({ const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 29 - Upper output polarity"] #[inline] pub fn tmrb3pol23(&self) -> TMRB3POL23R { TMRB3POL23R::_from({ const MASK: bool = true; const OFFSET: u8 = 29; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 28 - Counter/Timer B3 Invert on trigger."] #[inline] pub fn tmrb3tinv(&self) -> TMRB3TINVR { TMRB3TINVR::_from({ const MASK: bool = true; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 27 - Source clock synchronization control."] #[inline] pub fn tmrb3nosync(&self) -> TMRB3NOSYNCR { TMRB3NOSYNCR::_from({ const MASK: bool = true; const OFFSET: u8 = 27; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 23:26 - Counter/Timer B3 Trigger Select."] #[inline] pub fn tmrb3trig(&self) -> TMRB3TRIGR { TMRB3TRIGR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 16:21 - Counter/Timer B3 Pattern Limit Count."] #[inline] pub fn tmrb3lmt(&self) -> TMRB3LMTR { let bits = { const MASK: u8 = 63; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; TMRB3LMTR { bits } } #[doc = "Bit 14 - Counter/Timer A3 Upper compare enable."] #[inline] pub fn tmra3en23(&self) -> TMRA3EN23R { TMRA3EN23R::_from({ const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 13 - Counter/Timer A3 Upper output polarity"] #[inline] pub fn tmra3pol23(&self) -> TMRA3POL23R { TMRA3POL23R::_from({ const MASK: bool = true; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 12 - Counter/Timer A3 Invert on trigger."] #[inline] pub fn tmra3tinv(&self) -> TMRA3TINVR { TMRA3TINVR::_from({ const MASK: bool = true; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 11 - Source clock synchronization control."] #[inline] pub fn tmra3nosync(&self) -> TMRA3NOSYNCR { TMRA3NOSYNCR::_from({ const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 7:10 - Counter/Timer A3 Trigger Select."] #[inline] pub fn tmra3trig(&self) -> TMRA3TRIGR { TMRA3TRIGR::_from({ const MASK: u8 = 15; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 0:6 - Counter/Timer A3 Pattern Limit Count."] #[inline] pub fn tmra3lmt(&self) -> TMRA3LMTR { let bits = { const MASK: u8 = 127; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; TMRA3LMTR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 30 - Counter/Timer B3 Upper compare enable."] #[inline] pub fn tmrb3en23(&mut self) -> _TMRB3EN23W { _TMRB3EN23W { w: self } } #[doc = "Bit 29 - Upper output polarity"] #[inline] pub fn tmrb3pol23(&mut self) -> _TMRB3POL23W { _TMRB3POL23W { w: self } } #[doc = "Bit 28 - Counter/Timer B3 Invert on trigger."] #[inline] pub fn tmrb3tinv(&mut self) -> _TMRB3TINVW { _TMRB3TINVW { w: self } } #[doc = "Bit 27 - Source clock synchronization control."] #[inline] pub fn tmrb3nosync(&mut self) -> _TMRB3NOSYNCW { _TMRB3NOSYNCW { w: self } } #[doc = "Bits 23:26 - Counter/Timer B3 Trigger Select."] #[inline] pub fn tmrb3trig(&mut self) -> _TMRB3TRIGW { _TMRB3TRIGW { w: self } } #[doc = "Bits 16:21 - Counter/Timer B3 Pattern Limit Count."] #[inline] pub fn tmrb3lmt(&mut self) -> _TMRB3LMTW { _TMRB3LMTW { w: self } } #[doc = "Bit 14 - Counter/Timer A3 Upper compare enable."] #[inline] pub fn tmra3en23(&mut self) -> _TMRA3EN23W { _TMRA3EN23W { w: self } } #[doc = "Bit 13 - Counter/Timer A3 Upper output polarity"] #[inline] pub fn tmra3pol23(&mut self) -> _TMRA3POL23W { _TMRA3POL23W { w: self } } #[doc = "Bit 12 - Counter/Timer A3 Invert on trigger."] #[inline] pub fn tmra3tinv(&mut self) -> _TMRA3TINVW { _TMRA3TINVW { w: self } } #[doc = "Bit 11 - Source clock synchronization control."] #[inline] pub fn tmra3nosync(&mut self) -> _TMRA3NOSYNCW { _TMRA3NOSYNCW { w: self } } #[doc = "Bits 7:10 - Counter/Timer A3 Trigger Select."] #[inline] pub fn tmra3trig(&mut self) -> _TMRA3TRIGW { _TMRA3TRIGW { w: self } } #[doc = "Bits 0:6 - Counter/Timer A3 Pattern Limit Count."] #[inline] pub fn tmra3lmt(&mut self) -> _TMRA3LMTW { _TMRA3LMTW { w: self } } }
use std::collections::HashMap; use std::io; // private let employee_to_department = HashMap::new(); fn list_employees_in_department( department_name: String, employee_to_department: &HashMap<String, String>, ) -> Vec<String> { let mut employees: Vec<String> = Vec::new(); for (employeeName, departmentName) in employee_to_department { let employee_name = String::from(employeeName); if &department_name == departmentName { employees.push(employee_name); } } return employees; } pub fn run() { let mut employee_to_department: HashMap<String, String> = HashMap::new(); loop { println!("Enter 'add' to add an employee to a department."); println!("Enter 'list' to list the employees by department."); println!("Enter 'q' to quit."); let mut command = String::new(); io::stdin() .read_line(&mut command) .expect("Failed to read line."); let command: String = match command.trim().parse() { Ok(s) => s, Err(_) => continue, }; if command == "q" { break; } else if command == "add" { println!("Enter employee name:\n"); let mut employee = String::new(); io::stdin() .read_line(&mut employee) .expect("Failed to read line."); let employee: String = match employee.trim().parse() { Ok(s) => s, Err(_) => continue, }; if employee.len() == 0 { println!("Employee must have length greater than 0."); continue; } println!("Enter department name:\n"); let mut department = String::new(); io::stdin() .read_line(&mut department) .expect("Failed to read line."); let department: String = match department.trim().parse() { Ok(s) => s, Err(_) => continue, }; if department.len() == 0 { println!("Department must have length greater than 0."); continue; } employee_to_department.insert(employee, department); } else if command == "list" { println!("Enter department name:\n"); let mut department = String::new(); io::stdin() .read_line(&mut department) .expect("Failed to read line."); let department: String = match department.trim().parse() { Ok(s) => s, Err(_) => continue, }; println!( "{}", list_employees_in_department(department, &employee_to_department).join(" ") ); } } }
extern crate cairo; extern crate gdk; extern crate gdk_sys; extern crate gtk; extern crate i3ipc; extern crate time; use std::cell::RefCell; use std::ops::Range; use std::process::Command; use std::rc::Rc; use std::thread; use gtk::prelude::*; use i3ipc::{I3Connection, I3EventListener, Subscription}; use relm::{Channel, Relm, Update, Widget}; use ::config::Config; pub struct WorkspaceModel { config: &'static Config, channel: Channel<WorkspaceMsg>, items: Vec<Item>, } pub struct WorkspaceWidget { model: Rc<RefCell<WorkspaceModel>>, widget: gtk::DrawingArea, } #[derive(Debug, Msg)] pub enum WorkspaceMsg { Items(Vec<Item>), Click((f64, f64)), } #[derive(Debug)] pub struct Item { workspace: (i64, i64), position: Range<f64>, state: State, } #[derive(Debug)] enum State { /// A workspace that doesn't actually exist (has no windows) but should be shown and can be /// switched to. Phantom, /// A regular workspace that has windows in it, but isn't visible. Inhibited, /// A workspace that's visible but not currently active. Visible, /// The workspace that is currently active. Active, /// A workspace with an urgent window in it, even if the workspace is visible or active. Urgent, } impl WorkspaceWidget { fn render(model: &WorkspaceModel, widget: &gtk::DrawingArea, cx: &cairo::Context) { let width = widget.get_allocated_width() as f64; let height = widget.get_allocated_height() as f64; let dpi = model.config.dpi; if model.items.is_empty() { return } let workspace_height = height * 0.25; let skew_ratio = 0.2; let skew = workspace_height * skew_ratio; let required_width = model.items.last().unwrap().position.end * dpi + skew + 5.0; if required_width > width { widget.set_size_request(required_width as i32 + 5, height as i32); return; } if required_width < width - 10.0 { widget.set_size_request(required_width as i32 + 5, height as i32); return; } let first_workspace = model.items.first().unwrap() as *const Item; let last_workspace = model.items.last().unwrap() as *const Item; let line_width = (1.0 * dpi).floor() * 2.0; let top = (height / 2.0 - workspace_height / 2.0).ceil(); let bottom = (height / 2.0 + workspace_height / 2.0).floor(); cx.set_operator(cairo::Operator::Source); for workspace in &model.items { let mut left_top = workspace.position.start * dpi; let mut left_bottom = left_top; let mut right_top = workspace.position.end * dpi; let mut right_bottom = right_top; if workspace as *const Item != first_workspace { left_top += skew; left_bottom -= skew; } if workspace as *const Item != last_workspace { right_top += skew; right_bottom -= skew; } cx.move_to(left_top, top); cx.line_to(right_top, top); cx.line_to(right_bottom, bottom); cx.line_to(left_bottom, bottom); cx.close_path(); match workspace.state { State::Urgent => cx.set_source_rgba(1.0, 0.7, 0.0, 0.92), State::Active => cx.set_source_rgba(1.0, 1.0, 1.0, 0.92), State::Visible => cx.set_source_rgba(0.7, 0.7, 0.7, 0.92), State::Inhibited => cx.set_source_rgba(0.4, 0.4, 0.4, 0.92), State::Phantom => cx.set_source_rgba(0.4, 0.4, 0.4, 0.92), } cx.set_line_width(line_width); cx.stroke_preserve(); match workspace.state { State::Urgent => cx.set_source_rgba(1.0, 0.7, 0.0, 0.92), State::Active => cx.set_source_rgba(0.8, 0.8, 0.8, 0.92), State::Visible => cx.set_source_rgba(0.4, 0.4, 0.4, 0.92), State::Inhibited => cx.set_source_rgba(0.4, 0.4, 0.4, 0.92), State::Phantom => cx.set_source_rgba(0.1, 0.1, 0.1, 0.92), } cx.set_line_width(0.0); cx.fill(); } } fn handle_click(&self, (x, _y): (f64, f64)) { let model = self.model.borrow(); for item in &model.items { if item.position.contains(&(x / model.config.dpi)) { Command::new("/bin/bash") .arg("-c") .arg(format!("i3 workspace {}-{}", item.workspace.0, item.workspace.1)) .spawn() .expect("failed to execute child"); } } } } impl Update for WorkspaceWidget { type Model = WorkspaceModel; type ModelParam = &'static Config; type Msg = WorkspaceMsg; // Return the initial model. fn model(relm: &Relm<Self>, config: Self::ModelParam) -> Self::Model { let stream = relm.stream().clone(); let (channel, sx) = Channel::new(move |msg| { stream.emit(msg); }); thread::spawn(move || { let mut i3 = I3Connection::connect().unwrap(); let mut listener = I3EventListener::connect().unwrap(); let subs = [ Subscription::Workspace ]; listener.subscribe(&subs).unwrap(); let mut listener = listener.listen(); loop { /// Turns workspace names such as 1-2 (screen-workspace) into a tuple of the numbers fn parse_workspace_name(name: &str) -> Result<(i64, i64), &'static str> { if name.len() < 3 { return Err("name too short"); } if name.len() != name.chars().count() { return Err("name contains multibyte characters"); } let (screen, workspace) = name.split_at(1); let screen = screen.parse().map_err(|_| "invalid workspace name")?; let workspace = (&workspace[1..]).parse().map_err(|_| "invalid workspace name")?; Ok((screen, workspace)) } let res = i3.get_workspaces().unwrap().workspaces.iter().map(|workspace| { parse_workspace_name(&workspace.name) .map(|position| { let state = if workspace.urgent { State::Urgent } else if workspace.focused { State::Active } else if workspace.visible { State::Visible } else { State::Inhibited }; (position, state) }) }).collect::<Result<Vec<_>, _>>(); let res = res.map(|mut workspaces| { if workspaces.is_empty() { return vec![] } let min_desktops = &[4, 2, 1]; let screen_order = &[1, 0, 2]; workspaces.sort_by_key(|(pos, _state)| (screen_order[pos.0 as usize - 1], pos.1)); let workspaces = workspaces.into_iter().peekable(); let item_width = 35.0; let padding = 6.0; let spacing = 15.0; let mut items = vec![]; let mut left = -padding; let mut last_screen = 0; let mut last_desktop = 0; for (workspace, state) in workspaces { left += padding; if last_screen != workspace.0 { if last_screen != 0 { for n in (last_desktop + 1) .. (min_desktops[last_screen as usize - 1] + 1) { let workspace = (last_screen, n); let position = (left) .. (left + item_width); left += item_width + padding; let state = State::Phantom; items.push(Item { workspace, position, state, }); } } left += spacing; last_desktop = 0; } for n in (last_desktop + 1) .. workspace.1 { let workspace = (workspace.0, n); let position = (left) .. (left + item_width); left += item_width + padding; let state = State::Phantom; items.push(Item { workspace, position, state, }); } let position = (left) .. (left + item_width); left += item_width; items.push(Item { workspace, position, state, }); last_screen = workspace.0; last_desktop = workspace.1; } items }); sx.send(WorkspaceMsg::Items(res.unwrap())); listener.next(); } }); WorkspaceModel { config, items: vec![], channel, } } fn update(&mut self, msg: Self::Msg) { use self::WorkspaceMsg::*; match msg { Items(v) => self.model.borrow_mut().items = v, Click(e) => self.handle_click(e), } self.widget.queue_draw(); } fn subscriptions(&mut self, _relm: &Relm<Self>) { } } impl Widget for WorkspaceWidget { type Root = gtk::DrawingArea; fn root(&self) -> Self::Root { self.widget.clone() } fn view(relm: &Relm<Self>, model: Self::Model) -> Self { let widget = gtk::DrawingArea::new(); let model = Rc::new(RefCell::new(model)); widget.add_events(gdk::EventMask::BUTTON_PRESS_MASK.bits() as i32); widget.add_events(gdk::EventMask::BUTTON_RELEASE_MASK.bits() as i32); connect!(relm, widget, connect_button_release_event(_, e), return if e.get_button() == 1 { (Some(WorkspaceMsg::Click(e.get_position())), Inhibit(true)) } else { (None, Inhibit(false)) }); widget.connect_draw(clone!(model => move |widget, cx| { WorkspaceWidget::render(&model.borrow(), widget, cx); Inhibit(false) })); WorkspaceWidget { model, widget, } } }
pub mod cam; pub mod plane; pub mod settings; pub mod world; use bevy::prelude::*; fn main() { App::build() .add_plugin(settings::SettingsPlugin) .add_plugin(world::WorldPlugin) .add_resource(Msaa { samples: 4 }) .add_plugin(plane::PlanePlugin) .add_plugin(cam::CameraPlugin) .add_default_plugins() .run(); }
mod cf; mod request; mod response; pub mod prelude { pub use crate::cf::Cf; pub use crate::request::Request; pub use crate::response::{Response, ResponseInit}; } pub use cf::Cf; pub use request::Request; pub use response::{Response, ResponseInit};
use clap::Parser; use image_encryption::{decrypt_image, encrypt_image, load_image, write_image}; #[derive(Debug, Clone, Copy, clap::ValueEnum)] pub enum Mode { Enc, Dec, } /// simple image encryption program #[derive(Debug, Parser)] struct Args { /// encrypt an image or decrypt an encrypted one #[clap(value_enum)] mode: Mode, /// the encryption/decryption key key: u64, /// image input path input: String, /// image output path /// if omitted, input file is overwritten output: Option<String>, } fn main() { let args = Args::parse(); let mut img = match load_image(&args.input) { Ok(val) => val, Err(err) => { eprintln!("{}", err); return; } }; match args.mode { Mode::Enc => encrypt_image(&mut img, args.key), Mode::Dec => decrypt_image(&mut img, args.key), } if let Err(err) = write_image(args.output.unwrap_or(args.input), img) { eprintln!("{}", err) }; }
pub mod gillespie;
use chiropterm::*; use euclid::{rect, size2}; use super::WidgetDimensions; // TODO: "InternalWidgetDimensions" with an optional max and align // ExternalWidgetDimensions with no max or align #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct InternalWidgetDimensions { // widget will force its width below this if possible pub min: CellSize, pub preferred: CellSize, pub max: Option<CellSize>, pub align_size_to: CellSize, pub horizontal_spacer_count: usize, pub vertical_spacer_count: usize, } impl InternalWidgetDimensions { pub const fn zero() -> InternalWidgetDimensions { InternalWidgetDimensions { min: size2(0, 0), preferred: size2(0, 0), max: None, align_size_to: size2(1, 1), horizontal_spacer_count: 0, vertical_spacer_count: 0, } } pub(crate) fn fixup(mut self) -> InternalWidgetDimensions { // TODO: fix impossibilities self = self.shape_to_align(self.align_size_to); self } pub fn tailor<'a>(&self, brush: Brush<'a>) -> Brush<'a> { let existing_size = brush.rect().size; let region = brush.region(rect( 0, 0, existing_size.width - existing_size.width % self.align_size_to.width, existing_size.height - existing_size.height % self.align_size_to.height, )); let existing_size = brush.rect().size; let region = if let Some(max) = self.max { region.region(rect( 0, 0, self.min.width.max(max.width.min(existing_size.width)), self.min.height.max(max.height.min(existing_size.height)), )) } else { region.region(rect( 0, 0, self.min.width.max(existing_size.width), self.min.height.max(existing_size.height), )) }; region } pub(crate) fn shape_to_align(mut self, align: CellSize) -> InternalWidgetDimensions { fn fix(align: CellSize, mut sz: CellSize) -> CellSize { if align.width > 0 && sz.width % align.width != 0 { sz.width += align.width - (sz.width % align.width); } if align.height > 0 && sz.height % align.height != 0 { sz.height += align.height - (sz.height % align.height); } sz } self.min = fix(align, self.min); self.preferred = fix(align, self.preferred); if let Some(max) = self.max { self.max = Some(fix(align, max)); } self } pub(crate) fn increase(mut self, amt: CellSize) -> InternalWidgetDimensions { self.min.width += amt.width; self.min.height += amt.height; self.preferred.width += amt.width; self.preferred.height += amt.height; if let Some(mut max) = self.max { max.width += amt.width; max.height += amt.height; self.max = Some(max); } self } pub(crate) fn to_external(mut self) -> super::WidgetDimensions { self = self.fixup(); WidgetDimensions { min: self.min, preferred: self.preferred, align_size_to: self.align_size_to, horizontal_spacer_count: self.horizontal_spacer_count, vertical_spacer_count: self.vertical_spacer_count, } } }
/*! # Advent of Code 2020 - Day 02 [Link to task.](https://adventofcode.com/2020/day/2) How many password are valid based on password policies at the time? Input file is in rows similar to "1-3 a: abcde". Number range implies how many letters there has to be. After semicolon is the password itself. In this example atleast 1, but at most 3, instances of letter "a" is allowed on the password "abcde". The example password is thus valid. Go through input data and validate all password. Count valid passwords. ## Usage example ```text ignore PS> cargo run --bin day_02 Compiling day_02 v0.1.0 (...\advent_of_code_2020\day_02) Finished dev [unoptimized + debuginfo] target(s) in 1.81s Running `target\debug\day_02.exe` Advent of Code 2020 - Day 02 Info: Using hard-coded test data. ".aoc-session" not found. Answer: 2 valid passwords in input data. ``` !*/ use anyhow::{bail, Result}; use reqwest; use std::fs::read_to_string; use std::path::Path; static AOC_URL: &'static str = "https://adventofcode.com/2020/day/2/input"; static AOC_SESSION_FILE: &'static str = ".aoc-session"; #[derive(Debug)] pub struct PassPolicy { required_letter: char, pos_1: u32, pos_2: u32, } #[derive(Debug)] pub struct PassInstance { policy: PassPolicy, password: String, } impl PassInstance { fn from_string(txt: &str) -> PassInstance { // Split string to amount, required letter and password parts. let parts: Vec<&str> = txt.split_whitespace().map(|s| s.into()).collect(); let charpos: Vec<&str> = parts[0].split("-").collect(); assert_eq!(parts.len(), 3); PassInstance { policy: PassPolicy { required_letter: parts[1].replace(":", "").chars().nth(0).unwrap(), pos_1: charpos[0].parse().expect("Failed to parse password policy"), pos_2: charpos[1].parse().expect("failed to parse password policy"), }, password: parts[2].to_owned(), } } fn is_valid(&self) -> bool { let req1: bool = match self.password.chars().nth(self.policy.pos_1 as usize - 1) { Some(char) => { if char == self.policy.required_letter { true } else { false } } None => false, }; let req2: bool = match self.password.chars().nth(self.policy.pos_2 as usize - 1) { Some(char) => { if char == self.policy.required_letter { true } else { false } } None => false, }; // Password is valid when exactly one position is required_letter. return req1 ^ req2; } } /// This function downloads input data from Advent of Code /// if .aoc-session file is available and download succeeds. fn get_input_aoc() -> Result<String> { let f = Path::new(&AOC_SESSION_FILE); if !f.is_file() { bail!("{:?} not found.", &AOC_SESSION_FILE); } // Load session key let session_key = read_to_string(f)?; // Load input data let client = reqwest::blocking::Client::new(); let response = client .get(AOC_URL) .header("Cookie", format!("session={}", session_key)) .send() .expect("Sending request failed."); if response.status().is_success() { let resp = response.text()?; return Ok(resp); } else { bail!( "Failed to load {:?}. Response: {:?}", &AOC_URL, response.status() ) } } /// If input data download was not available, this function /// returns hardcoded test data which is allowed to be shared. fn get_input_test() -> String { String::from( "1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc", ) .to_owned() } /// Get input data either from AOC website or fall-back to local /// hard-coded test data. pub fn get_input() -> Vec<String> { let input: String = match get_input_aoc() { Ok(data) => { println!("Info: Downloaded test data from: {}", AOC_URL); data } Err(e) => { println!("Info: Using hard-coded test data. {}", e); get_input_test() } }; let data = input.lines().map(|s| s.trim().to_string()).collect(); return data; } pub fn parse_input(input: Vec<String>) -> Vec<PassInstance> { let mut output: Vec<PassInstance> = Vec::new(); for line in input.iter() { output.push(PassInstance::from_string(line)); } return output; } pub fn count_valid_passwords(input: Vec<PassInstance>) -> u32 { let amount: u32 = input.iter().filter(|x| x.is_valid()).count() as u32; amount } fn main() { println!("Advent of Code 2020 - Day 02"); let valid_count = count_valid_passwords(parse_input(get_input())); println!("Answer: {} valid passwords in input data.", valid_count); } #[cfg(test)] mod day_02 { use super::*; #[test] fn run() { main(); } }
#[macro_use] extern crate criterion; extern crate netlink_packet_core; extern crate netlink_packet_route; extern crate pcap_file; use criterion::Criterion; use netlink_packet_core::NetlinkMessage; use netlink_packet_route::RtnlMessage; use pcap_file::PcapReader; use std; use std::fs::File; fn bench(c: &mut Criterion) { let pcap_reader = PcapReader::new(File::open("data/rtnetlink.pcap").unwrap()).unwrap(); let packets: Vec<Vec<u8>> = pcap_reader .map(|pkt| pkt.unwrap().data.into_owned().to_vec()) .collect(); c.bench_function("parse", move |b| { b.iter(|| { for (i, buf) in packets.iter().enumerate() { NetlinkMessage::<RtnlMessage>::deserialize(&buf[16..]) .expect(&format!("message {} failed", i)); } }) }); } criterion_group!(benches, bench); criterion_main!(benches);
#[doc = "Register `GTZC1_TZSC_PRIVCFGR3` reader"] pub type R = crate::R<GTZC1_TZSC_PRIVCFGR3_SPEC>; #[doc = "Register `GTZC1_TZSC_PRIVCFGR3` writer"] pub type W = crate::W<GTZC1_TZSC_PRIVCFGR3_SPEC>; #[doc = "Field `I3C2PRIV` reader - privileged access mode for I3C2"] pub type I3C2PRIV_R = crate::BitReader; #[doc = "Field `I3C2PRIV` writer - privileged access mode for I3C2"] pub type I3C2PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRCPRIV` reader - privileged access mode for CRC"] pub type CRCPRIV_R = crate::BitReader; #[doc = "Field `CRCPRIV` writer - privileged access mode for CRC"] pub type CRCPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ICACHEPRIV` reader - privileged access mode for ICACHE"] pub type ICACHEPRIV_R = crate::BitReader; #[doc = "Field `ICACHEPRIV` writer - privileged access mode for ICACHE"] pub type ICACHEPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADC1PRIV` reader - privileged access mode for ADC1"] pub type ADC1PRIV_R = crate::BitReader; #[doc = "Field `ADC1PRIV` writer - privileged access mode for ADC1"] pub type ADC1PRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HASHPRIV` reader - privileged access mode for HASH"] pub type HASHPRIV_R = crate::BitReader; #[doc = "Field `HASHPRIV` writer - privileged access mode for HASH"] pub type HASHPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RNGPRIV` reader - privileged access mode for RNG"] pub type RNGPRIV_R = crate::BitReader; #[doc = "Field `RNGPRIV` writer - privileged access mode for RNG"] pub type RNGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RAMCFGPRIV` reader - privileged access mode for RAMSCFG"] pub type RAMCFGPRIV_R = crate::BitReader; #[doc = "Field `RAMCFGPRIV` writer - privileged access mode for RAMSCFG"] pub type RAMCFGPRIV_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 2 - privileged access mode for I3C2"] #[inline(always)] pub fn i3c2priv(&self) -> I3C2PRIV_R { I3C2PRIV_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 8 - privileged access mode for CRC"] #[inline(always)] pub fn crcpriv(&self) -> CRCPRIV_R { CRCPRIV_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 12 - privileged access mode for ICACHE"] #[inline(always)] pub fn icachepriv(&self) -> ICACHEPRIV_R { ICACHEPRIV_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 14 - privileged access mode for ADC1"] #[inline(always)] pub fn adc1priv(&self) -> ADC1PRIV_R { ADC1PRIV_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 17 - privileged access mode for HASH"] #[inline(always)] pub fn hashpriv(&self) -> HASHPRIV_R { HASHPRIV_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - privileged access mode for RNG"] #[inline(always)] pub fn rngpriv(&self) -> RNGPRIV_R { RNGPRIV_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 26 - privileged access mode for RAMSCFG"] #[inline(always)] pub fn ramcfgpriv(&self) -> RAMCFGPRIV_R { RAMCFGPRIV_R::new(((self.bits >> 26) & 1) != 0) } } impl W { #[doc = "Bit 2 - privileged access mode for I3C2"] #[inline(always)] #[must_use] pub fn i3c2priv(&mut self) -> I3C2PRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 2> { I3C2PRIV_W::new(self) } #[doc = "Bit 8 - privileged access mode for CRC"] #[inline(always)] #[must_use] pub fn crcpriv(&mut self) -> CRCPRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 8> { CRCPRIV_W::new(self) } #[doc = "Bit 12 - privileged access mode for ICACHE"] #[inline(always)] #[must_use] pub fn icachepriv(&mut self) -> ICACHEPRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 12> { ICACHEPRIV_W::new(self) } #[doc = "Bit 14 - privileged access mode for ADC1"] #[inline(always)] #[must_use] pub fn adc1priv(&mut self) -> ADC1PRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 14> { ADC1PRIV_W::new(self) } #[doc = "Bit 17 - privileged access mode for HASH"] #[inline(always)] #[must_use] pub fn hashpriv(&mut self) -> HASHPRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 17> { HASHPRIV_W::new(self) } #[doc = "Bit 18 - privileged access mode for RNG"] #[inline(always)] #[must_use] pub fn rngpriv(&mut self) -> RNGPRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 18> { RNGPRIV_W::new(self) } #[doc = "Bit 26 - privileged access mode for RAMSCFG"] #[inline(always)] #[must_use] pub fn ramcfgpriv(&mut self) -> RAMCFGPRIV_W<GTZC1_TZSC_PRIVCFGR3_SPEC, 26> { RAMCFGPRIV_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "GTZC1 TZSC privilege configuration register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gtzc1_tzsc_privcfgr3::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gtzc1_tzsc_privcfgr3::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GTZC1_TZSC_PRIVCFGR3_SPEC; impl crate::RegisterSpec for GTZC1_TZSC_PRIVCFGR3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gtzc1_tzsc_privcfgr3::R`](R) reader structure"] impl crate::Readable for GTZC1_TZSC_PRIVCFGR3_SPEC {} #[doc = "`write(|w| ..)` method takes [`gtzc1_tzsc_privcfgr3::W`](W) writer structure"] impl crate::Writable for GTZC1_TZSC_PRIVCFGR3_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets GTZC1_TZSC_PRIVCFGR3 to value 0"] impl crate::Resettable for GTZC1_TZSC_PRIVCFGR3_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! Contains various pre-build expressions. pub mod irreducibles; pub mod operations;
//! This module implements the internal storage format for //! the voxel data in each sector. use crate::{block::Block, side::Side}; use core::slice; /// The number of voxels that comprise one edge of a sector, /// excluding padding. pub const SECTOR_DIM_EXCL: usize = 16; /// The number of voxels that are shared with the neighboring /// sector within one sector. pub const SECTOR_PAD: usize = 1; /// The number of voxels along one edge of a sector, including /// padding. pub const SECTOR_DIM: usize = SECTOR_PAD + SECTOR_DIM_EXCL + SECTOR_PAD; /// The total number of voxels in one cubic sector. pub const SECTOR_LEN: usize = SECTOR_DIM * SECTOR_DIM * SECTOR_DIM; /// The smallest component allowed in a sector space coordinate. pub const SECTOR_MIN: usize = 0; /// The largest component allowed in a sector space coordinate. pub const SECTOR_MAX: usize = SECTOR_DIM - 1; /// Represents a position relative to the back lower left of a sector. /// /// Each triplet of integers maps to one voxel. #[derive(Clone, Copy, Debug)] pub struct SectorCoords(pub usize, pub usize, pub usize); impl SectorCoords { /// Return the coordinates for the neighboring block /// specified by ``neighbor``, if they exist. /// /// If ``self`` is already on a sector boundary and the /// indicated direction points to a block outside the /// valid sector range, ``None`` is returned. pub fn neighbor(self, neighbor: Side) -> Option<SectorCoords> { let SectorCoords(x, y, z) = self; match neighbor { Side::Front => { if z < SECTOR_MAX { Some(SectorCoords(x, y, z + 1)) } else { None } } Side::Back => { if z > SECTOR_MIN { Some(SectorCoords(x, y, z - 1)) } else { None } } Side::RightSide => { if x < SECTOR_MAX { Some(SectorCoords(x + 1, y, z)) } else { None } } Side::LeftSide => { if x > SECTOR_MIN { Some(SectorCoords(x - 1, y, z)) } else { None } } Side::Top => { if y < SECTOR_MAX { Some(SectorCoords(x, y + 1, z)) } else { None } } Side::Bottom => { if y > SECTOR_MIN { Some(SectorCoords(x, y - 1, z)) } else { None } } } } } /// Holds the voxel data for a sector. pub struct SectorData { blocks: [Block; SECTOR_LEN], } impl SectorData { /// Create a new ``SectorData`` filled with the default block. pub fn new() -> SectorData { SectorData { blocks: [Block::default(); SECTOR_LEN], } } /// Return a reference to the block located at the given position. pub fn block(&self, sector_coords: SectorCoords) -> &Block { let idx = Self::index(sector_coords); &self.blocks[idx] } /// Return a mutable reference to the block located at the given position. pub fn block_mut(&mut self, sector_coords: SectorCoords) -> &mut Block { let idx = Self::index(sector_coords); &mut self.blocks[idx] } /// Iterate over the entries of the ``SectorData``. pub fn iter(&self) -> SectorIter<'_> { self.into_iter() } /// Iterate mutably over the entries of the ``SectorData``. pub fn iter_mut(&mut self) -> SectorIterMut<'_> { self.into_iter() } /// Determine the array index of a particular voxel coordinate. fn index(sector_coords: SectorCoords) -> usize { let SectorCoords(x, y, z) = sector_coords; x + y * SECTOR_DIM + z * SECTOR_DIM * SECTOR_DIM } // Determine the sector coordinates that correspond to a // particular array index. fn coords(idx: usize) -> SectorCoords { let mut remaining = idx; let z = remaining / (SECTOR_DIM * SECTOR_DIM); remaining -= z * SECTOR_DIM * SECTOR_DIM; let y = remaining / SECTOR_DIM; remaining -= y * SECTOR_DIM; let x = remaining; SectorCoords(x, y, z) } } /// The type of the ``Item`` that ``SectorIter`` yields. pub type DataEntry<'a> = (SectorCoords, &'a Block); /// Iterates over the ``Block``s in a ``SectorData`` instance. pub struct SectorIter<'a> { inner: slice::Iter<'a, Block>, current: usize, } impl<'a> Iterator for SectorIter<'a> { type Item = DataEntry<'a>; fn next(&mut self) -> Option<Self::Item> { if let Some(item) = self.inner.next() { let coords = SectorData::coords(self.current); self.current += 1; Some((coords, item)) } else { None } } } impl<'a> IntoIterator for &'a SectorData { type Item = DataEntry<'a>; type IntoIter = SectorIter<'a>; fn into_iter(self) -> Self::IntoIter { SectorIter { inner: self.blocks.iter(), current: 0, } } } /// The type of the ``Item`` that ``SectorIterMut`` yields; pub type DataEntryMut<'a> = (SectorCoords, &'a mut Block); /// Iterates mutably over the ``Block``s in a ``SectorData`` instance. pub struct SectorIterMut<'a> { inner: slice::IterMut<'a, Block>, current: usize, } impl<'a> Iterator for SectorIterMut<'a> { type Item = DataEntryMut<'a>; fn next(&mut self) -> Option<Self::Item> { if let Some(item) = self.inner.next() { let coords = SectorData::coords(self.current); self.current += 1; Some((coords, item)) } else { None } } } impl<'a> IntoIterator for &'a mut SectorData { type Item = DataEntryMut<'a>; type IntoIter = SectorIterMut<'a>; fn into_iter(self) -> Self::IntoIter { SectorIterMut { inner: self.blocks.iter_mut(), current: 0, } } }
use serde::{Deserialize, Serialize}; use super::asset_format::AssetFormat; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct NativeFormat { asset: Vec<AssetFormat>, ext: Option<NativeFormatExt>, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct NativeFormatExt {}
extern crate problem12; use std::collections::HashMap; use problem12::{rule_set, plants}; use std::fs; fn main() -> Result<(), String> { let input = fs::read_to_string("input/data.txt").map_err(|e| e.to_string())?; let rules = rule_set::get_rule_set(&input); let initial_state = "#.##.#.##..#.#...##...#......##..#..###..##..#.#.....##..###...#.#..#...######...#####..##....#..###"; assert_eq!(2166, evaluate_generations(&initial_state, &rules, 20)); // Turned out to be a pattern: 21(0{N-1})61, where N = the number of zeros // Similar patterns emerged for 1E3+, etc. // dbg!(evaluate_generations(&initial_state, &rules, 50000000000)); Ok(()) } fn evaluate_generations( initial_state: &str, rules: &HashMap<Vec<u8>, u8>, num_generations: u64, ) -> i32 { let mut plants = plants::PlantSet::from_string(initial_state); for _ in 0..num_generations { plants.get_next_generation(rules); } plants.get_sum_of_indexes() }
pub fn build_vector_verbose() -> Vec<i16> { let mut v: Vec<i16> = Vec::<i16>::new(); v.push(10i16); v.push(20i16); v }
use xtensa_lx_rt::exception::Context; use xtensa_lx_rt::interrupt; use crate::ram; #[repr(u8)] pub enum InterruptType { SLC = 1, SPI = 2, GPIO = 4, UART = 5, CCOMPARE = 6, SOFT = 7, WDT = 8, TIMER1 = 9, } impl InterruptType { const fn mask(self) -> u32 { 1 << self as u8 } } extern "Rust" { // interrupt handlers set by #[interrupt] macro fn __slc_interrupt(context: &Context); fn __spi_interrupt(context: &Context); fn __gpio_interrupt(context: &Context); fn __uart_interrupt(context: &Context); fn __ccompare_interrupt(context: &Context); fn __soft_interrupt(context: &Context); fn __wdt_interrupt(context: &Context); fn __timer1_interrupt(context: &Context); // interrupt handlers for the hal to use fn __slc_hal_interrupt(context: &Context); fn __spi_hal_interrupt(context: &Context); fn __gpio_hal_interrupt(context: &Context); fn __uart_hal_interrupt(context: &Context); fn __ccompare_hal_interrupt(context: &Context); fn __soft_hal_interrupt(context: &Context); fn __wdt_hal_interrupt(context: &Context); fn __timer1_hal_interrupt(context: &Context); } #[interrupt] #[ram] fn interrupt_trampoline(level: u32, frame: Context) { let _ = level; let mask = xtensa_lx::interrupt::get(); unsafe { xtensa_lx::interrupt::clear(mask); } unsafe { if InterruptType::SLC.mask() & mask > 0 { __slc_interrupt(&frame); __slc_hal_interrupt(&frame); }; if InterruptType::SPI.mask() & mask > 0 { __spi_interrupt(&frame); __spi_hal_interrupt(&frame); }; if InterruptType::GPIO.mask() & mask > 0 { __gpio_interrupt(&frame); __gpio_hal_interrupt(&frame); }; if InterruptType::UART.mask() & mask > 0 { __uart_interrupt(&frame); __uart_hal_interrupt(&frame); }; if InterruptType::CCOMPARE.mask() & mask > 0 { __ccompare_interrupt(&frame); __ccompare_hal_interrupt(&frame); }; if InterruptType::SOFT.mask() & mask > 0 { __soft_interrupt(&frame); __soft_hal_interrupt(&frame); }; if InterruptType::WDT.mask() & mask > 0 { __wdt_interrupt(&frame); __wdt_hal_interrupt(&frame); }; if InterruptType::TIMER1.mask() & mask > 0 { __timer1_interrupt(&frame); __timer1_hal_interrupt(&frame); }; } } pub fn enable_interrupt(ty: InterruptType) -> u32 { let type_mask = ty.mask(); unsafe { xtensa_lx::interrupt::enable_mask(type_mask) } } pub fn disable_interrupt(ty: InterruptType) -> u32 { let type_mask = !(1u32 << ty as u8); unsafe { xtensa_lx::interrupt::enable_mask(type_mask) } } /// Uses the magic of monomorphization to "save" the type parameter for our interrupt handler /// /// Because a new version of this function will be compiled for every H, the function pointer /// for a monomorphized version of this function will "remember" it's function pointer, /// allowing us to cast the function pointer into a monomorphized interrupt handler. pub(crate) fn trampoline<H: Callable>(handler: *mut ()) { let handler: &mut H = unsafe { &mut *(handler as *mut H) }; handler.call(); } pub(crate) trait Callable { fn call(&mut self); } /// Setup an interrupt handler accepting a closure macro_rules! int_handler { ($INT_TYPE:ident => $INT:ident($DATA:ty)) => { use crate::interrupt::*; use core::intrinsics::transmute; use core::marker::PhantomPinned; use core::pin::Pin; use paste::paste; use xtensa_lx_rt::exception::Context; paste! { static mut [<INT_ $INT_TYPE _TRAMPOLINE>]: Option<fn(handler: *mut ())> = None; } paste! { static mut [<INT_ $INT_TYPE _HANDLER>]: *mut () = core::ptr::null_mut(); } paste! { #[no_mangle] fn [<__ $INT_TYPE:lower _hal_interrupt>](_frame: &Context) { // this is safe because the drop impl for the handler cleans up the pointers unsafe { if let Some(trampoline) = paste!{[<INT_ $INT_TYPE _TRAMPOLINE>]} { trampoline(paste!{[<INT_ $INT_TYPE _HANDLER>]}) } } } } pub struct $INT<F> { closure: F, data: $DATA, _pin: PhantomPinned, } impl<F: FnMut(&mut $DATA)> $INT<F> { /// Create interrupt handler that keeps the closure in scope and sets the static pointers /// /// returns the handler pinned to ensure that the pointers stay valid pub(crate) fn new(data: $DATA, closure: F) -> Pin<Self> { enable_interrupt(InterruptType::$INT_TYPE); let handler = unsafe { Pin::new_unchecked($INT { data, closure, _pin: PhantomPinned, }) }; unsafe { paste! {[<INT_ $INT_TYPE _TRAMPOLINE>] = Some(trampoline::<Self>) }; paste! {[<INT_ $INT_TYPE _HANDLER>] = transmute(&handler) }; } handler } } impl<F: FnMut(&mut $DATA)> Callable for $INT<F> { fn call(&mut self) { (self.closure)(&mut self.data) } } impl<F> Drop for $INT<F> { fn drop(&mut self) { disable_interrupt(InterruptType::$INT_TYPE); unsafe { paste! {[<INT_ $INT_TYPE _TRAMPOLINE>] = None }; paste! {[<INT_ $INT_TYPE _HANDLER>] = core::ptr::null_mut() }; } } } impl<F> core::ops::Deref for $INT<F> { type Target = $DATA; fn deref(&self) -> &Self::Target { &self.data } } impl<F> core::ops::DerefMut for $INT<F> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data } } }; }
#[derive(Default, Debug, Clone, Copy)] pub struct PerVerexParams { pub in_pos: [f32; 4], pub in_uv: [f32; 2], pub in_color: [f32; 3], pub in_normal: [f32; 3], pub in_tangent: [f32; 3], } vulkano::impl_vertex!( PerVerexParams, in_pos, in_uv, in_color, in_normal, in_tangent ); impl PerVerexParams { pub fn new( in_pos: [f32; 4], in_uv: [f32; 2], in_color: [f32; 3], in_normal: [f32; 3], in_tangent: [f32; 3], ) -> Self { // log::trace!("insance of {}", std::any::type_name::<Self>()); PerVerexParams { in_pos, in_uv, in_color, in_normal, in_tangent, } } } #[derive(Default, Debug, Clone, Copy)] pub struct FigureMutation { position_offset: [f32; 3], scale: f32, } impl FigureMutation { pub fn new(position_offset: [f32; 3], scale: f32) -> Self { log::trace!("insance of {}", std::any::type_name::<Self>()); Self { position_offset, scale, } } pub fn unit() -> Self { Self::new([0.0, 0.0, 0.0], 1.0) } } #[derive(Debug, Clone)] pub enum RenderableMesh { Indexed(IndexedMesh), Regular(RegularMesh), } #[derive(Debug, Clone)] pub struct MeshPoint { pub vert: [f32; 3], pub color: [f32; 3], pub normal: [f32; 3], pub tangent: [f32; 3], } impl MeshPoint { pub fn new(vert: [f32; 3], color: [f32; 3], normal: [f32; 3], tangent: [f32; 3]) -> Self { // log::trace!("insance of {}", std::any::type_name::<Self>()); MeshPoint { vert: [vert[0], vert[1], vert[2]], color: [color[0], color[1], color[2]], normal: [normal[0], normal[1], normal[2]], tangent: [tangent[0], tangent[1], tangent[2]], } } pub fn to_vert(&self) -> PerVerexParams { let p = self; PerVerexParams::new( [p.vert[0], p.vert[1], p.vert[2], 1.0], [0.0, 0.0], [p.color[0], p.color[1], p.color[2]], [p.normal[0], p.normal[1], p.normal[2]], [p.tangent[0], p.tangent[1], p.tangent[2]], ) } } #[derive(Debug, Clone)] pub struct IndexedMesh { pub points: Vec<MeshPoint>, pub indices: Vec<u32>, } #[derive(Debug, Clone)] pub struct RegularMesh { pub points: Vec<MeshPoint>, } #[derive(Debug, Clone)] pub struct FigureSet { pub mesh: RenderableMesh, pub mutations: Vec<FigureMutation>, pub color_texture_path: String, pub normal_texture_path: String, } impl FigureSet { pub fn new( mesh: RenderableMesh, mutations: Vec<FigureMutation>, color_texture_path: String, normal_texture_path: String, ) -> Self { log::trace!("insance of {}", std::any::type_name::<Self>()); FigureSet { mesh, mutations, color_texture_path, normal_texture_path, } } }
use crate::rm::Error as RmError; use thiserror::Error; /// Error of Transaction Manager. #[derive(Debug, Error)] pub enum XaError { /// Error was caused by one or multiple Resource Manager Errors. #[error("Error was caused by one or multiple Resource Manager Errors")] RmErrors(Vec<RmError>), /// Error was caused by wrong methods calls (wrong state, or wrong parameters). #[error("Error was caused by wrong methods calls (wrong state, or wrong parameters)")] Usage(&'static str), /// Error was caused by wrong methods calls (wrong state, or wrong parameters). #[error("Error was caused by wrong methods calls (wrong state, or wrong parameters)")] UsageDetails(String), /// Some Resource Managers responded with unexpected errors, /// leaving the whole system potentially in an inconsistent state. #[error("Some Resource Managers responded with unexpected errors")] Inconsistency(String, Vec<RmError>), /// Reading an XaTransactionId from a byte stream failed. #[error("Reading an XaTransactionId from a byte stream failed")] ReadXid(String), } impl From<std::io::Error> for XaError { fn from(e: std::io::Error) -> XaError { XaError::ReadXid(e.to_string()) } }
#![cfg_attr(not(feature = "std"), no_std)] use liquid::storage; use liquid_lang as liquid; #[liquid::contract] mod hello_world { use super::*; #[liquid(storage)] struct HelloWorld { name: storage::Value<String>, } #[liquid(methods)] impl HelloWorld { pub fn new(&mut self) { self.name.initialize(String::from("Alice")); } pub fn get(&self) -> String { self.name.clone() } pub fn set(&mut self, name: String) { self.name.set(name) } } #[cfg(test)] mod tests { use super::*; #[test] fn get_works() { let contract = HelloWorld::new(); assert_eq!(contract.get(), "Alice"); } #[test] fn set_works() { let mut contract = HelloWorld::new(); let new_name = String::from("Bob"); contract.set(new_name.clone()); assert_eq!(contract.get(), "Bob"); } } }
pub struct Stylesheet { pub rules: Vec<Rule>, } impl Stylesheet { pub fn new(rules: Vec<Rule>) -> Stylesheet { Stylesheet { rules } } } pub struct Rule { pub selectors: Vec<Selector>, pub declarations: Vec<Declaration>, pub level: Origin, } impl Rule { pub fn new(selectors: Vec<Selector>, declarations: Vec<Declaration>, level: Origin) -> Rule { Rule { selectors, declarations, level, } } } #[derive(Clone, PartialEq)] pub enum Origin { UA, Author, } impl Origin { pub fn to_index(&self) -> i8 { match self { Origin::UA => 0, Origin::Author => 1, } } } pub enum Selector { Simple(SimpleSelector), } pub type Specificity = (usize, usize, usize); impl Selector { pub fn specificity(&self) -> Specificity { // http://www.w3.org/TR/selectors/#specificity let Selector::Simple(simple) = self; let a = simple.id.iter().count(); let b = simple.class.len(); let c = simple.tag_name.iter().count(); (a, b, c) } } pub struct SimpleSelector { pub tag_name: Option<String>, pub id: Option<String>, pub class: Vec<String>, } impl SimpleSelector { pub fn new(tag_name: Option<String>, id: Option<String>, class: Vec<String>) -> SimpleSelector { SimpleSelector { tag_name, id, class, } } } pub struct Declaration { pub name: String, pub value: Value, } impl Declaration { pub fn new(name: String, value: Value) -> Declaration { Declaration { name, value } } } #[derive(Clone, Debug, PartialEq)] pub enum Value { Keyword(String), KeywordArray(Vec<String>), Length(f32, Unit), Number(f32), ColorValue(Color), None, } impl Value { pub fn to_px(&self) -> f32 { match *self { Value::Length(f, Unit::Px) => f, Value::Number(f) => f, _ => 0.0, } } } #[derive(Debug, PartialEq, Clone)] pub enum Unit { Px, } #[derive(Debug, PartialEq, Clone)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, pub a: f32, } impl Color { pub fn new(r: u8, g: u8, b: u8, a: f32) -> Color { Color { r, g, b, a } } }
use std::io::prelude::*; use std::fs::File; use std::error::Error; use std::io::BufReader; use std::cmp; fn main() { let reader = read_file("input.txt"); let result = parse(reader); println!("{}", result) } fn parse(reader: BufReader<File>) -> i32 { let mut total = 0; for line in reader.lines() { let line = line.unwrap(); if line.len() > 1 { total += calculate(line); } } total } fn calculate(line: String) -> i32 { let s: Vec<&str> = line.split('x').collect(); let l = s[0].parse::<i32>().unwrap(); let w = s[1].parse::<i32>().unwrap(); let h = s[2].parse::<i32>().unwrap(); let first = cmp::min(l, w); let second = cmp::min(cmp::max(l, w), h); let ribbon = first * 2 + second * 2; ribbon + (l * w * h) } fn read_file(filename: &str) -> BufReader<File> { // Open file let file = match File::open(filename) { // The `description` method of `io::Error` returns a string that // describes the error Err(why) => panic!("couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let reader = BufReader::new(file); reader } #[test] fn check() { assert!(calculate(String::from("22x19x18")) == 7598); assert!(calculate(String::from("13x1x24")) == 340); }
// Copyright 2018-2020, Wayfair GmbH // // 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. #![deny(warnings)] #![deny(clippy::all, clippy::pedantic)] mod backend; mod language; mod lsp_utils; use backend::Backend; use clap::{App, Arg}; use tower_lsp::{LspService, Server}; #[tokio::main] async fn main() { backend::file_dbg("main", "main"); let matches = App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .about(env!("CARGO_PKG_DESCRIPTION")) .author(env!("CARGO_PKG_AUTHORS")) .arg( Arg::with_name("language") .help("Tremor language to support") .short("l") .long("language") .takes_value(true) .possible_values(language::LANGUAGE_NAMES) .default_value(language::DEFAULT_LANGUAGE_NAME), ) .arg( Arg::with_name("path") .help("TREMOR_PATH to set") .short("p") .long("path") .takes_value(true) .default_value(""), ) .get_matches(); let language_name = matches .value_of("language") // this is safe because we provide a default value for this arg above .unwrap_or_else(|| unreachable!()); let path = matches .value_of("path") // this is safe because we provide a default value for this arg above .unwrap_or_else(|| unreachable!()); if !path.is_empty() { std::env::set_var( "TREMOR_PATH", match std::env::var("TREMOR_PATH") { // append to existing path if it's already set Ok(p) => format!("{}:{}", p, path), Err(_) => path.to_string(), }, ); } if let Some(language) = language::lookup(language_name) { let stdin = tokio::io::stdin(); let stdout = tokio::io::stdout(); let (service, messages) = LspService::new(|client| Backend::new(client, language)); Server::new(stdin, stdout) .interleave(messages) .serve(service) .await; } else { eprintln!("Error: unknown tremor language {}", language_name); std::process::exit(1) } }
extern crate mylib; use mylib::*; const INPUT: &str = include_str!("../data/input.txt"); pub fn main() { // part 1 let result = INPUT .lines() .map(|l| count_letters(l)) .fold((0usize, 0usize), |acc, (two, three)| { (acc.0 + two, acc.1 + three) }); // println!("{:?}", result); println!("{}", result.0 * result.1); // part 2 let lines: Vec<String> = INPUT.lines().map(|l| l.into()).collect(); for (i, id) in lines.iter().enumerate() { for id2 in lines.iter().skip(i + 1) { if ids_prototypes(id, id2) { // println!("{}", id); // println!("{}", id2); println!( "{}", id.chars() .zip(id2.chars()) .filter(|(a, b)| a == b) .map(|(a, _)| a) .collect::<String>() ); } } } }
use crate::ip::{IPv4, IPv6}; use crate::v2::error::ParseError; use std::borrow::Cow; use std::fmt; use std::net::SocketAddr; use std::ops::BitOr; /// The prefix of the PROXY protocol header. pub const PROTOCOL_PREFIX: &[u8] = b"\r\n\r\n\0\r\nQUIT\n"; /// The minimum length in bytes of a PROXY protocol header. pub const MINIMUM_LENGTH: usize = 16; /// The minimum length in bytes of a Type-Length-Value payload. pub const MINIMUM_TLV_LENGTH: usize = 3; /// The number of bytes for an IPv4 addresses payload. const IPV4_ADDRESSES_BYTES: usize = 12; /// The number of bytes for an IPv6 addresses payload. const IPV6_ADDRESSES_BYTES: usize = 36; /// The number of bytes for a unix addresses payload. const UNIX_ADDRESSES_BYTES: usize = 216; /// A proxy protocol version 2 header. /// /// ## Examples /// ```rust /// use ppp::v2::{Addresses, AddressFamily, Command, Header, IPv4, ParseError, Protocol, PROTOCOL_PREFIX, Type, TypeLengthValue, Version}; /// let mut header = Vec::from(PROTOCOL_PREFIX); /// header.extend([ /// 0x21, 0x12, 0, 16, 127, 0, 0, 1, 192, 168, 1, 1, 0, 80, 1, 187, 4, 0, 1, 42 /// ]); /// /// let addresses: Addresses = IPv4::new([127, 0, 0, 1], [192, 168, 1, 1], 80, 443).into(); /// let expected = Header { /// header: header.as_slice().into(), /// version: Version::Two, /// command: Command::Proxy, /// protocol: Protocol::Datagram, /// addresses /// }; /// let actual = Header::try_from(header.as_slice()).unwrap(); /// /// assert_eq!(actual, expected); /// assert_eq!(actual.tlvs().collect::<Vec<Result<TypeLengthValue<'_>, ParseError>>>(), vec![Ok(TypeLengthValue::new(Type::NoOp, &[42]))]); /// ``` #[derive(Clone, Debug, PartialEq)] pub struct Header<'a> { pub header: Cow<'a, [u8]>, pub version: Version, pub command: Command, pub protocol: Protocol, pub addresses: Addresses, } /// The supported `Version`s for binary headers. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Version { Two = 0x20, } /// The supported `Command`s for a PROXY protocol header. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Command { Local = 0, Proxy, } /// The supported `AddressFamily` for a PROXY protocol header. #[derive(Copy, Clone, Debug, PartialEq)] pub enum AddressFamily { Unspecified = 0x00, IPv4 = 0x10, IPv6 = 0x20, Unix = 0x30, } /// The supported `Protocol`s for a PROXY protocol header. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Protocol { Unspecified = 0, Stream, Datagram, } /// The source and destination address information for a given `AddressFamily`. /// /// ## Examples /// ```rust /// use ppp::v2::{Addresses, AddressFamily}; /// use std::net::SocketAddr; /// /// let addresses: Addresses = ("127.0.0.1:80".parse::<SocketAddr>().unwrap(), "192.168.1.1:443".parse::<SocketAddr>().unwrap()).into(); /// /// assert_eq!(addresses.address_family(), AddressFamily::IPv4); /// ``` #[derive(Copy, Clone, Debug, PartialEq)] pub enum Addresses { Unspecified, IPv4(IPv4), IPv6(IPv6), Unix(Unix), } /// The source and destination addresses of UNIX sockets. #[derive(Copy, Clone, Debug, PartialEq)] pub struct Unix { pub source: [u8; 108], pub destination: [u8; 108], } /// An `Iterator` of `TypeLengthValue`s stored in a byte slice. #[derive(Copy, Clone, Debug, PartialEq)] pub struct TypeLengthValues<'a> { bytes: &'a [u8], offset: usize, } /// A Type-Length-Value payload. #[derive(Clone, Debug, PartialEq)] pub struct TypeLengthValue<'a> { pub kind: u8, pub value: Cow<'a, [u8]>, } /// Supported types for `TypeLengthValue` payloads. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Type { ALPN = 0x01, Authority, CRC32C, NoOp, UniqueId, SSL = 0x20, SSLVersion, SSLCommonName, SSLCipher, SSLSignatureAlgorithm, SSLKeyAlgorithm, NetworkNamespace = 0x30, } impl<'a> fmt::Display for Header<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{:?} {:#X} {:#X} ({} bytes)", PROTOCOL_PREFIX, self.version | self.command, self.protocol | self.address_family(), self.length() ) } } impl<'a> Header<'a> { /// Creates an owned clone of this [`Header`]. pub fn to_owned(&self) -> Header<'static> { Header { header: Cow::Owned(self.header.to_vec()), version: self.version, command: self.command, protocol: self.protocol, addresses: self.addresses, } } /// The length of this `Header`'s payload in bytes. pub fn length(&self) -> usize { self.header[MINIMUM_LENGTH..].len() } /// The total length of this `Header` in bytes. pub fn len(&self) -> usize { self.header.len() } /// Tests whether this `Header`'s underlying byte slice is empty. pub fn is_empty(&self) -> bool { self.header.is_empty() } /// The `AddressFamily` of this `Header`. pub fn address_family(&self) -> AddressFamily { self.addresses.address_family() } /// The length in bytes of the address portion of the payload. fn address_bytes_end(&self) -> usize { let length = self.length(); let address_bytes = self.address_family().byte_length().unwrap_or(length); MINIMUM_LENGTH + std::cmp::min(address_bytes, length) } /// The bytes of the address portion of the payload. pub fn address_bytes(&self) -> &[u8] { &self.header[MINIMUM_LENGTH..self.address_bytes_end()] } /// The bytes of the `TypeLengthValue` portion of the payload. pub fn tlv_bytes(&self) -> &[u8] { &self.header[self.address_bytes_end()..] } /// An `Iterator` of `TypeLengthValue`s. pub fn tlvs(&self) -> TypeLengthValues<'_> { TypeLengthValues { bytes: self.tlv_bytes().into(), offset: 0, } } /// The underlying byte slice this `Header` is built on. pub fn as_bytes(&self) -> &[u8] { self.header.as_ref() } } impl<'a> TypeLengthValues<'a> { /// The underlying byte slice of the `TypeLengthValue`s portion of the `Header` payload. pub fn as_bytes(&self) -> &[u8] { self.bytes.as_ref() } } impl<'a> From<&'a [u8]> for TypeLengthValues<'a> { fn from(bytes: &'a [u8]) -> Self { TypeLengthValues { bytes: bytes.into(), offset: 0, } } } impl<'a> Iterator for TypeLengthValues<'a> { type Item = Result<TypeLengthValue<'a>, ParseError>; fn next(&mut self) -> Option<Self::Item> { if self.offset >= self.bytes.len() { return None; } let remaining = &self.bytes[self.offset..]; if remaining.len() < MINIMUM_TLV_LENGTH { self.offset = self.bytes.len(); return Some(Err(ParseError::Leftovers(self.bytes.len()))); } let tlv_type = remaining[0]; let length = u16::from_be_bytes([remaining[1], remaining[2]]); let tlv_length = MINIMUM_TLV_LENGTH + length as usize; if remaining.len() < tlv_length { self.offset = self.bytes.len(); return Some(Err(ParseError::InvalidTLV(tlv_type, length))); } self.offset += tlv_length; Some(Ok(TypeLengthValue { kind: tlv_type, value: Cow::Borrowed(&remaining[MINIMUM_TLV_LENGTH..tlv_length]), })) } } impl<'a> TypeLengthValues<'a> { /// The number of bytes in the `TypeLengthValue` portion of the `Header`. pub fn len(&self) -> u16 { self.bytes.len() as u16 } /// Whether there are any bytes to be interpreted as `TypeLengthValue`s. pub fn is_empty(&self) -> bool { self.bytes.is_empty() } } impl BitOr<Command> for Version { type Output = u8; fn bitor(self, command: Command) -> Self::Output { (self as u8) | (command as u8) } } impl BitOr<Version> for Command { type Output = u8; fn bitor(self, version: Version) -> Self::Output { (self as u8) | (version as u8) } } impl BitOr<Protocol> for AddressFamily { type Output = u8; fn bitor(self, protocol: Protocol) -> Self::Output { (self as u8) | (protocol as u8) } } impl AddressFamily { /// The length in bytes for this `AddressFamily`. /// `AddressFamily::Unspecified` does not require any bytes, and is represented as `None`. pub fn byte_length(&self) -> Option<usize> { match self { AddressFamily::IPv4 => Some(IPV4_ADDRESSES_BYTES), AddressFamily::IPv6 => Some(IPV6_ADDRESSES_BYTES), AddressFamily::Unix => Some(UNIX_ADDRESSES_BYTES), AddressFamily::Unspecified => None, } } } impl From<AddressFamily> for u16 { fn from(address_family: AddressFamily) -> Self { address_family.byte_length().unwrap_or_default() as u16 } } impl From<(SocketAddr, SocketAddr)> for Addresses { fn from(addresses: (SocketAddr, SocketAddr)) -> Self { match addresses { (SocketAddr::V4(source), SocketAddr::V4(destination)) => Addresses::IPv4(IPv4::new( *source.ip(), *destination.ip(), source.port(), destination.port(), )), (SocketAddr::V6(source), SocketAddr::V6(destination)) => Addresses::IPv6(IPv6::new( *source.ip(), *destination.ip(), source.port(), destination.port(), )), _ => Addresses::Unspecified, } } } impl From<IPv4> for Addresses { fn from(addresses: IPv4) -> Self { Addresses::IPv4(addresses) } } impl From<IPv6> for Addresses { fn from(addresses: IPv6) -> Self { Addresses::IPv6(addresses) } } impl From<Unix> for Addresses { fn from(addresses: Unix) -> Self { Addresses::Unix(addresses) } } impl Addresses { /// The `AddressFamily` for this `Addresses`. pub fn address_family(&self) -> AddressFamily { match self { Addresses::Unspecified => AddressFamily::Unspecified, Addresses::IPv4(..) => AddressFamily::IPv4, Addresses::IPv6(..) => AddressFamily::IPv6, Addresses::Unix(..) => AddressFamily::Unix, } } /// The length in bytes of the `Addresses` in the `Header`'s payload. pub fn len(&self) -> usize { self.address_family().byte_length().unwrap_or_default() } /// Tests whether the `Addresses` consume any space in the `Header`'s payload. /// `AddressFamily::Unspecified` does not require any bytes, and always returns true. pub fn is_empty(&self) -> bool { self.address_family().byte_length().is_none() } } impl Unix { /// Creates a new instance of a source and destination address pair for Unix sockets. pub fn new(source: [u8; 108], destination: [u8; 108]) -> Self { Unix { source, destination, } } } impl BitOr<AddressFamily> for Protocol { type Output = u8; fn bitor(self, address_family: AddressFamily) -> Self::Output { (self as u8) | (address_family as u8) } } impl<'a, T: Into<u8>> From<(T, &'a [u8])> for TypeLengthValue<'a> { fn from((kind, value): (T, &'a [u8])) -> Self { TypeLengthValue { kind: kind.into(), value: value.into(), } } } impl<'a> TypeLengthValue<'a> { /// Creates an owned clone of this [`TypeLengthValue`]. pub fn to_owned(&self) -> TypeLengthValue<'static> { TypeLengthValue { kind: self.kind, value: Cow::Owned(self.value.to_vec()), } } /// Creates a new instance of a `TypeLengthValue`, where the length is determine by the length of the byte slice. /// No check is done to ensure the byte slice's length fits in a `u16`. pub fn new<T: Into<u8>>(kind: T, value: &'a [u8]) -> Self { TypeLengthValue { kind: kind.into(), value: value.into(), } } /// The length in bytes of this `TypeLengthValue`'s value. pub fn len(&self) -> usize { self.value.len() } /// Tests whether the value of this `TypeLengthValue` is empty. pub fn is_empty(&self) -> bool { self.value.is_empty() } } impl From<Type> for u8 { fn from(kind: Type) -> Self { kind as u8 } }
mod energy_regen; mod health_regen; mod packet_handler; mod poll_complete; mod position_update; mod register; mod run_futures; mod timer_handler; pub mod collision; pub mod handlers; pub mod missile; pub mod specials; pub mod spectate; pub use self::energy_regen::EnergyRegenSystem; pub use self::health_regen::HealthRegenSystem; pub use self::packet_handler::PacketHandler; pub use self::poll_complete::PollComplete; pub use self::position_update::PositionUpdate; pub use self::timer_handler::TimerHandler; pub use self::register::register;
use std::cmp::Ordering; use std::fmt::{self, Display}; use std::str; use common::{Literal, SqlType}; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub enum FunctionExpression { Avg(Column, bool), Count(Column, bool), CountStar, Sum(Column, bool), Max(Column), Min(Column), GroupConcat(Column, String), } impl Display for FunctionExpression { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FunctionExpression::Avg(ref col, d) if d => { write!(f, "avg(distinct {})", col.name.as_str()) } FunctionExpression::Count(ref col, d) if d => { write!(f, "count(distinct {})", col.name.as_str()) } FunctionExpression::Sum(ref col, d) if d => { write!(f, "sum(distinct {})", col.name.as_str()) } FunctionExpression::Avg(ref col, _) => write!(f, "avg({})", col.name.as_str()), FunctionExpression::Count(ref col, _) => write!(f, "count({})", col.name.as_str()), FunctionExpression::CountStar => write!(f, "count(all)"), FunctionExpression::Sum(ref col, _) => write!(f, "sum({})", col.name.as_str()), FunctionExpression::Max(ref col) => write!(f, "max({})", col.name.as_str()), FunctionExpression::Min(ref col) => write!(f, "min({})", col.name.as_str()), FunctionExpression::GroupConcat(ref col, ref s) => { write!(f, "group_concat({}, {})", col.name.as_str(), s) } } } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct Column { pub name: String, pub alias: Option<String>, pub table: Option<String>, pub function: Option<Box<FunctionExpression>>, } impl<'a> From<&'a str> for Column { fn from(c: &str) -> Column { match c.find(".") { None => { Column { name: String::from(c), alias: None, table: None, function: None, } } Some(i) => { Column { name: String::from(&c[i + 1..]), alias: None, table: Some(String::from(&c[0..i])), function: None, } } } } } impl Ord for Column { fn cmp(&self, other: &Column) -> Ordering { if self.table.is_some() && other.table.is_some() { match self.table.cmp(&other.table) { Ordering::Equal => self.name.cmp(&other.name), x => x, } } else { self.name.cmp(&other.name) } } } impl PartialOrd for Column { fn partial_cmp(&self, other: &Column) -> Option<Ordering> { if self.table.is_some() && other.table.is_some() { match self.table.cmp(&other.table) { Ordering::Equal => Some(self.name.cmp(&other.name)), x => Some(x), } } else if self.table.is_none() && other.table.is_none() { Some(self.name.cmp(&other.name)) } else { None } } } #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub enum ColumnConstraint { NotNull, DefaultValue(Literal), AutoIncrement, } #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct ColumnSpecification { pub column: Column, pub sql_type: SqlType, pub constraints: Vec<ColumnConstraint>, } impl ColumnSpecification { pub fn new(c: Column, t: SqlType) -> ColumnSpecification { ColumnSpecification { column: c, sql_type: t, constraints: vec![], } } pub fn with_constraints( c: Column, t: SqlType, ccs: Vec<ColumnConstraint>, ) -> ColumnSpecification { ColumnSpecification { column: c, sql_type: t, constraints: ccs, } } } #[cfg(test)] mod tests { use super::*; #[test] fn column_from_str() { let s = "table.col"; let c = Column::from(s); assert_eq!( c, Column { name: String::from("col"), alias: None, table: Some(String::from("table")), function: None, } ); } }
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let a: i64 = sc.input(); let b: i64 = sc.input(); let c: i64 = sc.input(); let x: i64 = sc.input(); let y: i64 = sc.input(); let mut ans = c * std::cmp::max(x * 2, y * 2); for z in 0..std::cmp::max(x * 2, y * 2) { let na = if x > z / 2 { x - z / 2 } else { 0 }; let nb = if y > z / 2 { y - z / 2 } else { 0 }; ans = std::cmp::min(ans, a * na + b * nb + c * z); } println!("{}", ans); }
// El discurso de Zoe // // Copyright (C) 2016 GUL UC3M // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use texture::scenario::Scenario; use state::TypeState; pub struct OneZero; /// Actions zone B fn actions_b<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> { match command { "ir a C" | "ir C" => { state.set_string("one_zone".to_string(), "C".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "ir a E" | "ir E" => { state.set_string("one_zone".to_string(), "E".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "ir a F" | "ir F" => { state.set_string("one_zone".to_string(), "F".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "subir" => { println!("Subes por las escaleras y tienes la mala suerte de encontrarte"); println!("de frente con alguien del BEHTS. Te han atrapado."); return Some("game_over".to_string()); }, "salir" => { return Some("exterior_ir".to_string()); }, _ => {} } println!("No es buena idea quedarse aquí"); return None; } /// Actions zone C fn actions_c<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> { match command { "ir a B" | "ir B" => { state.set_string("one_zone".to_string(), "B".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "ir a F" | "ir F" => { state.set_string("one_zone".to_string(), "F".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "ir a G" | "ir G" => { state.set_string("one_zone".to_string(), "G".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "subir" => { state.reduce_time(10); return Some("one_one".to_string()); }, "salir" => { println!("Mira por dónde, has tentado a la suerte y has perdido. El BETHS"); println!("te ha atrapado."); return Some("game_over".to_string()); }, _ => {} } println!("No es buena idea quedarse aquí"); return None; } /// Actions zone E fn actions_e<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> { match command { "ir a B" | "ir B" => { state.set_string("one_zone".to_string(), "B".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "subir" => { println!("Subes por las escaleras y tienes la mala suerte de encontrarte"); println!("de frente con alguien del BEHTS. Te han atrapado."); return Some("game_over".to_string()); }, "salir" => { return Some("exterior_ir".to_string()); }, _ => {} } println!("No es buena idea quedarse aquí"); return None; } /// Actions zone F fn actions_f<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> { match command { "ir a B" | "ir B" => { state.set_string("one_zone".to_string(), "B".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "ir a C" | "ir C" => { state.set_string("one_zone".to_string(), "C".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "subir" => { state.reduce_time(10); return Some("one_one".to_string()); }, "salir" => { return Some("exterior_ir".to_string()); }, _ => {} } println!("No es buena idea quedarse aquí"); return None; } /// Actions zone G fn actions_g<S: TypeState>(command: &str, state: &mut Box<S>) -> Option<String> { match command { "ir a C" | "ir C" => { state.set_string("one_zone".to_string(), "C".to_string()); state.reduce_time(10); return Some("one_zero".to_string()); }, "subir" => { state.reduce_time(10); return Some("one_one".to_string()); }, "salir" => { return Some("exterior_ir".to_string()); }, _ => {} } println!("No es buena idea quedarse aquí"); return None; } impl <S: TypeState> Scenario <S> for OneZero { fn load(&self, state: &mut Box<S>) -> Option<String> { match state.get_string("one_zone".to_string()).as_ref() { "B" => { println!("Parece despejado. Puedes salir al exterior o ir a los pasillos E, F"); println!("o C, o subir a la planta de arriba, lo cual te da mala espina."); }, "C" => { println!("Te llama la atención que en la puerta de salida del edificio hacia"); println!("el 7 hay un joven que te mira sospechosamente. Debe ser uno del"); println!("BEHTS, aunque es probable que sea un novato, pues parece que no"); println!("está seguro de si eres un alumno random o un siervo de Zoe."); println!("Piensas que es mejor no tentar a la suerte."); println!(" "); println!("Aparte de la puerta que vigila el joven, puedes ir a los pasillos F,"); println!("B o G, o subir las escaleras."); }, "E" => { println!("Estás en la entrada del edificio, todo en orden. Ves las escaleras"); println!("para subir al primer piso, aunque se oye mucho ruido, mejor no ir"); println!("por ahi, el pasillo que comunica con la zona B y la puerta para"); println!("salir del edificio."); }, "F" => { println!("Estás en la entrada del edificio, nada que te llame la atención."); println!("Ves las escaleras para subir al primer piso y el pasillo que"); println!("comunica con las zonas B o C y la puerta para salir del edificio."); }, "G" => { println!("Estás en la entrada del edificio, nada fuera de lo común. Ves las"); println!("escaleras para subir al primer piso, el pasillo que comunica con"); println!("la zona C y la puerta para salir del edificio."); }, _ => {} }; return None; } fn do_action(&self, command: &str, state: &mut Box<S>) -> Option<String> { match state.get_string("one_zone".to_string()).as_ref() { "B" => return actions_b(command, state), "C" => return actions_c(command, state), "E" => return actions_e(command, state), "F" => return actions_f(command, state), "G" => return actions_g(command, state), _ => {} }; println!("No es buena idea quedarse aquí."); return None; } }
/* Module: int */ /* Const: max_value The maximum value of an integer */ // FIXME: Find another way to access the machine word size in a const expr #[cfg(target_arch="x86")] const max_value: int = (-1 << 31)-1; #[cfg(target_arch="x86_64")] const max_value: int = (-1 << 63)-1; /* Const: min_value The minumum value of an integer */ #[cfg(target_arch="x86")] const min_value: int = -1 << 31; #[cfg(target_arch="x86_64")] const min_value: int = -1 << 63; /* Function: add */ pure fn add(x: int, y: int) -> int { ret x + y; } /* Function: sub */ pure fn sub(x: int, y: int) -> int { ret x - y; } /* Function: mul */ pure fn mul(x: int, y: int) -> int { ret x * y; } /* Function: div */ pure fn div(x: int, y: int) -> int { ret x / y; } /* Function: rem */ pure fn rem(x: int, y: int) -> int { ret x % y; } /* Predicate: lt */ pure fn lt(x: int, y: int) -> bool { ret x < y; } /* Predicate: le */ pure fn le(x: int, y: int) -> bool { ret x <= y; } /* Predicate: eq */ pure fn eq(x: int, y: int) -> bool { ret x == y; } /* Predicate: ne */ pure fn ne(x: int, y: int) -> bool { ret x != y; } /* Predicate: ge */ pure fn ge(x: int, y: int) -> bool { ret x >= y; } /* Predicate: gt */ pure fn gt(x: int, y: int) -> bool { ret x > y; } /* Predicate: positive */ pure fn positive(x: int) -> bool { ret x > 0; } /* Predicate: negative */ pure fn negative(x: int) -> bool { ret x < 0; } /* Predicate: nonpositive */ pure fn nonpositive(x: int) -> bool { ret x <= 0; } /* Predicate: nonnegative */ pure fn nonnegative(x: int) -> bool { ret x >= 0; } // FIXME: Make sure this works with negative integers. /* Function: hash Produce a uint suitable for use in a hash table */ fn hash(x: int) -> uint { ret x as uint; } /* Function: range Iterate over the range [`lo`..`hi`) */ fn range(lo: int, hi: int, it: fn(int)) { let i = lo; while i < hi { it(i); i += 1; } } /* Function: parse_buf Parse a buffer of bytes Parameters: buf - A byte buffer radix - The base of the number Failure: buf must not be empty */ fn parse_buf(buf: [u8], radix: uint) -> int { if vec::len::<u8>(buf) == 0u { #error("parse_buf(): buf is empty"); fail; } let i = vec::len::<u8>(buf) - 1u; let start = 0u; let power = 1; if buf[0] == ('-' as u8) { power = -1; start = 1u; } let n = 0; while true { let digit = char::to_digit(buf[i] as char); if (digit as uint) >= radix { fail; } n += (digit as int) * power; power *= radix as int; if i <= start { ret n; } i -= 1u; } fail; } /* Function: from_str Parse a string to an int Failure: s must not be empty */ fn from_str(s: str) -> int { parse_buf(str::bytes(s), 10u) } /* Function: to_str Convert to a string in a given base */ fn to_str(n: int, radix: uint) -> str { assert (0u < radix && radix <= 16u); ret if n < 0 { "-" + uint::to_str(-n as uint, radix) } else { uint::to_str(n as uint, radix) }; } /* Function: str Convert to a string */ fn str(i: int) -> str { ret to_str(i, 10u); } /* Function: pow Returns `base` raised to the power of `exponent` */ fn pow(base: int, exponent: uint) -> int { if exponent == 0u { ret 1; } //Not mathemtically true if [base == 0] if base == 0 { ret 0; } let my_pow = exponent; let acc = 1; let multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; } ret acc; } #[test] fn test_from_str() { assert(from_str("0") == 0); assert(from_str("3") == 3); assert(from_str("10") == 10); assert(from_str("123456789") == 123456789); assert(from_str("00100") == 100); assert(from_str("-1") == -1); assert(from_str("-3") == -3); assert(from_str("-10") == -10); assert(from_str("-123456789") == -123456789); assert(from_str("-00100") == -100); } #[test] #[should_fail] #[ignore(cfg(target_os = "win32"))] fn test_from_str_fail_1() { from_str(" "); } #[test] #[should_fail] #[ignore(cfg(target_os = "win32"))] fn test_from_str_fail_2() { from_str("x"); } #[test] fn test_parse_buf() { import str::bytes; assert (parse_buf(bytes("123"), 10u) == 123); assert (parse_buf(bytes("1001"), 2u) == 9); assert (parse_buf(bytes("123"), 8u) == 83); assert (parse_buf(bytes("123"), 16u) == 291); assert (parse_buf(bytes("ffff"), 16u) == 65535); assert (parse_buf(bytes("FFFF"), 16u) == 65535); assert (parse_buf(bytes("z"), 36u) == 35); assert (parse_buf(bytes("Z"), 36u) == 35); assert (parse_buf(bytes("-123"), 10u) == -123); assert (parse_buf(bytes("-1001"), 2u) == -9); assert (parse_buf(bytes("-123"), 8u) == -83); assert (parse_buf(bytes("-123"), 16u) == -291); assert (parse_buf(bytes("-ffff"), 16u) == -65535); assert (parse_buf(bytes("-FFFF"), 16u) == -65535); assert (parse_buf(bytes("-z"), 36u) == -35); assert (parse_buf(bytes("-Z"), 36u) == -35); } #[test] #[should_fail] #[ignore(cfg(target_os = "win32"))] fn test_parse_buf_fail_1() { parse_buf(str::bytes("Z"), 35u); } #[test] #[should_fail] #[ignore(cfg(target_os = "win32"))] fn test_parse_buf_fail_2() { parse_buf(str::bytes("-9"), 2u); } #[test] fn test_to_str() { import str::eq; assert (eq(to_str(0, 10u), "0")); assert (eq(to_str(1, 10u), "1")); assert (eq(to_str(-1, 10u), "-1")); assert (eq(to_str(255, 16u), "ff")); assert (eq(to_str(100, 10u), "100")); } #[test] fn test_pow() { assert (pow(0, 0u) == 1); assert (pow(0, 1u) == 0); assert (pow(0, 2u) == 0); assert (pow(-1, 0u) == 1); assert (pow(1, 0u) == 1); assert (pow(-3, 2u) == 9); assert (pow(-3, 3u) == -27); assert (pow(4, 9u) == 262144); } #[test] fn test_overflows() { assert (max_value > 0); assert (min_value <= 0); assert (min_value + max_value + 1 == 0); } // Local Variables: // mode: rust; // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End:
/* chapter 4 functions function pointers */ fn plus_one(i: i32) -> i32 { i + 1 } fn main() { // without type inference let a: fn(i32) -> i32 = plusOne; // with type inference let b = plusOne; let c = a(5); println!("{}", b); let d = c(6); println!("{}", d); } // output should be: /* 6 7 */
#![allow(non_camel_case_types)] #![allow(dead_code)] #![allow(const_err)] // TODO: check later without that use libusb_sys as ffi; use std::str::FromStr; pub const FTDI_MAJOR_VERSION: u8 = 1; pub const FTDI_MINOR_VERSION: u8 = 5; pub const FTDI_MICRO_VERSION: u8 = 0; pub const FTDI_VERSION_STRING: &str = "1.5.0"; pub const FTDI_SNAPSHOT_VERSION: &str = "v1.5rc1"; /// FTDI chip type #[non_exhaustive] #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_chip_type { TYPE_AM = 0, TYPE_BM = 1, TYPE_2232C = 2, TYPE_R = 3, TYPE_2232H = 4, TYPE_4232H = 5, TYPE_232H = 6, TYPE_230X = 7, } impl From<u8> for ftdi_chip_type { // #[inline] fn from(value: u8) -> ftdi_chip_type { // unsafe { transmute(value as u8) } match value { 0 => ftdi_chip_type::TYPE_AM, 1 => ftdi_chip_type::TYPE_BM, 2 => ftdi_chip_type::TYPE_2232C, 3 => ftdi_chip_type::TYPE_R, 4 => ftdi_chip_type::TYPE_2232H, 5 => ftdi_chip_type::TYPE_4232H, 6 => ftdi_chip_type::TYPE_232H, 7 => ftdi_chip_type::TYPE_230X, _ => panic!("ftdi_chip_type is unknown for value = {}", value), } } } /// Parity mode for ftdi_set_line_property() #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_parity_type { NONE = 0, ODD = 1, EVEN = 2, MARK = 3, SPACE = 4 } impl From<u8> for ftdi_parity_type { fn from(value: u8) -> ftdi_parity_type { match value { 0 => ftdi_parity_type::NONE, 1 => ftdi_parity_type::ODD, 2 => ftdi_parity_type::EVEN, 3 => ftdi_parity_type::MARK, 4 => ftdi_parity_type::SPACE, _ => panic!("ftdi_parity_type is unknown for value = {}", value), } } } /// Number of stop bits for ftdi_set_line_property() #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_stopbits_type { STOP_BIT_1 = 0, STOP_BIT_15 = 1, STOP_BIT_2 = 2 } impl From<u8> for ftdi_stopbits_type { fn from(value: u8) -> ftdi_stopbits_type { match value { 0 => ftdi_stopbits_type::STOP_BIT_1, 1 => ftdi_stopbits_type::STOP_BIT_15, 2 => ftdi_stopbits_type::STOP_BIT_2, _ => panic!("ftdi_stopbits_type is unknown for value = {}", value), } } } /// Number of bits for ftdi_set_line_property() #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_bits_type { BITS_7 = 7, BITS_8 = 8 } impl From<u8> for ftdi_bits_type { fn from(value: u8) -> ftdi_bits_type { match value { 7 => ftdi_bits_type::BITS_7, 8 => ftdi_bits_type::BITS_8, _ => panic!("ftdi_bits_type is unknown for value = {}", value), } } } /// Break type for ftdi_set_line_property2() #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_break_type { BREAK_OFF = 0, BREAK_ON = 1 } impl From<u8> for ftdi_break_type { fn from(value: u8) -> ftdi_break_type { match value { 0 => ftdi_break_type::BREAK_OFF, 1 => ftdi_break_type::BREAK_ON, _ => panic!("ftdi_break_type is unknown for value = {}", value), } } } /// MPSSE bitbang modes #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_mpsse_mode { ///< switch off bitbang mode, back to regular serial/FIFO BITMODE_RESET = 0x00, ///< classical asynchronous bitbang mode, introduced with B-type chips BITMODE_BITBANG = 0x01, ///< MPSSE mode, available on 2232x chips BITMODE_MPSSE = 0x02, ///< synchronous bitbang mode, available on 2232x and R-type chips BITMODE_SYNCBB = 0x04, ///< MCU Host Bus Emulation mode, available on 2232x chips BITMODE_MCU = 0x08, /// CPU-style fifo mode gets set via EEPROM ///< Fast Opto-Isolated Serial Interface Mode, available on 2232x chips BITMODE_OPTO = 0x10, ///< Bitbang on CBUS pins of R-type chips, configure in EEPROM before BITMODE_CBUS = 0x20, ///< Single Channel Synchronous FIFO mode, available on 2232H chips BITMODE_SYNCFF = 0x40, ///< FT1284 mode, available on 232H chips BITMODE_FT1284 = 0x80, } impl From<u8> for ftdi_mpsse_mode { fn from(value: u8) -> ftdi_mpsse_mode { match value { 0 => ftdi_mpsse_mode::BITMODE_RESET, 1 => ftdi_mpsse_mode::BITMODE_BITBANG, 2 => ftdi_mpsse_mode::BITMODE_MPSSE, 4 => ftdi_mpsse_mode::BITMODE_SYNCBB, 8 => ftdi_mpsse_mode::BITMODE_MCU, 10 => ftdi_mpsse_mode::BITMODE_OPTO, 20 => ftdi_mpsse_mode::BITMODE_CBUS, 40 => ftdi_mpsse_mode::BITMODE_SYNCFF, 80 => ftdi_mpsse_mode::BITMODE_FT1284, _ => panic!("ftdi_mpsse_mode is unknown for value = {}", value), } } } /// Port interface for chips with multiple interfaces #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Debug)] #[repr(u8)] pub enum ftdi_interface { INTERFACE_ANY = 0, INTERFACE_A = 1, INTERFACE_B = 2, INTERFACE_C = 3, INTERFACE_D = 4 } impl From<u8> for ftdi_interface { fn from(value: u8) -> ftdi_interface { match value { 0 => ftdi_interface::INTERFACE_ANY, 1 => ftdi_interface::INTERFACE_A, 2 => ftdi_interface::INTERFACE_B, 3 => ftdi_interface::INTERFACE_C, 4 => ftdi_interface::INTERFACE_D, _ => panic!("ftdi_interface is unknown for value = {}", value), } } } impl Into<u8> for ftdi_interface { #[inline] fn into(self) -> u8 { self as u8 } } impl FromStr for ftdi_interface { type Err = &'static str; fn from_str(value: &str) -> Result<Self, Self::Err> { match value { "INTERFACE_ANY" | "ANY" => Ok(ftdi_interface::INTERFACE_ANY), "INTERFACE_A" | "A" => Ok(ftdi_interface::INTERFACE_A), "INTERFACE_B" | "B" => Ok(ftdi_interface::INTERFACE_B), "INTERFACE_C" | "C" => Ok(ftdi_interface::INTERFACE_C), "INTERFACE_D" | "D" => Ok(ftdi_interface::INTERFACE_D), _ => Err("no match"), } } } /// Automatic loading / unloading of kernel modules #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[repr(u8)] pub enum ftdi_module_detach_mode { AUTO_DETACH_SIO_MODULE = 0, DONT_DETACH_SIO_MODULE = 1, AUTO_DETACH_REATACH_SIO_MODULE = 2 } impl From<u8> for ftdi_module_detach_mode { fn from(value: u8) -> ftdi_module_detach_mode { match value { 0 => ftdi_module_detach_mode::AUTO_DETACH_SIO_MODULE, 1 => ftdi_module_detach_mode::DONT_DETACH_SIO_MODULE, 2 => ftdi_module_detach_mode::AUTO_DETACH_REATACH_SIO_MODULE, _ => panic!("ftdi_module_detach_mode is unknown for value = {}", value), } } } // #[cfg(any(target_os = "windows", target_os = "macos"))] pub const READ_BUFFER_CHUNKSIZE: u32 = 4096; pub const WRITE_BUFFER_CHUNKSIZE: u32 = 4096; /// We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH, /// which is defined in libusb-1.0. Otherwise, each USB read request will /// be divided into multiple URBs. This will cause issues on Linux kernel /// older than 2.6.32. #[cfg(target_os = "linux")] pub const READ_BUFFER_CHUNKSIZE_LINUX_LOW_KERNEL: u32 = 16384; /* Shifting commands IN MPSSE Mode*/ /// Write TDI/DO on negative TCK/SK edge pub const MPSSE_WRITE_NEG: u8 = 0x01; /// Write bits, not bytes pub const MPSSE_BITMODE: u8 = 0x02; /// Sample TDO/DI on negative TCK/SK edge pub const MPSSE_READ_NEG: u8 = 0x04; /// LSB first pub const MPSSE_LSB: u8 = 0x08; /// Write TDI/DO pub const MPSSE_DO_WRITE: u8 = 0x10; /// Read TDO/DI pub const MPSSE_DO_READ: u8 = 0x20; /// Write TMS/CS pub const MPSSE_WRITE_TMS: u8 = 0x40; // FTDI MPSSE commands pub const SET_BITS_LOW: u8 = 0x80; ///BYTE DATA ///BYTE Direction pub const SET_BITS_HIGH: u8 = 0x82; ///BYTE DATA ///BYTE Direction pub const GET_BITS_LOW: u8 = 0x81; pub const GET_BITS_HIGH: u8 = 0x83; pub const LOOPBACK_START: u8 = 0x84; pub const LOOPBACK_END: u8 = 0x85; pub const TCK_DIVISOR: u8 = 0x86; /// H Type specific commands pub const DIS_DIV_5: u8 = 0x8a; pub const EN_DIV_5: u8 = 0x8b; pub const EN_3_PHASE: u8 = 0x8c; pub const DIS_3_PHASE: u8 = 0x8d; pub const CLK_BITS: u8 = 0x8e; pub const CLK_BYTES: u8 = 0x8f; pub const CLK_WAIT_HIGH: u8 = 0x94; pub const CLK_WAIT_LOW: u8 = 0x95; pub const EN_ADAPTIVE: u8 = 0x96; pub const DIS_ADAPTIVE: u8 = 0x97; pub const CLK_BYTES_OR_HIGH: u8 = 0x9c; pub const CLK_BYTES_OR_LOW: u8 = 0x9d; /// FT232H specific commands pub const DRIVE_OPEN_COLLECTOR: u8 = 0x9e; /// Value Low /// Value HIGH */ /*rate is 12000000/((1+value)*2) //pub static DIV_VALUE(rate) = (rate > 6000000)?0:((6000000/rate -1) > 0xffff)? 0xffff: (6000000/rate -1); /// Commands in MPSSE and Host Emulation Mode pub const SEND_IMMEDIATE: u8 = 0x87; pub const WAIT_ON_HIGH: u8 = 0x88; pub const WAIT_ON_LOW: u8 = 0x89; /// Commands in Host Emulation Mode pub const READ_SHORT: u8 = 0x90; /// Address_Low pub const READ_EXTENDED: u8 = 0x91; /// Address High / Address Low pub const WRITE_SHORT: u8 = 0x92; /// Address_Low pub const WRITE_EXTENDED: u8 = 0x93; /* Definitions for flow control */ /// Reset the port pub const SIO_RESET: u8 = 0; /// Set the modem control register pub const SIO_MODEM_CTRL: u8 = 1; /// Set flow control register pub const SIO_SET_FLOW_CTRL: u8 = 2; /// Set baud rate pub const SIO_SET_BAUD_RATE: u8 = 3; /// Set the data characteristics of the port pub const SIO_SET_DATA: u8 = 4; pub const FTDI_DEVICE_OUT_REQTYPE: u8 = ffi::LIBUSB_REQUEST_TYPE_VENDOR | ffi::LIBUSB_RECIPIENT_DEVICE | ffi::LIBUSB_ENDPOINT_OUT; pub const FTDI_DEVICE_IN_REQTYPE: u8 = ffi::LIBUSB_REQUEST_TYPE_VENDOR | ffi::LIBUSB_RECIPIENT_DEVICE | ffi::LIBUSB_ENDPOINT_IN; /// Requests pub const SIO_RESET_REQUEST: u8 = SIO_RESET; pub const SIO_SET_BAUDRATE_REQUEST: u8 = SIO_SET_BAUD_RATE; pub const SIO_SET_DATA_REQUEST: u8 = SIO_SET_DATA; pub const SIO_SET_FLOW_CTRL_REQUEST: u8 = SIO_SET_FLOW_CTRL; pub const SIO_SET_MODEM_CTRL_REQUEST: u8 = SIO_MODEM_CTRL; pub const SIO_POLL_MODEM_STATUS_REQUEST: u8 = 0x05; pub const SIO_SET_EVENT_CHAR_REQUEST: u8 = 0x06; pub const SIO_SET_ERROR_CHAR_REQUEST: u8 = 0x07; pub const SIO_SET_LATENCY_TIMER_REQUEST: u8 = 0x09; pub const SIO_GET_LATENCY_TIMER_REQUEST: u8 = 0x0A; pub const SIO_SET_BITMODE_REQUEST: u8 = 0x0B; pub const SIO_READ_PINS_REQUEST: u8 = 0x0C; pub const SIO_READ_EEPROM_REQUEST: u8 = 0x90; pub const SIO_WRITE_EEPROM_REQUEST: u8 = 0x91; pub const SIO_ERASE_EEPROM_REQUEST: u8 = 0x92; pub const SIO_RESET_SIO: u8 = 0; pub const SIO_RESET_PURGE_RX: u8 = 1; pub const SIO_RESET_PURGE_TX: u8 = 2; /// New names for the values used internally to flush (purge). pub const SIO_TCIFLUSH: u8 = 2; pub const SIO_TCOFLUSH: u8 = 1; pub const SIO_DISABLE_FLOW_CTRL: u8 = 0x0; pub const SIO_RTS_CTS_HS: u8 = (0x1 << 8) as u8; pub const SIO_DTR_DSR_HS: u8 = (0x2 << 8) as u8; pub const SIO_XON_XOFF_HS: u8 = (0x4 << 8) as u8; pub const SIO_SET_DTR_MASK: u8 = 0x1; pub const SIO_SET_DTR_HIGH: u8 = (1 | ((SIO_SET_DTR_MASK << 8) as u8) as u8) as u8; // pub const SIO_SET_DTR_LOW: u8 = (0 | ((SIO_SET_DTR_MASK << 8) as u8) as u8) as u8; pub const SIO_SET_RTS_MASK: u8 = 0x2; pub const SIO_SET_DTR_LOW: u8 = ((SIO_SET_RTS_MASK << 8) as u8) as u8; pub const SIO_SET_RTS_HIGH: u8 = (2 | ((SIO_SET_RTS_MASK << 8) as u8) as u8) as u8; // pub const SIO_SET_RTS_LOW: u8 = (0 | ((SIO_SET_RTS_MASK << 8) as u8) as u8) as u8; pub const SIO_SET_RTS_LOW: u8 = ((SIO_SET_RTS_MASK << 8) as u8) as u8; pub const FT1284_CLK_IDLE_STATE: u8 = 0x01; /// DS_FT232H 1.3 amd ftd2xx.h 1.0.4 disagree here pub const FT1284_DATA_LSB: u8 = 0x02; pub const FT1284_FLOW_CONTROL: u8 = 0x04; pub const POWER_SAVE_DISABLE_H: u8 = 0x80; pub const USE_SERIAL_NUM: u8 = 0x08; /// Invert TXD# pub const INVERT_TXD: u8 = 0x01; /// Invert RXD# pub const INVERT_RXD: u8 = 0x02; /// Invert RTS# pub const INVERT_RTS: u8 = 0x04; /// Invert CTS# pub const INVERT_CTS: u8 = 0x08; /// Invert DTR# pub const INVERT_DTR: u8 = 0x10; /// Invert DSR# pub const INVERT_DSR: u8 = 0x20; /// Invert DCD# pub const INVERT_DCD: u8 = 0x40; /// Invert RI# pub const INVERT_RI: u8 = 0x80; //// Interface Mode pub const CHANNEL_IS_UART: u8 = 0x0; pub const CHANNEL_IS_FIFO: u8 = 0x1; pub const CHANNEL_IS_OPTO: u8 = 0x2; pub const CHANNEL_IS_CPU: u8 = 0x4; pub const CHANNEL_IS_FT1284: u8 = 0x8; pub const CHANNEL_IS_RS485: u8 = 0x10; pub const DRIVE_4MA: u8 = 0; pub const DRIVE_8MA: u8 = 1; pub const DRIVE_12MA: u8 = 2; pub const DRIVE_16MA: u8 = 3; pub const SLOW_SLEW: u8 = 4; pub const IS_SCHMITT: u8 = 8; /// Driver Type pub const DRIVER_VCP: u8 = 0x08; /// FT232H has moved the VCP bit pub const DRIVER_VCPH: u8 = 0x10; pub const USE_USB_VERSION_BIT: u8 = 0x10; pub const SUSPEND_DBUS7_BIT: u8 = 0x80; /// High current drive pub const HIGH_CURRENT_DRIVE: u8 = 0x10; pub const HIGH_CURRENT_DRIVE_R: u8 = 0x04;
use std::fmt; use slab::Slab; pub struct Subscription { key: usize, } #[derive(Debug)] pub struct SubscriptionMissing; impl fmt::Display for SubscriptionMissing { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Attempt to unsubscribe delegate without subscription") } } impl std::error::Error for SubscriptionMissing {} pub struct Event<T> { handlers: Slab<Box<Fn(T) + Send + Sync>>, } impl<T> Default for Event<T> { fn default() -> Self { Event { handlers: Slab::new(), } } } impl<T> Event<T> where T: Clone, { pub fn new() -> Self { Event::default() } pub fn subscribe<F>(&mut self, handler: F) -> Subscription where F: Fn(T) + Send + Sync + 'static, { Subscription { key: self.handlers.insert(Box::new(handler)), } } pub fn unsubscribe( &mut self, subscription: Subscription, ) -> Result<(), SubscriptionMissing> { if self.handlers.contains(subscription.key) { self.handlers.remove(subscription.key); Ok(()) } else { Err(SubscriptionMissing) } } pub fn emit(&self, args: T) { for (_, handler) in &self.handlers { (*handler)(args.clone()) } } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Mutex}; #[test] fn test_event() { let called1 = Arc::new(Mutex::new(false)); let called2 = Arc::new(Mutex::new(false)); let some_buffer = Arc::new(Mutex::new(Vec::new())); { let mut my_event = Event::<u8>::new(); let called1 = called1.clone(); my_event.subscribe(move |x| { *called1.lock().unwrap() = true; assert_eq!(x, 42); }); let called2 = called2.clone(); let some_buffer = some_buffer.clone(); my_event.subscribe(move |x| { *called2.lock().unwrap() = true; some_buffer.lock().unwrap().push(x); }); my_event.emit(42); } assert!(*called1.lock().unwrap()); assert!(*called2.lock().unwrap()); assert_eq!(*some_buffer.lock().unwrap(), vec![42]); } #[test] fn test_unsubscribe() { let called = Arc::new(Mutex::new(0u8)); { let mut my_event = Event::<()>::new(); let called = called.clone(); let subscription = my_event.subscribe(move |_| { *called.lock().unwrap() += 1; }); my_event.emit(()); my_event.emit(()); my_event.unsubscribe(subscription).unwrap(); my_event.emit(()); my_event.emit(()); } assert_eq!(*called.lock().unwrap(), 2); } }
enum Expr { Add(i32, i32), Sub(i32, i32), Val(i32), } fn main() { print_expr(Expr::Sub(40, 2)); print_expr(Expr::Add(40, 2)); println!("{}", uppercase(b'A')); } fn print_expr(expr: Expr) { match expr { Expr::Add(x, y) => println!("{}", x + y), Expr::Sub(x, y) => println!("{}", x - y), Expr::Val(x) => println!("{}", x), } } fn uppercase(c: u8) -> u8 { match c { b'a'...b'z' => c - 32, _ => c, } }
#[doc = "Register `SYSCFG_CMPENSETR` reader"] pub type R = crate::R<SYSCFG_CMPENSETR_SPEC>; #[doc = "Register `SYSCFG_CMPENSETR` writer"] pub type W = crate::W<SYSCFG_CMPENSETR_SPEC>; #[doc = "Field `MPU_EN` reader - MPU_EN"] pub type MPU_EN_R = crate::BitReader; #[doc = "Field `MPU_EN` writer - MPU_EN"] pub type MPU_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MCU_EN` reader - MCU_EN"] pub type MCU_EN_R = crate::BitReader; #[doc = "Field `MCU_EN` writer - MCU_EN"] pub type MCU_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - MPU_EN"] #[inline(always)] pub fn mpu_en(&self) -> MPU_EN_R { MPU_EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - MCU_EN"] #[inline(always)] pub fn mcu_en(&self) -> MCU_EN_R { MCU_EN_R::new(((self.bits >> 1) & 1) != 0) } } impl W { #[doc = "Bit 0 - MPU_EN"] #[inline(always)] #[must_use] pub fn mpu_en(&mut self) -> MPU_EN_W<SYSCFG_CMPENSETR_SPEC, 0> { MPU_EN_W::new(self) } #[doc = "Bit 1 - MCU_EN"] #[inline(always)] #[must_use] pub fn mcu_en(&mut self) -> MCU_EN_W<SYSCFG_CMPENSETR_SPEC, 1> { MCU_EN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "SYSCFG compensation cell enable set register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`syscfg_cmpensetr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`syscfg_cmpensetr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SYSCFG_CMPENSETR_SPEC; impl crate::RegisterSpec for SYSCFG_CMPENSETR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`syscfg_cmpensetr::R`](R) reader structure"] impl crate::Readable for SYSCFG_CMPENSETR_SPEC {} #[doc = "`write(|w| ..)` method takes [`syscfg_cmpensetr::W`](W) writer structure"] impl crate::Writable for SYSCFG_CMPENSETR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SYSCFG_CMPENSETR to value 0"] impl crate::Resettable for SYSCFG_CMPENSETR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use askama::Template; #[derive(Template)] #[template(path = "base.html")] pub struct Base { pub henlo: Option<String>, }
use context::{Context}; use std::vec::Vec; use std::cell::Cell; // pub type Middleware<T: Context> = fn(T, chain: &MiddlewareChain<T>) -> T; pub type Middleware<T> = fn(T, chain: &MiddlewareChain<T>) -> T; pub struct MiddlewareChain<T: Context> { _chain_index: Cell<usize>, pub middleware: Vec<Middleware<T>> } impl<T: Context> MiddlewareChain<T> { pub fn new(middleware: Vec<Middleware<T>>) -> MiddlewareChain<T> { MiddlewareChain { middleware: middleware, _chain_index: Cell::new(0) } } pub fn next(&self, context: T) -> T { let next_middleware = self.middleware.get(self._chain_index.get()); self._chain_index.set(self._chain_index.get() + 1); match next_middleware { Some(middleware) => middleware(context, self), None => context } } }
//! An implementation of the [MD4][1] cryptographic hash algorithm. //! //! # Usage //! //! ```rust //! use md4::{Md4, Digest}; //! use hex_literal::hex; //! //! // create a Md4 hasher instance //! let mut hasher = Md4::new(); //! //! // process input message //! hasher.update(b"hello world"); //! //! // acquire hash digest in the form of GenericArray, //! // which in this case is equivalent to [u8; 16] //! let result = hasher.finalize(); //! assert_eq!(result[..], hex!("aa010fbc1d14c795d86ef98c95479d17")); //! ``` //! //! Also see [RustCrypto/hashes][2] readme. //! //! [1]: https://en.wikipedia.org/wiki/MD4 //! [2]: https://github.com/RustCrypto/hashes #![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![deny(unsafe_code)] #![warn(rust_2018_idioms)] #![allow(clippy::many_single_char_names)] #[cfg(feature = "std")] extern crate std; use core::convert::TryInto; pub use digest::{self, Digest}; use block_buffer::BlockBuffer; use digest::{ consts::{U16, U64}, generic_array::GenericArray, }; use digest::{BlockInput, FixedOutputDirty, Reset, Update}; // initial values for Md4State const S: [u32; 4] = [0x6745_2301, 0xEFCD_AB89, 0x98BA_DCFE, 0x1032_5476]; type Block = GenericArray<u8, U64>; #[derive(Copy, Clone)] struct Md4State { s: [u32; 4], } /// The MD4 hasher #[derive(Clone, Default)] pub struct Md4 { length_bytes: u64, buffer: BlockBuffer<U64>, state: Md4State, } impl Md4State { fn process_block(&mut self, input: &Block) { fn f(x: u32, y: u32, z: u32) -> u32 { (x & y) | (!x & z) } fn g(x: u32, y: u32, z: u32) -> u32 { (x & y) | (x & z) | (y & z) } fn h(x: u32, y: u32, z: u32) -> u32 { x ^ y ^ z } fn op1(a: u32, b: u32, c: u32, d: u32, k: u32, s: u32) -> u32 { a.wrapping_add(f(b, c, d)).wrapping_add(k).rotate_left(s) } fn op2(a: u32, b: u32, c: u32, d: u32, k: u32, s: u32) -> u32 { a.wrapping_add(g(b, c, d)) .wrapping_add(k) .wrapping_add(0x5A82_7999) .rotate_left(s) } fn op3(a: u32, b: u32, c: u32, d: u32, k: u32, s: u32) -> u32 { a.wrapping_add(h(b, c, d)) .wrapping_add(k) .wrapping_add(0x6ED9_EBA1) .rotate_left(s) } let mut a = self.s[0]; let mut b = self.s[1]; let mut c = self.s[2]; let mut d = self.s[3]; // load block to data let mut data = [0u32; 16]; for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { *o = u32::from_le_bytes(chunk.try_into().unwrap()); } // round 1 for &i in &[0, 4, 8, 12] { a = op1(a, b, c, d, data[i], 3); d = op1(d, a, b, c, data[i + 1], 7); c = op1(c, d, a, b, data[i + 2], 11); b = op1(b, c, d, a, data[i + 3], 19); } // round 2 for i in 0..4 { a = op2(a, b, c, d, data[i], 3); d = op2(d, a, b, c, data[i + 4], 5); c = op2(c, d, a, b, data[i + 8], 9); b = op2(b, c, d, a, data[i + 12], 13); } // round 3 for &i in &[0, 2, 1, 3] { a = op3(a, b, c, d, data[i], 3); d = op3(d, a, b, c, data[i + 8], 9); c = op3(c, d, a, b, data[i + 4], 11); b = op3(b, c, d, a, data[i + 12], 15); } self.s[0] = self.s[0].wrapping_add(a); self.s[1] = self.s[1].wrapping_add(b); self.s[2] = self.s[2].wrapping_add(c); self.s[3] = self.s[3].wrapping_add(d); } } impl Default for Md4State { fn default() -> Self { Md4State { s: S } } } impl Md4 { pub fn from_state(state: [u32; 4], len: u64) -> Self { Self { state: Md4State { s: state }, length_bytes: len, buffer: Default::default(), } } fn finalize_inner(&mut self) { let state = &mut self.state; let l = (self.length_bytes << 3) as u64; self.buffer.len64_padding_le(l, |d| state.process_block(d)) } } impl BlockInput for Md4 { type BlockSize = U64; } impl Update for Md4 { fn update(&mut self, input: impl AsRef<[u8]>) { let input = input.as_ref(); // Unlike Sha1 and Sha2, the length value in MD4 is defined as // the length of the message mod 2^64 - ie: integer overflow is OK. self.length_bytes = self.length_bytes.wrapping_add(input.len() as u64); let s = &mut self.state; self.buffer.input_block(input, |d| s.process_block(d)); } } impl FixedOutputDirty for Md4 { type OutputSize = U16; fn finalize_into_dirty(&mut self, out: &mut digest::Output<Self>) { self.finalize_inner(); for (chunk, v) in out.chunks_exact_mut(4).zip(self.state.s.iter()) { chunk.copy_from_slice(&v.to_le_bytes()); } } } impl Reset for Md4 { fn reset(&mut self) { self.state = Default::default(); self.length_bytes = 0; self.buffer.reset(); } } opaque_debug::implement!(Md4); digest::impl_write!(Md4);
#[derive(Debug, PartialEq)] pub enum Comparison { Equal, Sublist, Superlist, Unequal, } pub fn sublist<A>(list_1: &[A], list_2: &[A]) -> Comparison where A: PartialEq { match (list_1.len(), list_2.len()) { (len_1, len_2) if len_1 < len_2 && is_sublist(list_1, list_2) => Comparison::Sublist, (len_1, len_2) if len_2 < len_1 && is_sublist(list_2, list_1) => Comparison::Superlist, _ if list_1 == list_2 => Comparison::Equal, _ => Comparison::Unequal, } } fn is_sublist<A>(short_list: &[A], long_list: &[A]) -> bool where A: PartialEq { short_list.is_empty() || long_list .windows(short_list.len()) .any(|candidate| candidate == short_list) }
use crate::requests::presence_topology_get::PresenceTopologyGetRequester; use crate::{Client, Config, DirectoryClient}; use serde::{Deserialize, Serialize}; use topology::{CocoNode, MixNode, MixProviderNode, NymTopology}; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CocoPresence { pub host: String, pub pub_key: String, pub last_seen: u64, pub version: String, } impl Into<topology::CocoNode> for CocoPresence { fn into(self) -> topology::CocoNode { topology::CocoNode { host: self.host, pub_key: self.pub_key, last_seen: self.last_seen, version: self.version, } } } impl From<topology::CocoNode> for CocoPresence { fn from(cn: CocoNode) -> Self { CocoPresence { host: cn.host, pub_key: cn.pub_key, last_seen: cn.last_seen, version: cn.version, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MixNodePresence { pub host: String, pub pub_key: String, pub layer: u64, pub last_seen: u64, pub version: String, } impl Into<topology::MixNode> for MixNodePresence { fn into(self) -> topology::MixNode { topology::MixNode { host: self.host.parse().unwrap(), pub_key: self.pub_key, layer: self.layer, last_seen: self.last_seen, version: self.version, } } } impl From<topology::MixNode> for MixNodePresence { fn from(mn: MixNode) -> Self { MixNodePresence { host: mn.host.to_string(), pub_key: mn.pub_key, layer: mn.layer, last_seen: mn.last_seen, version: mn.version, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MixProviderPresence { pub client_listener: String, pub mixnet_listener: String, pub pub_key: String, pub registered_clients: Vec<MixProviderClient>, pub last_seen: u64, pub version: String, } impl Into<topology::MixProviderNode> for MixProviderPresence { fn into(self) -> topology::MixProviderNode { topology::MixProviderNode { client_listener: self.client_listener.parse().unwrap(), mixnet_listener: self.mixnet_listener.parse().unwrap(), pub_key: self.pub_key, registered_clients: self .registered_clients .into_iter() .map(|c| c.into()) .collect(), last_seen: self.last_seen, version: self.version, } } } impl From<topology::MixProviderNode> for MixProviderPresence { fn from(mpn: MixProviderNode) -> Self { MixProviderPresence { client_listener: mpn.client_listener.to_string(), mixnet_listener: mpn.mixnet_listener.to_string(), pub_key: mpn.pub_key, registered_clients: mpn .registered_clients .into_iter() .map(|c| c.into()) .collect(), last_seen: mpn.last_seen, version: mpn.version, } } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct MixProviderClient { pub pub_key: String, } impl Into<topology::MixProviderClient> for MixProviderClient { fn into(self) -> topology::MixProviderClient { topology::MixProviderClient { pub_key: self.pub_key, } } } impl From<topology::MixProviderClient> for MixProviderClient { fn from(mpc: topology::MixProviderClient) -> Self { MixProviderClient { pub_key: mpc.pub_key, } } } // Topology shows us the current state of the overall Nym network #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Topology { pub coco_nodes: Vec<CocoPresence>, pub mix_nodes: Vec<MixNodePresence>, pub mix_provider_nodes: Vec<MixProviderPresence>, } impl NymTopology for Topology { fn new(directory_server: String) -> Self { println!("Using directory server: {:?}", directory_server); let directory_config = Config { base_url: directory_server, }; let directory = Client::new(directory_config); let topology = directory .presence_topology .get() .expect("Failed to retrieve network topology."); topology } fn new_from_nodes( mix_nodes: Vec<MixNode>, mix_provider_nodes: Vec<MixProviderNode>, coco_nodes: Vec<CocoNode>, ) -> Self { Topology { coco_nodes: coco_nodes.into_iter().map(|node| node.into()).collect(), mix_nodes: mix_nodes.into_iter().map(|node| node.into()).collect(), mix_provider_nodes: mix_provider_nodes .into_iter() .map(|node| node.into()) .collect(), } } fn get_mix_nodes(&self) -> Vec<topology::MixNode> { self.mix_nodes.iter().map(|x| x.clone().into()).collect() } fn get_mix_provider_nodes(&self) -> Vec<topology::MixProviderNode> { self.mix_provider_nodes .iter() .map(|x| x.clone().into()) .collect() } fn get_coco_nodes(&self) -> Vec<topology::CocoNode> { self.coco_nodes.iter().map(|x| x.clone().into()).collect() } }
pub enum AddressingMode { Immediate, ZeroPage, ZeroPageX, ZeroPageY, Absolute, AbsoluteX, AbsoluteY, IndexedIndirect, IndirectIndexed } pub enum JumpAddressingMode { Absolute, Indirect } pub enum SingleByteMnemonic { ASL, CLC, CLD, CLI, CLV, DEX, DEY, INX, INY, LSR, NOP, ROL, ROR, SEC, SED, SEI, TAX, TAY, TSX, TXA, TXS, TYA } pub enum ReadMnemonic { ADC, AND, BIT, CMP, CPX, CPY, EOR, LDA, LDX, LDY, ORA, SBC } pub enum StoreMnemonic { STA, STX, STY } pub enum RMWMnemonic { ASL, DEC, INC, LSR, ROL, ROR } pub enum PushMnemonic { PHA, PHP } pub enum PullMnemonic { PLA, PLP } pub enum BranchMnemonic { BCC, BCS, BEQ, BMI, BNE, BPL, BVC, BVS } pub enum MiscMnemonic { JSR, BRK, RTI, RTS } pub enum Instruction { SingleByte(SingleByteMnemonic), Read(ReadMnemonic, AddressingMode), Store(StoreMnemonic, AddressingMode), ReadModifyWrite(RMWMnemonic, AddressingMode), Push(PushMnemonic), Pull(PullMnemonic), Branch(BranchMnemonic), Jump(JumpAddressingMode), Misc(MiscMnemonic) } pub fn decode(opcode: u8) -> Option<Instruction> { match opcode { 0x69 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::Immediate)), 0x65 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::ZeroPage)), 0x75 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::ZeroPageX)), 0x6d => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::Absolute)), 0x7d => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::AbsoluteX)), 0x79 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::AbsoluteY)), 0x61 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::IndexedIndirect)), 0x71 => Some(Instruction::Read(ReadMnemonic::ADC, AddressingMode::IndirectIndexed)), 0x29 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::Immediate)), 0x25 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::ZeroPage)), 0x35 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::ZeroPageX)), 0x2d => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::Absolute)), 0x3d => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::AbsoluteX)), 0x39 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::AbsoluteY)), 0x21 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::IndexedIndirect)), 0x31 => Some(Instruction::Read(ReadMnemonic::AND, AddressingMode::IndirectIndexed)), 0x0a => Some(Instruction::SingleByte(SingleByteMnemonic::ASL)), 0x06 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ASL, AddressingMode::ZeroPage)), 0x16 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ASL, AddressingMode::ZeroPageX)), 0x0e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ASL, AddressingMode::Absolute)), 0x1e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ASL, AddressingMode::AbsoluteX)), 0x24 => Some(Instruction::Read(ReadMnemonic::BIT, AddressingMode::ZeroPage)), 0x2c => Some(Instruction::Read(ReadMnemonic::BIT, AddressingMode::Absolute)), 0x90 => Some(Instruction::Branch(BranchMnemonic::BCC)), 0xd0 => Some(Instruction::Branch(BranchMnemonic::BNE)), 0x10 => Some(Instruction::Branch(BranchMnemonic::BPL)), 0x00 => Some(Instruction::Misc(MiscMnemonic::BRK)), 0x50 => Some(Instruction::Branch(BranchMnemonic::BVC)), 0xb0 => Some(Instruction::Branch(BranchMnemonic::BCS)), 0xf0 => Some(Instruction::Branch(BranchMnemonic::BEQ)), 0x30 => Some(Instruction::Branch(BranchMnemonic::BMI)), 0x70 => Some(Instruction::Branch(BranchMnemonic::BVS)), 0x18 => Some(Instruction::SingleByte(SingleByteMnemonic::CLC)), 0xd8 => Some(Instruction::SingleByte(SingleByteMnemonic::CLD)), 0x58 => Some(Instruction::SingleByte(SingleByteMnemonic::CLI)), 0xb8 => Some(Instruction::SingleByte(SingleByteMnemonic::CLV)), 0xc9 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::Immediate)), 0xc5 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::ZeroPage)), 0xd5 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::ZeroPageX)), 0xcd => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::Absolute)), 0xdd => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::AbsoluteX)), 0xd9 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::AbsoluteY)), 0xc1 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::IndexedIndirect)), 0xd1 => Some(Instruction::Read(ReadMnemonic::CMP, AddressingMode::IndirectIndexed)), 0xe0 => Some(Instruction::Read(ReadMnemonic::CPX, AddressingMode::Immediate)), 0xe4 => Some(Instruction::Read(ReadMnemonic::CPX, AddressingMode::ZeroPage)), 0xec => Some(Instruction::Read(ReadMnemonic::CPX, AddressingMode::Absolute)), 0xc0 => Some(Instruction::Read(ReadMnemonic::CPY, AddressingMode::Immediate)), 0xc4 => Some(Instruction::Read(ReadMnemonic::CPY, AddressingMode::ZeroPage)), 0xcc => Some(Instruction::Read(ReadMnemonic::CPY, AddressingMode::Absolute)), 0xc6 => Some(Instruction::ReadModifyWrite(RMWMnemonic::DEC, AddressingMode::ZeroPage)), 0xd6 => Some(Instruction::ReadModifyWrite(RMWMnemonic::DEC, AddressingMode::ZeroPageX)), 0xce => Some(Instruction::ReadModifyWrite(RMWMnemonic::DEC, AddressingMode::Absolute)), 0xde => Some(Instruction::ReadModifyWrite(RMWMnemonic::DEC, AddressingMode::AbsoluteX)), 0xca => Some(Instruction::SingleByte(SingleByteMnemonic::DEX)), 0x88 => Some(Instruction::SingleByte(SingleByteMnemonic::DEY)), 0x41 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::IndexedIndirect)), 0x45 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::ZeroPage)), 0x49 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::Immediate)), 0x4d => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::Absolute)), 0x51 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::IndirectIndexed)), 0x55 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::ZeroPageX)), 0x5d => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::AbsoluteX)), 0x59 => Some(Instruction::Read(ReadMnemonic::EOR, AddressingMode::AbsoluteY)), 0xe6 => Some(Instruction::ReadModifyWrite(RMWMnemonic::INC, AddressingMode::ZeroPage)), 0xf6 => Some(Instruction::ReadModifyWrite(RMWMnemonic::INC, AddressingMode::ZeroPageX)), 0xee => Some(Instruction::ReadModifyWrite(RMWMnemonic::INC, AddressingMode::Absolute)), 0xfe => Some(Instruction::ReadModifyWrite(RMWMnemonic::INC, AddressingMode::AbsoluteX)), 0xe8 => Some(Instruction::SingleByte(SingleByteMnemonic::INX)), 0xc8 => Some(Instruction::SingleByte(SingleByteMnemonic::INY)), 0x4c => Some(Instruction::Jump(JumpAddressingMode::Absolute)), 0x6c => Some(Instruction::Jump(JumpAddressingMode::Indirect)), 0x20 => Some(Instruction::Misc(MiscMnemonic::JSR)), 0xa1 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::IndexedIndirect)), 0xa5 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::ZeroPage)), 0xa9 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::Immediate)), 0xad => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::Absolute)), 0xb1 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::IndirectIndexed)), 0xb5 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::ZeroPageX)), 0xbd => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::AbsoluteX)), 0xb9 => Some(Instruction::Read(ReadMnemonic::LDA, AddressingMode::AbsoluteY)), 0xa2 => Some(Instruction::Read(ReadMnemonic::LDX, AddressingMode::Immediate)), 0xa6 => Some(Instruction::Read(ReadMnemonic::LDX, AddressingMode::ZeroPage)), 0xb6 => Some(Instruction::Read(ReadMnemonic::LDX, AddressingMode::ZeroPageY)), 0xae => Some(Instruction::Read(ReadMnemonic::LDX, AddressingMode::Absolute)), 0xbe => Some(Instruction::Read(ReadMnemonic::LDX, AddressingMode::AbsoluteY)), 0xa0 => Some(Instruction::Read(ReadMnemonic::LDY, AddressingMode::Immediate)), 0xa4 => Some(Instruction::Read(ReadMnemonic::LDY, AddressingMode::ZeroPage)), 0xb4 => Some(Instruction::Read(ReadMnemonic::LDY, AddressingMode::ZeroPageX)), 0xac => Some(Instruction::Read(ReadMnemonic::LDY, AddressingMode::Absolute)), 0xbc => Some(Instruction::Read(ReadMnemonic::LDY, AddressingMode::AbsoluteX)), 0x4a => Some(Instruction::SingleByte(SingleByteMnemonic::LSR)), 0x46 => Some(Instruction::ReadModifyWrite(RMWMnemonic::LSR, AddressingMode::ZeroPage)), 0x56 => Some(Instruction::ReadModifyWrite(RMWMnemonic::LSR, AddressingMode::ZeroPageX)), 0x4e => Some(Instruction::ReadModifyWrite(RMWMnemonic::LSR, AddressingMode::Absolute)), 0x5e => Some(Instruction::ReadModifyWrite(RMWMnemonic::LSR, AddressingMode::AbsoluteX)), 0xea => Some(Instruction::SingleByte(SingleByteMnemonic::NOP)), 0x09 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::Immediate)), 0x05 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::ZeroPage)), 0x15 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::ZeroPageX)), 0x0d => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::Absolute)), 0x1d => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::AbsoluteX)), 0x19 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::AbsoluteY)), 0x01 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::IndexedIndirect)), 0x11 => Some(Instruction::Read(ReadMnemonic::ORA, AddressingMode::IndirectIndexed)), 0x48 => Some(Instruction::Push(PushMnemonic::PHA)), 0x08 => Some(Instruction::Push(PushMnemonic::PHP)), 0x68 => Some(Instruction::Pull(PullMnemonic::PLA)), 0x28 => Some(Instruction::Pull(PullMnemonic::PLP)), 0x2a => Some(Instruction::SingleByte(SingleByteMnemonic::ROL)), 0x26 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROL, AddressingMode::ZeroPage)), 0x36 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROL, AddressingMode::ZeroPageX)), 0x2e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROL, AddressingMode::Absolute)), 0x3e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROL, AddressingMode::AbsoluteX)), 0x6a => Some(Instruction::SingleByte(SingleByteMnemonic::ROR)), 0x66 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROR, AddressingMode::ZeroPage)), 0x76 => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROR, AddressingMode::ZeroPageX)), 0x6e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROR, AddressingMode::Absolute)), 0x7e => Some(Instruction::ReadModifyWrite(RMWMnemonic::ROR, AddressingMode::AbsoluteX)), 0x40 => Some(Instruction::Misc(MiscMnemonic::RTI)), 0x60 => Some(Instruction::Misc(MiscMnemonic::RTS)), 0xe9 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::Immediate)), 0xe5 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::ZeroPage)), 0xf5 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::ZeroPageX)), 0xed => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::Absolute)), 0xfd => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::AbsoluteX)), 0xf9 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::AbsoluteY)), 0xe1 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::IndexedIndirect)), 0xf1 => Some(Instruction::Read(ReadMnemonic::SBC, AddressingMode::IndirectIndexed)), 0x38 => Some(Instruction::SingleByte(SingleByteMnemonic::SEC)), 0xf8 => Some(Instruction::SingleByte(SingleByteMnemonic::SED)), 0x78 => Some(Instruction::SingleByte(SingleByteMnemonic::SEI)), 0x85 => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::ZeroPage)), 0x95 => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::ZeroPageX)), 0x8d => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::Absolute)), 0x9d => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::AbsoluteX)), 0x99 => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::AbsoluteY)), 0x81 => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::IndexedIndirect)), 0x91 => Some(Instruction::Store(StoreMnemonic::STA, AddressingMode::IndirectIndexed)), 0x86 => Some(Instruction::Store(StoreMnemonic::STX, AddressingMode::ZeroPage)), 0x97 => Some(Instruction::Store(StoreMnemonic::STX, AddressingMode::ZeroPageY)), 0x8e => Some(Instruction::Store(StoreMnemonic::STX, AddressingMode::Absolute)), 0x84 => Some(Instruction::Store(StoreMnemonic::STY, AddressingMode::ZeroPage)), 0x94 => Some(Instruction::Store(StoreMnemonic::STY, AddressingMode::ZeroPageX)), 0x8c => Some(Instruction::Store(StoreMnemonic::STY, AddressingMode::Absolute)), 0xaa => Some(Instruction::SingleByte(SingleByteMnemonic::TAX)), 0xa8 => Some(Instruction::SingleByte(SingleByteMnemonic::TAY)), 0x98 => Some(Instruction::SingleByte(SingleByteMnemonic::TYA)), 0xba => Some(Instruction::SingleByte(SingleByteMnemonic::TSX)), 0x8a => Some(Instruction::SingleByte(SingleByteMnemonic::TXA)), 0x9a => Some(Instruction::SingleByte(SingleByteMnemonic::TXS)), _ => None } }