text
stringlengths
8
4.13M
// functions1.rs // Make me compile! Execute `rustlings hint functions1` for hints :) // I AM DONE fn call_me(a: i32, b:i32) -> i32 { if a > b { return a; } else { return b; } } fn main() { call_me(10,20); }
use num::Signed; use std::convert::TryFrom; use std::ops::{Add, Sub}; use std::result::Result; macro_rules! impl_value { ($self: ident) => { impl<S: Copy + Signed + Sized> AsValue<S> for $self<S> { fn value(&self) -> S { self.0 } } }; } macro_rules! zero_operator { ($st: ident, $Ops: ident, $ops: ident) => { impl<S: Signed + Copy + $Ops> $Ops<Zero> for $st<S> { type Output = Self; fn $ops(self, _: Zero) -> Self::Output { self } } }; } macro_rules! zero_operators { ($self_type: ident) => { impl<S: Signed + Copy + Add> Add<Zero> for $self_type<S> { type Output = $self_type<S>; fn add(self, rhs: Zero) -> Self::Output { self } } impl<S: Signed + Copy + Add> Sub<Zero> for $self_type<S> { type Output = $self_type<S>; fn sub(self, rhs: Zero) -> Self::Output { self } } }; } macro_rules! add_operator { ($self_type: ident) => { add_operator!($self_type, $self_type, $self_type<S>, from_value_unchecked); }; ($self_type: ident, $other_type: ident) => { add_operator!($self_type, $other_type, $self_type<S>, from_value_unchecked); }; ($self_type: ident, $other_type: ident, $output_type: ty) => { add_operator!($self_type, $other_type, $output_type, from_value); }; ($self_type: ident, $other_type: ident, $output_type: ty, $from_value_function: ident) => { impl<S: Signed + Copy + Add> Add<$other_type<S>> for $self_type<S> { type Output = $output_type; fn add(self, rhs: $other_type<S>) -> Self::Output { Self::$from_value_function(self.value().add(rhs.value())) } } }; } macro_rules! sub_operator { ($self_type: ident, $other_type: ident, $from_value_function: ident) => { impl<S: Signed + Copy + Sub> Sub<$other_type<S>> for $self_type<S> { type Output = output_type; fn sub(self, rhs: $other_type<S>) -> Self::Output { Self::$from_value_function(self.value().sub(rhs.value())) } } }; } macro_rules! add_sub_operator { ($positive_type: ident, $negative_type: ident, $non_negative_type: ident, $non_positive_type: ident) => { zero_operator!($positive_type, Add, add); zero_operator!($positive_type, Sub, sub); impl<S: Signed + Copy + Add> Add for $positive_type<S> { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self::from_value_unchecked(self.value().add(rhs.value())) } } impl<S: Signed + Copy + Sub> Sub for $positive_type<S> { type Output = Result<Self, $non_positive_type<S>>; fn sub(self, rhs: Self) -> Self::Output { let result = self.value().sub(rhs.value()); Self::from_value(result) } } impl<S: Signed + Copy + Add> Add<$negative_type<S>> for $positive_type<S> { type Output = Result<Self, $non_positive_type<S>>; fn add(self, rhs: $negative_type<S>) -> Self::Output { let result = self.0.add(rhs.0); Self::from_value(result) } } impl<S: Signed + Copy + Sub> Sub<$negative_type<S>> for $positive_type<S> { type Output = Self; fn sub(self, rhs: $negative_type<S>) -> Self::Output { Self::from_value_unchecked(self.0.sub(rhs.0)) } } }; } pub enum Sign { Positive, Zero, Negative, } impl<S: Signed> From<S> for Sign { fn from(value: S) -> Self { if value.is_zero() { Self::Zero } else if value.is_positive() { Self::Positive } else { Self::Negative } } } pub trait AsValue<S: Copy + Signed + Sized> { fn value(&self) -> S; } #[derive(Copy, Clone)] pub struct Positive<S: Signed + Copy>(S); impl_value!(Positive); pub trait FromValue<S: Copy> where Self: Sized, { type Other: FromValue<S>; fn from_value(value: S) -> Result<Self, Self::Other>; fn from_value_unchecked(value: S) -> Self; } impl<S: Signed + Copy + Sized> FromValue<S> for Positive<S> { type Other = NonPositive<S>; fn from_value(value: S) -> Result<Self, Self::Other> { value .is_positive() .then(|| Self(value)) .ok_or_else(|| NonPositive::from_value_unchecked(value)) } fn from_value_unchecked(value: S) -> Self { Self(value) } } //add_sub_operator!(Positive, Negative, NonNegative, NonPositive); zero_operators!(Positive); add_operator!(Positive); add_operator!(Positive, NonNegative); add_operator!(Positive, Negative, Result<Positive<S>, NonPositive<S>>); add_operator!(Positive, NonPositive, Result<Positive<S>, NonPositive<S>>); #[derive(Copy, Clone)] pub struct Negative<S: Signed>(S); impl_value!(Negative); impl<S: Signed + Copy + Sized> FromValue<S> for Negative<S> { type Other = NonNegative<S>; fn from_value(value: S) -> Result<Self, Self::Other> { value .is_negative() .then(|| Self(value)) .ok_or_else(|| Self::Other::from_value_unchecked(value)) } fn from_value_unchecked(value: S) -> Self { Self(value) } } zero_operators!(Negative); add_operator!(Negative, Positive, Result<Negative<S>, NonNegative<S>>); add_operator!(Negative, NonNegative, Result<Negative<S>, NonNegative<S>>); add_operator!(Negative); add_operator!(Negative, NonPositive); #[derive(Copy, Clone)] pub struct Zero {} #[derive(Copy, Clone)] pub enum NonNegative<S: Copy + Signed> { Zero, Positive(Positive<S>), } impl<S: Copy + Signed + Sized> AsValue<S> for NonNegative<S> { fn value(&self) -> S { self.positive().map(|x| x.value()).unwrap_or(S::zero()) } } impl<S: Copy + Signed + Sized> FromValue<S> for NonNegative<S> { type Other = Negative<S>; fn from_value(value: S) -> Result<Self, Self::Other> { if value.is_zero() { Ok(Self::Zero) } else if value.is_positive() { Ok(Self::Positive(Positive::from_value_unchecked(value))) } else { Err(Negative::from_value_unchecked(value)) } } fn from_value_unchecked(value: S) -> Self { if value.is_zero() { Self::Zero } else { Self::Positive(Positive::from_value_unchecked(value)) } } } zero_operators!(NonNegative); add_operator!(NonNegative, Positive); add_operator!(NonNegative); add_operator!(NonNegative, Negative, Result<NonNegative<S>, Negative<S>>); add_operator!( NonNegative, NonPositive, Result<NonNegative<S>, Negative<S>> ); macro_rules! non_some_one_impls { ($self: ident, $self_inner: ident, $self_inner_lower: ident) => { impl<S: Copy + Signed> $self<S> { pub fn zero(&self) -> Result<Zero, $self_inner<S>> { match self { Self::Zero => Ok(Zero {}), Self::$self_inner(p) => Err(*p), } } pub fn $self_inner_lower(&self) -> Result<$self_inner<S>, Zero> { match self { Self::Zero => Err(Zero {}), Self::$self_inner(p) => Ok(*p), } } } }; } non_some_one_impls!(NonNegative, Positive, positive); #[derive(Copy, Clone)] pub enum NonPositive<S: Copy + Signed + Sized> { Zero, Negative(Negative<S>), } impl<S: Copy + Signed + Sized> AsValue<S> for NonPositive<S> { fn value(&self) -> S { self.negative().map(|x| x.value()).unwrap_or(S::zero()) } } impl<S: Copy + Signed + Sized> FromValue<S> for NonPositive<S> { type Other = Positive<S>; fn from_value(value: S) -> Result<Self, Self::Other> { if value.is_zero() { Ok(Self::Zero) } else if value.is_negative() { Ok(Self::Negative(Negative::from_value_unchecked(value))) } else { Err(Positive::from_value_unchecked(value)) } } fn from_value_unchecked(value: S) -> Self { if value.is_zero() { Self::Zero } else { Self::Negative(Negative::from_value_unchecked(value)) } } } zero_operators!(NonPositive); add_operator!(NonPositive, Positive, Result<NonPositive<S>, Positive<S>>); add_operator!( NonPositive, NonNegative, Result<NonPositive<S>, Positive<S>> ); add_operator!(NonPositive, Negative); add_operator!(NonPositive); non_some_one_impls!(NonPositive, Negative, negative); #[cfg(test)] mod tests { use crate::Negative; use crate::Positive; #[test] fn it_works() { let p1 = Positive(1.0); let p2 = Positive(3.0); let p3 = p1 + p2; let n1 = Negative(2.0); let e1 = p1 + n1; } }
use bitbuffer::{BitRead, BitWrite, BitWriteStream, LittleEndian}; use crate::{Parse, ParserState, Result, Stream}; use self::consolecmd::ConsoleCmdPacket; use self::datatable::DataTablePacket; use self::message::MessagePacket; use self::stop::StopPacket; use self::stringtable::StringTablePacket; use self::synctick::SyncTickPacket; use self::usercmd::UserCmdPacket; use crate::demo::data::DemoTick; use crate::demo::parser::Encode; use serde::{Deserialize, Serialize}; #[cfg(feature = "trace")] use tracing::{event, span, Level}; pub mod consolecmd; pub mod datatable; pub mod message; pub mod stop; pub mod stringtable; pub mod synctick; pub mod usercmd; #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] #[serde(bound(deserialize = "'a: 'static"))] #[serde(tag = "type")] pub enum Packet<'a> { Signon(MessagePacket<'a>), Message(MessagePacket<'a>), SyncTick(SyncTickPacket), ConsoleCmd(ConsoleCmdPacket), UserCmd(UserCmdPacket), DataTables(DataTablePacket), Stop(StopPacket), StringTables(StringTablePacket<'a>), } impl Packet<'_> { pub fn tick(&self) -> DemoTick { match self { Packet::Signon(msg) => msg.tick, Packet::Message(msg) => msg.tick, Packet::SyncTick(msg) => msg.tick, Packet::ConsoleCmd(msg) => msg.tick, Packet::UserCmd(msg) => msg.tick, Packet::DataTables(msg) => msg.tick, Packet::Stop(msg) => msg.tick, Packet::StringTables(msg) => msg.tick, } } pub fn set_tick(&mut self, tick: DemoTick) { match self { Packet::Signon(msg) => msg.tick = tick, Packet::Message(msg) => msg.tick = tick, Packet::SyncTick(msg) => msg.tick = tick, Packet::ConsoleCmd(msg) => msg.tick = tick, Packet::UserCmd(msg) => msg.tick = tick, Packet::DataTables(msg) => msg.tick = tick, Packet::Stop(msg) => msg.tick = tick, Packet::StringTables(msg) => msg.tick = tick, } } } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(BitRead, BitWrite, Debug, Clone, Copy, Eq, PartialEq)] #[discriminant_bits = 8] #[repr(u8)] pub enum PacketType { Signon = 1, Message = 2, SyncTick = 3, ConsoleCmd = 4, UserCmd = 5, DataTables = 6, Stop = 7, StringTables = 8, } impl Packet<'_> { pub fn packet_type(&self) -> PacketType { match self { Packet::Signon(_) => PacketType::Signon, Packet::Message(_) => PacketType::Message, Packet::SyncTick(_) => PacketType::SyncTick, Packet::ConsoleCmd(_) => PacketType::ConsoleCmd, Packet::UserCmd(_) => PacketType::UserCmd, Packet::DataTables(_) => PacketType::DataTables, Packet::Stop(_) => PacketType::Stop, Packet::StringTables(_) => PacketType::StringTables, } } } impl<'a> Parse<'a> for Packet<'a> { fn parse(stream: &mut Stream<'a>, state: &ParserState) -> Result<Self> { let packet_type = PacketType::read(stream)?; #[cfg(feature = "trace")] { let tick: u32 = stream.read()?; stream.set_pos(stream.pos() - 32)?; let _span = span!(Level::INFO, "reading packet", packet_type = ?packet_type, tick = tick) .entered(); event!(Level::DEBUG, "parsing packet"); } Ok(match packet_type { PacketType::Signon => Packet::Signon(MessagePacket::parse(stream, state)?), PacketType::Message => Packet::Message(MessagePacket::parse(stream, state)?), PacketType::SyncTick => Packet::SyncTick(SyncTickPacket::parse(stream, state)?), PacketType::ConsoleCmd => Packet::ConsoleCmd(ConsoleCmdPacket::parse(stream, state)?), PacketType::UserCmd => Packet::UserCmd(UserCmdPacket::parse(stream, state)?), PacketType::DataTables => Packet::DataTables(DataTablePacket::parse(stream, state)?), PacketType::Stop => Packet::Stop(StopPacket::parse(stream, state)?), PacketType::StringTables => { Packet::StringTables(StringTablePacket::parse(stream, state)?) } }) } } impl Encode for Packet<'_> { fn encode(&self, stream: &mut BitWriteStream<LittleEndian>, state: &ParserState) -> Result<()> { #[cfg(feature = "trace")] let _span = span!(Level::INFO, "encoding packet", packet_type = ?self.packet_type(), tick = self.tick()).entered(); self.packet_type().write(stream)?; match self { Packet::Signon(inner) => inner.encode(stream, state), Packet::Message(inner) => inner.encode(stream, state), Packet::SyncTick(inner) => inner.encode(stream, state), Packet::ConsoleCmd(inner) => inner.encode(stream, state), Packet::UserCmd(inner) => inner.encode(stream, state), Packet::DataTables(inner) => inner.encode(stream, state), Packet::Stop(inner) => inner.encode(stream, state), Packet::StringTables(inner) => inner.encode(stream, state), } } } impl PacketType { pub fn as_str(&self) -> &'static str { match self { PacketType::Signon => "Signon", PacketType::Message => "Message", PacketType::SyncTick => "SyncTick", PacketType::ConsoleCmd => "ConsoleCmd", PacketType::UserCmd => "UserCmd", PacketType::DataTables => "DataTables", PacketType::Stop => "Stop", PacketType::StringTables => "StringTables", } } pub fn as_lowercase_str(&self) -> &'static str { match self { PacketType::Signon => "signon", PacketType::Message => "message", PacketType::SyncTick => "synctick", PacketType::ConsoleCmd => "consolecmd", PacketType::UserCmd => "usercmd", PacketType::DataTables => "datatables", PacketType::Stop => "stop", PacketType::StringTables => "stringtables", } } }
use super::{Cartridge, Mapper, Mirror, serialize::*}; pub struct Nrom { cart: Cartridge, chr_ram: Vec<u8>, } impl Nrom { pub fn new(cart: Cartridge) -> Self { Nrom{ cart: cart, chr_ram: vec![0; 0x2000], } } } impl Mapper for Nrom { fn read(&self, address: usize) -> u8 { let addr = address % 0x4000; match address { 0x0000..=0x1FFF => { if self.cart.chr_rom_size > 0 { self.cart.chr_rom[0][address] } else { self.chr_ram[address] } }, 0x8000..=0xBFFF => { self.cart.prg_rom[0][addr] }, 0xC000..=0xFFFF => { self.cart.prg_rom[self.cart.prg_rom_size - 1][addr] }, _ => {println!("bad address read from NROM mapper: 0x{:X}", address); 0}, } } fn write(&mut self, address: usize, value: u8) { match address { 0x0000..=0x1FFF => { // ROM isn't written to if self.cart.chr_rom_size == 0 { self.chr_ram[address] = value; } }, 0x8000..=0xBFFF => (), 0xC000..=0xFFFF => (), _ => println!("bad address written to NROM mapper: 0x{:X}", address), } } fn get_mirroring(&self) -> Mirror { self.cart.mirroring } fn load_battery_backed_ram(&mut self) {} fn save_battery_backed_ram(&self) {} fn clock(&mut self) {} fn check_irq(&mut self) -> bool {false} fn save_state(&self) -> MapperData { MapperData::Nrom( NromData { cart: self.cart.clone(), chr_ram: self.chr_ram.clone(), } ) } fn load_state(&mut self, mapper_data: MapperData) { if let MapperData::Nrom(nrom_data) = mapper_data { self.cart = nrom_data.cart; self.chr_ram = nrom_data.chr_ram; } } }
use std::env; //args() use std::io::Write; //writeln!() use std::process; //exit() use std::net::TcpListener; //TcpListener::*() use std::str::from_utf8; //from_utf8() use std::string::String; //as_bytes() //Uses u8 buffer array, noting that ASCII and utf8 share the same memory alignment but not nessisarily the same code-point sizes. const BUF_SIZE : usize = 256; //inlined numeric constant fn main() { //get port string from argv let args: Vec<String> = env::args().collect(); if args.len() < 2 { writeln!( &mut std::io::stderr(), "ERROR, no port provided\n").unwrap(); //write to stderr, panic if it fails. process::exit(0); //explicit exit value, and terminates the process without calling destructors. } //verify port is itype let _ : isize = args[1].parse().unwrap_or_else(|_| { writeln!( &mut std::io::stderr(), "ERROR, port must be an integer\n").unwrap(); process::exit(0); }); let ip = "127.0.0.1".to_string(); //open socket, get ip/port from string, and bind. let listener = TcpListener::bind(ip + ":" + args[1].as_str()).unwrap_or_else(|_| { writeln!( &mut std::io::stderr(), "ERROR, socket bind failed\n").unwrap(); process::exit(1); }); //listen to socket let mut acceptor = listener.listen(); //set listener properties //open socket contents let mut stream = acceptor.accept().unwrap_or_else(|_| { writeln!( &mut std::io::stderr(), "ERROR, stream accept failed\n").unwrap(); process::exit(1); }); //display data let mut buffer = [0u8; BUF_SIZE]; stream.read(buffer); let msg = from_utf8( &buffer ).unwrap_or_else(|_| { writeln!( &mut std::io::stderr(), "ERROR, unable to decode utf8 in received message"); process::exit(1); }); //assumes utf8 input, returns &str println!("Here is the message: {}\n", msg); //respond buffer = [0u8; BUF_SIZE]; buffer.copy_from_slice( "I got your message".as_bytes() ); //stores utf8 in bytes (bytes!("msg") is depreciated) stream.write(buffer); //disconnect (implicit) //exit process::exit(0); }
/*! ```rudra-poc [target] crate = "abi_stable" version = "0.9.0" indexed_version = "0.8.3" [report] issue_url = "https://github.com/rodrimati1992/abi_stable_crates/issues/44" issue_date = 2020-12-21 rustsec_url = "https://github.com/RustSec/advisory-db/pull/609" rustsec_id = "RUSTSEC-2020-0105" [[bugs]] analyzer = "UnsafeDataflow" bug_class = "PanicSafety" bug_count = 2 rudra_report_locations = [ "src/std_types/vec/iters.rs:294:5: 312:6", "src/std_types/string.rs:613:5: 646:6", ] ``` !*/ #![forbid(unsafe_code)] fn main() { panic!("This issue was reported without PoC"); }
pub use self::greetings::*; pub use self::farewells::*; pub mod greetings; pub mod farewells;
pub mod node; pub mod rpc; pub mod test; pub mod types; pub mod prelude { pub use super::rpc::RpcExtension; pub use super::test::*; }
use crate::protocol::error::ProtocolError; #[derive(Debug, Clone, Copy)] pub enum Speed { S4 = 1, S5 = 2, S6 = 3, S7 = 4, S8 = 5, } impl Default for Speed { fn default() -> Self { Self::S4 } } impl Speed { pub fn from_raw(raw: u8) -> Result<Self, ProtocolError> { let id = (raw - 0x02) / 0x10; Self::from_id(id) } pub fn from_id(id: u8) -> Result<Self, ProtocolError> { Ok(match id { 1 => Speed::S4, 2 => Speed::S5, 3 => Speed::S6, 4 => Speed::S7, 5 => Speed::S8, _ => return Err(ProtocolError::InvalidRawInput), }) } pub fn to_raw(&self) -> u8 { *self as u8 * 0x10 + 0x02 } } #[cfg(test)] mod tests { use super::*; #[test] fn speed() { assert_eq!(0x12, Speed::S4.to_raw()); assert_eq!(0x22, Speed::S5.to_raw()); assert_eq!(0x32, Speed::S6.to_raw()); assert_eq!(0x42, Speed::S7.to_raw()); assert_eq!(0x52, Speed::S8.to_raw()); } }
pub enum TokenType { // Single-character tokens. LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, SemiColon, Slash, Star, // One or two character tokens. Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, LessEqual, // Literals. Identifier, STRING, Number, // Keywords. And, Class, Else, False, Fun, For, If, Nil, Or, Print, Return, Super, This, True, Var, While, Eof }
use tokio_postgres::{Client, Statement, types::Type, IsolationLevel}; use crate::queries::errors::Result; use crate::api::app_state::AppDatabase; pub struct Query { pub update_bucket: Statement, pub acquire_token_from_bucket: Statement, } impl Query { pub async fn new(client: &Client) -> Self { let update_bucket = client.prepare_typed( "INSERT INTO limits (subject, remote, available_tokens, last_time) \ VALUES ($1, $2, $3, NOW()) \ ON CONFLICT (subject, remote) \ DO UPDATE SET \ available_tokens = LEAST(limits.available_tokens + \ $4 * EXTRACT(EPOCH from excluded.last_time - limits.last_time), $3), \ last_time = EXCLUDED.last_time \ RETURNING available_tokens", &[Type::TEXT, Type::TEXT, Type::FLOAT8, Type::FLOAT8], ).await.unwrap(); let acquire_token_from_bucket = client.prepare_typed( "UPDATE limits SET available_tokens = GREATEST(available_tokens - 1.0, 0.0) \ WHERE subject = $1 AND remote = $2", &[Type::TEXT, Type::TEXT] ).await.unwrap(); Self { update_bucket, acquire_token_from_bucket, } } } impl AppDatabase { pub async fn limit_try_acquire_token( &self, subject: &str, remote: &str, burst: f64, rate: f64, reset_on_fail: bool, ) -> Result<bool> { let mut writable_client = self.db.write().await; let transaction = writable_client.build_transaction() .isolation_level(IsolationLevel::RepeatableRead) .start() .await?; let tokens: f64 = transaction .query_one(&self.limit.update_bucket, &[&subject, &remote, &burst, &rate]) .await? .get("available_tokens"); let success = tokens >= 1.0; if success || reset_on_fail { transaction .query(&self.limit.acquire_token_from_bucket, &[&subject, &remote]) .await?; } transaction.commit().await?; Ok(success) } }
pub mod manage_chart_data; pub mod types;
use im::{HashMap, HashSet}; use rustc_session::Session; use crate::rustspec::*; use crate::util::check_vec; use std::{ ops::Add, sync::atomic::{AtomicUsize, Ordering}, }; use crate::name_resolution::{FnKey, FnValue, TopLevelContext}; pub static ID_COUNTER: AtomicUsize = AtomicUsize::new(0); fn fresh_hacspec_id() -> usize { ID_COUNTER.fetch_add(1, Ordering::SeqCst) } pub(crate) fn to_fresh_ident(x: &String, mutable: bool) -> Ident { Ident::Local(LocalIdent { id: fresh_hacspec_id(), name: x.clone(), mutable, }) } pub type ResolutionResult<T> = Result<T, ()>; #[derive(Clone, Debug)] pub struct ScopeMutInfo { pub funcs: FunctionDependencies, } impl ScopeMutInfo { fn new() -> Self { ScopeMutInfo { funcs: FunctionDependencies(HashSet::new()), } } fn extend(&mut self, s: ScopeMutInfo) { self.funcs.0.extend(s.funcs.0); } fn extend_with_block(&mut self, b: Block) { self.funcs.0.extend(b.function_dependencies.0); } } fn resolve_expression( sess: &Session, (e, e_span): Spanned<Expression>, top_level_ctx: &TopLevelContext, ) -> ResolutionResult<ScopeMutInfo> { log::trace!("resolve_expression ({:?}, {:?})", e, e_span); match e { Expression::Unary(_, e1, _) => { let smi_new_e1 = resolve_expression(sess, *e1, top_level_ctx)?; Ok(smi_new_e1) } Expression::Binary(_, e1, e2, _) => { let smi_new_e1 = resolve_expression(sess, *e1, top_level_ctx)?; let smi_new_e2 = resolve_expression(sess, *e2, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_e1); smi.extend(smi_new_e2); Ok(smi) } Expression::MonadicLet(..) => // TODO: eliminiate this `panic!` with nicer types (See issue #303) { panic!( "The name resolution phase expects an AST free of [Expression::MonadicLet] node." ) } Expression::QuestionMark(e, _) => { let smi_new_e = resolve_expression(sess, *e, top_level_ctx)?; Ok(smi_new_e) } Expression::MatchWith(arg, arms) => { let smi_new_arg = resolve_expression(sess, *arg, top_level_ctx)?; let smi_new_arms: Vec<_> = check_vec( arms.into_iter() .map(|(_, arm)| { let smi_new_arm = resolve_expression(sess, arm, top_level_ctx)?; Ok(smi_new_arm) }) .collect(), )?; let smi_new_arms: ScopeMutInfo = smi_new_arms .into_iter() .fold(ScopeMutInfo::new(), |mut smi, x| { smi.extend(x); smi }); let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_arg); smi.extend(smi_new_arms); Ok(smi) } Expression::FieldAccessor(box e1, _) => { let smi = resolve_expression(sess, e1, top_level_ctx)?; Ok(smi) } Expression::EnumInject(_, _, payload) => { let smi_payload = match payload { None => ScopeMutInfo::new(), Some(payload) => { let smi_payload = resolve_expression(sess, (*payload.0, payload.1), top_level_ctx)?; smi_payload } }; Ok(smi_payload) } Expression::InlineConditional(e1, e2, e3) => { let smi_new_e1 = resolve_expression(sess, *e1, top_level_ctx)?; let smi_new_e2 = resolve_expression(sess, *e2, top_level_ctx)?; let smi_new_e3 = resolve_expression(sess, *e3, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_e1); smi.extend(smi_new_e2); smi.extend(smi_new_e3); Ok(smi) } Expression::Named(_) => Ok(ScopeMutInfo::new()), Expression::FuncCall(_, f, args, _) => { let smi_new_args: Vec<_> = check_vec( args.into_iter() .map(|arg| Ok(resolve_expression(sess, arg.0, top_level_ctx)?)) .collect(), )?; let smi_new_args: ScopeMutInfo = smi_new_args .into_iter() .fold(ScopeMutInfo::new(), |mut smi, x| { smi.extend(x); smi }); let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_args); smi.funcs.0.insert(f.clone().0); match top_level_ctx .functions .get(&FnKey::Independent(f.clone().0)) { Some(FnValue::Local(sig)) => { smi.funcs.0.extend(sig.function_dependencies.clone().0); () } _ => (), }; Ok(smi) } Expression::MethodCall(self_, _, f, args, _) => { let (self_, _) = *self_; let smi_new_self = resolve_expression(sess, self_, top_level_ctx)?; let smi_new_args: Vec<_> = check_vec( args.into_iter() .map(|arg| { let smi_new_arg0 = resolve_expression(sess, arg.0, top_level_ctx)?; Ok(smi_new_arg0) }) .collect(), )?; let smi_new_args: ScopeMutInfo = smi_new_args .into_iter() .fold(ScopeMutInfo::new(), |mut smi, x| { smi.extend(x); smi }); let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_self); smi.extend(smi_new_args); smi.funcs.0.insert(f.clone().0); match top_level_ctx .functions .get(&FnKey::Independent(f.clone().0)) { Some(FnValue::Local(sig)) => { smi.funcs.0.extend(sig.function_dependencies.clone().0); () } _ => (), }; Ok(smi) } Expression::Lit(_) => Ok(ScopeMutInfo::new()), Expression::ArrayIndex(_, e1, _) => { let smi_new_e1 = resolve_expression(sess, *e1, top_level_ctx)?; Ok(smi_new_e1) } Expression::NewArray(_, _, args) => { let smi_new_args: Vec<_> = check_vec( args.into_iter() .map(|arg| resolve_expression(sess, arg, top_level_ctx)) .collect(), )?; let smi_new_args: ScopeMutInfo = smi_new_args .into_iter() .fold(ScopeMutInfo::new(), |mut smi, x| { smi.extend(x); smi }); Ok(smi_new_args) } Expression::Tuple(args) => { let smi_new_args: Vec<_> = check_vec( args.into_iter() .map(|arg| resolve_expression(sess, arg, top_level_ctx)) .collect(), )?; let smi_new_args: ScopeMutInfo = smi_new_args .into_iter() .fold(ScopeMutInfo::new(), |mut smi, x| { smi.extend(x); smi }); Ok(smi_new_args) } Expression::IntegerCasting(e1, _, _) => { let smi_new_e1 = resolve_expression(sess, *e1, top_level_ctx)?; Ok(smi_new_e1) } } } fn resolve_statement( sess: &Session, (s, s_span): Spanned<Statement>, top_level_ctx: &TopLevelContext, ) -> ResolutionResult<ScopeMutInfo> { log::trace!("resolve_statements ({:?}, {:?})", s, s_span); match s { Statement::Conditional(cond, then_b, else_b, _) => { let smi_new_cond = resolve_expression(sess, cond, top_level_ctx)?; let new_then_b = resolve_block(sess, then_b, top_level_ctx)?; let smi_new_else_b = match else_b { None => ScopeMutInfo::new(), Some(else_b) => { let new_else_b = resolve_block(sess, else_b, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend_with_block(new_else_b.0.clone()); smi } }; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_cond); smi.extend_with_block(new_then_b.0.clone()); smi.extend(smi_new_else_b); Ok(smi) } Statement::ForLoop(_, lower, upper, body) => { let smi_new_lower = resolve_expression(sess, lower, top_level_ctx)?; let smi_new_upper = resolve_expression(sess, upper, top_level_ctx)?; let new_body = resolve_block(sess, body, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_lower); smi.extend(smi_new_upper); smi.extend_with_block(new_body.clone().0); Ok(smi) } Statement::ReturnExp(e, _) => { let smi_new_e = resolve_expression(sess, (e, s_span.clone()), top_level_ctx)?; Ok(smi_new_e) } Statement::ArrayUpdate(_, index, e, _, _, _) => { let smi_new_index = resolve_expression(sess, index, top_level_ctx)?; let smi_new_e = resolve_expression(sess, e, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_index); smi.extend(smi_new_e); Ok(smi.clone()) } Statement::Reassignment(_, _, e, _, _) => { let smi_new_e = resolve_expression(sess, e, top_level_ctx)?; Ok(smi_new_e.clone()) } Statement::LetBinding(_, _, e, _, _) => { let smi_new_e = resolve_expression(sess, e, top_level_ctx)?; let mut smi = ScopeMutInfo::new(); smi.extend(smi_new_e); Ok(smi.clone()) } } } fn resolve_block( sess: &Session, (b, b_span): Spanned<Block>, top_level_ctx: &TopLevelContext, ) -> ResolutionResult<Spanned<Block>> { log::trace!("resolve_block ({:#?}, {:#?})", b, b_span); let mut smi = ScopeMutInfo::new(); for s in b.stmts.clone().into_iter() { let smi_stmt = resolve_statement(sess, s, top_level_ctx)?; smi.extend(smi_stmt); } Ok(( Block { function_dependencies: smi.funcs, ..b }, b_span, )) } fn resolve_item( sess: &Session, (item, i_span): Spanned<DecoratedItem>, top_level_ctx: &TopLevelContext, ) -> ResolutionResult<Spanned<DecoratedItem>> { log::trace!("resolve_item ({:?}, {:?})", item, i_span); let i = item.clone().item; let i = match i { Item::FnDecl((f, f_span), mut sig, (b, b_span)) => { let new_sig_args = sig.args .iter() .fold(Vec::new(), |mut new_sig_acc, ((x, x_span), (t, t_span))| { let new_x = match x { Ident::Unresolved(s) => to_fresh_ident(s, false), s => s.clone(), }; new_sig_acc.push(((new_x, x_span.clone()), (t.clone(), t_span.clone()))); new_sig_acc }); sig.args = new_sig_args; let new_b = resolve_block(sess, (b, b_span), top_level_ctx)?; sig.function_dependencies = new_b.clone().0.function_dependencies; Ok((Item::FnDecl((f, f_span), sig, new_b), i_span)) } i => Ok((i, i_span)), }; match i { Ok((i, i_span)) => Ok(( DecoratedItem { item: i, tags: item.tags, }, i_span, )), Err(a) => Err(a), } } pub fn resolve_fun_dep( f: FunctionDependency, f_dep: FunctionDependencies, f_deps_map: HashMap<FunctionDependency, FunctionDependencies>, ) -> FunctionDependencies { if f_deps_map.contains_key(&f.clone()) { let mut fdeps: FunctionDependencies = f_deps_map[&f.clone()].clone(); for f_other in f_dep.0 { fdeps.0.insert(f_other.clone()); if f_deps_map.contains_key(&f_other.clone()) { for x in resolve_fun_dep( f.clone(), f_deps_map[&f_other.clone()].clone(), f_deps_map.clone(), ) .0 { fdeps.0.insert(x); } } } fdeps } else { FunctionDependencies(HashSet::new()) } } pub fn resolve_crate( sess: &Session, p: Program, top_level_ctx: &mut TopLevelContext, ) -> ResolutionResult<Program> { let mut items = p.items; items = check_vec( items .into_iter() .map(|i| resolve_item(sess, i, &top_level_ctx)) .collect(), )?; // let mut f_deps_map: HashMap<FunctionDependency, FunctionDependencies> = HashMap::new(); // for x in items.clone().into_iter() { // match x.0.item { // Item::FnDecl((f, _f_span), sig, _b) => { // println!("{:?} depends on {:?}", f, sig.function_dependencies); // f_deps_map.insert(f.clone(), sig.function_dependencies.clone()); // } // _ => (), // } // } // let items : Vec<Spanned<DecoratedItem>> = items // .clone() // .into_iter() // .map(|x| { // ( // DecoratedItem { // item: match x.0.item { // Item::FnDecl((f, f_span), sig, b) => { // let sig = FuncSig { // function_dependencies: resolve_fun_dep( // f.clone(), // sig.function_dependencies, // f_deps_map.clone(), // ), // ..sig // }; // top_level_ctx // .functions // .insert(FnKey::Independent(f.clone()), FnValue::Local(sig.clone())); // Item::FnDecl((f.clone(), f_span), sig, b) // } // i => i.clone(), // }, // ..x.0 // }, // x.1, // ) // }) // .collect(); // let items = check_vec( // items.clone() // .into_iter() // .map(|i| resolve_item(sess, i, &top_level_ctx)) // .collect(), // )?; Ok(Program { items }) }
use std::collections::BTreeSet; use serde::{Serialize, Deserialize}; use super::{Column, Task, Id}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Project { id: Id, name: String, description: String, columns: Vec<Column>, tasks: Vec<Task>, } impl Project { pub fn new<I: AsRef<str>>(id: I) -> ProjectBuilder { ProjectBuilder::new(id.as_ref().to_string().into()) } pub fn id(&self) -> &Id { &self.id } pub fn name(&self) -> &str { self.name.as_str() } pub fn description(&self) -> &str { self.description.as_str() } pub fn columns(&self) -> &[Column] { self.columns.as_slice() } pub fn tasks(&self) -> &[Task] { self.tasks.as_slice() } pub fn task_with_id(&self, task_id: &Id) -> Option<&Task> { self.tasks.iter() .find(|task| task.id() == task_id) } pub fn column_of_task(&self, task: &Task) -> Option<&Column> { self.columns.iter() .find(|column| column.tasks().contains(task.id())) } pub fn column_index_of_task(&self, task: &Task) -> Option<usize> { self.columns.iter() .position(|column| column.tasks().contains(task.id())) } pub fn all_assignees(&self) -> BTreeSet<&str> { self.tasks.iter() .filter_map(|task| task.assignee()) .collect() } pub fn all_tags(&self) -> BTreeSet<&str> { self.tasks.iter() .flat_map(|task| task.tags()) .map(|string| string.as_str()) .collect() } pub fn add_task(&mut self, task: Task, column: usize) -> bool { if self.tasks.iter().find(|t| t.id() == task.id()).is_some() { return false } self.columns[column].add_task(&task); self.tasks.push(task); true } pub fn replace_task(&mut self, original_task: &Id, task: Task, column: Option<usize>) { if let Some(column_index) = column { for column in self.columns.iter_mut() { column.remove_task(original_task); } self.columns[column_index].add_task(&task); } self.tasks.retain(|task| task.id() != original_task); self.tasks.push(task); } pub fn delete_task(&mut self, task_id: &Id) { for column in self.columns.iter_mut() { column.remove_task(task_id); } self.tasks.retain(|task| task.id() != task_id); } pub fn move_task(&mut self, task: &Task, distance: isize) { let previous_column = match self.column_index_of_task(task) { Some(column) => column, None => return, }; let new_column = previous_column as isize + distance; if new_column < 0 || new_column > self.columns.len() as isize { return; } let new_column = new_column as usize; self.columns[previous_column].remove_task(task.id()); self.columns[new_column].add_task(task); } pub fn move_task_to_column(&mut self, task_id: Id, column_id: Id) { for column in self.columns.iter_mut() { column.remove_task(&task_id); } let target_column = self.columns .iter_mut() .find(|column| column.id() == &column_id); if let Some(column) = target_column { column.add_task_id(task_id); } } } #[derive(Debug)] pub struct ProjectBuilder { id: Id, name: Option<String>, description: Option<String>, columns: Vec<Column>, tasks: Vec<Task>, } impl ProjectBuilder { fn new(id: Id) -> Self { Self { id, name: None, description: None, columns: vec![], tasks: vec![], } } pub fn description<I: AsRef<str>>(self, description: I) -> Self { Self { description: Some(description.as_ref().to_string()), ..self } } pub fn name<I: AsRef<str>>(self, name: I) -> Self { Self { name: Some(name.as_ref().to_string()), ..self } } pub fn column(mut self, column: Column) -> Self { self.columns.push(column); self } pub fn task(mut self, task: Task) -> Self { self.tasks.push(task); self } pub fn build(self) -> Result<Project, Self> { match self { ProjectBuilder { id, name: Some(name), description: Some(description), columns, tasks } => Ok(Project { id, name, description, columns, tasks }), _=> Err(self), } } }
use clap::{value_t, App, Arg, SubCommand}; use rusqlite::Connection; mod error; mod item; mod salvage; mod utils; use crate::error::NumeneraError; use crate::utils::roll_dice; fn main() -> Result<(), NumeneraError> { let conn = Connection::open("./numenera.db")?; let matches = App::new("Numenera Helper") .version("0.1") .author("Ostrosco") .about("Makes a Numenera campaign smoother") .subcommand( SubCommand::with_name("salvage") .about("Generate a random salvage result.") .arg( Arg::with_name("level") .short("l") .required(true) .help("Item level of the object being salvaged.") .index(1), ), ) .subcommand( SubCommand::with_name("loot") .arg( Arg::with_name("cyphers") .short("c") .help("Generate a number of cyphers.") .takes_value(true), ) .arg( Arg::with_name("artifacts") .short("a") .help("Generate a number of artifacts.") .takes_value(true), ) .arg( Arg::with_name("oddities") .short("o") .help("Generate a number of oddities.") .takes_value(true), ), ) .get_matches(); if let Some(matches) = matches.subcommand_matches("salvage") { let level = value_t!(matches, "level", u8).unwrap(); println!("Random salvage result:"); println!("{:#?}", salvage::random_salvage(&conn, level)?); } if let Some(matches) = matches.subcommand_matches("loot") { let num_cyphers = roll_dice(matches.value_of("cyphers").unwrap_or("0"))?; let num_artifacts = roll_dice(matches.value_of("artifacts").unwrap_or("0"))?; let num_oddities = roll_dice(matches.value_of("oddities").unwrap_or("0"))?; for _ in 0..num_cyphers { println!("{:#?}", item::get_cypher(&conn)?); } for _ in 0..num_artifacts { println!("{:#?}", item::get_artifact(&conn)?); } for _ in 0..num_oddities { println!("{:#?}", item::get_oddity(&conn)?); } } Ok(()) }
tag thing { a; b; c; } iter foo() -> int { put 10; } fn main() { let x = true; alt a { a. { x = true; for each i: int in foo() { } } b. { x = false; } c. { x = false; } } }
// -*- rust -*- iter two() -> int { put 0; put 1; } iter range(start: int, stop: int) -> int { let i: int = start; while i < stop { put i; i += 1; } } fn main() { let a: [mutable int] = [mutable -1, -1, -1, -1, -1, -1, -1, -1]; let p: int = 0; for each i: int in two() { for each j: int in range(0, 2) { let tmp: int = 10 * i + j; for each k: int in range(0, 2) { a[p] = 10 * tmp + k; p += 1; } } } assert (a[0] == 0); assert (a[1] == 1); assert (a[2] == 10); assert (a[3] == 11); assert (a[4] == 100); assert (a[5] == 101); assert (a[6] == 110); assert (a[7] == 111); }
extern crate regex; use colored::*; use regex::Regex; use std::cmp::Ordering; use std::env; use std::fs; use std::process::Command; fn fetch_problem_url() -> Option<String> { let args: Vec<String> = env::args().collect(); if args.len() == 2 { return Some(args[1].to_string()); } println!("Incorrect usage"); return None; } fn fetch_libs(contents: &str) -> String { let mut result = "".to_string(); for (_, line) in contents.lines().into_iter().enumerate() { if line == "" { break; } result = format!("{}{}\n", result, line); } return result; } fn fetch_block(content: &str, mark: String) -> Option<String> { let at_eq = |ind: usize, other: &str| -> bool { return content[ind..ind + 1].cmp(other) == Ordering::Equal; }; let opt_ind = content.find(&mark); if opt_ind.is_none() { return None; } let mut ind = opt_ind.unwrap() as usize; while !at_eq(ind, "\n") { ind -= 1; } ind += 1; let start = ind.clone(); let (mut brackets, mut was) = (0, false); while !was || (brackets != 0) { if at_eq(ind, "{") { brackets += 1; was = true; } if at_eq(ind, "}") { brackets -= 1; } ind += 1; } return Some(content[start..ind].to_string()); } fn fetch_deps(content: &str, target: String) -> String { let re = Regex::new(r"use crate::\{(.+)}").unwrap(); let cap = re.captures(&target); if cap.is_none() { return "".to_string(); } return cap .unwrap() .get(1) .unwrap() .as_str() .split(", ") .map(|dep| fetch_block(content, dep.to_string()).unwrap()) .fold("".to_string(), |i, j| format!("{}{}\n\n", i, j)); } fn make_main(target: &str) -> String { let re = Regex::new(r"pub mod (\w+) \{").unwrap(); let cap = re.captures(&target); if cap.is_none() { panic!("mod not found") } let name = cap.unwrap().get(1).unwrap().as_str(); format!( r" fn main() {} {}::solve(); {}", "{", name, "}" ) } fn compile(source_path: &str, compile_path: &str) { let cmd = format!("rustc {} -o {}", source_path, compile_path); println!( "{:?}", Command::new("sh") .args(&["-c", &cmd]) .output() .unwrap() .stdout ); } fn copy_to_clipboard(t: &str) { Command::new("bash") .args(&["-c", &format!("echo -n '{}' | xsel -ib", t)]) .output() .unwrap() .stdout; } fn main() { let problem_ident_opt = fetch_problem_url(); if problem_ident_opt.is_none() { return; } let problem_ident = problem_ident_opt.unwrap(); let filename = "codeforces/src/main.rs"; let contents = fs::read_to_string(filename).expect("Something went wrong reading the file"); let mod_code_opt = fetch_block(&contents, problem_ident.clone()); if mod_code_opt.is_none() { return println!("Couldn't parse main function"); } let mod_code = mod_code_opt.unwrap(); let code = format!( "{}\n{}{}\n{}\n", fetch_libs(&contents), fetch_deps(&contents, mod_code.clone()), mod_code.clone(), make_main(&mod_code) ); let source_path = format!("cf_preparator/gen/{}.rs", problem_ident); let compile_path = format!("cf_preparator/gen/{}", problem_ident); fs::write(&source_path, code).expect("Something went wrong writing the file"); compile(&source_path, &compile_path); let mut invite = format!("cd cf_preparator/gen/ && ./{} > out.txt &", problem_ident); invite.push_str("& echo -ne \"\\033[0;33m\" && cat out.txt && echo -ne \"\\033[0m\" && cd -"); copy_to_clipboard(&invite); println!("Check:\n{}", (&invite).blue().bold()); }
extern crate hoge; use hoge::hoge; //mod hoge; struct TimeBomb { s: &'static str } impl Drop for TimeBomb { fn drop(&mut self) { println!("dropped {}", self.s) } } trait Seq<T> { fn length(&self) -> uint; } impl<T> Seq<T> for Vec<T> { fn length(&self) -> uint { self.len() } } fn print_length<T>(xs: &Seq<T>) { println!("{}", xs.length()) } fn main () { print_length(&(*(box vec![TimeBomb{s:"0"}, TimeBomb{s:"1"}])) as &Seq<TimeBomb>); hoge(); print_length(&(*(box vec![TimeBomb{s:"2"}])) as &Seq<TimeBomb>); hoge(); }
#[doc = "Register `DMACRXIWTR` reader"] pub type R = crate::R<DMACRXIWTR_SPEC>; #[doc = "Register `DMACRXIWTR` writer"] pub type W = crate::W<DMACRXIWTR_SPEC>; #[doc = "Field `RWT` reader - Receive Interrupt Watchdog Timer Count This field indicates the number of system clock cycles, multiplied by factor indicated in RWTU field, for which the watchdog timer is set. The watchdog timer is triggered with the programmed value after the Rx DMA completes the transfer of a packet for which the RI bit is not set in the ETH_DMACSR, because of the setting of Interrupt Enable bit in the corresponding descriptor RDES3\\[30\\]. When the watchdog timer runs out, the RI bit is set and the timer is stopped. The watchdog timer is reset when the RI bit is set high because of automatic setting of RI as per the Interrupt Enable bit RDES3\\[30\\] of any received packet."] pub type RWT_R = crate::FieldReader; #[doc = "Field `RWT` writer - Receive Interrupt Watchdog Timer Count This field indicates the number of system clock cycles, multiplied by factor indicated in RWTU field, for which the watchdog timer is set. The watchdog timer is triggered with the programmed value after the Rx DMA completes the transfer of a packet for which the RI bit is not set in the ETH_DMACSR, because of the setting of Interrupt Enable bit in the corresponding descriptor RDES3\\[30\\]. When the watchdog timer runs out, the RI bit is set and the timer is stopped. The watchdog timer is reset when the RI bit is set high because of automatic setting of RI as per the Interrupt Enable bit RDES3\\[30\\] of any received packet."] pub type RWT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `RWTU` reader - Receive Interrupt Watchdog Timer Count Units This field indicates the number of system clock cycles corresponding to one unit in RWT\\[7:0\\] field. For example, when RWT\\[7:0\\]�=�2 and RWTU\\[1:0\\]�=�1, the watchdog timer is set for 2�*�512�=�1024 system clock cycles."] pub type RWTU_R = crate::FieldReader; #[doc = "Field `RWTU` writer - Receive Interrupt Watchdog Timer Count Units This field indicates the number of system clock cycles corresponding to one unit in RWT\\[7:0\\] field. For example, when RWT\\[7:0\\]�=�2 and RWTU\\[1:0\\]�=�1, the watchdog timer is set for 2�*�512�=�1024 system clock cycles."] pub type RWTU_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:7 - Receive Interrupt Watchdog Timer Count This field indicates the number of system clock cycles, multiplied by factor indicated in RWTU field, for which the watchdog timer is set. The watchdog timer is triggered with the programmed value after the Rx DMA completes the transfer of a packet for which the RI bit is not set in the ETH_DMACSR, because of the setting of Interrupt Enable bit in the corresponding descriptor RDES3\\[30\\]. When the watchdog timer runs out, the RI bit is set and the timer is stopped. The watchdog timer is reset when the RI bit is set high because of automatic setting of RI as per the Interrupt Enable bit RDES3\\[30\\] of any received packet."] #[inline(always)] pub fn rwt(&self) -> RWT_R { RWT_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 16:17 - Receive Interrupt Watchdog Timer Count Units This field indicates the number of system clock cycles corresponding to one unit in RWT\\[7:0\\] field. For example, when RWT\\[7:0\\]�=�2 and RWTU\\[1:0\\]�=�1, the watchdog timer is set for 2�*�512�=�1024 system clock cycles."] #[inline(always)] pub fn rwtu(&self) -> RWTU_R { RWTU_R::new(((self.bits >> 16) & 3) as u8) } } impl W { #[doc = "Bits 0:7 - Receive Interrupt Watchdog Timer Count This field indicates the number of system clock cycles, multiplied by factor indicated in RWTU field, for which the watchdog timer is set. The watchdog timer is triggered with the programmed value after the Rx DMA completes the transfer of a packet for which the RI bit is not set in the ETH_DMACSR, because of the setting of Interrupt Enable bit in the corresponding descriptor RDES3\\[30\\]. When the watchdog timer runs out, the RI bit is set and the timer is stopped. The watchdog timer is reset when the RI bit is set high because of automatic setting of RI as per the Interrupt Enable bit RDES3\\[30\\] of any received packet."] #[inline(always)] #[must_use] pub fn rwt(&mut self) -> RWT_W<DMACRXIWTR_SPEC, 0> { RWT_W::new(self) } #[doc = "Bits 16:17 - Receive Interrupt Watchdog Timer Count Units This field indicates the number of system clock cycles corresponding to one unit in RWT\\[7:0\\] field. For example, when RWT\\[7:0\\]�=�2 and RWTU\\[1:0\\]�=�1, the watchdog timer is set for 2�*�512�=�1024 system clock cycles."] #[inline(always)] #[must_use] pub fn rwtu(&mut self) -> RWTU_W<DMACRXIWTR_SPEC, 16> { RWTU_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 = "Channel Rx interrupt watchdog timer register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmacrxiwtr::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 [`dmacrxiwtr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DMACRXIWTR_SPEC; impl crate::RegisterSpec for DMACRXIWTR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dmacrxiwtr::R`](R) reader structure"] impl crate::Readable for DMACRXIWTR_SPEC {} #[doc = "`write(|w| ..)` method takes [`dmacrxiwtr::W`](W) writer structure"] impl crate::Writable for DMACRXIWTR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DMACRXIWTR to value 0"] impl crate::Resettable for DMACRXIWTR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::{convert::TryFrom, fmt::Debug, ops::Deref}; use time::{ error::ComponentRange, format_description::well_known::Iso8601, Date as _Date, OffsetDateTime, PrimitiveDateTime, Time, }; use crate::Error; use librespot_protocol as protocol; use protocol::metadata::Date as DateMessage; impl From<ComponentRange> for Error { fn from(err: ComponentRange) -> Self { Error::out_of_range(err) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Date(pub OffsetDateTime); impl Deref for Date { type Target = OffsetDateTime; fn deref(&self) -> &Self::Target { &self.0 } } impl Date { pub fn as_timestamp_ms(&self) -> i64 { (self.0.unix_timestamp_nanos() / 1_000_000) as i64 } pub fn from_timestamp_ms(timestamp: i64) -> Result<Self, Error> { let date_time = OffsetDateTime::from_unix_timestamp_nanos(timestamp as i128 * 1_000_000)?; Ok(Self(date_time)) } pub fn as_utc(&self) -> OffsetDateTime { self.0 } pub fn from_utc(date_time: PrimitiveDateTime) -> Self { Self(date_time.assume_utc()) } pub fn now_utc() -> Self { Self(OffsetDateTime::now_utc()) } pub fn from_iso8601(input: &str) -> Result<Self, Error> { let date_time = OffsetDateTime::parse(input, &Iso8601::DEFAULT)?; Ok(Self(date_time)) } } impl TryFrom<&DateMessage> for Date { type Error = crate::Error; fn try_from(msg: &DateMessage) -> Result<Self, Self::Error> { // Some metadata contains a year, but no month. In that case just set January. let month = if msg.has_month() { msg.month() as u8 } else { 1 }; // Having no day will work, but may be unexpected: it will imply the last day // of the month before. So prevent that, and just set day 1. let day = if msg.has_day() { msg.day() as u8 } else { 1 }; let date = _Date::from_calendar_date(msg.year(), month.try_into()?, day)?; let time = Time::from_hms(msg.hour() as u8, msg.minute() as u8, 0)?; Ok(Self::from_utc(PrimitiveDateTime::new(date, time))) } } impl From<OffsetDateTime> for Date { fn from(datetime: OffsetDateTime) -> Self { Self(datetime) } }
use std::fs::{File}; use std::io::{BufRead, BufReader}; use std::vec::{Vec}; use std::collections::{HashMap}; type Coord = (usize, usize); type AstList = Vec<Coord>; fn parse_program(inp: &str) -> AstList { let f = BufReader::new(File::open(inp).unwrap()); return f.lines() .enumerate() .map(|(x,l)| l.unwrap() .chars() .enumerate() .filter(|&(_,v)| v == '#') .map(|(y,_)| (y, x)) .collect::<AstList>()) .collect::<Vec<_>>() .into_iter() .flatten() .collect(); } fn process_asterodis(asteroids: &AstList, origo: &Coord) -> HashMap<i32, AstList> { let mut processed: HashMap<i32, AstList> = HashMap::new(); let origo_x = origo.0 as f32; let origo_y = origo.1 as f32; for ast in asteroids { let ast_x = ast.0 as f32; let ast_y = ast.1 as f32; let degree = 360.0 - (ast_x - origo_x).atan2(ast_y - origo_y).to_degrees() - 180.0; // let deg_str = degree.to_string(); // if !processed.contains_key(&deg_str) { // processed.insert(deg_str.clone(), Vec::new()); // } // processed.get_mut(&deg_str).unwrap().push(ast.clone()); // let degree = PI - (ast_x - origo_x).atan2(ast_y - origo_y); processed.entry((degree * 1_000_000.0) as i32).or_insert_with(||Vec::new()).push(ast.clone()); } // return processed; return processed; } fn part1(asteroids: &AstList) -> (&Coord, HashMap<i32, AstList>) { let result = asteroids.iter() .map(|ast| (ast, process_asterodis(&asteroids, &ast))) .into_iter() .max_by_key(|a| a.1.len()) .unwrap(); println!("{:?}", result.0); // .collect(); return result; } // fn part2(origo: &Coord, angles: &HashMap<String, AstList>) { // angles.keys().sort() // // for (angle, asteroids) in angles { // // println!("{:?}", angle); // // } // } fn main() { // let filename = "input.txt"; let filename = "test5.txt"; let asteroids = parse_program(filename); let station_best_data = part1(&asteroids); // part2(&station_best_data.0, &station_best_data.1); // println!("{:?}", program); }
extern crate proc_macro; use proc_macro::{TokenStream}; use syn::{ parse_macro_input, ItemImpl, ImplItem, Visibility, Signature, Path, FnArg, Pat, PatIdent, Ident, }; use syn::spanned::Spanned; use syn::parse::Error; use quote::{quote, ToTokens}; /// Make `pub` methods in the annotated `impl Trait for Type` block into /// inherited methods, which can be used without having to import the trait. /// /// ``` /// mod module { /// # use inherent_pub::inherent_pub; /// pub trait Foo { /// fn foo(self); /// fn bar(self); /// } /// /// pub struct Bar; /// /// #[inherent_pub] /// impl Foo for Bar { /// // `foo` becomes an inherent method. /// pub fn foo(self) {} /// // `bar` is not an inherent method (not `pub`) /// fn bar(self) {} /// } /// } /// /// fn main() { /// // We didn't `use foo:Foo`, but we can still use `Bar.foo()`: /// module::Bar.foo(); /// /// // This does not compile: /// // bar::Bar.bar(); /// /// { /// // We need to import the trait in order to use `Bar.bar()`: /// use module::Foo; /// module::Bar.bar(); /// } /// } /// ``` #[proc_macro_attribute] pub fn inherent_pub(_args: TokenStream, input: TokenStream) -> TokenStream { let input: ItemImpl = parse_macro_input!(input as ItemImpl); match inherent_pub_impl(input) { Ok(output) => { output }, Err(error) => { error.to_compile_error().into() } } } fn inherent_pub_impl(mut input: ItemImpl) -> Result<TokenStream, Error> { let (_, trait_, _) = input.trait_.clone().ok_or_else(|| { Error::new(input.span(), "expected `impl <Trait> for <Type>`") }).unwrap(); let methods = extract_pub_methods(&mut input.items); let mut result = TokenStream::new().into(); input.to_tokens(&mut result); let pub_impls = methods.into_iter().map(|(vis, sig)| { redirect_method(vis, sig, &trait_) }).collect::<Result<Vec<_>, Error>>()?; let inherent_impl = ItemImpl { attrs: Vec::new(), // attributes that work on the trait impl are not usually designed to work on the regular impl trait_: None, items: pub_impls, ..input }; inherent_impl.to_tokens(&mut result); Ok(result.into()) } fn extract_pub_methods(items: &mut Vec<ImplItem>) -> Vec<(Visibility, Signature)> { items.iter_mut().filter_map(|item| { if let ImplItem::Method(method) = item { let vis = method.vis.clone(); let sig = method.sig.clone(); method.vis = Visibility::Inherited; Some((vis, sig)) } else { None } }).collect() } fn redirect_method(vis: Visibility, mut sig: Signature, trait_: &Path) -> Result<ImplItem, Error> { let mut arg_count: usize = 0; let mut args = Vec::new(); for arg in sig.inputs.iter_mut() { match arg { FnArg::Receiver(arg) => { if arg.reference.is_none() { arg.mutability = None; } let ident = Ident::new("self", arg.span()); args.push(ident); }, FnArg::Typed(arg) => { match *arg.pat { Pat::Ident(ref mut pat_ident) if pat_ident.ident == "self" => { pat_ident.mutability = None; args.push(pat_ident.ident.clone()); }, _ => { arg_count += 1; let ident = Ident::new(&format!("arg{}", arg_count), arg.span()); arg.pat = Box::new(Pat::Ident(PatIdent { attrs: Vec::new(), by_ref: None, mutability: None, ident: ident.clone(), subpat: None, })); args.push(ident); }, } }, } } let await_ = sig.asyncness.map(|_| Some(quote!(.await))); let fn_name = &sig.ident; Ok(ImplItem::Verbatim(quote!( #[doc(hidden)] #[inline(always)] #vis #sig { <Self as #trait_>::#fn_name(#(#args),*) #await_ } ))) }
use std::{ convert::{TryFrom, TryInto}, fmt::Debug, ops::{Deref, DerefMut}, }; use crate::{ audio::file::AudioFiles, availability::Availabilities, content_rating::ContentRatings, image::Images, request::RequestResult, restriction::Restrictions, util::{impl_deref_wrapped, impl_try_from_repeated}, video::VideoFiles, Metadata, }; use librespot_core::{date::Date, Error, Session, SpotifyId}; use librespot_protocol as protocol; pub use protocol::metadata::episode::EpisodeType; #[derive(Debug, Clone)] pub struct Episode { pub id: SpotifyId, pub name: String, pub duration: i32, pub audio: AudioFiles, pub description: String, pub number: i32, pub publish_time: Date, pub covers: Images, pub language: String, pub is_explicit: bool, pub show_name: String, pub videos: VideoFiles, pub video_previews: VideoFiles, pub audio_previews: AudioFiles, pub restrictions: Restrictions, pub freeze_frames: Images, pub keywords: Vec<String>, pub allow_background_playback: bool, pub availability: Availabilities, pub external_url: String, pub episode_type: EpisodeType, pub has_music_and_talk: bool, pub content_rating: ContentRatings, pub is_audiobook_chapter: bool, } #[derive(Debug, Clone, Default)] pub struct Episodes(pub Vec<SpotifyId>); impl_deref_wrapped!(Episodes, Vec<SpotifyId>); #[async_trait] impl Metadata for Episode { type Message = protocol::metadata::Episode; async fn request(session: &Session, episode_id: &SpotifyId) -> RequestResult { session.spclient().get_episode_metadata(episode_id).await } fn parse(msg: &Self::Message, _: &SpotifyId) -> Result<Self, Error> { Self::try_from(msg) } } impl TryFrom<&<Self as Metadata>::Message> for Episode { type Error = librespot_core::Error; fn try_from(episode: &<Self as Metadata>::Message) -> Result<Self, Self::Error> { Ok(Self { id: episode.try_into()?, name: episode.name().to_owned(), duration: episode.duration().to_owned(), audio: episode.audio.as_slice().into(), description: episode.description().to_owned(), number: episode.number(), publish_time: episode.publish_time.get_or_default().try_into()?, covers: episode.cover_image.image.as_slice().into(), language: episode.language().to_owned(), is_explicit: episode.explicit().to_owned(), show_name: episode.show.name().to_owned(), videos: episode.video.as_slice().into(), video_previews: episode.video_preview.as_slice().into(), audio_previews: episode.audio_preview.as_slice().into(), restrictions: episode.restriction.as_slice().into(), freeze_frames: episode.freeze_frame.image.as_slice().into(), keywords: episode.keyword.to_vec(), allow_background_playback: episode.allow_background_playback(), availability: episode.availability.as_slice().try_into()?, external_url: episode.external_url().to_owned(), episode_type: episode.type_(), has_music_and_talk: episode.music_and_talk(), content_rating: episode.content_rating.as_slice().into(), is_audiobook_chapter: episode.is_audiobook_chapter(), }) } } impl_try_from_repeated!(<Episode as Metadata>::Message, Episodes);
use super::{DataClass, DataIdDefinition}; use ::ErrorKind; use ::std::marker::PhantomData; pub type DataIdSimpleType = f32; pub(crate) static DATAID_DEFINITION : DataIdDefinition<DataIdSimpleType, DataIdType> = DataIdDefinition { data_id: 28, class: DataClass::SensorAndInformationalData, read: true, write: false, check: Some(|simpletype| if simpletype >= -40f32 && simpletype <= 127f32 { Ok(()) } else { Err(ErrorKind::InvalidApplicationData.into()) } ), phantom_simple: PhantomData {}, phantom_complex: PhantomData {} }; dataidtypedef!(return_water_temp: f32);
use std::ops::{Add,Sub}; use std::convert::TryInto; pub type pLcpKar<T> = Vec<T>; impl <T> pLcp<T> for pLcpKar<T> where T:Copy + Add<Output = T> + Sub<Output = T> + PartialOrd + From<u8> + Into<usize> { fn compute(t: String, sa: Vec<T>) -> Result<pLcpKar<T>,Error>{ assert_eq!(t.len(), sa.len()); let n = t.len(); let text = t.as_bytes(); // provide the lexicographical rank for each suffix let mut rank = vec![0;n]; for (r, p) in sa.iter().enumerate() { rank[(*p).into()] = r; } let mut lcp : Vec<T> = vec![T::from(0);n]; let mut l = 0; for (p, &r) in rank.iter().enumerate().take(n - 1) { let pred = sa[r - 1].into(); while pred + l < n && p + l < n && text[p + l] == text[pred + l] { l += 1; } lcp[r] = T::from(l.try_into().unwrap()); l = if l > 0 { l - 1 } else { 0 }; } Ok(lcp) } }
use std::io; fn main() { println!("Welcome to the temperature convertor!"); let temperature_unit = loop { println!("Input \"F\" to convert from Fahrenheit or \"C\" to convert from Celsius."); let mut temperature_unit = String::new(); io::stdin() .read_line(&mut temperature_unit) .expect("Failed to read line"); let temperature_unit: String = temperature_unit.trim().to_lowercase(); if temperature_unit == "f" { println!("Fahrenheit"); break temperature_unit; } else if temperature_unit == "c" { println!("Celsius"); break temperature_unit; } else { println!("Incorrect selection, must be \"C\" or \"F\""); } }; let temperature: i32 = loop{ let mut temperature = String::new(); println!("Enter a number to convert"); io::stdin() .read_line(&mut temperature) .expect("Failed to read line"); let temperature: i32 = match temperature.trim().parse() { Ok(num) => num, Err(_) => continue, }; break temperature; }; if temperature_unit == "f" { let converted = (temperature as f64 -32.0) * 5.0 /9.0 ; println!("Converted temperature is {:.4} degrees celsius.", converted); } else { let converted = temperature as f64 * 9.0 / 5.0 + 32.0; println!("Converted temperature is {:.4} degrees fahrenheit.", converted); }; }
use nom::*; use nom::types::CompleteStr; use ::ast::{StringlyTyped, StringlyTypedInner}; fn is_quote(c: char) -> bool { match c as char { '\'' | '"' => true, _ => false } } named!{stringly_typed <CompleteStr, (StringlyTyped<&str>)>, alt!(double_quote | single_quote)} named!{double_quote <CompleteStr, (StringlyTyped<'_, &'_ str>)>, do_parse!( char!('"') >> quasi: opt!(quasi_quote) >> inner: double_quote_inner >> char!('"') >> component: take_till1!(is_quote) >> ( StringlyTyped { inner, component: &component, quasi } ) )} fn double_quote_inner<'s>(input: CompleteStr<'s>) -> Result<(CompleteStr<'s>, StringlyTypedInner<'s, &'s str>), ::nom::Err<CompleteStr<'s>>> { alt!(input, many1!(single_quote) => { |i| StringlyTypedInner::Inners(i) } | take_until!("\"") => { |s: CompleteStr<'s>| StringlyTypedInner::Str(&s) } ) } named!{single_quote <CompleteStr, (StringlyTyped<&'_ str>)>, do_parse!( char!('\'') >> quasi: opt!(quasi_quote) >> inner: single_quote_inner >> char!('\'') >> component: take_till1!(is_quote) >> ( StringlyTyped { inner, component: &component, quasi } ) )} fn single_quote_inner<'s>(input: CompleteStr<'s>) -> Result<(CompleteStr<'s>, StringlyTypedInner<'s, &'s str>), ::nom::Err<CompleteStr<'s>>> { alt!(input, many1!(double_quote) => { |i| StringlyTypedInner::Inners(i) } | take_until!("'") => { |s: CompleteStr<'s>| StringlyTypedInner::Str(&s) } ) } fn quasi_quote<'s>(input: CompleteStr<'s>) -> Result<(CompleteStr<'s>, StringlyTypedInner<'s, &'s str>), ::nom::Err<CompleteStr<'s>>> { delimited!(input, tag!("`"), alt!( many1!(double_quote) => { |i| StringlyTypedInner::Inners(i) } | many1!(single_quote) => { |i| StringlyTypedInner::Inners(i) } | take_until!("`") => { |s: CompleteStr<'s>| StringlyTypedInner::Str(&s) } ), tag!("`") ) } /// Parse a string into a StringlyTyped tree. /// /// # Panics /// /// If parsing fails because the string is not a legal Stringly Typed program, then this function panics. pub(crate) fn parse<'s>(input: &'s str) -> StringlyTyped<'s, &'s str> { stringly_typed(CompleteStr(input)).unwrap().1 } #[cfg(test)] mod test { use super::*; type StStr<'s> = StringlyTyped<'s, &'s str>; #[test] fn parse_double_quote() { assert_eq!(parse("\"\"xyz"), StStr { inner: StringlyTypedInner::Str(""), component: "xyz", quasi: None }); assert_eq!(parse("\"abc\"xyz"), StStr { inner: StringlyTypedInner::Str("abc"), component: "xyz", quasi: None }); assert_eq!(parse("\"abc\"xyz\"def\"uvw"), StStr { inner: StringlyTypedInner::Str("abc"), component: "xyz", quasi: None }); } #[test] fn parse_single_quote() { assert_eq!(parse("''xyz"), StStr { inner: StringlyTypedInner::Str(""), component: "xyz", quasi: None }); } #[test] fn parse_quasi_quote() { assert_eq!(parse("'`abc`def'xyz"), StStr { inner: StringlyTypedInner::Str("def"), component: "xyz", quasi: Some(StringlyTypedInner::Str("abc")) }); } }
// use chrono::Local; // extern crate serde_json; use serde::{Deserialize, Serialize}; use serde_json::Result; #[derive(Serialize, Deserialize, Debug)] pub struct Task { name: String, created: String, description: String, log_time: i64, } use thiserror::Error; #[derive(Error, Debug)] pub enum TaskError { #[error("Description must be a string of 256 characters")] DescriptionValError(String), #[error("Unknown error related to tasks")] Unknown, } pub fn create_task( tnam: String, tdesc: String, tcreated: chrono::Date<chrono::Local>, ) -> Result<Task> { // serialization let ntask = Task { name: tnam, description: tdesc, created: tcreated.to_string().to_owned(), log_time: 0, }; Ok(ntask) // // current_date.format("task_%Y%m%d").to_string() // serde_json::to_string(&ntask)?; // Ok(tnam) } // #[cfg(test)] // mod tests { // use super::*; // // use chrono::Local; // // use chrono::TimeZone; // #[test] // fn test_create_task_description_length() { // Task { // name: "t1", // description: "", // } // } // }
use std::ops::Mul; pub const BLACK: Color = Color::new(0, 0, 0); pub const WHITE: Color = Color::new(255, 255, 255); pub const RED: Color = Color::new(255, 0, 0); pub const GREEN: Color = Color::new(0, 255, 0); pub const BLUE: Color = Color::new(0, 0, 255); #[derive(Copy, Clone)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, } impl Color { pub const fn new(red: u8, green: u8, blue: u8) -> Self { Color { red, green, blue } } } impl Mul<f32> for Color { type Output = Self; fn mul(self, v: f32) -> Self::Output { Color::new( (self.red as f32 * v) as u8, (self.green as f32 * v) as u8, (self.blue as f32 * v) as u8, ) } }
use std::sync::Arc; use chrono::{DateTime, Utc}; use common::result::Result; use crate::domain::interaction::{InteractionRepository, Like, Reading, Review, View}; use crate::domain::publication::{PublicationId, Statistics}; use crate::domain::reader::ReaderId; pub struct StatisticsService { interaction_repo: Arc<dyn InteractionRepository>, } impl StatisticsService { pub fn new(interaction_repo: Arc<dyn InteractionRepository>) -> Self { StatisticsService { interaction_repo } } pub fn from_interactions( &self, views: &[View], readings: &[Reading], likes: &[Like], reviews: &[Review], ) -> Result<Statistics> { let unique_views = views.iter().fold( 0u32, |acc, view| { if view.is_unique() { acc + 1 } else { acc } }, ); let stars = reviews .iter() .fold(0u32, |acc, review| acc + review.stars().value() as u32); let stars = stars as f32 / reviews.len() as f32; Ok(Statistics::new( views.len() as u32, unique_views, readings.len() as u32, likes.len() as u32, reviews.len() as u32, stars, )?) } pub async fn get_history( &self, reader_id: Option<&ReaderId>, publication_id: Option<&PublicationId>, from: Option<&DateTime<Utc>>, to: Option<&DateTime<Utc>>, ) -> Result<Statistics> { let views = self .interaction_repo .find_views( reader_id.clone(), publication_id.clone(), from.clone(), to.clone(), ) .await?; let readings = self .interaction_repo .find_readings( reader_id.clone(), publication_id.clone(), from.clone(), to.clone(), ) .await?; let likes = self .interaction_repo .find_likes( reader_id.clone(), publication_id.clone(), from.clone(), to.clone(), ) .await?; let reviews = self .interaction_repo .find_reviews( reader_id.clone(), publication_id.clone(), from.clone(), to.clone(), ) .await?; self.from_interactions(&views, &readings, &likes, &reviews) } }
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate serde_yaml; extern crate toml; /// # Deserialization of the JSON in the readable TOML and YAML formats /// /// The module deserializes the json file into the `Request` object. /// The `Request` object can be printed in YAML and TOML [formats]:https://serde.rs/index.html#data-formats /// /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use json::*; /// /// use request::*; /// /// if let Ok(request) = deserialized_to_request("request.json") { /// /// println!("Format YAML:"); /// print_yaml(&request); /// /// } /// ``` mod request { use super::*; use std::error; use std::fmt; use std::io; use std::result; use serde::ser::{Serialize, SerializeStruct, Serializer}; use std::fs::File; use std::path::Path; /// The structures representing the object `Request`. /// The reserved name `type` will be deserialized in the field `req_type`. #[derive(Deserialize)] pub struct Request { #[serde(rename(deserialize = "type"))] pub req_type: String, pub stream: Stream, pub gifts: Vec<Block>, } #[derive(Serialize, Deserialize)] pub struct Stream { pub model_id: i32, pub is_private: bool, pub erotic: i32, pub places: i32, pub shard_url: String, pub public_tariff: PublicTariff, pub private_tariff: PrivateTariff, } #[derive(Serialize, Deserialize)] pub struct PublicTariff { #[serde(flatten)] pub block: Block, pub duration: i32, } #[derive(Serialize, Deserialize)] pub struct PrivateTariff { #[serde(flatten)] pub block: Block, pub duration: i32, } /// Used for repetitive data structures. #[derive(Serialize, Deserialize)] pub struct Block { pub id: i32, pub model_price: i32, pub client_price: i32, pub description: String, } /// Alias for result::Result with FormatError , /// combining types of format errors. type Result<T> = result::Result<T, FormatError>; /// The `FormatError` contains all types of errors necessary /// for the operation of the module with formats. #[derive(Debug)] pub enum FormatError { Io(io::Error), Json(serde_json::Error), Yaml(serde_yaml::Error), Toml(toml::ser::Error), } /// Implementation trait std::fmt::Display for FormatError impl fmt::Display for FormatError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FormatError::Io(ref err) => write!(f, "IO error: {}", err), FormatError::Json(ref err) => write!(f, "JSON error: {};", err), FormatError::Yaml(ref err) => write!(f, "YAML error: {}", err), FormatError::Toml(ref err) => write!(f, "TOML error: {}", err), } } } /// Implementation trait std::error::Error for FormatError impl error::Error for FormatError { fn description(&self) -> &str { match *self { FormatError::Io(ref err) => err.description(), FormatError::Json(ref err) => err.description(), FormatError::Yaml(ref err) => err.description(), FormatError::Toml(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { FormatError::Io(ref err) => Some(err), FormatError::Json(ref err) => Some(err), FormatError::Yaml(ref err) => Some(err), FormatError::Toml(ref err) => Some(err), } } } /// Type conversion io::Error in FormatError. impl From<io::Error> for FormatError { fn from(err: io::Error) -> FormatError { FormatError::Io(err) } } /// Type conversion serde_json::Error in FormatError. impl From<serde_json::Error> for FormatError { fn from(err: serde_json::Error) -> FormatError { FormatError::Json(err) } } /// Type conversion serde_yaml::Error in FormatError. impl From<serde_yaml::Error> for FormatError { fn from(err: serde_yaml::Error) -> FormatError { FormatError::Yaml(err) } } /// Type conversion toml::ser::Error in FormatError. impl From<toml::ser::Error> for FormatError { fn from(err: toml::ser::Error) -> FormatError { FormatError::Toml(err) } } /// Implementation trait Serialize /// to replace the reserved name `req_type` with` type` impl Serialize for Request { fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("Request", 3)?; state.serialize_field("type", &self.req_type)?; state.serialize_field("stream", &self.stream)?; state.serialize_field("gifts", &self.gifts)?; state.end() } } /// The function `deserialized_to_request` deserializes the file json /// into the object of the `Request` /// Prints a `Request` object in the TOML format. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use json::*; /// /// use request::*; /// /// let request:Request = deserialized_to_request("request.json"); /// ``` pub fn deserialized_to_request<P: AsRef<Path>>(path: P) -> Result<Request> { let file = File::open(path)?; let deserialized: Request = serde_json::from_reader(file)?; Ok(deserialized) } /// Prints a `Request` object in the YAML format. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use json::*; /// /// use request::*; /// /// if let Ok(request) = deserialized_to_request("request.json") { /// /// println!("Format YAML:"); /// print_yaml(&request); /// /// } /// ``` pub fn print_yaml(request: &Request) -> Result<()> { let s: String = serde_yaml::to_string(&request)?; println!("{}", s); Ok(()) } /// Prints a `Request` object in the TOML format. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// use json::*; /// /// use request::*; /// /// if let Ok(request) = deserialized_to_request("request.json") { /// /// println!("Format TOML:"); /// print_toml(&request); /// /// } /// ``` pub fn print_toml(request: &Request) -> Result<()> { let s: String = toml::to_string(&request)?; println!("{}", s); Ok(()) } #[cfg(test)] mod test { #[test] fn test_yaml() { use request::*; if let Ok(request) = deserialized_to_request("request.json") { assert!(print_yaml(&request).is_ok()); } else { assert!(false); } } #[test] fn test_toml() { use request::*; if let Ok(request) = deserialized_to_request("request.json") { assert!(print_toml(&request).is_ok()); } else { assert!(false); } } } } fn main() { use request::*; if let Ok(request) = deserialized_to_request("request.json") { println!("Format YAML:"); print_yaml(&request); println!("Format TOML:"); print_toml(&request); } }
use std::num::sqrt; use std::ptr::null; use pancurses::Window; enum NodeDirection { PathRight, PathLeft, PathDown, PathUp, } pub struct Node { x: i32, y: i32, hcost: i32, gcost: i32, fcost: i32, flag: Option<NodeDirection>, parent: Arc<Node>, } impl Node { pub fn new(x: i32, y: i32) { Node { x: x, y: y, hcost: 0, gcost: 0, fcost: 0, flag: None, parent: ptr::null(), } } pub fn draw(&self, win: &Window) {} pub fn get_x(&self) { &self.x } pub fn get_y(&self) { &self.y } pub fn set_parent() pub fn calculate_costs(&mut self, end: &Node) { let dx_end: i32 = end.get_x() - self.x; let dy_end: i32 = end.get_y() - self.y; self.hcost = sqrt(dx_end*dx_end + dy_end*dy_end); // TODO: calculate gcost based on parent self.gcost = self.fcost = self.hcost + self.gcost; } pub fn set_flag(&mut self, next_node: &Node) { let dx: i32 = self.x - next_node.get_x(); let dy: i32 = self.y - next_node.get_y(); if dx > 0 { self.flag = NodeDirection::PathLeft; } else if dx < 0 { self.flag = NodeDirection::PathRight; } else if dy > 0 { self.flag = NodeDirection::PathUp; } else if dy < 0 { self.flag = NodeDirection::PathDown; } } fn get_char_representation(&self) -> &str { match self.flag.unwrap() { NodeDirection::PathRight => ">", NodeDirection::PathLeft => "<", NodeDirection::PathUp => "^", NodeDirection::PathDown => "v", _ => "?", } } }
//! The top-level documentation resides on the [project README](https://github.com/tomhoule/graphql-client) at the moment. //! //! The main interface to this library is the custom derive that generates modules from a GraphQL query and schema. See the docs for the [`GraphQLQuery`] trait for a full example. #![deny(warnings)] #![deny(missing_docs)] extern crate serde; #[macro_use] extern crate serde_derive; pub extern crate graphql_query_derive; #[cfg_attr(test, macro_use)] extern crate serde_json; #[doc(hidden)] pub use graphql_query_derive::*; use std::collections::HashMap; /// A convenience trait that can be used to build a GraphQL request body. /// /// This will be implemented for you by codegen in the normal case. It is implemented on the struct you place the derive on. /// /// Example: /// /// ``` /// extern crate failure; /// #[macro_use] /// extern crate graphql_client; /// #[macro_use] /// extern crate serde_derive; /// #[macro_use] /// extern crate serde_json; /// extern crate serde; /// /// #[derive(GraphQLQuery)] /// #[graphql( /// query_path = "graphql_query_derive/src/tests/star_wars_query.graphql", /// schema_path = "graphql_query_derive/src/tests/star_wars_schema.graphql" /// )] /// struct StarWarsQuery; /// /// fn main() -> Result<(), failure::Error> { /// use graphql_client::GraphQLQuery; /// /// let variables = star_wars_query::Variables { /// episode_for_hero: star_wars_query::Episode::NEWHOPE, /// }; /// /// let expected_body = json!({ /// "query": star_wars_query::QUERY, /// "variables": { /// "episodeForHero": "NEWHOPE" /// }, /// }); /// /// let actual_body = serde_json::to_value( /// StarWarsQuery::build_query(variables) /// )?; /// /// assert_eq!(actual_body, expected_body); /// /// Ok(()) /// } /// ``` pub trait GraphQLQuery<'de> { /// The shape of the variables expected by the query. This should be a generated struct most of the time. type Variables: serde::Serialize; /// The top-level shape of the response data (the `data` field in the GraphQL response). In practice this should be generated, since it is hard to write by hand without error. type ResponseData: serde::Deserialize<'de>; /// Produce a GraphQL query struct that can be JSON serialized and sent to a GraphQL API. fn build_query(variables: Self::Variables) -> GraphQLQueryBody<Self::Variables>; } /// The form in which queries are sent over HTTP in most implementations. This will be built using the [`GraphQLQuery`] trait normally. #[derive(Debug, Serialize, Deserialize)] pub struct GraphQLQueryBody<Variables> where Variables: serde::Serialize, { /// The values for the variables. They must match those declared in the queries. This should be the `Variables` struct from the generated module corresponding to the query. pub variables: Variables, /// The GraphQL query, as a string. pub query: &'static str, } /// Represents a location inside a query string. Used in errors. See [`GraphQLError`]. #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct Location { /// The line number in the query string where the error originated (starting from 1). pub line: i32, /// The column number in the query string where the error originated (starting from 1). pub column: i32, } /// Part of a path in a query. It can be an object key or an array index. See [`GraphQLError`]. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum PathFragment { /// A key inside an object Key(String), /// An index inside an array Index(i32), } /// An element in the top-level `errors` array of a response body. /// /// This tries to be as close to the spec as possible. /// /// [Spec](https://github.com/facebook/graphql/blob/master/spec/Section%207%20--%20Response.md) /// /// /// ``` /// # extern crate failure; /// # #[macro_use] /// # extern crate serde_json; /// # extern crate graphql_client; /// # #[macro_use] /// # extern crate serde_derive; /// # /// # #[derive(Debug, Deserialize, PartialEq)] /// # struct ResponseData { /// # something: i32 /// # } /// # /// # fn main() -> Result<(), failure::Error> { /// use graphql_client::*; /// /// let body: GraphQLResponse<ResponseData> = serde_json::from_value(json!({ /// "data": null, /// "errors": [ /// { /// "message": "The server crashed. Sorry.", /// "locations": [{ "line": 1, "column": 1 }] /// }, /// { /// "message": "Seismic activity detected", /// "path": ["undeground", 20] /// }, /// ], /// }))?; /// /// let expected: GraphQLResponse<ResponseData> = GraphQLResponse { /// data: None, /// errors: Some(vec![ /// GraphQLError { /// message: "The server crashed. Sorry.".to_owned(), /// locations: Some(vec![ /// Location { /// line: 1, /// column: 1, /// } /// ]), /// path: None, /// extensions: None, /// }, /// GraphQLError { /// message: "Seismic activity detected".to_owned(), /// locations: None, /// path: Some(vec![ /// PathFragment::Key("undeground".into()), /// PathFragment::Index(20), /// ]), /// extensions: None, /// }, /// ]), /// }; /// /// assert_eq!(body, expected); /// /// # Ok(()) /// # } /// ``` #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct GraphQLError { /// The human-readable error message. This is the only required field. pub message: String, /// Which locations in the query the error applies to. pub locations: Option<Vec<Location>>, /// Which path in the query the error applies to, e.g. `["users", 0, "email"]`. pub path: Option<Vec<PathFragment>>, /// Additional errors. Their exact format is defined by the server. pub extensions: Option<HashMap<String, serde_json::Value>>, } /// The generic shape taken by the responses of GraphQL APIs. /// /// This will generally be used with the `ResponseData` struct from a derived module. /// /// [Spec](https://github.com/facebook/graphql/blob/master/spec/Section%207%20--%20Response.md) /// /// ``` /// # extern crate failure; /// # #[macro_use] /// # extern crate serde_json; /// # extern crate graphql_client; /// # #[macro_use] /// # extern crate serde_derive; /// # /// # #[derive(Debug, Deserialize, PartialEq)] /// # struct User { /// # id: i32, /// # } /// # /// # #[derive(Debug, Deserialize, PartialEq)] /// # struct Dog { /// # name: String /// # } /// # /// # #[derive(Debug, Deserialize, PartialEq)] /// # struct ResponseData { /// # users: Vec<User>, /// # dogs: Vec<Dog>, /// # } /// # /// # fn main() -> Result<(), failure::Error> { /// use graphql_client::GraphQLResponse; /// /// let body: GraphQLResponse<ResponseData> = serde_json::from_value(json!({ /// "data": { /// "users": [{"id": 13}], /// "dogs": [{"name": "Strelka"}], /// }, /// "errors": [], /// }))?; /// /// let expected: GraphQLResponse<ResponseData> = GraphQLResponse { /// data: Some(ResponseData { /// users: vec![User { id: 13 }], /// dogs: vec![Dog { name: "Strelka".to_owned() }], /// }), /// errors: Some(vec![]), /// }; /// /// assert_eq!(body, expected); /// /// # Ok(()) /// # } /// ``` #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct GraphQLResponse<Data> { /// The absent, partial or complete response data. pub data: Option<Data>, /// The top-level errors returned by the server. pub errors: Option<Vec<GraphQLError>>, } #[cfg(test)] mod tests { use super::*; #[test] fn graphql_error_works_with_just_message() { let err = json!({ "message": "I accidentally your whole query" }); let deserialized_error: GraphQLError = serde_json::from_value(err).unwrap(); assert_eq!( deserialized_error, GraphQLError { message: "I accidentally your whole query".to_string(), locations: None, path: None, extensions: None, } ) } #[test] fn full_graphql_error_deserialization() { let err = json!({ "message": "I accidentally your whole query", "locations": [{ "line": 3, "column": 13}, {"line": 56, "column": 1}], "path": ["home", "alone", 3, "rating"] }); let deserialized_error: GraphQLError = serde_json::from_value(err).unwrap(); assert_eq!( deserialized_error, GraphQLError { message: "I accidentally your whole query".to_string(), locations: Some(vec![ Location { line: 3, column: 13, }, Location { line: 56, column: 1, }, ]), path: Some(vec![ PathFragment::Key("home".to_owned()), PathFragment::Key("alone".to_owned()), PathFragment::Index(3), PathFragment::Key("rating".to_owned()), ]), extensions: None, } ) } #[test] fn full_graphql_error_with_extensions_deserialization() { let err = json!({ "message": "I accidentally your whole query", "locations": [{ "line": 3, "column": 13}, {"line": 56, "column": 1}], "path": ["home", "alone", 3, "rating"], "extensions": { "code": "CAN_NOT_FETCH_BY_ID", "timestamp": "Fri Feb 9 14:33:09 UTC 2018" } }); let deserialized_error: GraphQLError = serde_json::from_value(err).unwrap(); let mut expected_extensions = HashMap::new(); expected_extensions.insert("code".to_owned(), json!("CAN_NOT_FETCH_BY_ID")); expected_extensions.insert("timestamp".to_owned(), json!("Fri Feb 9 14:33:09 UTC 2018")); let expected_extensions = Some(expected_extensions); assert_eq!( deserialized_error, GraphQLError { message: "I accidentally your whole query".to_string(), locations: Some(vec![ Location { line: 3, column: 13, }, Location { line: 56, column: 1, }, ]), path: Some(vec![ PathFragment::Key("home".to_owned()), PathFragment::Key("alone".to_owned()), PathFragment::Index(3), PathFragment::Key("rating".to_owned()), ]), extensions: expected_extensions, } ) } }
#[doc = "Logging"]; export console_on, console_off; #[nolink] native mod rustrt { fn rust_log_console_on(); fn rust_log_console_off(); } #[doc = "Turns on logging to stdout globally"] fn console_on() { rustrt::rust_log_console_on(); } #[doc( brief = "Turns off logging to stdout globally", desc = "Turns off the console unless the user has overridden the \ runtime environment's logging spec, e.g. by setting \ the RUST_LOG environment variable" )] fn console_off() { rustrt::rust_log_console_off(); }
extern crate pest; #[macro_use] extern crate pest_derive; #[macro_use] extern crate lazy_static; extern crate regex; pub mod mm_parser; extern crate mockall; pub mod io { use std::fs; pub struct FileIO { } use mockall::automock; #[automock] pub trait IO { fn slurp(&self, filename: &str) -> String; } impl IO for FileIO { fn slurp(&self, filename: &str) -> String { return fs::read_to_string(filename) .expect("Could not read file"); } } }
use diesel::Queryable; use uuid::Uuid; #[derive(Debug, PartialEq, Eq)] pub struct UserId(Uuid); impl Into<Uuid> for UserId { fn into(self) -> Uuid { self.0 } } impl Queryable<diesel::sql_types::Uuid, diesel::pg::Pg> for UserId { type Row = Uuid; fn build(row: Self::Row) -> Self { UserId(row) } } #[derive(Debug, PartialEq, Eq)] pub struct PostId(Uuid); impl Into<Uuid> for PostId { fn into(self) -> Uuid { self.0 } } impl Queryable<diesel::sql_types::Uuid, diesel::pg::Pg> for PostId { type Row = Uuid; fn build(row: Self::Row) -> Self { PostId(row) } }
#[test] fn wrap_nodes_with_content_sizing_overflowing_margin() { let layout = stretch::node::Node::new( stretch::style::Style { flex_direction: stretch::style::FlexDirection::Column, size: stretch::geometry::Size { width: stretch::style::Dimension::Points(500f32), height: stretch::style::Dimension::Points(500f32), ..Default::default() }, ..Default::default() }, vec![&stretch::node::Node::new( stretch::style::Style { flex_wrap: stretch::style::FlexWrap::Wrap, size: stretch::geometry::Size { width: stretch::style::Dimension::Points(85f32), ..Default::default() }, ..Default::default() }, vec![ &stretch::node::Node::new( stretch::style::Style { flex_direction: stretch::style::FlexDirection::Column, ..Default::default() }, vec![&stretch::node::Node::new( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(40f32), height: stretch::style::Dimension::Points(40f32), ..Default::default() }, ..Default::default() }, vec![], )], ), &stretch::node::Node::new( stretch::style::Style { flex_direction: stretch::style::FlexDirection::Column, margin: stretch::geometry::Rect { end: stretch::style::Dimension::Points(10f32), ..Default::default() }, ..Default::default() }, vec![&stretch::node::Node::new( stretch::style::Style { size: stretch::geometry::Size { width: stretch::style::Dimension::Points(40f32), height: stretch::style::Dimension::Points(40f32), ..Default::default() }, ..Default::default() }, vec![], )], ), ], )], ) .compute_layout(stretch::geometry::Size::undefined()) .unwrap(); assert_eq!(layout.size.width, 500f32); assert_eq!(layout.size.height, 500f32); assert_eq!(layout.location.x, 0f32); assert_eq!(layout.location.y, 0f32); assert_eq!(layout.children[0usize].size.width, 85f32); assert_eq!(layout.children[0usize].size.height, 80f32); assert_eq!(layout.children[0usize].location.x, 0f32); assert_eq!(layout.children[0usize].location.y, 0f32); assert_eq!(layout.children[0usize].children[0usize].size.width, 40f32); assert_eq!(layout.children[0usize].children[0usize].size.height, 40f32); assert_eq!(layout.children[0usize].children[0usize].location.x, 0f32); assert_eq!(layout.children[0usize].children[0usize].location.y, 0f32); assert_eq!(layout.children[0usize].children[0usize].children[0usize].size.width, 40f32); assert_eq!(layout.children[0usize].children[0usize].children[0usize].size.height, 40f32); assert_eq!(layout.children[0usize].children[0usize].children[0usize].location.x, 0f32); assert_eq!(layout.children[0usize].children[0usize].children[0usize].location.y, 0f32); assert_eq!(layout.children[0usize].children[1usize].size.width, 40f32); assert_eq!(layout.children[0usize].children[1usize].size.height, 40f32); assert_eq!(layout.children[0usize].children[1usize].location.x, 0f32); assert_eq!(layout.children[0usize].children[1usize].location.y, 40f32); assert_eq!(layout.children[0usize].children[1usize].children[0usize].size.width, 40f32); assert_eq!(layout.children[0usize].children[1usize].children[0usize].size.height, 40f32); assert_eq!(layout.children[0usize].children[1usize].children[0usize].location.x, 0f32); assert_eq!(layout.children[0usize].children[1usize].children[0usize].location.y, 0f32); }
use log::info; use rocket::{http::Status, post, State}; use rocket_contrib::{ json, json::{Json, JsonValue}, }; use rustflake::Snowflake; use serde::{Deserialize, Serialize}; use std::process::Command; use std::sync::{mpsc, mpsc::RecvTimeoutError}; use std::thread; use std::time::Duration; use crate::docker::Docker; use crate::Config; #[derive(Serialize, Deserialize)] pub struct EvalInput { language: String, code: String, } #[post("/eval", format = "json", data = "<eval>")] pub fn index(eval: Json<EvalInput>, config: State<Config>) -> Result<JsonValue, Status> { if !config.languages.contains(&eval.language) { return Err(Status::NotFound); } let snowflake = Snowflake::default().generate(); info!( "Creating unique eval folder in container: myrias_{}", eval.language ); Docker::exec(&[ "exec", &format!("myrias_{}", eval.language), "mkdir", &format!("eval/{}", &snowflake), ]); info!( "Created unique eval folder in container: myrias_{}", eval.language ); info!( "Chmod unique eval directory to 711 in container: myrias_{}", eval.language ); Docker::exec(&[ "exec", &format!("myrias_{}", eval.language), "chmod", "777", &format!("eval/{}", &snowflake), ]); info!( "Chmod' unique eval directory in container: myrias_{}", eval.language ); info!("Eval in container: myrias_{}", eval.language); let e = eval.language.clone(); let (sender, recv) = mpsc::channel(); thread::spawn(move || { if let Ok(()) = sender.send( Command::new("docker") .args(&[ "exec", "-u1001:1001", &format!("-w/tmp/eval/{}", &snowflake), &format!("myrias_{}", eval.language), "/bin/sh", "/var/run/run.sh", &eval.code, ]) .output() .unwrap(), ) {} }); let output = match recv.recv_timeout(Duration::from_secs(15)) { Ok(res) => res, Err(RecvTimeoutError::Timeout) => { info!("Eval timed out in container: myrias_{}", e); info!("Killing container: myrias_{}", e); Docker::exec(&["kill", &format!("myrias_{}", e)]); info!("Killed container: myrias_{}", e); info!("Restarting container: myrias_{}", e); Docker::start_container(&e); info!("Restarted container: myrias_{}", e); return Err(Status::GatewayTimeout); } Err(RecvTimeoutError::Disconnected) => { return Err(Status::InternalServerError); } }; info!("Finished eval in container: myrias_{}", e); let res = if output.stderr.is_empty() { String::from_utf8_lossy(&output.stdout) } else { String::from_utf8_lossy(&output.stderr) }; info!("Removing unique eval folder in container: myrias_{}", e); Docker::exec(&[ "exec", &format!("myrias_{}", e), "rm", "-rf", &format!("eval/{}", &snowflake), ]); info!("Removed unique eval folder in container: myrias_{}", e); Ok(json!({ "result": res.to_string() })) }
use std::convert::TryInto; use std::env; use std::num::Wrapping; const REPLACEMENT_TABLE: [[u8; 16]; 8] = [ [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], [7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3], [6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2], [4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14], [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12], [1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12], ]; const KEYS: [u32; 8] = [ 0xE2C1_04F9, 0xE41D_7CDE, 0x7FE5_E857, 0x0602_65B4, 0x281C_CC85, 0x2E2C_929A, 0x4746_4503, 0xE00_CE510, ]; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { let plain_text: Vec<u8> = vec![0x04, 0x3B, 0x04, 0x21, 0x04, 0x32, 0x04, 0x30]; println!( "Before one step: {}\n", plain_text .iter() .cloned() .fold("".to_string(), |b, y| b + &format!("{:02X} ", y)) ); let encoded_text = main_step(plain_text, KEYS[0]); println!( "After one step : {}\n", encoded_text .iter() .cloned() .fold("".to_string(), |b, y| b + &format!("{:02X} ", y)) ); } else { let mut t = args[1].clone(); // "They call him... Баба Яга" t += &" ".repeat((8 - t.len() % 8) % 8); let text_bytes = t.bytes().collect::<Vec<_>>(); let plain_text = text_bytes.chunks(8).collect::<Vec<_>>(); println!( "Plain text : {}\n", plain_text.iter().cloned().fold("".to_string(), |a, x| a + "[" + &x.iter() .fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23] + "]") ); let encoded_text = plain_text .iter() .map(|c| encode(c.to_vec())) .collect::<Vec<_>>(); println!( "Encoded text: {}\n", encoded_text.iter().cloned().fold("".to_string(), |a, x| a + "[" + &x.into_iter() .fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23] + "]") ); let decoded_text = encoded_text .iter() .map(|c| decode(c.to_vec())) .collect::<Vec<_>>(); println!( "Decoded text: {}\n", decoded_text.iter().cloned().fold("".to_string(), |a, x| a + "[" + &x.into_iter() .fold("".to_string(), |b, y| b + &format!("{:02X} ", y))[..23] + "]") ); let recovered_text = String::from_utf8(decoded_text.iter().cloned().flatten().collect::<Vec<_>>()).unwrap(); println!("Recovered text: {}\n", recovered_text); } } fn encode(text_block: Vec<u8>) -> Vec<u8> { let mut step = text_block; for i in 0..24 { step = main_step(step, KEYS[i % 8]); } for i in (0..8).rev() { step = main_step(step, KEYS[i]); } step } fn decode(text_block: Vec<u8>) -> Vec<u8> { let mut step = text_block[4..].to_vec(); let mut temp = text_block[..4].to_vec(); step.append(&mut temp); for key in &KEYS { step = main_step(step, *key); } for i in (0..24).rev() { step = main_step(step, KEYS[i % 8]); } let mut ans = step[4..].to_vec(); let mut temp = step[..4].to_vec(); ans.append(&mut temp); ans } fn main_step(text_block: Vec<u8>, key_element: u32) -> Vec<u8> { let mut n = text_block; let mut s = (Wrapping( u32::from(n[0]) << 24 | u32::from(n[1]) << 16 | u32::from(n[2]) << 8 | u32::from(n[3]), ) + Wrapping(key_element)) .0; let mut new_s: u32 = 0; for mid in 0..4 { let cell = (s >> (mid << 3)) & 0xFF; new_s += (u32::from(REPLACEMENT_TABLE[(mid * 2) as usize][(cell & 0x0f) as usize]) + (u32::from(REPLACEMENT_TABLE[(mid * 2 + 1) as usize][(cell >> 4) as usize]) << 4)) << (mid << 3); } s = ((new_s << 11) + (new_s >> 21)) ^ (u32::from(n[4]) << 24 | u32::from(n[5]) << 16 | u32::from(n[6]) << 8 | u32::from(n[7])); n[4] = n[0]; n[5] = n[1]; n[6] = n[2]; n[7] = n[3]; n[0] = (s >> 24).try_into().unwrap(); n[1] = ((s >> 16) & 0xFF).try_into().unwrap(); n[2] = ((s >> 8) & 0xFF).try_into().unwrap(); n[3] = (s & 0xFF).try_into().unwrap(); n }
use crate::tentacle::LogLine; use futures::Async::*; use futures::{Poll, Stream}; use log::*; use std::fmt; use std::fmt::Display; use std::vec::Vec; #[derive(Debug)] pub enum LogStreamError { DefaultError(String), } impl Display for LogStreamError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Failed stream.") } } pub type LogStream = Box<Stream<Item = LogLine, Error = LogStreamError>>; #[derive(PartialEq)] enum SourceState { NeedsPoll, Delivered, Finished, Failed, } #[derive(Debug)] struct BufferEntry { log_line: LogLine, source_idx: usize, } pub struct LogMerge { running_sources: usize, sources: Vec<LogStream>, source_state: Vec<SourceState>, buffer: Vec<BufferEntry>, current_timestamp: i64, } impl LogMerge { pub fn new(sources: Vec<LogStream>) -> LogMerge { let num_sources = sources.len(); let mut source_state = Vec::with_capacity(sources.len()); for _ in 0..sources.len() { source_state.push(SourceState::NeedsPoll); } LogMerge { running_sources: num_sources, sources: sources, source_state: source_state, buffer: Vec::with_capacity(num_sources), current_timestamp: 0, } } fn next_entry(&mut self) -> BufferEntry { // TODO: better error handling, remove_item -> rust nightly / 2019-02-20 let e = self.buffer.remove(0); return e; } fn insert_into_buffer(&mut self, log_line: LogLine, source_idx: usize) { let line = BufferEntry { log_line, source_idx, }; let buffer_size = self.buffer.len(); let mut insert_at = 0; for idx in 0..buffer_size { if line.log_line.timestamp < self.buffer[idx].log_line.timestamp { break; } insert_at += 1; } self.buffer.insert(insert_at, line); } fn inject_error(&mut self, err: LogStreamError, source_idx: usize) { match err { LogStreamError::DefaultError(tentacle) => { let log_line = LogLine { timestamp: self.current_timestamp, message: format!("A tentacle failed while retrieving the log."), loglevel: Some(format!("ERROR")), id: format!(""), source: tentacle, }; self.insert_into_buffer(log_line, source_idx); } }; } fn poll_source(&mut self, source_idx: usize) -> Result<(), LogStreamError> { match self.sources[source_idx].poll() { Ok(Ready(Some(line))) => { self.insert_into_buffer(line, source_idx); self.source_state[source_idx] = SourceState::Delivered; } Ok(Ready(None)) => { self.source_state[source_idx] = SourceState::Finished; self.running_sources -= 1; } Ok(NotReady) => { self.source_state[source_idx] = SourceState::NeedsPoll; } Err(e) => { error!("Source failed: {}", e); self.inject_error(e, source_idx); self.source_state[source_idx] = SourceState::Failed; self.running_sources -= 1; } } Ok(()) } } impl Stream for LogMerge { type Item = LogLine; type Error = LogStreamError; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { for s in 0..self.source_state.len() { match self.source_state[s] { SourceState::NeedsPoll => { if let Err(err) = self.poll_source(s) { return Err(err); } } _ => {} } } if self.running_sources == 0 && self.buffer.is_empty() { Ok(Ready(None)) } else if self.running_sources <= self.buffer.len() { let entry = self.next_entry(); if self.source_state[entry.source_idx] == SourceState::Delivered { self.source_state[entry.source_idx] = SourceState::NeedsPoll; } self.current_timestamp = entry.log_line.timestamp; Ok(Ready(Some(entry.log_line))) } else { Ok(NotReady) } } } #[cfg(test)] mod tests { use crate::log_merge::{LogMerge, LogStream}; use crate::tentacle::LogLine; use futures::stream::{empty, iter_ok, once}; use futures::Stream; use tokio::runtime::current_thread::Runtime; fn line_at(timestamp: i64, line: &str) -> LogLine { LogLine { timestamp: timestamp, message: line.to_string(), loglevel: None, id: String::from("system-syslog"), source: String::from("node1"), } } #[test] fn test_new() { let s1: LogStream = Box::new(once(Ok(line_at(0, "s1")))); let s2: LogStream = Box::new(once(Ok(line_at(1, "s2")))); let sources = vec![s1, s2]; let merge = LogMerge::new(sources); assert!(merge.sources.len() == 2); assert!(merge.source_state.len() == 2); } #[test] fn empty_streams() { let s1: LogStream = Box::new(empty()); let sources = vec![s1]; let merge = LogMerge::new(sources); let mut rt = Runtime::new().unwrap(); let result = rt.block_on(merge.collect()).unwrap(); assert!(result.is_empty()); } #[test] fn test_single_stream() { let l1 = line_at(0, "s1"); let l2 = line_at(1, "s1"); let s1: LogStream = Box::new(iter_ok(vec![l1.clone(), l2.clone()])); let sources = vec![s1]; let merge = LogMerge::new(sources); let mut rt = Runtime::new().unwrap(); let result = rt.block_on(merge.collect()).unwrap(); assert_eq!(vec![l1, l2], result); } #[test] fn test_multiple_streams() { let l11 = line_at(100, "s11"); let l12 = line_at(300, "s12"); let l13 = line_at(520, "s13"); let l21 = line_at(90, "s21"); let l22 = line_at(430, "s22"); let l31 = line_at(120, "s31"); let l32 = line_at(120, "s32"); let l33 = line_at(320, "s33"); let l34 = line_at(520, "s34"); let s1: LogStream = Box::new(iter_ok(vec![l11.clone(), l12.clone(), l13.clone()])); let s2: LogStream = Box::new(iter_ok(vec![l21.clone(), l22.clone()])); let s3: LogStream = Box::new(iter_ok(vec![ l31.clone(), l32.clone(), l33.clone(), l34.clone(), ])); let sources = vec![s1, s2, s3]; let merge = LogMerge::new(sources); let mut rt = Runtime::new().unwrap(); let result = rt.block_on(merge.collect()).unwrap(); assert_eq!(vec![l21, l11, l31, l32, l12, l33, l22, l13, l34], result); } }
mod restore_structure; mod parse_commands; use crate::restore_structure::{Restore}; use crate::parse_commands::ParseCommand; use cassandra_restore_keyspace::show_err_msg; fn main() { match ParseCommand::new() { Ok(config) => { let restore = Restore::new(config); restore.run() } Err(e) => show_err_msg(&e.to_string()) } }
use getopts; use getopts::Options; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use std::process; fn main() { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optopt("n", "lines", "number of lines", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; if matches.opt_present("h") { println!("Usage: {:?} [-n LINES] [FILE...]", &args[0]); process::exit(0); } // --line tmp でtmpがない場合既に19行目でpanicしている? let nlines: i32 = match matches.opt_str("n") { Some(n) => n.parse().unwrap(), None => { println!("Usage: {:?} [-n LINES] [FILE...]", &args[0]); process::exit(1); } }; if matches.free.is_empty() { let mut buf_file = BufReader::new(io::stdin()); do_head(&mut buf_file, nlines); } else { for i in 0..matches.free.len() { let f = match File::open(&matches.free[i]) { Ok(file) => file, Err(why) => panic!("couln't open {}: {}", &args[i], why.to_string()), }; let mut buf_file = BufReader::new(f); do_head(&mut buf_file, nlines); } } process::exit(0); } fn do_head(f: &mut dyn BufRead, mut nlines: i32) { let mut buf_out = BufWriter::new(io::stdout()); for byte in f.bytes() { let c = byte.unwrap(); buf_out.write(&[c]).unwrap(); if c == b'\n' { nlines -= 1; if nlines == 0 { return; } } } }
fn main() { let mut x = 5; println!("The value of x is {}", x); x = 6; println!("The value of x is {}", x); const MAX_POINTS: u32 = 100_000; println!("Constant variable {}", MAX_POINTS); let x = 7; // shadowing println!("The value of x is {}", x); let spaces = " "; let spaces = spaces.len(); println!("Space count {}", spaces); let a = 2.0; // f64, double precision let b: f32 = 3.4; // explicit f32 let c = 'z'; let z = 'ℤ'; let heart_eyed_cat = '😻'; // Unicode Scalar Value support let tup = (2, 5.4, "hi"); // mixed type tuple let (x, y, z) = tup; println!("The value of z is: {}", z); println!("first {} and second {}", tup.0, tup.1); let d: [i32; 5] = [1, 2, 3, 4, 5]; let e: [i32; 3]; // rust will exit the program during runtime when attempting to access out of bounds element d[6] // this is an example of rust safety principles }
use crate::uwu::uwuify; use crate::ResultExt; use serenity::{ async_trait, model::{ gateway::Ready, interactions::{Interaction, InteractionResponseType}, }, prelude::*, }; pub struct Handler; impl Handler { async fn handle_uwuify(&self, ctx: Context, interaction: Interaction) { let data = interaction.data.as_ref().unwrap(); let option = &data.options[0]; assert_eq!("text", option.name); let value = option .value .as_ref() .expect("text is a required argument") .as_str() .expect("text is always a String type"); let uwud = uwuify(value); let http = &ctx.http; interaction .create_interaction_response(http, |response| { response .kind(InteractionResponseType::ChannelMessageWithSource) .interaction_response_data(|data| data.content(uwud)) }) .await .unwrap_or_report(); } } #[async_trait] impl EventHandler for Handler { async fn ready(&self, _: Context, ready: Ready) { println!("{} is connected!", ready.user.name); } async fn interaction_create(&self, ctx: Context, interaction: Interaction) { if let Some(data) = &interaction.data { match data.name.as_str() { "uwuify" => self.handle_uwuify(ctx, interaction).await, _ => { println!("unknown interaction"); dbg!(&interaction); } } } } }
use regex::Regex; use std::str::FromStr as StrFromStr; use strum_macros::EnumString; use crate::util; pub fn solve() { let input_file = "input-day-19.txt"; println!("Day 19 answers"); print!(" first puzzle: "); let (answer_p1, _answer_p2) = solve_both_file(input_file); println!("{}", answer_p1); // print!(" second puzzle: "); // println!("{}", answer_p2); } fn solve_both_file(input: &str) -> (usize, usize) { let v = util::aoc2018_row_file_to_vector(input); solve_both(&v) } fn solve_both(str_vector: &[String]) -> (usize, usize) { let (ip_register, program) = shared_puzzle_start(&str_vector); let mut registers: Registers = vec![0; 6]; run_program(&program, ip_register, &mut registers); let mut registers2: Registers = vec![0; 6]; registers2[0] = 1; run_program(&program, ip_register, &mut registers2); (registers[0], registers2[0]) } fn run_program(program: &[Instruction], ip_register: usize, registers: &mut Vec<usize>) { let mut ip: usize = 0; // println!("XXX: IP: {:?} IP reg: {}", ip, ip_register); loop { if ip >= program.len() { println!("XXX: ip: {} -> registers: {:?}", ip, registers); break; } let ins = &program[ip]; let op_code = OpCode::from_str(&ins.opcode).expect("Not a valid OpCode"); // print!("XXX: PRE OP: ip: {} registers instr ip refgisters {:?} {:?} ", ip, registers, ins); ip = op_code.execute( ins.input_a, ins.input_b, ins.output, registers, ip, ip_register, ); // println!("XXX: ip: {} -> registers: {:?}", ip, registers); } } fn shared_puzzle_start(str_vector: &[String]) -> (usize, Vec<Instruction>) { let re = Regex::new(r"^(\w{4})\s*(\d+)\s*(\d+)\s*(\d+)\s*$").unwrap(); let re_ip_register = Regex::new(r"^#ip\s*(\d)\s*$").unwrap(); let mut program: Vec<Instruction> = vec![]; let mut ip_reg: Option<usize> = None; for (_index, line) in str_vector.iter().enumerate() { // println!("XXX: PArsing line: {:?}", line); if !line.trim().is_empty() { let caps = re.captures(&line); if let Some(caps) = caps { let ins_str = caps[1].to_owned(); // let o = OpCode::from_str(&ins_str).expect("Not a valid OpCode"); let i = Instruction { opcode: ins_str, input_a: caps[2].parse().expect("Not an usize"), input_b: caps[3].parse().expect("Not an usize"), output: caps[4].parse().expect("Not an usize"), }; program.push(i); } else { // println!("XXX: PArsing line: {:?}", line); let caps = re_ip_register.captures(&line); if let Some(caps) = caps { ip_reg = Some(caps[1].parse().expect("Not an usize")); } } } } (ip_reg.unwrap(), program) } #[derive(Debug, EnumString)] #[strum(serialize_all = "snake_case")] enum OpCode { Addr = 6, Addi = 2, Mulr = 12, Muli = 13, Banr = 15, Bani = 3, Borr = 8, Bori = 1, Setr = 10, Seti = 4, Gtir = 9, Gtri = 7, Gtrr = 14, Eqir = 11, Eqri = 0, Eqrr = 5, } // struct Registers (Vec<usize>); type Registers = Vec<usize>; impl OpCode { fn execute( self, a: usize, b: usize, o: usize, register: &mut Registers, ip: usize, ip_register: usize, ) -> usize { register[ip_register] = ip; match self { OpCode::Addr => { register[o] = register[a] + register[b]; } OpCode::Addi => { register[o] = register[a] + b; } OpCode::Mulr => { register[o] = register[a] * register[b]; } OpCode::Muli => { register[o] = register[a] * b; } OpCode::Banr => { register[o] = register[a] & register[b]; } OpCode::Bani => { register[o] = register[a] & b; } OpCode::Borr => { register[o] = register[a] | register[b]; } OpCode::Bori => { register[o] = register[a] | b; } OpCode::Setr => { register[o] = register[a]; } OpCode::Seti => { register[o] = a; } OpCode::Gtir => { if a > register[b] { register[o] = 1; } else { register[o] = 0; } } OpCode::Gtri => { if register[a] > b { register[o] = 1; } else { register[o] = 0; } } OpCode::Gtrr => { if register[a] > register[b] { register[o] = 1; } else { register[o] = 0; } } OpCode::Eqir => { if a == register[b] { register[o] = 1; } else { register[o] = 0; } } OpCode::Eqri => { let cmp_res = register[a] == b; if cmp_res { register[o] = 1; } else { register[o] = 0; } } OpCode::Eqrr => { let cmp_res = register[a] == register[b]; if cmp_res { register[o] = 1; } else { register[o] = 0; } } } register[ip_register] += 1; register[ip_register] } } #[derive(Debug)] struct Instruction { opcode: String, input_a: usize, input_b: usize, output: usize, } #[cfg(test)] mod tests { use super::*; #[test] fn test_day_19() { // provided examples let input = &[ String::from("#ip 0"), String::from("seti 5 0 1"), String::from("seti 6 0 2"), String::from("addi 0 1 0"), String::from("addr 1 2 3"), String::from("setr 1 0 0"), String::from("seti 8 0 4"), String::from("seti 9 0 5"), ]; let (a1, _a2) = solve_both(input); assert_eq!(a1, 7); // assert_eq!(a2, 7); } }
use std::collections::HashMap; use std::sync::mpsc; use std::cmp; use intcode; #[macro_use] extern crate itertools; fn main() { let start_time = std::time::Instant::now(); let program = intcode::load_program("day11/input.txt").unwrap_or_else(|err| { println!("Could not load input file!\n{:?}", err); std::process::exit(1); }); let part_1_robot = run_paint_sequence(&program, false); let part_2_robot = run_paint_sequence(&program, true); let picture = part_2_robot.draw_painting(); println!( "Part 1: {}\nPart 2: {}\nTime: {}ms", part_1_robot.count_painted_panels(), picture, start_time.elapsed().as_millis() ); } fn run_paint_sequence(program: &[i64], paint_current_panel: bool) -> Robot { let (in_send, in_recv) = mpsc::channel(); let (out_send, out_recv) = mpsc::channel(); let mut computer = intcode::ChannelIOComputer::new(program, in_recv, out_send); std::thread::spawn(move || { computer.run(); }); let mut robot = Robot::new(); if paint_current_panel { robot.paint(1); } loop { if in_send.send(robot.get_current_color()).is_err() { break; } match out_recv.recv() { Ok(val) => match val { 0 | 1 => robot.paint(val), _ => unreachable!("Invalid paint instruction received: {}", val), }, Err(_) => break, }; match out_recv.recv() { Ok(val) => match val { 0 => robot.turn_and_move(Turn::Left), 1 => robot.turn_and_move(Turn::Right), _ => unreachable!("Invalid turn instruction received: {}", val), }, Err(_) => break, }; } robot } #[derive(Clone, Copy)] enum Turn { Left, Right, } #[derive(Clone, Copy)] enum Direction { Up, Down, Left, Right, } impl Direction { fn turn(self, turn: Turn) -> Self { match turn { Turn::Left => match self { Self::Up => Self::Left, Self::Left => Self::Down, Self::Down => Self::Right, Self::Right => Self::Up, }, Turn::Right => match self { Self::Up => Self::Right, Self::Right => Self::Down, Self::Down => Self::Left, Self::Left => Self::Up, }, } } } struct Robot { x: isize, y: isize, dir: Direction, panels: HashMap<(isize, isize), Panel>, } impl Robot { fn new() -> Self { Self { x: 0, y: 0, dir: Direction::Up, panels: HashMap::new(), } } fn count_painted_panels(&self) -> usize { self.panels.values().filter(|panel| panel.painted).count() } fn paint(&mut self, color: i64) { self.get_current_panel().paint(color); } fn get_current_color(&mut self) -> i64 { self.get_current_panel().color } fn turn_and_move(&mut self, turn: Turn) { self.dir = self.dir.turn(turn); match self.dir { Direction::Up => { self.y -= 1; } Direction::Down => { self.y += 1; } Direction::Left => { self.x -= 1; } Direction::Right => { self.x += 1; } } } fn get_current_panel(&mut self) -> &mut Panel { self.panels.entry((self.x, self.y)).or_insert_with(Panel::new) } fn get_color_at(&self, x: isize, y: isize) -> i64 { self.panels.get(&(x, y)).map_or(0, |panel| panel.color) } fn draw_painting(&self) -> String { // Calculate boundaries let (min_x, min_y, max_x, max_y) = self.panels.keys().fold((0,0,0,0), |(min_x, min_y, max_x, max_y), &(x, y)| { let min_x = cmp::min(min_x, x); let min_y = cmp::min(min_y, y); let max_x = cmp::max(max_x, x); let max_y = cmp::max(max_y, y); (min_x, min_y, max_x, max_y) }); let mut picture = String::new(); for (y, x) in iproduct!((min_y..=max_y), (min_x..=max_x)) { if x == min_x { picture.push('\n'); } match self.get_color_at(x, y) { 1 => picture.push('#'), _ => picture.push(' '), }; } picture } } struct Panel { color: i64, painted: bool, } impl Panel { fn new() -> Self { Self { color: 0, painted: false, } } fn paint(&mut self, color: i64) { self.color = color; self.painted = true; } }
// verification-helper: PROBLEM https://onlinejudge.u-aizu.ac.jp/problems/1009 fn main() { loop { let mut line = String::new(); if std::io::stdin().read_line(&mut line) .map(|bytes| bytes == 0) .unwrap_or(false) { break; } let nums = line .split_ascii_whitespace() .map(|s| s.parse::<u64>().unwrap()) .collect::<Vec<_>>(); println!("{}", solve(nums)); } } fn solve(nums: Vec<u64>) -> u64 { cprlib::gcd::calc_gcd_multi(nums.into_iter()) }
// TODO: Needs improvement pub fn count_smaller(nums: Vec<i32>) -> Vec<i32> { let n = nums.len(); let mut result = vec![0; n]; for i in 0..n { for j in i + 1..n { if nums[i] > nums[j] { result[i] += 1; } } } result }
use portmidi::types::MidiEvent; use std::fmt; const NUM_SLIDERS: usize = 8; #[derive(Debug, PartialEq)] pub enum Korg { S, M, R, Knob, Slider, TrackLeft, TrackRight, Cycle, Set, MarkerLeft, MarkerRight, Rewind, FastForward, Stop, Play, Record, } // A more readable representation of a midi event pub struct Message { pub name: Korg, pub group: u8, pub value: u8, pub timestamp: u32, } impl Message { // Creates Message from MidiEvent pub fn new(midi_event: &MidiEvent) -> Message { let timestamp = midi_event.timestamp; let data1 = midi_event.message.data1; let data2 = midi_event.message.data2; let control = match data1 { 0...7 => Korg::Slider, 16...23 => Korg::Knob, 32...39 => Korg::S, 48...55 => Korg::M, 64...71 => Korg::R, 41 => Korg::Play, 42 => Korg::Stop, 43 => Korg::Rewind, 44 => Korg::FastForward, 45 => Korg::Record, 46 => Korg::Cycle, 58 => Korg::TrackLeft, 59 => Korg::TrackRight, 60 => Korg::Set, 61 => Korg::MarkerLeft, 62 => Korg::MarkerRight, _ => Korg::Cycle, }; let group: u8 = match data1 { 41...46 => 0, 58...62 => 0, _ => data1 % 8 + 1, }; Message {name:control, group:group, value:data2, timestamp:timestamp} } pub fn to_bool(&self) -> bool { match self.value { 0 => false, _ => true, } } } impl fmt::Display for Message { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let group = self.group; let value = self.value; let timestamp = self.timestamp; let pressed = self.to_bool(); let name = &self.name; match name { Korg::Knob | Korg::Slider => write!(f, "Group {}, Value {}, {:?}, Time {}", group, value, name, timestamp), _ => write!(f, "Group {}, Value {}, {:?}, Time {}", group, pressed, name, timestamp), } } } #[derive(Copy, Clone, Default)] pub struct Control { pub knob: u8, pub slider: u8, pub solo: bool, pub mute: bool, pub rec: bool, } #[derive(Default)] pub struct NK2 { pub controls: [Control; NUM_SLIDERS], pub track_left: bool, pub track_right: bool, pub cycle: bool, pub set: bool, pub marker_left: bool, pub marker_right: bool, pub rewind: bool, pub fast_forward: bool, pub stop: bool, pub play: bool, pub record: bool, } impl NK2 { //Updates NK2 with the midi message pub fn update(&mut self, message: &Message) { let value_idx = (message.group - 1) as usize; // The groups are off by 1 let pressed = message.to_bool(); match message.name { Korg::Knob => self.controls[value_idx].knob = message.value, Korg::Slider => self.controls[value_idx].slider = message.value, Korg::S => self.controls[value_idx].solo = pressed, Korg::M => self.controls[value_idx].mute = pressed, Korg::R => self.controls[value_idx].rec = pressed, Korg::TrackLeft => self.track_left = pressed, Korg::TrackRight => self.track_right = pressed, Korg::Cycle => self.cycle = pressed, Korg::Set => self.set = pressed, Korg::MarkerLeft => self.marker_left = pressed, Korg::MarkerRight => self.marker_right = pressed, Korg::Rewind => self.rewind = pressed, Korg::FastForward => self.fast_forward = pressed, Korg::Stop => self.stop = pressed, Korg::Play => self.play = pressed, Korg::Record => self.record = pressed, } } }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `HSION` reader - Internal high-speed clock enable"] pub type HSION_R = crate::BitReader<HSION_A>; #[doc = "Internal high-speed clock enable\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSION_A { #[doc = "0: Clock Off"] Off = 0, #[doc = "1: Clock On"] On = 1, } impl From<HSION_A> for bool { #[inline(always)] fn from(variant: HSION_A) -> Self { variant as u8 != 0 } } impl HSION_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSION_A { match self.bits { false => HSION_A::Off, true => HSION_A::On, } } #[doc = "Clock Off"] #[inline(always)] pub fn is_off(&self) -> bool { *self == HSION_A::Off } #[doc = "Clock On"] #[inline(always)] pub fn is_on(&self) -> bool { *self == HSION_A::On } } #[doc = "Field `HSION` writer - Internal high-speed clock enable"] pub type HSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSION_A>; impl<'a, REG, const O: u8> HSION_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clock Off"] #[inline(always)] pub fn off(self) -> &'a mut crate::W<REG> { self.variant(HSION_A::Off) } #[doc = "Clock On"] #[inline(always)] pub fn on(self) -> &'a mut crate::W<REG> { self.variant(HSION_A::On) } } #[doc = "Field `HSIKERON` reader - High Speed Internal clock enable in Stop mode"] pub use HSION_R as HSIKERON_R; #[doc = "Field `HSIKERON` writer - High Speed Internal clock enable in Stop mode"] pub use HSION_W as HSIKERON_W; #[doc = "Field `HSIRDY` reader - HSI clock ready flag"] pub type HSIRDY_R = crate::BitReader<HSIRDYR_A>; #[doc = "HSI clock ready flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSIRDYR_A { #[doc = "0: Clock not ready"] NotReady = 0, #[doc = "1: Clock ready"] Ready = 1, } impl From<HSIRDYR_A> for bool { #[inline(always)] fn from(variant: HSIRDYR_A) -> Self { variant as u8 != 0 } } impl HSIRDY_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIRDYR_A { match self.bits { false => HSIRDYR_A::NotReady, true => HSIRDYR_A::Ready, } } #[doc = "Clock not ready"] #[inline(always)] pub fn is_not_ready(&self) -> bool { *self == HSIRDYR_A::NotReady } #[doc = "Clock ready"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == HSIRDYR_A::Ready } } #[doc = "Field `HSIRDY` writer - HSI clock ready flag"] pub type HSIRDY_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSIRDYR_A>; impl<'a, REG, const O: u8> HSIRDY_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clock not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut crate::W<REG> { self.variant(HSIRDYR_A::NotReady) } #[doc = "Clock ready"] #[inline(always)] pub fn ready(self) -> &'a mut crate::W<REG> { self.variant(HSIRDYR_A::Ready) } } #[doc = "Field `HSIDIV` reader - HSI clock divider"] pub type HSIDIV_R = crate::FieldReader<HSIDIV_A>; #[doc = "HSI clock divider\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum HSIDIV_A { #[doc = "0: No division"] Div1 = 0, #[doc = "1: Division by 2"] Div2 = 1, #[doc = "2: Division by 4"] Div4 = 2, #[doc = "3: Division by 8"] Div8 = 3, } impl From<HSIDIV_A> for u8 { #[inline(always)] fn from(variant: HSIDIV_A) -> Self { variant as _ } } impl crate::FieldSpec for HSIDIV_A { type Ux = u8; } impl HSIDIV_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIDIV_A { match self.bits { 0 => HSIDIV_A::Div1, 1 => HSIDIV_A::Div2, 2 => HSIDIV_A::Div4, 3 => HSIDIV_A::Div8, _ => unreachable!(), } } #[doc = "No division"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == HSIDIV_A::Div1 } #[doc = "Division by 2"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == HSIDIV_A::Div2 } #[doc = "Division by 4"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == HSIDIV_A::Div4 } #[doc = "Division by 8"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == HSIDIV_A::Div8 } } #[doc = "Field `HSIDIV` writer - HSI clock divider"] pub type HSIDIV_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, HSIDIV_A>; impl<'a, REG, const O: u8> HSIDIV_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "No division"] #[inline(always)] pub fn div1(self) -> &'a mut crate::W<REG> { self.variant(HSIDIV_A::Div1) } #[doc = "Division by 2"] #[inline(always)] pub fn div2(self) -> &'a mut crate::W<REG> { self.variant(HSIDIV_A::Div2) } #[doc = "Division by 4"] #[inline(always)] pub fn div4(self) -> &'a mut crate::W<REG> { self.variant(HSIDIV_A::Div4) } #[doc = "Division by 8"] #[inline(always)] pub fn div8(self) -> &'a mut crate::W<REG> { self.variant(HSIDIV_A::Div8) } } #[doc = "Field `HSIDIVF` reader - HSI divider flag"] pub type HSIDIVF_R = crate::BitReader<HSIDIVFR_A>; #[doc = "HSI divider flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSIDIVFR_A { #[doc = "0: New HSIDIV ratio has not yet propagated to hsi_ck"] NotPropagated = 0, #[doc = "1: HSIDIV ratio has propagated to hsi_ck"] Propagated = 1, } impl From<HSIDIVFR_A> for bool { #[inline(always)] fn from(variant: HSIDIVFR_A) -> Self { variant as u8 != 0 } } impl HSIDIVF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSIDIVFR_A { match self.bits { false => HSIDIVFR_A::NotPropagated, true => HSIDIVFR_A::Propagated, } } #[doc = "New HSIDIV ratio has not yet propagated to hsi_ck"] #[inline(always)] pub fn is_not_propagated(&self) -> bool { *self == HSIDIVFR_A::NotPropagated } #[doc = "HSIDIV ratio has propagated to hsi_ck"] #[inline(always)] pub fn is_propagated(&self) -> bool { *self == HSIDIVFR_A::Propagated } } #[doc = "Field `HSIDIVF` writer - HSI divider flag"] pub type HSIDIVF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSIDIVFR_A>; impl<'a, REG, const O: u8> HSIDIVF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "New HSIDIV ratio has not yet propagated to hsi_ck"] #[inline(always)] pub fn not_propagated(self) -> &'a mut crate::W<REG> { self.variant(HSIDIVFR_A::NotPropagated) } #[doc = "HSIDIV ratio has propagated to hsi_ck"] #[inline(always)] pub fn propagated(self) -> &'a mut crate::W<REG> { self.variant(HSIDIVFR_A::Propagated) } } #[doc = "Field `CSION` reader - CSI clock enable"] pub use HSION_R as CSION_R; #[doc = "Field `CSIKERON` reader - CSI clock enable in Stop mode"] pub use HSION_R as CSIKERON_R; #[doc = "Field `HSI48ON` reader - RC48 clock enable"] pub use HSION_R as HSI48ON_R; #[doc = "Field `HSEON` reader - HSE clock enable"] pub use HSION_R as HSEON_R; #[doc = "Field `CSION` writer - CSI clock enable"] pub use HSION_W as CSION_W; #[doc = "Field `CSIKERON` writer - CSI clock enable in Stop mode"] pub use HSION_W as CSIKERON_W; #[doc = "Field `HSI48ON` writer - RC48 clock enable"] pub use HSION_W as HSI48ON_W; #[doc = "Field `HSEON` writer - HSE clock enable"] pub use HSION_W as HSEON_W; #[doc = "Field `CSIRDY` reader - CSI clock ready flag"] pub use HSIRDY_R as CSIRDY_R; #[doc = "Field `HSI48RDY` reader - RC48 clock ready flag"] pub use HSIRDY_R as HSI48RDY_R; #[doc = "Field `D1CKRDY` reader - D1 domain clocks ready flag"] pub use HSIRDY_R as D1CKRDY_R; #[doc = "Field `D2CKRDY` reader - D2 domain clocks ready flag"] pub use HSIRDY_R as D2CKRDY_R; #[doc = "Field `HSERDY` reader - HSE clock ready flag"] pub use HSIRDY_R as HSERDY_R; #[doc = "Field `CSIRDY` writer - CSI clock ready flag"] pub use HSIRDY_W as CSIRDY_W; #[doc = "Field `HSI48RDY` writer - RC48 clock ready flag"] pub use HSIRDY_W as HSI48RDY_W; #[doc = "Field `D1CKRDY` writer - D1 domain clocks ready flag"] pub use HSIRDY_W as D1CKRDY_W; #[doc = "Field `D2CKRDY` writer - D2 domain clocks ready flag"] pub use HSIRDY_W as D2CKRDY_W; #[doc = "Field `HSERDY` writer - HSE clock ready flag"] pub use HSIRDY_W as HSERDY_W; #[doc = "Field `HSEBYP` reader - HSE clock bypass"] pub type HSEBYP_R = crate::BitReader<HSEBYP_A>; #[doc = "HSE clock bypass\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSEBYP_A { #[doc = "0: HSE crystal oscillator not bypassed"] NotBypassed = 0, #[doc = "1: HSE crystal oscillator bypassed with external clock"] Bypassed = 1, } impl From<HSEBYP_A> for bool { #[inline(always)] fn from(variant: HSEBYP_A) -> Self { variant as u8 != 0 } } impl HSEBYP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSEBYP_A { match self.bits { false => HSEBYP_A::NotBypassed, true => HSEBYP_A::Bypassed, } } #[doc = "HSE crystal oscillator not bypassed"] #[inline(always)] pub fn is_not_bypassed(&self) -> bool { *self == HSEBYP_A::NotBypassed } #[doc = "HSE crystal oscillator bypassed with external clock"] #[inline(always)] pub fn is_bypassed(&self) -> bool { *self == HSEBYP_A::Bypassed } } #[doc = "Field `HSEBYP` writer - HSE clock bypass"] pub type HSEBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSEBYP_A>; impl<'a, REG, const O: u8> HSEBYP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "HSE crystal oscillator not bypassed"] #[inline(always)] pub fn not_bypassed(self) -> &'a mut crate::W<REG> { self.variant(HSEBYP_A::NotBypassed) } #[doc = "HSE crystal oscillator bypassed with external clock"] #[inline(always)] pub fn bypassed(self) -> &'a mut crate::W<REG> { self.variant(HSEBYP_A::Bypassed) } } #[doc = "Field `HSECSSON` reader - HSE Clock Security System enable"] pub use HSION_R as HSECSSON_R; #[doc = "Field `PLL1ON` reader - PLL1 enable"] pub use HSION_R as PLL1ON_R; #[doc = "Field `PLL2ON` reader - PLL2 enable"] pub use HSION_R as PLL2ON_R; #[doc = "Field `PLL3ON` reader - PLL3 enable"] pub use HSION_R as PLL3ON_R; #[doc = "Field `HSECSSON` writer - HSE Clock Security System enable"] pub use HSION_W as HSECSSON_W; #[doc = "Field `PLL1ON` writer - PLL1 enable"] pub use HSION_W as PLL1ON_W; #[doc = "Field `PLL2ON` writer - PLL2 enable"] pub use HSION_W as PLL2ON_W; #[doc = "Field `PLL3ON` writer - PLL3 enable"] pub use HSION_W as PLL3ON_W; #[doc = "Field `PLL1RDY` reader - PLL1 clock ready flag"] pub use HSIRDY_R as PLL1RDY_R; #[doc = "Field `PLL2RDY` reader - PLL2 clock ready flag"] pub use HSIRDY_R as PLL2RDY_R; #[doc = "Field `PLL3RDY` reader - PLL3 clock ready flag"] pub use HSIRDY_R as PLL3RDY_R; #[doc = "Field `PLL1RDY` writer - PLL1 clock ready flag"] pub use HSIRDY_W as PLL1RDY_W; #[doc = "Field `PLL2RDY` writer - PLL2 clock ready flag"] pub use HSIRDY_W as PLL2RDY_W; #[doc = "Field `PLL3RDY` writer - PLL3 clock ready flag"] pub use HSIRDY_W as PLL3RDY_W; impl R { #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&self) -> HSION_R { HSION_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - High Speed Internal clock enable in Stop mode"] #[inline(always)] pub fn hsikeron(&self) -> HSIKERON_R { HSIKERON_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - HSI clock ready flag"] #[inline(always)] pub fn hsirdy(&self) -> HSIRDY_R { HSIRDY_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 3:4 - HSI clock divider"] #[inline(always)] pub fn hsidiv(&self) -> HSIDIV_R { HSIDIV_R::new(((self.bits >> 3) & 3) as u8) } #[doc = "Bit 5 - HSI divider flag"] #[inline(always)] pub fn hsidivf(&self) -> HSIDIVF_R { HSIDIVF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 7 - CSI clock enable"] #[inline(always)] pub fn csion(&self) -> CSION_R { CSION_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - CSI clock ready flag"] #[inline(always)] pub fn csirdy(&self) -> CSIRDY_R { CSIRDY_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - CSI clock enable in Stop mode"] #[inline(always)] pub fn csikeron(&self) -> CSIKERON_R { CSIKERON_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 12 - RC48 clock enable"] #[inline(always)] pub fn hsi48on(&self) -> HSI48ON_R { HSI48ON_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - RC48 clock ready flag"] #[inline(always)] pub fn hsi48rdy(&self) -> HSI48RDY_R { HSI48RDY_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - D1 domain clocks ready flag"] #[inline(always)] pub fn d1ckrdy(&self) -> D1CKRDY_R { D1CKRDY_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - D2 domain clocks ready flag"] #[inline(always)] pub fn d2ckrdy(&self) -> D2CKRDY_R { D2CKRDY_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - HSE Clock Security System enable"] #[inline(always)] pub fn hsecsson(&self) -> HSECSSON_R { HSECSSON_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 24 - PLL1 enable"] #[inline(always)] pub fn pll1on(&self) -> PLL1ON_R { PLL1ON_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - PLL1 clock ready flag"] #[inline(always)] pub fn pll1rdy(&self) -> PLL1RDY_R { PLL1RDY_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - PLL2 enable"] #[inline(always)] pub fn pll2on(&self) -> PLL2ON_R { PLL2ON_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - PLL2 clock ready flag"] #[inline(always)] pub fn pll2rdy(&self) -> PLL2RDY_R { PLL2RDY_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - PLL3 enable"] #[inline(always)] pub fn pll3on(&self) -> PLL3ON_R { PLL3ON_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - PLL3 clock ready flag"] #[inline(always)] pub fn pll3rdy(&self) -> PLL3RDY_R { PLL3RDY_R::new(((self.bits >> 29) & 1) != 0) } } impl W { #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] #[must_use] pub fn hsion(&mut self) -> HSION_W<CR_SPEC, 0> { HSION_W::new(self) } #[doc = "Bit 1 - High Speed Internal clock enable in Stop mode"] #[inline(always)] #[must_use] pub fn hsikeron(&mut self) -> HSIKERON_W<CR_SPEC, 1> { HSIKERON_W::new(self) } #[doc = "Bit 2 - HSI clock ready flag"] #[inline(always)] #[must_use] pub fn hsirdy(&mut self) -> HSIRDY_W<CR_SPEC, 2> { HSIRDY_W::new(self) } #[doc = "Bits 3:4 - HSI clock divider"] #[inline(always)] #[must_use] pub fn hsidiv(&mut self) -> HSIDIV_W<CR_SPEC, 3> { HSIDIV_W::new(self) } #[doc = "Bit 5 - HSI divider flag"] #[inline(always)] #[must_use] pub fn hsidivf(&mut self) -> HSIDIVF_W<CR_SPEC, 5> { HSIDIVF_W::new(self) } #[doc = "Bit 7 - CSI clock enable"] #[inline(always)] #[must_use] pub fn csion(&mut self) -> CSION_W<CR_SPEC, 7> { CSION_W::new(self) } #[doc = "Bit 8 - CSI clock ready flag"] #[inline(always)] #[must_use] pub fn csirdy(&mut self) -> CSIRDY_W<CR_SPEC, 8> { CSIRDY_W::new(self) } #[doc = "Bit 9 - CSI clock enable in Stop mode"] #[inline(always)] #[must_use] pub fn csikeron(&mut self) -> CSIKERON_W<CR_SPEC, 9> { CSIKERON_W::new(self) } #[doc = "Bit 12 - RC48 clock enable"] #[inline(always)] #[must_use] pub fn hsi48on(&mut self) -> HSI48ON_W<CR_SPEC, 12> { HSI48ON_W::new(self) } #[doc = "Bit 13 - RC48 clock ready flag"] #[inline(always)] #[must_use] pub fn hsi48rdy(&mut self) -> HSI48RDY_W<CR_SPEC, 13> { HSI48RDY_W::new(self) } #[doc = "Bit 14 - D1 domain clocks ready flag"] #[inline(always)] #[must_use] pub fn d1ckrdy(&mut self) -> D1CKRDY_W<CR_SPEC, 14> { D1CKRDY_W::new(self) } #[doc = "Bit 15 - D2 domain clocks ready flag"] #[inline(always)] #[must_use] pub fn d2ckrdy(&mut self) -> D2CKRDY_W<CR_SPEC, 15> { D2CKRDY_W::new(self) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] #[must_use] pub fn hseon(&mut self) -> HSEON_W<CR_SPEC, 16> { HSEON_W::new(self) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] #[must_use] pub fn hserdy(&mut self) -> HSERDY_W<CR_SPEC, 17> { HSERDY_W::new(self) } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] #[must_use] pub fn hsebyp(&mut self) -> HSEBYP_W<CR_SPEC, 18> { HSEBYP_W::new(self) } #[doc = "Bit 19 - HSE Clock Security System enable"] #[inline(always)] #[must_use] pub fn hsecsson(&mut self) -> HSECSSON_W<CR_SPEC, 19> { HSECSSON_W::new(self) } #[doc = "Bit 24 - PLL1 enable"] #[inline(always)] #[must_use] pub fn pll1on(&mut self) -> PLL1ON_W<CR_SPEC, 24> { PLL1ON_W::new(self) } #[doc = "Bit 25 - PLL1 clock ready flag"] #[inline(always)] #[must_use] pub fn pll1rdy(&mut self) -> PLL1RDY_W<CR_SPEC, 25> { PLL1RDY_W::new(self) } #[doc = "Bit 26 - PLL2 enable"] #[inline(always)] #[must_use] pub fn pll2on(&mut self) -> PLL2ON_W<CR_SPEC, 26> { PLL2ON_W::new(self) } #[doc = "Bit 27 - PLL2 clock ready flag"] #[inline(always)] #[must_use] pub fn pll2rdy(&mut self) -> PLL2RDY_W<CR_SPEC, 27> { PLL2RDY_W::new(self) } #[doc = "Bit 28 - PLL3 enable"] #[inline(always)] #[must_use] pub fn pll3on(&mut self) -> PLL3ON_W<CR_SPEC, 28> { PLL3ON_W::new(self) } #[doc = "Bit 29 - PLL3 clock ready flag"] #[inline(always)] #[must_use] pub fn pll3rdy(&mut self) -> PLL3RDY_W<CR_SPEC, 29> { PLL3RDY_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 = "clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0x83"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0x83; }
mod support; use cubik::server::ServerContainer; use cubik::player::{Player, PlayerControlType}; use cubik::quadoctree::{QuadOctreeNode, BoundingBox}; use support::msg::AppMessage; use std::time::{Instant, Duration}; use std::thread::sleep; use std::collections::HashMap; use crate::support::constants::APP_ID; use cubik::map::GameMap; const PORT: u16 = 27020; fn main() { let mut server_container: ServerContainer<AppMessage> = ServerContainer::new(PORT, 10).unwrap(); println!("server listening on port {}", PORT); let mut last_status_update = Instant::now(); let mut player_map: HashMap<u8, Player> = HashMap::new(); let map = GameMap::load_map("models/map2", APP_ID, None, None, true).unwrap(); let mut last_time = Instant::now(); loop { server_container.update(); let current_pids = server_container.pids(); player_map.retain(|&k, _| current_pids.contains(&k)); for pid in current_pids { let player = player_map.entry(pid) .or_insert(Player::new([0., 1.5, 0.], PlayerControlType::MultiplayerServer, [-0.28, 0.275, 0.0], [0.44, 0.275, 0.08])); if let Ok(msgs) = server_container.get_msgs(pid) { for msg in msgs { if let AppMessage::PlayerChange { msg, .. } = msg { player.update(0., Some(map.quadoctree.as_ref().unwrap()), None, Some(msg)); } } } if let Some(msg) = player.update(last_time.elapsed().as_secs_f32(), Some(map.quadoctree.as_ref().unwrap()), None, None) { server_container.broadcast(AppMessage::PlayerChange { msg: msg, player_id: pid }); } } if last_status_update.elapsed().as_secs_f32() > 5. { last_status_update = Instant::now(); println!("peer status update:"); for (pid, conn) in &server_container.connections { println!("pid: {} name: {}", pid, conn.name.as_ref().unwrap_or(&"".to_string())); } println!(""); server_container.broadcast(AppMessage::Chat { text: format!("I see {} peers", server_container.connections.len()), sender: None }); } last_time = Instant::now(); sleep(Duration::from_millis(17)); } }
mod parser; mod scanner; pub mod syntax_error; mod tokens; use ast::*; use front::parser::Parser; use front::syntax_error::SyntaxError; use front::tokens::Token; pub fn parse(filename: &str, input: &str) -> Result<Vec<Node>, Vec<SyntaxError>> { let mut p = Parser::new(filename, input); let mut values = Vec::new(); let mut errors = Vec::new(); p.next_token(&mut errors); while p.current_token != Token::EndOfFile { let n = p.parse_value(&mut errors); values.push(n); p.next_token(&mut errors); //DEBUG println!("processing: {:?}", p.current_token); } if errors.len() > 0 { Err(errors) } else { Ok(values) } }
#[doc = "Register `APBRSTR1` reader"] pub type R = crate::R<APBRSTR1_SPEC>; #[doc = "Register `APBRSTR1` writer"] pub type W = crate::W<APBRSTR1_SPEC>; #[doc = "Field `TIM3RST` reader - TIM3 timer reset"] pub type TIM3RST_R = crate::BitReader; #[doc = "Field `TIM3RST` writer - TIM3 timer reset"] pub type TIM3RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM6RST` reader - TIM6 timer reset"] pub type TIM6RST_R = crate::BitReader; #[doc = "Field `TIM6RST` writer - TIM6 timer reset"] pub type TIM6RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM7RST` reader - TIM7 timer reset"] pub type TIM7RST_R = crate::BitReader; #[doc = "Field `TIM7RST` writer - TIM7 timer reset"] pub type TIM7RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI2RST` reader - SPI2 reset"] pub type SPI2RST_R = crate::BitReader; #[doc = "Field `SPI2RST` writer - SPI2 reset"] pub type SPI2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART2RST` reader - USART2 reset"] pub type USART2RST_R = crate::BitReader; #[doc = "Field `USART2RST` writer - USART2 reset"] pub type USART2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART3RST` reader - USART3 reset"] pub type USART3RST_R = crate::BitReader; #[doc = "Field `USART3RST` writer - USART3 reset"] pub type USART3RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART4RST` reader - USART4 reset"] pub type USART4RST_R = crate::BitReader; #[doc = "Field `USART4RST` writer - USART4 reset"] pub type USART4RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C1RST` reader - I2C1 reset"] pub type I2C1RST_R = crate::BitReader; #[doc = "Field `I2C1RST` writer - I2C1 reset"] pub type I2C1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C2RST` reader - I2C2 reset"] pub type I2C2RST_R = crate::BitReader; #[doc = "Field `I2C2RST` writer - I2C2 reset"] pub type I2C2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBGRST` reader - Debug support reset"] pub type DBGRST_R = crate::BitReader; #[doc = "Field `DBGRST` writer - Debug support reset"] pub type DBGRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PWRRST` reader - Power interface reset"] pub type PWRRST_R = crate::BitReader; #[doc = "Field `PWRRST` writer - Power interface reset"] pub type PWRRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 1 - TIM3 timer reset"] #[inline(always)] pub fn tim3rst(&self) -> TIM3RST_R { TIM3RST_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 4 - TIM6 timer reset"] #[inline(always)] pub fn tim6rst(&self) -> TIM6RST_R { TIM6RST_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TIM7 timer reset"] #[inline(always)] pub fn tim7rst(&self) -> TIM7RST_R { TIM7RST_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 14 - SPI2 reset"] #[inline(always)] pub fn spi2rst(&self) -> SPI2RST_R { SPI2RST_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 17 - USART2 reset"] #[inline(always)] pub fn usart2rst(&self) -> USART2RST_R { USART2RST_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - USART3 reset"] #[inline(always)] pub fn usart3rst(&self) -> USART3RST_R { USART3RST_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - USART4 reset"] #[inline(always)] pub fn usart4rst(&self) -> USART4RST_R { USART4RST_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 21 - I2C1 reset"] #[inline(always)] pub fn i2c1rst(&self) -> I2C1RST_R { I2C1RST_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 reset"] #[inline(always)] pub fn i2c2rst(&self) -> I2C2RST_R { I2C2RST_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 27 - Debug support reset"] #[inline(always)] pub fn dbgrst(&self) -> DBGRST_R { DBGRST_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] pub fn pwrrst(&self) -> PWRRST_R { PWRRST_R::new(((self.bits >> 28) & 1) != 0) } } impl W { #[doc = "Bit 1 - TIM3 timer reset"] #[inline(always)] #[must_use] pub fn tim3rst(&mut self) -> TIM3RST_W<APBRSTR1_SPEC, 1> { TIM3RST_W::new(self) } #[doc = "Bit 4 - TIM6 timer reset"] #[inline(always)] #[must_use] pub fn tim6rst(&mut self) -> TIM6RST_W<APBRSTR1_SPEC, 4> { TIM6RST_W::new(self) } #[doc = "Bit 5 - TIM7 timer reset"] #[inline(always)] #[must_use] pub fn tim7rst(&mut self) -> TIM7RST_W<APBRSTR1_SPEC, 5> { TIM7RST_W::new(self) } #[doc = "Bit 14 - SPI2 reset"] #[inline(always)] #[must_use] pub fn spi2rst(&mut self) -> SPI2RST_W<APBRSTR1_SPEC, 14> { SPI2RST_W::new(self) } #[doc = "Bit 17 - USART2 reset"] #[inline(always)] #[must_use] pub fn usart2rst(&mut self) -> USART2RST_W<APBRSTR1_SPEC, 17> { USART2RST_W::new(self) } #[doc = "Bit 18 - USART3 reset"] #[inline(always)] #[must_use] pub fn usart3rst(&mut self) -> USART3RST_W<APBRSTR1_SPEC, 18> { USART3RST_W::new(self) } #[doc = "Bit 19 - USART4 reset"] #[inline(always)] #[must_use] pub fn usart4rst(&mut self) -> USART4RST_W<APBRSTR1_SPEC, 19> { USART4RST_W::new(self) } #[doc = "Bit 21 - I2C1 reset"] #[inline(always)] #[must_use] pub fn i2c1rst(&mut self) -> I2C1RST_W<APBRSTR1_SPEC, 21> { I2C1RST_W::new(self) } #[doc = "Bit 22 - I2C2 reset"] #[inline(always)] #[must_use] pub fn i2c2rst(&mut self) -> I2C2RST_W<APBRSTR1_SPEC, 22> { I2C2RST_W::new(self) } #[doc = "Bit 27 - Debug support reset"] #[inline(always)] #[must_use] pub fn dbgrst(&mut self) -> DBGRST_W<APBRSTR1_SPEC, 27> { DBGRST_W::new(self) } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] #[must_use] pub fn pwrrst(&mut self) -> PWRRST_W<APBRSTR1_SPEC, 28> { PWRRST_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 = "APB peripheral reset register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apbrstr1::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 [`apbrstr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APBRSTR1_SPEC; impl crate::RegisterSpec for APBRSTR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apbrstr1::R`](R) reader structure"] impl crate::Readable for APBRSTR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`apbrstr1::W`](W) writer structure"] impl crate::Writable for APBRSTR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APBRSTR1 to value 0"] impl crate::Resettable for APBRSTR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! This crate is responsible of providing [FFI] interface for `SVM`. //! //! [FFI]: https://doc.rust-lang.org/nomicon/ffi.html #![deny(missing_docs)] #![deny(unused)] #![deny(dead_code)] #![deny(unreachable_code)] #![feature(vec_into_raw_parts)] mod address; mod byte_array; mod macros; mod r#ref; mod state; pub mod tracking; pub use byte_array::svm_byte_array; pub use tracking::{svm_resource_iter_t, svm_resource_t}; use std::ffi::c_void; use svm_types::Type; mod api; mod error; mod result; #[cfg(feature = "default-rocksdb")] pub(crate) use error::raw_utf8_error; pub(crate) use error::{raw_error, raw_io_error, raw_validate_error}; #[cfg(feature = "default-rocksdb")] pub use api::svm_runtime_create; #[cfg(feature = "default-memory")] pub use api::svm_memory_runtime_create; /// `SVM` FFI Interface #[rustfmt::skip] pub use api::{ // Transactions Validation svm_validate_deploy, svm_validate_spawn, svm_validate_call, // Transactions Execution svm_deploy, svm_spawn, svm_verify, svm_call, // Destroy svm_runtime_destroy, svm_byte_array_destroy, // Allocation svm_envelope_alloc, svm_message_alloc, svm_context_alloc, // Resources tracking svm_total_live_resources, svm_resource_iter_new, svm_resource_iter_next, svm_resource_iter_destroy, svm_resource_destroy, svm_resource_type_name_resolve, svm_resource_type_name_destroy }; pub use result::svm_result_t; /// Receives an object, and returns a raw `*mut c_void` pointer to it. #[must_use] #[inline] pub fn into_raw<T: 'static>(ty: Type, obj: T) -> *mut c_void { let ptr: *mut T = Box::into_raw(Box::new(obj)); tracking::increment_live(ty); ptr as _ } /// Given a **pointer** to an object (of type `T`) allocated on the heap, returns the object (uses `Box::from_raw`) #[must_use] #[inline] pub(crate) unsafe fn from_raw<T: 'static>(ty: Type, ptr: *mut T) -> T { tracking::decrement_live(ty); *Box::from_raw(ptr) } /// Receives a `*const c_void` pointer and returns the a mutable borrowed reference to the underlying object. /// /// # Safety /// /// * If raw pointer doesn't point to a struct of type T it's an U.B /// * In case the referenced struct is already borrowed it's an U.B #[must_use] #[inline] pub(crate) unsafe fn as_mut<'a, T>(ptr: *mut c_void) -> &'a mut T { &mut *(ptr as *mut T) }
use crate::core::shared_access_signature::{format_date, format_form, sign, SasProtocol, SasToken}; use chrono::{DateTime, Utc}; use std::{fmt, marker::PhantomData}; const SERVICE_SAS_VERSION: &str = "2020-06-12"; pub enum BlobSignedResource { Blob, // b BlobVersion, // bv BlobSnapshot, // bs Container, // c Directory, // d } impl fmt::Display for BlobSignedResource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Self::Blob => write!(f, "b"), Self::BlobVersion => write!(f, "bv"), Self::BlobSnapshot => write!(f, "bs"), Self::Container => write!(f, "c"), Self::Directory => write!(f, "d"), } } } #[derive(Default)] pub struct BlobSasPermissions { pub read: bool, // r - Container | Directory | Blob pub add: bool, // a - Container | Directory | Blob pub create: bool, // c - Container | Directory | Blob pub write: bool, // w - Container | Directory | Blob pub delete: bool, // d - Container | Directory | Blob pub delete_version: bool, // x - Container | Blob pub permantent_delete: bool, // y - Blob pub list: bool, // l - Container | Directory pub tags: bool, // t - Tags pub move_: bool, // m - Container | Directory | Blob pub execute: bool, // e - Container | Directory | Blob pub ownership: bool, // o - Container | Directory | Blob pub permissions: bool, // p - Container | Directory | Blob // SetImmunabilityPolicy: bool, // i -- container } impl fmt::Display for BlobSasPermissions { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.read { write!(f, "r")? }; if self.add { write!(f, "a")? }; if self.create { write!(f, "c")? }; if self.write { write!(f, "w")? }; if self.delete { write!(f, "d")? }; if self.delete_version { write!(f, "x")? }; if self.permantent_delete { write!(f, "y")? }; if self.list { write!(f, "l")? }; if self.tags { write!(f, "t")? }; if self.move_ { write!(f, "m")? }; if self.execute { write!(f, "e")? }; if self.ownership { write!(f, "o")? }; if self.permissions { write!(f, "p")? }; Ok(()) } } pub struct BlobSharedAccessSignature { key: String, canonicalized_resource: String, signed_permissions: BlobSasPermissions, // sp signed_start: Option<DateTime<Utc>>, // st signed_expiry: DateTime<Utc>, // se signed_identifier: Option<String>, signed_ip: Option<String>, signed_protocol: Option<SasProtocol>, signed_resource: BlobSignedResource, } impl BlobSharedAccessSignature { fn sign(&self) -> String { let content = vec![ self.signed_permissions.to_string(), self.signed_start.map_or("".to_string(), format_date), format_date(self.signed_expiry), self.canonicalized_resource.clone(), self.signed_identifier .as_ref() .unwrap_or(&"".to_string()) .to_string(), self.signed_ip .as_ref() .unwrap_or(&"".to_string()) .to_string(), self.signed_protocol .map(|x| x.to_string()) .unwrap_or_else(|| "".to_string()), SERVICE_SAS_VERSION.to_string(), self.signed_resource.to_string(), "".to_string(), // snapshot time "".to_string(), // rscd "".to_string(), // rscc "".to_string(), // rsce "".to_string(), // rscl "".to_string(), // rsct ]; sign(&self.key, &content.join("\n")) } } impl SasToken for BlobSharedAccessSignature { fn token(&self) -> String { let mut elements: Vec<String> = vec![ format!("sv={}", SERVICE_SAS_VERSION), format!("sp={}", self.signed_permissions), format!("sr={}", self.signed_resource), format!("se={}", format_form(format_date(self.signed_expiry))), ]; if let Some(start) = &self.signed_start { elements.push(format!("st={}", format_form(format_date(*start)))) } if let Some(ip) = &self.signed_ip { elements.push(format!("sip={}", ip)) } if let Some(protocol) = &self.signed_protocol { elements.push(format!("spr={}", protocol)) } let sig = self.sign(); elements.push(format!("sig={}", format_form(sig))); elements.join("&") } } pub struct SetPerms {} pub struct SetResources {} pub struct SetExpiry {} #[derive(Default)] pub struct BlobSharedAccessSignatureBuilder<T1, T2, T3> { _phantom: PhantomData<(T1, T2, T3)>, key: String, canonicalized_resource: String, // required signed_permissions: Option<BlobSasPermissions>, signed_expiry: Option<DateTime<Utc>>, signed_resource: Option<BlobSignedResource>, // optional signed_start: Option<DateTime<Utc>>, signed_identifier: Option<String>, signed_ip: Option<String>, signed_protocol: Option<SasProtocol>, } impl BlobSharedAccessSignatureBuilder<(), (), ()> { pub fn new( key: String, canonicalized_resource: String, ) -> BlobSharedAccessSignatureBuilder<(), (), ()> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key, canonicalized_resource, signed_permissions: None, signed_expiry: None, signed_resource: None, signed_start: None, signed_identifier: None, signed_ip: None, signed_protocol: None, } } } impl<T1, T2, T3> BlobSharedAccessSignatureBuilder<T1, T2, T3> { pub fn with_start( self, signed_start: DateTime<Utc>, ) -> BlobSharedAccessSignatureBuilder<T1, T2, T3> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: self.signed_resource, signed_expiry: self.signed_expiry, signed_start: Some(signed_start), signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } pub fn with_ip(self, signed_ip: String) -> BlobSharedAccessSignatureBuilder<T1, T2, T3> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: self.signed_resource, signed_expiry: self.signed_expiry, signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: Some(signed_ip), } } pub fn with_identifier( self, signed_identifier: String, ) -> BlobSharedAccessSignatureBuilder<T1, T2, T3> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: self.signed_resource, signed_expiry: self.signed_expiry, signed_start: self.signed_start, signed_identifier: Some(signed_identifier), signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } pub fn with_protocol( self, signed_protocol: SasProtocol, ) -> BlobSharedAccessSignatureBuilder<T1, T2, T3> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: self.signed_resource, signed_expiry: self.signed_expiry, signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: Some(signed_protocol), signed_ip: self.signed_ip, } } } impl BlobSharedAccessSignatureBuilder<SetPerms, SetResources, SetExpiry> { pub fn finalize(self) -> BlobSharedAccessSignature { BlobSharedAccessSignature { key: self.key.clone(), canonicalized_resource: self.canonicalized_resource.clone(), signed_permissions: self.signed_permissions.unwrap(), signed_resource: self.signed_resource.unwrap(), signed_expiry: self.signed_expiry.unwrap(), signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } } impl<T1, T2> BlobSharedAccessSignatureBuilder<(), T1, T2> { pub fn with_permissions( self, permissions: BlobSasPermissions, ) -> BlobSharedAccessSignatureBuilder<SetPerms, T1, T2> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: Some(permissions), signed_resource: self.signed_resource, signed_expiry: self.signed_expiry, signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } } impl<T1, T2> BlobSharedAccessSignatureBuilder<T1, (), T2> { pub fn with_resources( self, signed_resource: BlobSignedResource, ) -> BlobSharedAccessSignatureBuilder<T1, SetResources, T2> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: Some(signed_resource), signed_expiry: self.signed_expiry, signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } } impl<T1, T2> BlobSharedAccessSignatureBuilder<T1, T2, ()> { pub fn with_expiry( self, signed_expiry: DateTime<Utc>, ) -> BlobSharedAccessSignatureBuilder<T1, T2, SetExpiry> { BlobSharedAccessSignatureBuilder { _phantom: PhantomData, key: self.key, canonicalized_resource: self.canonicalized_resource, signed_permissions: self.signed_permissions, signed_resource: self.signed_resource, signed_expiry: Some(signed_expiry), signed_start: self.signed_start, signed_identifier: self.signed_identifier, signed_protocol: self.signed_protocol, signed_ip: self.signed_ip, } } }
//! This module deals with configuration data including the management of the list of secrets #![allow(clippy::filter_map)] use crate::image::CONF_LINE_IDENTIFIER__CONTROL; use crate::image::CONF_LINE_IDENTIFIER__IMAGE; use rand::Rng; use thiserror::Error; //use serde::Deserialize; use serde_derive::Deserialize; /// Tags comment lines in the configuration file. pub const CONF_LINE_IDENTIFIER__COMMENT: char = '#'; /// Optionally tags secret strings in config-file. Can be omitted. pub const CONF_LINE_IDENTIFIER__WORD: char = '-'; /// A tag to enclose parts of the secret to be visible from the start, e.g. /// "guess_-me_" will be displayed in the game as "_ _ _ _ _ - m e" pub const CONF_LINE_SECRET_MODIFIER__VISIBLE: char = '_'; /// A tag to insert a linebreak when the secret is displayed. pub const CONF_LINE_SECRET_MODIFIER__LINEBREAK1: char = '\n'; pub const CONF_LINE_SECRET_MODIFIER__LINEBREAK2: char = '|'; // Custom error type used expressing potential syntax errors when parsing the configuration file. #[derive(Error, Debug)] pub enum ConfigParseError { #[error( "Syntax error in line {line_number:?}: `{line}`\n\n\ The game modifier must be one of the following:\n\ :traditional-rewarding\n\ :success-rewarding\n\n\ Edit config file and start again.\n" )] GameModifier { line_number: usize, line: String }, #[error( "Syntax error in line {line_number:?}: `{line}`\n\n\ The first character of every non-empty line has to be one of the following:\n\ any letter or digit (secret string),\n\ '#' (comment line),\n\ '-' (secret string),\n\ '|' (ASCII-Art image) or\n\ ':' (game modifier).\n\n\ Edit config file and start again.\n" )] LineIdentifier { line_number: usize, line: String }, #[error["No image data found."]] NoImageData, #[error["A config file must have a least one secret string, which is\n\ a non-empty line starting with a letter, digit, '_' or '-'."]] NoSecretString, #[error["Could not parse the proprietary format, because this is\n\ meant to be in (erroneous) YAML format."]] NotInProprietaryFormat, #[error( "Syntax error: Please follow the example below.\n\ (The custom image is optional, it's lines start with a space.):\n\ \t------------------------------\n\ \tsecrets: \n\ \t- guess me\n\ \t- \"guess me: with colon\"\n\ \t- line| break\n\ \t- _disclose _partly\n\ \n\ \timage: |1\n\ \t :\n\ \t |_|>\n\ \t------------------------------\n\ {0}" )] NotInYamlFormat(#[from] serde_yaml::Error), #[error["First line must be: `secrets:` (no spaces allowed before)."]] YamlSecretsLineMissing, } /// We need this because `serde_yaml::Error` does not implement `PartialEq`. /// We compare only types. impl PartialEq for ConfigParseError { fn eq(&self, other: &Self) -> bool { std::mem::discriminant(self) == std::mem::discriminant(other) && (self.to_string() == other.to_string()) } } /// A dictionary holding all secret sentences from among whom one is chosen randomly at the /// beginning of the game. #[derive(Debug, PartialEq, Deserialize)] pub struct Dict { secrets: Vec<String>, } impl Dict { /// First try ot parse YAML, if it fails try the depreciated proprietary format and populate the dictionary /// with secrets. pub fn from_formatted(lines: &str) -> Result<Self, ConfigParseError> { // If both return an error, return the first one here. Self::from_yaml(&lines).or_else(|e| Self::from_proprietary(&lines).or(Err(e))) } /// Parse configuration file as toml data. pub fn from_yaml(lines: &str) -> Result<Self, ConfigParseError> { // Trim BOM let lines = lines.trim_start_matches('\u{feff}'); for l in lines .lines() .filter(|s| !s.trim_start().starts_with('#')) .filter(|s| s.trim() != "") { if l.trim_end() == "secrets:" { break; } else { return Err(ConfigParseError::YamlSecretsLineMissing); } } let dict: Dict = serde_yaml::from_str(&lines)?; Ok(dict) } /// Parse the old configuration data format. fn from_proprietary(lines: &str) -> Result<Self, ConfigParseError> { // remove BOM let lines = lines.trim_start_matches("\u{feff}"); if lines .lines() .any(|s| s.trim().starts_with("secrets") || s.trim().starts_with("image:")) { return Err(ConfigParseError::NotInProprietaryFormat {}); }; let mut file_syntax_test2: Result<(), ConfigParseError> = Ok(()); let wordlist = // remove Unicode BOM if present (\u{feff} has in UTF8 3 bytes). lines // interpret identifier line .lines() .enumerate() .filter(|&(_,l)|!( l.trim().is_empty() || l.starts_with(CONF_LINE_IDENTIFIER__COMMENT) || l.starts_with(CONF_LINE_IDENTIFIER__CONTROL) || l.starts_with(CONF_LINE_IDENTIFIER__IMAGE) ) ) .map(|(n,l)| if l.starts_with(CONF_LINE_IDENTIFIER__WORD) { l[1..].trim().to_string() } else { // Lines starting alphanumerically are secret strings also. // We can safely unwrap here since all empty lines had been filtered. let c = l.trim_end().chars().next().unwrap(); if c.is_alphabetic() || c.is_digit(10) || c == CONF_LINE_SECRET_MODIFIER__VISIBLE { l.trim().to_string() } else { // we only save the first error if file_syntax_test2.is_ok() { file_syntax_test2 = Err(ConfigParseError::LineIdentifier { line_number: n+1, line: l.to_string() }); }; // This will never be used but we have to return something "".to_string() } } ) .collect::<Vec<String>>(); file_syntax_test2?; if wordlist.is_empty() { return Err(ConfigParseError::NoSecretString {}); } Ok(Dict { secrets: wordlist }) } /// Chooses randomly one secret from the dictionary and removes the secret from list pub fn get_random_secret(&mut self) -> Option<String> { match self.secrets.len() { 0 => None, 1 => Some(self.secrets.swap_remove(0)), _ => { let mut rng = rand::thread_rng(); let i = rng.gen_range(0, &self.secrets.len() - 1); Some(self.secrets.swap_remove(i)) } } } /// Is there exactly one secret left? pub fn is_empty(&self) -> bool { self.secrets.is_empty() } /// Add a secret to the list. pub fn add(&mut self, secret: String) { self.secrets.push(secret); } } // *********************** #[cfg(test)] mod tests { use super::ConfigParseError; use super::Dict; /// parse all 3 data types in configuration file format #[test] fn test_new_proprietary() { let config: &str = " # comment guess me hang_man_ _good l_uck :traditional-rewarding "; let dict = Dict::from_formatted(&config).unwrap(); let expected = Dict { secrets: vec![ "guess me".to_string(), "hang_man_".to_string(), "_good l_uck".to_string(), ], }; assert_eq!(dict, expected); let config: &str = "guess me"; let dict = Dict::from_formatted(&config); let expected = Ok(Dict { secrets: vec!["guess me".to_string()], // this is default }); assert_eq!(dict, expected); // indent of comments is not allowed let config = "\n\n\n # comment"; let dict = Dict::from_proprietary(&config); let expected = Err(ConfigParseError::LineIdentifier { line_number: 4, line: " # comment".to_string(), }); assert_eq!(dict, expected); // configuration must define at least one secret let config = "# nothing but comment"; let dict = Dict::from_proprietary(&config); let expected = Err(ConfigParseError::NoSecretString {}); assert_eq!(dict, expected); let config = "one secret\n\n :traditional-rewarding"; let dict = Dict::from_proprietary(&config); let expected = Err(ConfigParseError::LineIdentifier { line_number: 3, line: " :traditional-rewarding".to_string(), }); assert_eq!(dict, expected); } #[test] fn test_new_toml() { let config = "# comment\nsecrets:\n - guess me\n"; let dict = Dict::from_yaml(&config); let expected = Ok(Dict { secrets: vec!["guess me".to_string()], }); assert_eq!(dict, expected); let config = "# comment\nsecrets:\n- guess me\n"; let dict = Dict::from_yaml(&config); let expected = Ok(Dict { secrets: vec!["guess me".to_string()], }); assert_eq!(dict, expected); let config = "# comment\nsecrets:\n- 222\n"; let dict = Dict::from_yaml(&config); let expected = Ok(Dict { secrets: vec!["222".to_string()], }); assert_eq!(dict, expected); let config = "sxxxecrets:"; let dict = Dict::from_yaml(&config).unwrap_err(); assert!(matches!(dict, ConfigParseError::YamlSecretsLineMissing)); let config = " - guess me\nsecrets:\n"; let dict = Dict::from_yaml(&config).unwrap_err(); assert!(matches!(dict, ConfigParseError::YamlSecretsLineMissing)); let config = "# comment\nsecrets:\n guess me\n"; let dict = Dict::from_yaml(&config).unwrap_err(); assert!(matches!(dict, ConfigParseError::NotInYamlFormat(_))); } }
use std::{env, fmt, ops::Deref}; const DEFAULT_CONSUL_ADDR: &str = "http://127.0.0.1:8500"; /// Simple wrapper around a type to keep it from being printed. The wrapped value /// can still be printed if you wish by accessing it directly with .0 pub struct Secret<T>(pub T); impl<T> fmt::Debug for Secret<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Secret{...}") } } impl<T> fmt::Display for Secret<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("****") } } impl<T> Deref for Secret<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Debug)] pub struct Settings { pub consul_addr: String, pub consul_token: Secret<Option<String>>, } impl Settings { pub fn new() -> Self { let consul_addr = env::var("CONSUL_HTTP_ADDR").unwrap_or_else(|_| DEFAULT_CONSUL_ADDR.into()); let consul_token = Secret(env::var("CONSUL_HTTP_TOKEN").ok()); Self { consul_addr, consul_token, } } }
use crate::lib::builders::BuildConfig; use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::models::canister::CanisterPool; use crate::lib::models::canister_id_store::CanisterIdStore; use crate::lib::provider::create_agent_environment; use clap::Clap; /// Builds all or specific canisters from the code in your project. By default, all canisters are built. #[derive(Clap)] pub struct CanisterBuildOpts { /// Specifies the name of the canister to build. /// You must specify either a canister name or the --all option. canister_name: Option<String>, /// Builds all canisters configured in the dfx.json file. #[clap(long, conflicts_with("canister-name"))] all: bool, /// Build canisters without creating them. This can be used to check that canisters build ok. #[clap(long)] check: bool, /// Override the compute network to connect to. By default, the local network is used. /// A valid URL (starting with `http:` or `https:`) can be used here, and a special /// ephemeral network will be created specifically for this request. E.g. /// "http://localhost:12345/" is a valid network name. #[clap(long)] network: Option<String>, } pub fn exec(env: &dyn Environment, opts: CanisterBuildOpts) -> DfxResult { let env = create_agent_environment(env, opts.network)?; let logger = env.get_logger(); // Read the config. let config = env.get_config_or_anyhow()?; // Check the cache. This will only install the cache if there isn't one installed // already. env.get_cache().install()?; let build_mode_check = opts.check; let _all = opts.all; // Option can be None in which case --all was specified let canister_names = config .get_config() .get_canister_names_with_dependencies(opts.canister_name.as_deref())?; // Get pool of canisters to build let canister_pool = CanisterPool::load(&env, build_mode_check, &canister_names)?; // Create canisters on the replica and associate canister ids locally. if build_mode_check { slog::warn!( env.get_logger(), "Building canisters to check they build ok. Canister IDs might be hard coded." ); } else { // CanisterIds would have been set in CanisterPool::load, if available. // This is just to display an error if trying to build before creating the canister. let store = CanisterIdStore::for_env(&env)?; for canister in canister_pool.get_canister_list() { store.get(canister.get_name())?; } } slog::info!(logger, "Building canisters..."); canister_pool.build_or_fail( BuildConfig::from_config(&config)?.with_build_mode_check(build_mode_check), )?; Ok(()) }
/* * Rustの所有権(ムーブ)。 * CreatedAt: 2019-06-01 */ fn main() { let a = String::from("Hello Ownership !!"); // ヒープ領域の確保 let b = a; // ムーブ(ヒープ領域の所有権がポインタ変数`a`から`b`へ移った。所有できるのは必ず1つのポインタ変数のみ) println!("b = {}", b); // println!("a = {}", a); // error[E0382]: use of moved value: `a` }
extern crate iron; extern crate router; use std::env; use iron::{Iron, Request, Response, IronResult}; use router::Router; use iron::status; // Serves a string to the user. Try accessing "/". fn hello(_: &mut Request) -> IronResult<Response> { let resp = Response::with((status::Ok, "Hello world!")); Ok(resp) } // Serves a customized string to the user. Try accessing "/world". fn hello_name(req: &mut Request) -> IronResult<Response> { let params = req.extensions.get::<Router>().unwrap(); let name = params.find("name").unwrap(); let resp = Response::with((status::Ok, format!("Hello, {}!", name))); Ok(resp) } /// Look up our server port number in PORT, for compatibility with Heroku. fn get_server_port() -> u16 { env::var("PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(8080) } /// Configure and run our server. fn main() { // Set up our URL router. let mut router: Router = Router::new(); router.get("/", hello, "index"); router.get("/:name", hello_name, "name"); // Run the server. Iron::new(router).http(("0.0.0.0", get_server_port())).unwrap(); }
//! Provide animation time signals. //! //! Each time signal is in milliseconds, and starts from 0. Any live //! animation time signals will be updated each frame, and are strictly //! increasing. //! //! For example, this will show a progress bar that takes 10 seconds to //! fill: //! //! ```no_run //! # use silkenweb::{animation::finite_animation, elements::progress, mount}; //! //! mount( //! "app", //! progress() //! .value(finite_animation(10000.0).map(|&time| time as f32)) //! .max(10000.0), //! ); //! ``` use std::cell::Cell; use silkenweb_dom::render::{animation_timestamp, request_render_updates}; use silkenweb_reactive::signal::{ReadSignal, SignalReceiver}; #[derive(Default)] struct AnimationTime { base: Cell<Option<f64>>, } impl SignalReceiver<f64, f64> for AnimationTime { fn receive(&self, x: &f64) -> f64 { let base = self.base.get(); if let Some(base) = base { (x - base).max(0.0) } else { self.base.set(Some(*x)); 0.0 } } } /// Provide an infinite time signal for animations. /// /// The signal will tick each frame until it is dropped. /// /// See [module-level documentation](self) for more details. pub fn infinite_animation() -> ReadSignal<f64> { animation_timestamp() .map_to(AnimationTime::default()) .map(|time| { request_render_updates(); *time }) .only_changes() } /// Provide a finite time signal for animations. /// /// The signal will tick each frame until `duration_millis` has elapsed. The /// value will never exceed `duration_millis` and the last value will be /// `duration_millis`, unless the signal is dropped first. /// /// See [module-level documentation](self) for more details. pub fn finite_animation(duration_millis: f64) -> ReadSignal<f64> { animation_timestamp() .map_to(AnimationTime::default()) .map(move |&time| { if time < duration_millis { request_render_updates(); time } else { duration_millis } }) .only_changes() }
use std::{ io::{self, stdin, Write}, process, }; use crate::preloader::ADDR; use crate::compiler::npm_install; use colored::*; use once_cell::sync::Lazy; use std::sync::Mutex; pub static VERBOSE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false)); pub fn log(text: String, verbose: bool) { if !verbose { println!("{}", text); } else if verbose && *VERBOSE.lock().unwrap() { println!("{}: {}", "[VERBOSE LOGGER]".blue(), text); } } pub fn spawn() { npm_install().unwrap(); std::thread::spawn(move || loop { print!( "[{} @{}] => ", "TIDE-WEBSERVER".yellow(), ADDR.green().italic() ); io::stdout().flush().unwrap(); let mut line = String::new(); stdin().read_line(&mut line).unwrap(); match line.trim_end_matches('\n').to_ascii_lowercase().as_str() { "exit" => process::exit(0x0100), "verbose" => { println!("{}", "Expected option <on>, <off>, or <toggle>".red()); } "verbose on" => { *VERBOSE.lock().unwrap() = true; println!("{} {}", "Verbose logging is now".blue(), " ON ".black().on_green()); }, "verbose off" => { *VERBOSE.lock().unwrap() = false; println!("{} {}", "Verbose logging is now".blue(), " OFF ".black().on_red()); }, "verbose toggle" => { let mut b = VERBOSE.lock().unwrap(); *b = !*b; match *b { true => println!("{} {}", "Verbose logging is now".blue(), " ON ".black().on_green()), false => println!("{} {}", "Verbose logging is now".blue(), " OFF ".black().on_red()) } } "" => (), _ => println!( "{}", format!( "\"{}\" is not a recognized command.", line.trim_end_matches('\n') ) .red() ), } }); }
use clap::{App, Arg}; use rustbg::extitem::ExtItem; use rustbg::search::Search; use rustbg::Config; use std::fs::File; use std::io::BufReader; use std::io::{self, BufRead, Write}; use std::sync::RwLock; const UAGENT: &str = "RarSpyder/1.0 (Linux x86_64;) Rust/1.44.0-nightly"; const MIRROR: &str = "rarbgproxied.org"; lazy_static::lazy_static! { static ref CONFIG: RwLock<Config> = { let home = std::env::var("HOME").unwrap(); if let Ok(x) = File::open(format!("{}/.config/rarbg/config", home)) .and_then(|x| Ok(BufReader::new(x))) { if let Ok(x) = serde_json::from_reader(x) { return RwLock::new(x); } } let config = Config { cookie: String::new(), base_url: MIRROR.to_string() }; config.dump_config(); RwLock::new(config) }; } fn update_cookie(cookie: String) { if CONFIG.read().unwrap().cookie == cookie { return; } CONFIG.write().unwrap().cookie = cookie; CONFIG.write().unwrap().dump_config(); } #[tokio::main] async fn main() { let matches = App::new("Rustbg") .version("0.1") .author("Valerian G. <valerian.garleanu@pm.me>") .about("command-line interface for rarbg.") .arg( Arg::with_name("name") .short("n") .long("name") .value_name("NAME") .required(true) .help("Name or imdb tag you want to search for.") .takes_value(true), ) .arg( Arg::with_name("type") .short("t") .help("Select media type") .possible_values(&["movies", "tv", "porn", "all"]) .default_value("all") .required(false), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity"), ) .get_matches(); let mut search = Search::new( MIRROR.into(), CONFIG.read().unwrap().cookie.clone(), UAGENT.into(), ); let to_search = matches.value_of("name").unwrap(); println!("Searching for {}", to_search); let items = search.search(to_search.to_string()).await.unwrap(); println!("Found {} results", items.len()); for (idx, item) in items.iter().rev().enumerate() { println!( "[{}] {} ({} {}/{}) Uploaded by: {}", idx, item.name, item.size, item.seeds, item.leech, item.uploader ); } print!("==> "); io::stdout().flush().unwrap(); let stdin = io::stdin(); let input = items.len() - 1 - stdin .lock() .lines() .next() .unwrap() .unwrap() .parse::<usize>() .unwrap(); let item = items[input].clone(); let mut ext = ExtItem::new(search.get_cookie(), MIRROR.into(), item.id, UAGENT.into()); ext.fetch().await.unwrap(); println!("{}", ext.magnet); update_cookie(search.get_cookie()); }
use super::RingBufferStream; use ds::RingSlice; use ds::Slice; use protocol::{Protocol, RequestId}; use std::sync::Arc; pub(crate) struct Item { data: ResponseData, done: Option<(usize, Arc<RingBufferStream>)>, } pub struct ResponseData { data: RingSlice, req_id: RequestId, seq: usize, // response的seq } impl ResponseData { pub fn from(data: RingSlice, rid: RequestId, resp_seq: usize) -> Self { Self { data: data, req_id: rid, seq: resp_seq, } } #[inline(always)] pub fn data(&self) -> &RingSlice { &self.data } #[inline(always)] pub fn rid(&self) -> &RequestId { &self.req_id } #[inline(always)] pub fn seq(&self) -> usize { self.seq } } pub struct Response { pub(crate) items: Vec<Item>, } impl Response { fn _from(slice: ResponseData, done: Option<(usize, Arc<RingBufferStream>)>) -> Self { Self { items: vec![Item { data: slice, done: done, }], } } pub fn from(slice: ResponseData, cid: usize, release: Arc<RingBufferStream>) -> Self { Self::_from(slice, Some((cid, release))) } pub fn append(&mut self, other: Response) { self.items.extend(other.items); } pub(crate) fn into_reader<P>(self, parser: &P) -> ResponseReader<'_, P> { ResponseReader { idx: 0, items: self.items, parser: parser, } } pub fn len(&self) -> usize { let mut l = 0; for item in self.items.iter() { l += item.available(); } l } pub fn iter(&self) -> ResponseRingSliceIter { ResponseRingSliceIter { response: self, idx: 0, } } } pub struct ResponseRingSliceIter<'a> { idx: usize, response: &'a Response, } impl<'a> Iterator for ResponseRingSliceIter<'a> { type Item = &'a RingSlice; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.idx >= self.response.items.len() { None } else { let idx = self.idx; self.idx += 1; unsafe { Some(&self.response.items.get_unchecked(idx)) } } } } unsafe impl Send for Response {} unsafe impl Sync for Response {} impl AsRef<RingSlice> for Response { // 如果有多个item,应该使迭代方式 #[inline(always)] fn as_ref(&self) -> &RingSlice { debug_assert!(self.items.len() == 1); unsafe { &self.items.get_unchecked(self.items.len() - 1) } } } impl Drop for Item { fn drop(&mut self) { if let Some((cid, done)) = self.done.take() { done.response_done(cid, &self.data); } } } impl AsRef<RingSlice> for Item { fn as_ref(&self) -> &RingSlice { &self.data.data } } use std::ops::{Deref, DerefMut}; impl Deref for Item { type Target = RingSlice; fn deref(&self) -> &Self::Target { &self.data.data } } impl DerefMut for Item { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data.data } } pub(crate) struct ResponseReader<'a, P> { idx: usize, items: Vec<Item>, parser: &'a P, } impl<'a, P> Iterator for ResponseReader<'a, P> where P: Protocol, { type Item = Slice; fn next(&mut self) -> Option<Self::Item> { let len = self.items.len(); while self.idx < len { let item = unsafe { self.items.get_unchecked_mut(self.idx) }; let eof = self.parser.trim_eof(&item); let avail = item.available(); if avail > 0 { if self.idx < len - 1 { if avail > eof { let mut data = item.take_slice(); if item.available() < eof { data.backwards(eof - item.available()); } return Some(data); } } else { return Some(item.take_slice()); } } self.idx += 1; } None } } impl<'a, P> ResponseReader<'a, P> where P: Protocol, { #[inline] pub fn available(&self) -> usize { let mut len = 0; for i in self.idx..self.items.len() { len += unsafe { self.items.get_unchecked(i).available() }; } len } }
#[doc = "Register `APB1RSTR1` reader"] pub type R = crate::R<APB1RSTR1_SPEC>; #[doc = "Register `APB1RSTR1` writer"] pub type W = crate::W<APB1RSTR1_SPEC>; #[doc = "Field `TIM2RST` reader - TIM2 timer reset"] pub type TIM2RST_R = crate::BitReader<TIM2RST_A>; #[doc = "TIM2 timer reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIM2RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset TIMx"] Reset = 1, } impl From<TIM2RST_A> for bool { #[inline(always)] fn from(variant: TIM2RST_A) -> Self { variant as u8 != 0 } } impl TIM2RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM2RST_A { match self.bits { false => TIM2RST_A::NoEffect, true => TIM2RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == TIM2RST_A::NoEffect } #[doc = "Reset TIMx"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == TIM2RST_A::Reset } } #[doc = "Field `TIM2RST` writer - TIM2 timer reset"] pub type TIM2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIM2RST_A>; impl<'a, REG, const O: u8> TIM2RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(TIM2RST_A::NoEffect) } #[doc = "Reset TIMx"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(TIM2RST_A::Reset) } } #[doc = "Field `TIM3RST` reader - TIM3 timer reset"] pub use TIM2RST_R as TIM3RST_R; #[doc = "Field `TIM4RST` reader - TIM3 timer reset"] pub use TIM2RST_R as TIM4RST_R; #[doc = "Field `TIM5RST` reader - TIM5 timer reset"] pub use TIM2RST_R as TIM5RST_R; #[doc = "Field `TIM6RST` reader - TIM6 timer reset"] pub use TIM2RST_R as TIM6RST_R; #[doc = "Field `TIM7RST` reader - TIM7 timer reset"] pub use TIM2RST_R as TIM7RST_R; #[doc = "Field `TIM3RST` writer - TIM3 timer reset"] pub use TIM2RST_W as TIM3RST_W; #[doc = "Field `TIM4RST` writer - TIM3 timer reset"] pub use TIM2RST_W as TIM4RST_W; #[doc = "Field `TIM5RST` writer - TIM5 timer reset"] pub use TIM2RST_W as TIM5RST_W; #[doc = "Field `TIM6RST` writer - TIM6 timer reset"] pub use TIM2RST_W as TIM6RST_W; #[doc = "Field `TIM7RST` writer - TIM7 timer reset"] pub use TIM2RST_W as TIM7RST_W; #[doc = "Field `SPI2RST` reader - SPI2 reset"] pub type SPI2RST_R = crate::BitReader<SPI2RST_A>; #[doc = "SPI2 reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SPI2RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset SPIx"] Reset = 1, } impl From<SPI2RST_A> for bool { #[inline(always)] fn from(variant: SPI2RST_A) -> Self { variant as u8 != 0 } } impl SPI2RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SPI2RST_A { match self.bits { false => SPI2RST_A::NoEffect, true => SPI2RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == SPI2RST_A::NoEffect } #[doc = "Reset SPIx"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == SPI2RST_A::Reset } } #[doc = "Field `SPI2RST` writer - SPI2 reset"] pub type SPI2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, SPI2RST_A>; impl<'a, REG, const O: u8> SPI2RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(SPI2RST_A::NoEffect) } #[doc = "Reset SPIx"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(SPI2RST_A::Reset) } } #[doc = "Field `SPI3RST` reader - SPI3 reset"] pub use SPI2RST_R as SPI3RST_R; #[doc = "Field `SPI3RST` writer - SPI3 reset"] pub use SPI2RST_W as SPI3RST_W; #[doc = "Field `USART2RST` reader - USART2 reset"] pub type USART2RST_R = crate::BitReader<USART2RST_A>; #[doc = "USART2 reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum USART2RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset UARTx"] Reset = 1, } impl From<USART2RST_A> for bool { #[inline(always)] fn from(variant: USART2RST_A) -> Self { variant as u8 != 0 } } impl USART2RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USART2RST_A { match self.bits { false => USART2RST_A::NoEffect, true => USART2RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == USART2RST_A::NoEffect } #[doc = "Reset UARTx"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == USART2RST_A::Reset } } #[doc = "Field `USART2RST` writer - USART2 reset"] pub type USART2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, USART2RST_A>; impl<'a, REG, const O: u8> USART2RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(USART2RST_A::NoEffect) } #[doc = "Reset UARTx"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(USART2RST_A::Reset) } } #[doc = "Field `USART3RST` reader - USART3 reset"] pub use USART2RST_R as USART3RST_R; #[doc = "Field `USART3RST` writer - USART3 reset"] pub use USART2RST_W as USART3RST_W; #[doc = "Field `UART4RST` reader - UART4 reset"] pub type UART4RST_R = crate::BitReader; #[doc = "Field `UART4RST` writer - UART4 reset"] pub type UART4RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UART5RST` reader - UART5 reset"] pub type UART5RST_R = crate::BitReader; #[doc = "Field `UART5RST` writer - UART5 reset"] pub type UART5RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C1RST` reader - I2C1 reset"] pub type I2C1RST_R = crate::BitReader<I2C1RST_A>; #[doc = "I2C1 reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum I2C1RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset I2Cx"] Reset = 1, } impl From<I2C1RST_A> for bool { #[inline(always)] fn from(variant: I2C1RST_A) -> Self { variant as u8 != 0 } } impl I2C1RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> I2C1RST_A { match self.bits { false => I2C1RST_A::NoEffect, true => I2C1RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == I2C1RST_A::NoEffect } #[doc = "Reset I2Cx"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == I2C1RST_A::Reset } } #[doc = "Field `I2C1RST` writer - I2C1 reset"] pub type I2C1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, I2C1RST_A>; impl<'a, REG, const O: u8> I2C1RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(I2C1RST_A::NoEffect) } #[doc = "Reset I2Cx"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(I2C1RST_A::Reset) } } #[doc = "Field `I2C2RST` reader - I2C2 reset"] pub use I2C1RST_R as I2C2RST_R; #[doc = "Field `I2C3RST` reader - I2C3 reset"] pub use I2C1RST_R as I2C3RST_R; #[doc = "Field `I2C2RST` writer - I2C2 reset"] pub use I2C1RST_W as I2C2RST_W; #[doc = "Field `I2C3RST` writer - I2C3 reset"] pub use I2C1RST_W as I2C3RST_W; #[doc = "Field `CRSRST` reader - CRS reset"] pub type CRSRST_R = crate::BitReader<CRSRST_A>; #[doc = "CRS reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CRSRST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset CRS"] Reset = 1, } impl From<CRSRST_A> for bool { #[inline(always)] fn from(variant: CRSRST_A) -> Self { variant as u8 != 0 } } impl CRSRST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CRSRST_A { match self.bits { false => CRSRST_A::NoEffect, true => CRSRST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == CRSRST_A::NoEffect } #[doc = "Reset CRS"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == CRSRST_A::Reset } } #[doc = "Field `CRSRST` writer - CRS reset"] pub type CRSRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CRSRST_A>; impl<'a, REG, const O: u8> CRSRST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(CRSRST_A::NoEffect) } #[doc = "Reset CRS"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(CRSRST_A::Reset) } } #[doc = "Field `CAN1RST` reader - CAN1 reset"] pub type CAN1RST_R = crate::BitReader<CAN1RST_A>; #[doc = "CAN1 reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CAN1RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset CAN1"] Reset = 1, } impl From<CAN1RST_A> for bool { #[inline(always)] fn from(variant: CAN1RST_A) -> Self { variant as u8 != 0 } } impl CAN1RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CAN1RST_A { match self.bits { false => CAN1RST_A::NoEffect, true => CAN1RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == CAN1RST_A::NoEffect } #[doc = "Reset CAN1"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == CAN1RST_A::Reset } } #[doc = "Field `CAN1RST` writer - CAN1 reset"] pub type CAN1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CAN1RST_A>; impl<'a, REG, const O: u8> CAN1RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(CAN1RST_A::NoEffect) } #[doc = "Reset CAN1"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(CAN1RST_A::Reset) } } #[doc = "Field `PWRRST` reader - Power interface reset"] pub type PWRRST_R = crate::BitReader<PWRRST_A>; #[doc = "Power interface reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PWRRST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset PWR"] Reset = 1, } impl From<PWRRST_A> for bool { #[inline(always)] fn from(variant: PWRRST_A) -> Self { variant as u8 != 0 } } impl PWRRST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PWRRST_A { match self.bits { false => PWRRST_A::NoEffect, true => PWRRST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == PWRRST_A::NoEffect } #[doc = "Reset PWR"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == PWRRST_A::Reset } } #[doc = "Field `PWRRST` writer - Power interface reset"] pub type PWRRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, PWRRST_A>; impl<'a, REG, const O: u8> PWRRST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(PWRRST_A::NoEffect) } #[doc = "Reset PWR"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(PWRRST_A::Reset) } } #[doc = "Field `DAC1RST` reader - DAC1 interface reset"] pub type DAC1RST_R = crate::BitReader<DAC1RST_A>; #[doc = "DAC1 interface reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DAC1RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset DAC1"] Reset = 1, } impl From<DAC1RST_A> for bool { #[inline(always)] fn from(variant: DAC1RST_A) -> Self { variant as u8 != 0 } } impl DAC1RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DAC1RST_A { match self.bits { false => DAC1RST_A::NoEffect, true => DAC1RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == DAC1RST_A::NoEffect } #[doc = "Reset DAC1"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == DAC1RST_A::Reset } } #[doc = "Field `DAC1RST` writer - DAC1 interface reset"] pub type DAC1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DAC1RST_A>; impl<'a, REG, const O: u8> DAC1RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(DAC1RST_A::NoEffect) } #[doc = "Reset DAC1"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(DAC1RST_A::Reset) } } #[doc = "Field `OPAMPRST` reader - OPAMP interface reset"] pub type OPAMPRST_R = crate::BitReader<OPAMPRST_A>; #[doc = "OPAMP interface reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OPAMPRST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset OPAMP"] Reset = 1, } impl From<OPAMPRST_A> for bool { #[inline(always)] fn from(variant: OPAMPRST_A) -> Self { variant as u8 != 0 } } impl OPAMPRST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OPAMPRST_A { match self.bits { false => OPAMPRST_A::NoEffect, true => OPAMPRST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == OPAMPRST_A::NoEffect } #[doc = "Reset OPAMP"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == OPAMPRST_A::Reset } } #[doc = "Field `OPAMPRST` writer - OPAMP interface reset"] pub type OPAMPRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, OPAMPRST_A>; impl<'a, REG, const O: u8> OPAMPRST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(OPAMPRST_A::NoEffect) } #[doc = "Reset OPAMP"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(OPAMPRST_A::Reset) } } #[doc = "Field `LPTIM1RST` reader - Low Power Timer 1 reset"] pub type LPTIM1RST_R = crate::BitReader<LPTIM1RST_A>; #[doc = "Low Power Timer 1 reset\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LPTIM1RST_A { #[doc = "0: No effect"] NoEffect = 0, #[doc = "1: Reset LPTIM1"] Reset = 1, } impl From<LPTIM1RST_A> for bool { #[inline(always)] fn from(variant: LPTIM1RST_A) -> Self { variant as u8 != 0 } } impl LPTIM1RST_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM1RST_A { match self.bits { false => LPTIM1RST_A::NoEffect, true => LPTIM1RST_A::Reset, } } #[doc = "No effect"] #[inline(always)] pub fn is_no_effect(&self) -> bool { *self == LPTIM1RST_A::NoEffect } #[doc = "Reset LPTIM1"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == LPTIM1RST_A::Reset } } #[doc = "Field `LPTIM1RST` writer - Low Power Timer 1 reset"] pub type LPTIM1RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LPTIM1RST_A>; impl<'a, REG, const O: u8> LPTIM1RST_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No effect"] #[inline(always)] pub fn no_effect(self) -> &'a mut crate::W<REG> { self.variant(LPTIM1RST_A::NoEffect) } #[doc = "Reset LPTIM1"] #[inline(always)] pub fn reset(self) -> &'a mut crate::W<REG> { self.variant(LPTIM1RST_A::Reset) } } impl R { #[doc = "Bit 0 - TIM2 timer reset"] #[inline(always)] pub fn tim2rst(&self) -> TIM2RST_R { TIM2RST_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TIM3 timer reset"] #[inline(always)] pub fn tim3rst(&self) -> TIM3RST_R { TIM3RST_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - TIM3 timer reset"] #[inline(always)] pub fn tim4rst(&self) -> TIM4RST_R { TIM4RST_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - TIM5 timer reset"] #[inline(always)] pub fn tim5rst(&self) -> TIM5RST_R { TIM5RST_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - TIM6 timer reset"] #[inline(always)] pub fn tim6rst(&self) -> TIM6RST_R { TIM6RST_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TIM7 timer reset"] #[inline(always)] pub fn tim7rst(&self) -> TIM7RST_R { TIM7RST_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 14 - SPI2 reset"] #[inline(always)] pub fn spi2rst(&self) -> SPI2RST_R { SPI2RST_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - SPI3 reset"] #[inline(always)] pub fn spi3rst(&self) -> SPI3RST_R { SPI3RST_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 17 - USART2 reset"] #[inline(always)] pub fn usart2rst(&self) -> USART2RST_R { USART2RST_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - USART3 reset"] #[inline(always)] pub fn usart3rst(&self) -> USART3RST_R { USART3RST_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - UART4 reset"] #[inline(always)] pub fn uart4rst(&self) -> UART4RST_R { UART4RST_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - UART5 reset"] #[inline(always)] pub fn uart5rst(&self) -> UART5RST_R { UART5RST_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - I2C1 reset"] #[inline(always)] pub fn i2c1rst(&self) -> I2C1RST_R { I2C1RST_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 reset"] #[inline(always)] pub fn i2c2rst(&self) -> I2C2RST_R { I2C2RST_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - I2C3 reset"] #[inline(always)] pub fn i2c3rst(&self) -> I2C3RST_R { I2C3RST_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - CRS reset"] #[inline(always)] pub fn crsrst(&self) -> CRSRST_R { CRSRST_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - CAN1 reset"] #[inline(always)] pub fn can1rst(&self) -> CAN1RST_R { CAN1RST_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] pub fn pwrrst(&self) -> PWRRST_R { PWRRST_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - DAC1 interface reset"] #[inline(always)] pub fn dac1rst(&self) -> DAC1RST_R { DAC1RST_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - OPAMP interface reset"] #[inline(always)] pub fn opamprst(&self) -> OPAMPRST_R { OPAMPRST_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - Low Power Timer 1 reset"] #[inline(always)] pub fn lptim1rst(&self) -> LPTIM1RST_R { LPTIM1RST_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - TIM2 timer reset"] #[inline(always)] #[must_use] pub fn tim2rst(&mut self) -> TIM2RST_W<APB1RSTR1_SPEC, 0> { TIM2RST_W::new(self) } #[doc = "Bit 1 - TIM3 timer reset"] #[inline(always)] #[must_use] pub fn tim3rst(&mut self) -> TIM3RST_W<APB1RSTR1_SPEC, 1> { TIM3RST_W::new(self) } #[doc = "Bit 2 - TIM3 timer reset"] #[inline(always)] #[must_use] pub fn tim4rst(&mut self) -> TIM4RST_W<APB1RSTR1_SPEC, 2> { TIM4RST_W::new(self) } #[doc = "Bit 3 - TIM5 timer reset"] #[inline(always)] #[must_use] pub fn tim5rst(&mut self) -> TIM5RST_W<APB1RSTR1_SPEC, 3> { TIM5RST_W::new(self) } #[doc = "Bit 4 - TIM6 timer reset"] #[inline(always)] #[must_use] pub fn tim6rst(&mut self) -> TIM6RST_W<APB1RSTR1_SPEC, 4> { TIM6RST_W::new(self) } #[doc = "Bit 5 - TIM7 timer reset"] #[inline(always)] #[must_use] pub fn tim7rst(&mut self) -> TIM7RST_W<APB1RSTR1_SPEC, 5> { TIM7RST_W::new(self) } #[doc = "Bit 14 - SPI2 reset"] #[inline(always)] #[must_use] pub fn spi2rst(&mut self) -> SPI2RST_W<APB1RSTR1_SPEC, 14> { SPI2RST_W::new(self) } #[doc = "Bit 15 - SPI3 reset"] #[inline(always)] #[must_use] pub fn spi3rst(&mut self) -> SPI3RST_W<APB1RSTR1_SPEC, 15> { SPI3RST_W::new(self) } #[doc = "Bit 17 - USART2 reset"] #[inline(always)] #[must_use] pub fn usart2rst(&mut self) -> USART2RST_W<APB1RSTR1_SPEC, 17> { USART2RST_W::new(self) } #[doc = "Bit 18 - USART3 reset"] #[inline(always)] #[must_use] pub fn usart3rst(&mut self) -> USART3RST_W<APB1RSTR1_SPEC, 18> { USART3RST_W::new(self) } #[doc = "Bit 19 - UART4 reset"] #[inline(always)] #[must_use] pub fn uart4rst(&mut self) -> UART4RST_W<APB1RSTR1_SPEC, 19> { UART4RST_W::new(self) } #[doc = "Bit 20 - UART5 reset"] #[inline(always)] #[must_use] pub fn uart5rst(&mut self) -> UART5RST_W<APB1RSTR1_SPEC, 20> { UART5RST_W::new(self) } #[doc = "Bit 21 - I2C1 reset"] #[inline(always)] #[must_use] pub fn i2c1rst(&mut self) -> I2C1RST_W<APB1RSTR1_SPEC, 21> { I2C1RST_W::new(self) } #[doc = "Bit 22 - I2C2 reset"] #[inline(always)] #[must_use] pub fn i2c2rst(&mut self) -> I2C2RST_W<APB1RSTR1_SPEC, 22> { I2C2RST_W::new(self) } #[doc = "Bit 23 - I2C3 reset"] #[inline(always)] #[must_use] pub fn i2c3rst(&mut self) -> I2C3RST_W<APB1RSTR1_SPEC, 23> { I2C3RST_W::new(self) } #[doc = "Bit 24 - CRS reset"] #[inline(always)] #[must_use] pub fn crsrst(&mut self) -> CRSRST_W<APB1RSTR1_SPEC, 24> { CRSRST_W::new(self) } #[doc = "Bit 25 - CAN1 reset"] #[inline(always)] #[must_use] pub fn can1rst(&mut self) -> CAN1RST_W<APB1RSTR1_SPEC, 25> { CAN1RST_W::new(self) } #[doc = "Bit 28 - Power interface reset"] #[inline(always)] #[must_use] pub fn pwrrst(&mut self) -> PWRRST_W<APB1RSTR1_SPEC, 28> { PWRRST_W::new(self) } #[doc = "Bit 29 - DAC1 interface reset"] #[inline(always)] #[must_use] pub fn dac1rst(&mut self) -> DAC1RST_W<APB1RSTR1_SPEC, 29> { DAC1RST_W::new(self) } #[doc = "Bit 30 - OPAMP interface reset"] #[inline(always)] #[must_use] pub fn opamprst(&mut self) -> OPAMPRST_W<APB1RSTR1_SPEC, 30> { OPAMPRST_W::new(self) } #[doc = "Bit 31 - Low Power Timer 1 reset"] #[inline(always)] #[must_use] pub fn lptim1rst(&mut self) -> LPTIM1RST_W<APB1RSTR1_SPEC, 31> { LPTIM1RST_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 = "APB1 peripheral reset register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1rstr1::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 [`apb1rstr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB1RSTR1_SPEC; impl crate::RegisterSpec for APB1RSTR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb1rstr1::R`](R) reader structure"] impl crate::Readable for APB1RSTR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb1rstr1::W`](W) writer structure"] impl crate::Writable for APB1RSTR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB1RSTR1 to value 0"] impl crate::Resettable for APB1RSTR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `PLLI2SCFGR` reader"] pub type R = crate::R<PLLI2SCFGR_SPEC>; #[doc = "Register `PLLI2SCFGR` writer"] pub type W = crate::W<PLLI2SCFGR_SPEC>; #[doc = "Field `PLLI2SM` reader - Division factor for audio PLL (PLLI2S) input clock"] pub type PLLI2SM_R = crate::FieldReader; #[doc = "Field `PLLI2SM` writer - Division factor for audio PLL (PLLI2S) input clock"] pub type PLLI2SM_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; #[doc = "Field `PLLI2SN` reader - PLLI2S multiplication factor for VCO"] pub type PLLI2SN_R = crate::FieldReader<u16>; #[doc = "Field `PLLI2SN` writer - PLLI2S multiplication factor for VCO"] pub type PLLI2SN_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 9, O, u16>; #[doc = "Field `PLLI2SP` reader - PLLI2S division factor for SPDIF-IN clock"] pub type PLLI2SP_R = crate::FieldReader<PLLI2SP_A>; #[doc = "PLLI2S division factor for SPDIF-IN clock\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum PLLI2SP_A { #[doc = "0: PLL*P=2"] Div2 = 0, #[doc = "1: PLL*P=4"] Div4 = 1, #[doc = "2: PLL*P=6"] Div6 = 2, #[doc = "3: PLL*P=8"] Div8 = 3, } impl From<PLLI2SP_A> for u8 { #[inline(always)] fn from(variant: PLLI2SP_A) -> Self { variant as _ } } impl crate::FieldSpec for PLLI2SP_A { type Ux = u8; } impl PLLI2SP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PLLI2SP_A { match self.bits { 0 => PLLI2SP_A::Div2, 1 => PLLI2SP_A::Div4, 2 => PLLI2SP_A::Div6, 3 => PLLI2SP_A::Div8, _ => unreachable!(), } } #[doc = "PLL*P=2"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == PLLI2SP_A::Div2 } #[doc = "PLL*P=4"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == PLLI2SP_A::Div4 } #[doc = "PLL*P=6"] #[inline(always)] pub fn is_div6(&self) -> bool { *self == PLLI2SP_A::Div6 } #[doc = "PLL*P=8"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == PLLI2SP_A::Div8 } } #[doc = "Field `PLLI2SP` writer - PLLI2S division factor for SPDIF-IN clock"] pub type PLLI2SP_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, PLLI2SP_A>; impl<'a, REG, const O: u8> PLLI2SP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "PLL*P=2"] #[inline(always)] pub fn div2(self) -> &'a mut crate::W<REG> { self.variant(PLLI2SP_A::Div2) } #[doc = "PLL*P=4"] #[inline(always)] pub fn div4(self) -> &'a mut crate::W<REG> { self.variant(PLLI2SP_A::Div4) } #[doc = "PLL*P=6"] #[inline(always)] pub fn div6(self) -> &'a mut crate::W<REG> { self.variant(PLLI2SP_A::Div6) } #[doc = "PLL*P=8"] #[inline(always)] pub fn div8(self) -> &'a mut crate::W<REG> { self.variant(PLLI2SP_A::Div8) } } #[doc = "Field `PLLI2SQ` reader - PLLI2S division factor for SAI1 clock"] pub type PLLI2SQ_R = crate::FieldReader; #[doc = "Field `PLLI2SQ` writer - PLLI2S division factor for SAI1 clock"] pub type PLLI2SQ_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `PLLI2SR` reader - PLLI2S division factor for I2S clocks"] pub type PLLI2SR_R = crate::FieldReader; #[doc = "Field `PLLI2SR` writer - PLLI2S division factor for I2S clocks"] pub type PLLI2SR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; impl R { #[doc = "Bits 0:5 - Division factor for audio PLL (PLLI2S) input clock"] #[inline(always)] pub fn plli2sm(&self) -> PLLI2SM_R { PLLI2SM_R::new((self.bits & 0x3f) as u8) } #[doc = "Bits 6:14 - PLLI2S multiplication factor for VCO"] #[inline(always)] pub fn plli2sn(&self) -> PLLI2SN_R { PLLI2SN_R::new(((self.bits >> 6) & 0x01ff) as u16) } #[doc = "Bits 16:17 - PLLI2S division factor for SPDIF-IN clock"] #[inline(always)] pub fn plli2sp(&self) -> PLLI2SP_R { PLLI2SP_R::new(((self.bits >> 16) & 3) as u8) } #[doc = "Bits 24:27 - PLLI2S division factor for SAI1 clock"] #[inline(always)] pub fn plli2sq(&self) -> PLLI2SQ_R { PLLI2SQ_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:30 - PLLI2S division factor for I2S clocks"] #[inline(always)] pub fn plli2sr(&self) -> PLLI2SR_R { PLLI2SR_R::new(((self.bits >> 28) & 7) as u8) } } impl W { #[doc = "Bits 0:5 - Division factor for audio PLL (PLLI2S) input clock"] #[inline(always)] #[must_use] pub fn plli2sm(&mut self) -> PLLI2SM_W<PLLI2SCFGR_SPEC, 0> { PLLI2SM_W::new(self) } #[doc = "Bits 6:14 - PLLI2S multiplication factor for VCO"] #[inline(always)] #[must_use] pub fn plli2sn(&mut self) -> PLLI2SN_W<PLLI2SCFGR_SPEC, 6> { PLLI2SN_W::new(self) } #[doc = "Bits 16:17 - PLLI2S division factor for SPDIF-IN clock"] #[inline(always)] #[must_use] pub fn plli2sp(&mut self) -> PLLI2SP_W<PLLI2SCFGR_SPEC, 16> { PLLI2SP_W::new(self) } #[doc = "Bits 24:27 - PLLI2S division factor for SAI1 clock"] #[inline(always)] #[must_use] pub fn plli2sq(&mut self) -> PLLI2SQ_W<PLLI2SCFGR_SPEC, 24> { PLLI2SQ_W::new(self) } #[doc = "Bits 28:30 - PLLI2S division factor for I2S clocks"] #[inline(always)] #[must_use] pub fn plli2sr(&mut self) -> PLLI2SR_W<PLLI2SCFGR_SPEC, 28> { PLLI2SR_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 = "PLLI2S configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`plli2scfgr::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 [`plli2scfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PLLI2SCFGR_SPEC; impl crate::RegisterSpec for PLLI2SCFGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`plli2scfgr::R`](R) reader structure"] impl crate::Readable for PLLI2SCFGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`plli2scfgr::W`](W) writer structure"] impl crate::Writable for PLLI2SCFGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets PLLI2SCFGR to value 0x2000_3000"] impl crate::Resettable for PLLI2SCFGR_SPEC { const RESET_VALUE: Self::Ux = 0x2000_3000; }
use apllodb_sql_parser::apllodb_ast; use apllodb_shared_components::ApllodbResult; use apllodb_storage_engine_interface::AlterTableAction; use super::AstTranslator; impl AstTranslator { pub fn alter_table_action( ast_alter_table_action: apllodb_ast::Action, ) -> ApllodbResult<AlterTableAction> { match ast_alter_table_action { apllodb_ast::Action::AddColumnVariant(ac) => { let column_definition = Self::column_definition(ac.column_definition)?; Ok(AlterTableAction::AddColumn { column_definition }) } apllodb_ast::Action::DropColumnVariant(dc) => { let column_name = Self::column_name(dc.column_name)?; Ok(AlterTableAction::DropColumn { column_name }) } } } }
fn main() { let (a, b, c) = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut ws = line.trim_end().split_whitespace(); let n1: u64 = ws.next().unwrap().parse().unwrap(); let n2: u64 = ws.next().unwrap().parse().unwrap(); let n3: u64 = ws.next().unwrap().parse().unwrap(); (n1, n2, n3) }; let stdout = solve(a, b, c); stdout.iter().for_each(|s| { println!("{}", s); }) } fn solve(a: u64, b: u64, c: u64) -> Vec<String> { let ans = c % gcd(a, b) == 0; let mut buf = Vec::new(); buf.push(format!("{}", if ans { "YES" } else { "NO" })); buf } fn gcd(a: u64, b: u64) -> u64 { if b == 0 { a } else { gcd(b, a % b) } } #[test] fn test_solve_1() { assert_eq!(solve(7, 5, 1), vec!("YES")); } #[test] fn test_solve_2() { assert_eq!(solve(2, 2, 1), vec!("NO")); } #[test] fn test_solve_3() { assert_eq!(solve(1, 100, 97), vec!("YES")); } #[test] fn test_solve_4() { assert_eq!(solve(40, 98, 58), vec!("YES")); } #[test] fn test_solve_5() { assert_eq!(solve(77, 42, 36), vec!("NO")); }
use json::JsonValue; use regex::Regex; use super::{match_json_slice, try_to_match_filters, SelectionLens, SelectionLensParser}; struct Sequence { matchers: Vec<Box<dyn SelectionLens>>, } impl SelectionLens for Sequence { fn select<'a>(&self, input: Option<&'a JsonValue>) -> Option<&'a JsonValue> { match input { Some(json) => match json { JsonValue::Array(ref array) => array .iter() .find(|member| match_json_slice(&self.matchers, member, true).is_ok()), _ => None, }, None => None, } } } pub struct SequenceParser; impl SequenceParser { fn match_sequence(pattern: &str) -> Option<&str> { lazy_static! { static ref RE_SEQUENCE: Regex = Regex::new(r#"^\[(?P<sequence_matcher>(.)+)\]$"#).unwrap(); } RE_SEQUENCE .captures(pattern) .and_then(|cap| cap.name("sequence_matcher")) .map(|sequence_matcher| sequence_matcher.as_str()) } } impl SelectionLensParser for SequenceParser { fn try_parse<'a>( &self, lens_pattern: Option<&'a str>, ) -> Result<(Box<dyn SelectionLens>, Option<&'a str>), Option<&'a str>> { match lens_pattern .and_then(SequenceParser::match_sequence) .map(try_to_match_filters) { Some(Ok(matchers)) => Ok((Box::new(Sequence { matchers }), None)), _ => Err(lens_pattern), } } } #[cfg(test)] mod tests { use super::*; use json::array; use json::object; #[test] fn should_match_json_in_sequence_when_matching_query() { let sequence_parser = SequenceParser {}; let res = sequence_parser.try_parse(Some("[.name]")); assert!(res.is_ok()); let data = &object! { "name" => "John Doe", "age" => 30, "identities" => array![object! { "name" => "Richard Roe" }] }; match res { Ok((matcher, _)) => assert_eq!( matcher.select(Some(&data["identities"])), Some(&data["identities"][0]) ), _ => panic!("Invalid result"), } } #[test] fn should_return_none_when_json_sequence_is_empty() { let data = &object! { "name" => "John Doe", "age" => 30, "identities" => array![] }; let sequence = Sequence { matchers: try_to_match_filters(".").unwrap(), }; assert_eq!(sequence.select(Some(&data["identities"])), None); } }
use std::{net::TcpStream, io::{Read, Write}, path}; use crate::server::request::Request; use crate::server::file_manager::{get_file, get_mime_type, DEFAULT_PATH}; use std::sync::Arc; const BAD_REQUEST: &'static[u8] = b"HTTP/1.1 400 BAD REQUEST"; const NOT_FOUND: &'static[u8] = b"HTTP/1.1 404 NOT FOUND"; const OK_REQUEST: &'static[u8] = b"HTTP/1.1 200 OK"; const INTERNAL_ERROR: &'static[u8] = b"HTTP/1.1 500 INTERNAL SERVER ERROR"; const METHOD_NOT_ALLOWED: &'static[u8] = b"HTTP/1.1 405 METHOD NOT ALLOWED"; const FORBIDDEN: &'static[u8] = b"HTTP/1.1 403 FORBIDDEN"; const CONNECTION: &'static str = "Connection: Closed"; const SERVER: &'static str = "Server: Pismenniy Daniil"; const SEPARATOR: &'static[u8] = b"\r\n"; pub fn handle_request(mut conn: TcpStream, document_root: Arc<String>) { let root_path = path::Path::new(document_root.as_str()); let mut buf = [0; 1024]; let request_str = match conn.read(&mut buf) { Ok(_) => Ok(buf), Err(e) => Err(e), }; if request_str.is_err() { return respond_err(&mut conn, BAD_REQUEST).unwrap_or(()); } let request_str = request_str.unwrap(); let request = Request::new(&request_str); if request.is_none() { return respond_err(&mut conn, BAD_REQUEST).unwrap_or_else(|e| { println!("{}", e) }); } let mut request = request.unwrap(); if request.method != "GET" && request.method != "HEAD" { return respond_err(&mut conn, METHOD_NOT_ALLOWED).unwrap_or_else(|e| { println!("{}", e) }) } let file = get_file(root_path, &mut request.path); if file.is_err() && request.path.ends_with(DEFAULT_PATH) { return respond_err(&mut conn, FORBIDDEN).unwrap_or_else(|e| { println!("{}", e) }); } if file.is_err() { return respond_err(&mut conn, NOT_FOUND).unwrap_or_else(|e| { println!("{}", e) }); } let mut file = file.unwrap(); let mime_type = get_mime_type(&request.path); if mime_type.is_none() { return respond_err(&mut conn, NOT_FOUND).unwrap_or_else(|e| { println!("{}", e) }); } let mime_type = format!("Content-Type: {}", mime_type.unwrap()); let content_length = format!("Content-Length: {}", file.metadata().unwrap().len()); let headers = [mime_type, content_length]; let join = headers.join("\r\n"); write_with_sep(&mut conn, OK_REQUEST); write_with_sep(&mut conn, &join.as_bytes()); add_required_headers(&mut conn); if request.method == "GET" { let mut buffer = Vec::new(); match file.read_to_end(&mut buffer) { Err(_) => { return respond_err(&mut conn, INTERNAL_ERROR).unwrap_or(()); }, _ => (), } conn.write(&buffer); } conn.flush().unwrap() } fn respond_err(conn: &mut TcpStream, resp: &'static [u8]) -> std::io::Result<()> { write_with_sep(conn, resp)?; add_required_headers(conn)?; conn.flush()?; Ok(()) } fn add_required_headers(conn: &mut TcpStream) -> std::io::Result<()> { write_with_sep(conn, get_date().as_bytes())?; write_with_sep(conn, CONNECTION.as_bytes())?; write_with_sep(conn, SERVER.as_bytes())?; conn.write(SEPARATOR); Ok(()) } fn write_with_sep(conn: &mut TcpStream, data: &[u8]) -> std::io::Result<()> { conn.write(data)?; conn.write(SEPARATOR)?; Ok(()) } fn get_date() -> String { let now = chrono::Utc::now(); format!("Date: {}", now.to_rfc2822().replace("+0000", "GMT")) }
use crate::components::container::NavLinks; use crate::components::container::COPYRIGHT_YEARS; use crate::templates::docs::generation::{DocsManifest, DocsVersionStatus}; use perseus::{link, t}; use sycamore::context::use_context; use sycamore::prelude::Template as SycamoreTemplate; use sycamore::prelude::*; use sycamore_router::navigate; use wasm_bindgen::JsCast; #[derive(Clone)] struct DocsVersionSwitcherProps { manifest: DocsManifest, current_version: String, } #[component(DocsVersionSwitcher<G>)] fn docs_version_switcher(props: DocsVersionSwitcherProps) -> SycamoreTemplate<G> { let manifest = props.manifest.clone(); let manifest_2 = manifest.clone(); let current_version = props.current_version; let current_version_2 = current_version.clone(); let current_version_3 = current_version.clone(); let current_version_4 = current_version.clone(); let stable_version = manifest.stable.clone(); let stable_version_2 = stable_version.clone(); let stable_version_3 = stable_version.clone(); // We'll fill this in from the reactive scope // Astonishingly, this actually works... let locale = Signal::new(String::new()); let locale_2 = locale.clone(); template! { ({ locale.set(use_context::<perseus::template::RenderCtx>().translator.get_locale()); SycamoreTemplate::empty() }) // This doesn't navigate to the same page in the new version, because it may well not exist select( class = "p-1 rounded-sm dark:bg-navy", on:input = move |event| { let target: web_sys::HtmlInputElement = event.target().unwrap().unchecked_into(); let new_version = target.value(); // This isn't a reactive scope, so we can't use `link!` here // The base path will be included by HTML automatically let link = format!("{}/docs/{}/intro", *locale_2.get(), new_version); navigate(&link); } ) { option(value = "next", selected = current_version == "next") { (t!("docs-version-switcher.next")) } (SycamoreTemplate::new_fragment( manifest.beta.iter().map(cloned!((current_version_2) => move |version| { let version = version.clone(); let version_2 = version.clone(); let version_3 = version.clone(); let current_version = current_version_2.to_string(); template! { option(value = version, selected = current_version == version_2) { (t!("docs-version-switcher.beta", { "version": version_3.as_str() })) } } })).collect() )) option(value = stable_version, selected = current_version_3 == stable_version_2) { (t!("docs-version-switcher.stable", { "version": stable_version_3.as_str() })) } (SycamoreTemplate::new_fragment( manifest_2.outdated.iter().map(cloned!((current_version_4) => move |version| { let version = version.clone(); let version_2 = version.clone(); let version_3 = version.clone(); let current_version = current_version_4.to_string(); template! { option(value = version, selected = current_version == version_2) { (t!("docs-version-switcher.outdated", { "version": version_3.as_str() })) } } })).collect() )) } } } #[derive(Clone)] pub struct DocsContainerProps<G: GenericNode> { pub children: SycamoreTemplate<G>, pub docs_links: String, pub status: DocsVersionStatus, pub manifest: DocsManifest, pub current_version: String, } #[component(DocsContainer<G>)] pub fn docs_container(props: DocsContainerProps<G>) -> SycamoreTemplate<G> { let docs_links = props.docs_links.clone(); let docs_links_2 = docs_links.clone(); let status = props.status.clone(); let docs_version_switcher_props = DocsVersionSwitcherProps { manifest: props.manifest.clone(), current_version: props.current_version.clone(), }; let docs_version_switcher_props_2 = docs_version_switcher_props.clone(); let menu_open = Signal::new(false); // We need to verbatim copy the value because of how it's used in Sycamore's reactivity system let menu_open_2 = create_memo(cloned!((menu_open) => move || *menu_open.get())); let menu_open_3 = create_memo(cloned!((menu_open) => move || *menu_open.get())); let toggle_menu = cloned!((menu_open) => move |_| menu_open.set(!*menu_open.get())); template! { // TODO click-away events header(class = "shadow-md sm:p-2 w-full bg-white dark:text-white dark:bg-navy mb-20") { div(class = "flex justify-between") { a(class = "justify-self-start self-center m-3 ml-5 text-md sm:text-2xl", href = link!("/")) { (t!("perseus")) } // The button for opening/closing the hamburger menu on mobile // This is done by a Tailwind module div( class = format!( "md:hidden m-3 mr-5 tham tham-e-spin tham-w-6 {}", if *menu_open.get() { "tham-active" } else { "" } ), on:click = toggle_menu ) { div(class = "tham-box") { div(class = "dark:bg-white tham-inner") {} } } // This displays the navigation links on desktop // But it needs to hide at the same time as the sidebar nav(class = "hidden md:flex") { ul(class = "mr-5 flex") { NavLinks() } } } // This displays the navigation links when the menu is opened on mobile // TODO click-away event nav( id = "mobile_nav_menu", class = format!( "md:hidden w-full text-center justify-center overflow-y-scroll {}", if *menu_open_2.get() { "flex flex-col" } else { "hidden" } ) ) { // TODO find a solution that lets you scroll here that doesn't need a fixed height div(class = "mr-5 overflow-y-scroll", style = "max-height: 500px") { ul { NavLinks() } hr() div(class = "text-left p-3") { DocsVersionSwitcher(docs_version_switcher_props) div(class = "docs-links-markdown", dangerously_set_inner_html = &docs_links) } } } } div( class = format!( "mt-14 xs:mt-16 sm:mt-20 lg:mt-25 overflow-y-auto {}", if !*menu_open_3.get() { "flex" } else { "hidden" } ) ) { div(class = "flex w-full") { // The sidebar that'll display navigation through the docs div(class = "h-full hidden md:block max-w-xs w-full border-r") { div(class = "mr-5") { div(class = "text-left text-black dark:text-white p-3") { aside { DocsVersionSwitcher(docs_version_switcher_props_2) div(class = "docs-links-markdown", dangerously_set_inner_html = &docs_links_2) } } } } div(class = "h-full flex w-full") { // These styles were meticulously arrived at through pure trial and error... div(class = "px-3 w-full sm:mr-auto sm:ml-auto sm:max-w-prose lg:max-w-3xl xl:max-w-4xl 2xl:max-w-5xl") { (status.render()) main(class = "text-black dark:text-white") { (props.children.clone()) } } } } } footer(class = "w-full flex justify-center py-5 bg-gray-100 dark:bg-navy-deep") { p(class = "dark:text-white mx-5 text-center") { span(dangerously_set_inner_html = &t!("footer.copyright", { "years": COPYRIGHT_YEARS })) } } } }
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `XDCNT` reader - data counter - When the I3C is acting as controller: number of targets detected on the bus - When the I3C is acting as target: number of transmitted bytes - Whatever the I3C is acting as controller or target: number of data bytes read from or transmitted on the I3C bus during the MID\\[7:0\\] message"] pub type XDCNT_R = crate::FieldReader<u16>; #[doc = "Field `ABT` reader - a private read message is completed/aborted prematurely by the target (when the I3C is acting as controller) When the I3C is acting as controller, this bit indicates if the private read data which is transmitted by the target early terminates (i.e. the target drives T bit low earlier vs what does expect the controller in terms of programmed number of read data bytes i.e. I3C_CR.DCNT\\[15:0\\])."] pub type ABT_R = crate::BitReader; #[doc = "Field `DIR` reader - message direction Whatever the I3C is acting as controller or target, this bit indicates the direction of the related message on the I3C bus Note: ENTDAA CCC is considered as a write command."] pub type DIR_R = crate::BitReader; #[doc = "Field `MID` reader - message identifier/counter of a given frame (when the I3C is acting as controller) When the I3C is acting as controller, this field identifies the control word message (i.e. I3C_CR) to which the I3C_SR status register refers. First message of a frame is identified with MID\\[7:0\\]=0. This field is incremented (by hardware) on the completion of a new message control word (i.e. I3C_CR) over I3C bus. This field is reset for every new frame start."] pub type MID_R = crate::FieldReader; impl R { #[doc = "Bits 0:15 - data counter - When the I3C is acting as controller: number of targets detected on the bus - When the I3C is acting as target: number of transmitted bytes - Whatever the I3C is acting as controller or target: number of data bytes read from or transmitted on the I3C bus during the MID\\[7:0\\] message"] #[inline(always)] pub fn xdcnt(&self) -> XDCNT_R { XDCNT_R::new((self.bits & 0xffff) as u16) } #[doc = "Bit 17 - a private read message is completed/aborted prematurely by the target (when the I3C is acting as controller) When the I3C is acting as controller, this bit indicates if the private read data which is transmitted by the target early terminates (i.e. the target drives T bit low earlier vs what does expect the controller in terms of programmed number of read data bytes i.e. I3C_CR.DCNT\\[15:0\\])."] #[inline(always)] pub fn abt(&self) -> ABT_R { ABT_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - message direction Whatever the I3C is acting as controller or target, this bit indicates the direction of the related message on the I3C bus Note: ENTDAA CCC is considered as a write command."] #[inline(always)] pub fn dir(&self) -> DIR_R { DIR_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bits 24:31 - message identifier/counter of a given frame (when the I3C is acting as controller) When the I3C is acting as controller, this field identifies the control word message (i.e. I3C_CR) to which the I3C_SR status register refers. First message of a frame is identified with MID\\[7:0\\]=0. This field is incremented (by hardware) on the completion of a new message control word (i.e. I3C_CR) over I3C bus. This field is reset for every new frame start."] #[inline(always)] pub fn mid(&self) -> MID_R { MID_R::new(((self.bits >> 24) & 0xff) as u8) } } #[doc = "I3C status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). 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 = "`reset()` method sets SR to value 0"] impl crate::Resettable for SR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::common::*; pub fn run() -> Result<(), i32> { #[cfg(windows)] ansi_term::enable_ansi_support().ok(); env_logger::Builder::from_env( env_logger::Env::new() .filter("JUST_LOG") .write_style("JUST_LOG_STYLE"), ) .init(); let app = Config::app(); info!("Parsing command line arguments…"); let matches = app.get_matches(); let config = Config::from_matches(&matches).eprint(Color::auto())?; config.run_subcommand() }
/// Binary Preference-based measure fn bpref(rel: &Vec<bool>) -> f64 { let count_relevant = rel.iter().filter(|x| **x).count(); if count_relevant == 0 { return 0.0; } let mut i = rel.len() - 1; while !rel[i] { i -= 1; } let count_non_relevant = rel[0..i].iter().filter(|x| !**x).count(); if count_non_relevant == 0 { return 1.0; } let count_relevant = count_relevant as f64; let mut n = 0.0; let mut ret = 0.0; for c in rel.iter() { if *c { eprintln!("{}/{}", n, count_relevant); ret += (1.0 - n / count_relevant) / count_relevant; } else { n += 1.0; } } ret } #[cfg(test)] mod tests { use super::*; #[test] fn test_bpref() { assert_eq!(bpref(&vec![true, true,]), 1.0); assert_eq!(bpref(&vec![false, false, false]), 0.0); assert_eq!(bpref(&vec![false, true, true, true, true]), 0.75); assert_eq!( bpref(&vec![false, true, true, false, true]), 0.5555555555555556 // 1/3*((1-1/3)+(1-1/3)+(1-2/3)) ); assert_eq!( bpref(&vec![ true, false, true, true, true, false, true, true, true, true, false, false, true, false, false, true, false, false, false, true, false, true ]), 0.7222222222222221 ); } }
use crate::num::simd::SimdScalar; use crate::num::simd::{ f32s, f64s, i128s, i16s, i32s, i64s, i8s, isizes, u128s, u16s, u32s, u64s, u8s, usizes, }; pub trait Scalar: sealed::Ops { const ZERO: Self; const ONE: Self; type Simd: SimdScalar<Single = Self>; fn into_real<R: Real>(self) -> R; fn clamp(self, min: Self, max: Self) -> Self; } pub trait Signed: Scalar { const NEG_ONE: Self; fn abs(self) -> Self; fn signum(self) -> Self; fn negate(self) -> Self; fn is_positive(self) -> bool; fn is_negative(self) -> bool; } pub trait Real: Signed { const PI: Self; const TAU: Self; const FRAC_PI_2: Self; const FRAC_PI_3: Self; const FRAC_PI_4: Self; const FRAC_PI_6: Self; const FRAC_PI_8: Self; const FRAC_1_PI: Self; const FRAC_2_PI: Self; const FRAC_2_SQRT_PI: Self; const SQRT_2: Self; const FRAC_1_SQRT_2: Self; const E: Self; const LOG2_10: Self; const LOG2_E: Self; const LOG10_2: Self; const LOG10_E: Self; const LN_2: Self; const LN_10: Self; fn floor(self) -> Self; fn ceil(self) -> Self; fn round(self) -> Self; fn trunc(self) -> Self; fn fract(self) -> Self; fn mul_add(self, a: Self, b: Self) -> Self; fn div_euclid(self, rhs: Self) -> Self; fn rem_euclid(self, rhs: Self) -> Self; fn powi(self, n: i32) -> Self; fn powr(self, n: Self) -> Self; fn sqrt(self) -> Self; fn exp(self) -> Self; fn exp2(self) -> Self; fn ln(self) -> Self; fn log(self, base: Self) -> Self; fn log2(self) -> Self; fn log10(self) -> Self; fn cbrt(self) -> Self; fn hypot(self, other: Self) -> Self; fn sin(self) -> Self; fn cos(self) -> Self; fn tan(self) -> Self; fn asin(self) -> Self; fn acos(self) -> Self; fn atan(self) -> Self; fn atan2(self, other: Self) -> Self; fn sin_cos(self) -> (Self, Self); fn exp_m1(self) -> Self; fn ln_1p(self) -> Self; fn sinh(self) -> Self; fn cosh(self) -> Self; fn tanh(self) -> Self; fn asinh(self) -> Self; fn acosh(self) -> Self; fn atanh(self) -> Self; fn to_degrees(self) -> Self; fn to_radians(self) -> Self; fn from_scalar<T: Scalar>(t: T) -> Self; fn approx_eq(self, other: Self, epsilon: Self, max_relative: Self) -> bool; } macro_rules! impl_scalar { ($($t:ty, $simd:ty, $zero:literal, $one:literal);*$(;)?) => { $( impl $crate::num::single::Scalar for $t { const ZERO: Self = $zero; const ONE: Self = $one; type Simd = $simd; fn into_real<R: Real>(self) -> R { R::from_scalar(self) } fn clamp(self, min: Self, max: Self) -> Self { if self < min { min } else if self > max { max } else { self } } } )* } } macro_rules! impl_signed { ($($t:ty, $neg_one:literal, $pos:ident, $neg:ident);*$(;)?) => { $( impl $crate::num::single::Signed for $t { const NEG_ONE: Self = $neg_one; fn abs(self) -> Self { <$t>::abs(self) } fn signum(self) -> Self { <$t>::signum(self) } fn negate(self) -> Self { -self } fn is_positive(self) -> bool { <$t>::$pos(self) } fn is_negative(self) -> bool { <$t>::$neg(self) } } )* } } macro_rules! impl_real { ($($t:ident, $convert:ident);*$(;)?) => { $( impl $crate::num::single::Real for $t { const PI: Self = ::core::$t::consts::PI; const TAU: Self = ::core::$t::consts::TAU; const FRAC_PI_2: Self = ::core::$t::consts::FRAC_PI_2; const FRAC_PI_3: Self = ::core::$t::consts::FRAC_PI_3; const FRAC_PI_4: Self = ::core::$t::consts::FRAC_PI_4; const FRAC_PI_6: Self = ::core::$t::consts::FRAC_PI_6; const FRAC_PI_8: Self = ::core::$t::consts::FRAC_PI_8; const FRAC_1_PI: Self = ::core::$t::consts::FRAC_1_PI; const FRAC_2_PI: Self = ::core::$t::consts::FRAC_2_PI; const FRAC_2_SQRT_PI: Self = ::core::$t::consts::FRAC_2_SQRT_PI; const SQRT_2: Self = ::core::$t::consts::SQRT_2; const FRAC_1_SQRT_2: Self = ::core::$t::consts::FRAC_1_SQRT_2; const E: Self = ::core::$t::consts::E; const LOG2_10: Self = ::core::$t::consts::LOG2_10; const LOG2_E: Self = ::core::$t::consts::LOG2_E; const LOG10_2: Self = ::core::$t::consts::LOG10_2; const LOG10_E: Self = ::core::$t::consts::LOG10_2; const LN_2: Self = ::core::$t::consts::LN_2; const LN_10: Self = ::core::$t::consts::LN_10; fn floor(self) -> Self { <$t>::floor(self) } fn ceil(self) -> Self { <$t>::ceil(self) } fn round(self) -> Self { <$t>::round(self) } fn trunc(self) -> Self { <$t>::trunc(self) } fn fract(self) -> Self { <$t>::fract(self) } fn mul_add(self, a: Self, b: Self) -> Self { <$t>::mul_add(self, a, b) } fn div_euclid(self, rhs: Self) -> Self { <$t>::div_euclid(self, rhs) } fn rem_euclid(self, rhs: Self) -> Self { <$t>::rem_euclid(self, rhs) } fn powi(self, n: i32) -> Self { <$t>::powi(self, n) } fn powr(self, n: Self) -> Self { <$t>::powf(self, n) } fn sqrt(self) -> Self { <$t>::sqrt(self) } fn exp(self) -> Self { <$t>::exp(self) } fn exp2(self) -> Self { <$t>::exp2(self) } fn ln(self) -> Self { <$t>::ln(self) } fn log(self, base: Self) -> Self { <$t>::log(self, base) } fn log2(self) -> Self { <$t>::log2(self) } fn log10(self) -> Self { <$t>::log10(self) } fn cbrt(self) -> Self { <$t>::cbrt(self) } fn hypot(self, other: Self) -> Self { <$t>::hypot(self, other) } fn sin(self) -> Self { <$t>::sin(self) } fn cos(self) -> Self { <$t>::cos(self) } fn tan(self) -> Self { <$t>::tan(self) } fn asin(self) -> Self { <$t>::asin(self) } fn acos(self) -> Self { <$t>::acos(self) } fn atan(self) -> Self { <$t>::atan(self) } fn atan2(self, other: Self) -> Self { <$t>::atan2(self, other) } fn sin_cos(self) -> (Self, Self) { <$t>::sin_cos(self) } fn exp_m1(self) -> Self { <$t>::exp_m1(self) } fn ln_1p(self) -> Self { <$t>::ln_1p(self) } fn sinh(self) -> Self { <$t>::sinh(self) } fn cosh(self) -> Self { <$t>::cosh(self) } fn tanh(self) -> Self { <$t>::tanh(self) } fn asinh(self) -> Self { <$t>::asinh(self) } fn acosh(self) -> Self { <$t>::acosh(self) } fn atanh(self) -> Self { <$t>::atanh(self) } fn to_degrees(self) -> Self { <$t>::to_degrees(self) } fn to_radians(self) -> Self { <$t>::to_radians(self) } fn from_scalar<T: Scalar>(t: T) -> Self { <T as $crate::num::single::sealed::ToFloat>::$convert(t) } fn approx_eq(self, other: Self, epsilon: Self, max_relative: Self) -> bool { if self == other { true } else if self.is_infinite() || other.is_infinite() || self.is_nan() || other.is_nan() { false } else { let diff = (self - other).abs(); if diff <= epsilon { true } else { let abs_self = self.abs(); let abs_other = other.abs(); let largest = Self::max(abs_self, abs_other); diff < largest * max_relative } } } } )* } } impl_scalar! { i8, i8s, 0, 1; u8, u8s, 0, 1; i16, i16s, 0, 1; u16, u16s, 0, 1; i32, i32s, 0, 1; u32, u32s, 0, 1; i64, i64s, 0, 1; u64, u64s, 0, 1; i128, i128s, 0, 1; u128, u128s, 0, 1; isize, isizes, 0, 1; usize, usizes, 0, 1; f32, f32s, 0.0, 1.0; f64, f64s, 0.0, 1.0; } impl_signed! { i8, -1, is_positive, is_negative; i16, -1, is_positive, is_negative; i32, -1, is_positive, is_negative; i64, -1, is_positive, is_negative; i128, -1, is_positive, is_negative; isize, -1, is_positive, is_negative; f32, -1.0, is_sign_positive, is_sign_negative; f64, -1.0, is_sign_positive, is_sign_negative; } impl_real! { f32, to_f32; f64, to_f64; } mod sealed { use std::{ cmp::{PartialEq, PartialOrd}, fmt::Debug, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}, }; pub trait Ops: Copy + Clone + Debug + Add<Output = Self> + AddAssign + Div<Output = Self> + DivAssign + Mul<Output = Self> + MulAssign + Rem<Output = Self> + RemAssign + Sub<Output = Self> + SubAssign + PartialEq + PartialOrd + ToFloat { } pub trait ToFloat: Copy { fn to_f64(self) -> f64; fn to_f32(self) -> f32; } macro_rules! impl_ops { ($($t:ty),*) => { $( impl $crate::num::single::sealed::ToFloat for $t { fn to_f64(self) -> f64 { self as f64 } fn to_f32(self) -> f32 { self as f32 } } impl $crate::num::single::sealed::Ops for $t {} )* } } impl_ops! { i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize, f32, f64 } }
use std::env; use std::fs; use std::path::Path; const MATRIX_SIZE:usize =1000; enum LightMode{ Switch, Dimmer, } enum Ops{ On, Off, Toggle, } fn read_instructions(filename:&str)->String{ let fpath = Path::new(filename); let abspath = env::current_dir() .unwrap() .into_boxed_path() .join(fpath); let content = fs::read_to_string(abspath) .expect("Error occurred while reading file!"); return content } fn let_there_be_light(content:&String, light_mode:&LightMode) -> (i32, i32){ let light_stats:(i32, i32); let mut lights = vec![vec![0;MATRIX_SIZE];MATRIX_SIZE]; for line in content.lines(){ let (mode, start, end) = parse_line(&line); set_lights(&mut lights, &light_mode,&mode, start, end); } match light_mode{ &LightMode::Switch => light_stats = get_light_stats(&lights, light_mode), &LightMode::Dimmer => light_stats = get_light_stats(&lights, light_mode), } return light_stats; } fn parse_line(line:&str) -> (Ops, Vec<&str>, Vec<&str>){ let fields:Vec<&str> = line.split_whitespace().collect(); match fields[0]{ "toggle" => { let mode = Ops::Toggle; let start:Vec<&str> = fields[1].split(",").collect(); let end:Vec<&str> = fields[3].split(",").collect(); (mode, start, end) }, "turn" => { let mode:Ops; match fields[1]{ "on" => mode = Ops::On, "off" => mode = Ops::Off, _ => panic!() } let start:Vec<&str> = fields[2].split(",").collect(); let end:Vec<&str> = fields[4].split(",").collect(); (mode, start, end) } &_ => panic!() } } fn set_lights(lights:&mut Vec<Vec<i32>>,pattern:&LightMode, mode:&Ops, start:Vec<&str>, end:Vec<&str>){ let rs:usize = start[0].parse().unwrap(); let cs:usize = start[1].parse().unwrap(); let re:usize = end[0].parse().unwrap(); let ce:usize = end[1].parse().unwrap(); for r in rs..re+1{ for c in cs..ce+1{ match pattern{ &LightMode::Switch => { match mode{ &Ops::On => { lights[r][c] = 1; } &Ops::Off => { lights[r][c] = 0; } &Ops::Toggle => { lights[r][c] ^= 1; } } } &LightMode::Dimmer => { match mode{ &Ops::On => { lights[r][c] += 1; } &Ops::Off => { lights[r][c] -= 1; if lights[r][c] < 0{ lights[r][c] =0; } } &Ops::Toggle => { lights[r][c] += 2; } } } } } } } fn get_light_stats(lights:&Vec<Vec<i32>>, light_mode:&LightMode) -> (i32, i32){ let (mut on, mut off) = (0, 0); for r in 0..MATRIX_SIZE{ for c in 0..MATRIX_SIZE{ match light_mode{ &LightMode::Switch => { if lights[r][c] == 1{ on +=1; }else{ off +=1; } } &LightMode::Dimmer => { on += lights[r][c]; } } } } (on, off) } pub fn run(){ let content = read_instructions("inputs/day-06.txt"); let light_stats_switch = let_there_be_light(&content, &LightMode::Switch); let light_stats_dimmer = let_there_be_light(&content, &LightMode::Dimmer); println!("\n-- AoC 2015: -- Day 5: Doesn't He Have Intern-Elves For This? --"); println!("\n💡 Turned (ON/OFF): {} / {} \n🔆 Total Brightness: {}", light_stats_switch.0, light_stats_switch.1, light_stats_dimmer.0); println!("\n-- DONE --\n"); }
extern crate intrepion_x_fizz_buzz; #[test] fn test_one_is_one() { assert_eq!("1", intrepion_x_fizz_buzz::fizz_buzz(1)); } #[test] fn test_two_is_two() { assert_eq!("2", intrepion_x_fizz_buzz::fizz_buzz(2)); } #[test] fn test_three_is_fizz() { assert_eq!("Fizz", intrepion_x_fizz_buzz::fizz_buzz(3)); } #[test] fn test_five_is_buzz() { assert_eq!("Buzz", intrepion_x_fizz_buzz::fizz_buzz(5)); } #[test] fn test_six_is_fizz() { assert_eq!("Fizz", intrepion_x_fizz_buzz::fizz_buzz(6)); } #[test] fn test_ten_is_buzz() { assert_eq!("Buzz", intrepion_x_fizz_buzz::fizz_buzz(10)); } #[test] fn test_fifteen_is_fizz_buzz() { assert_eq!("Fizz Buzz", intrepion_x_fizz_buzz::fizz_buzz(15)); } #[test] fn test_thirty_is_fizz_buzz() { assert_eq!("Fizz Buzz", intrepion_x_fizz_buzz::fizz_buzz(30)); }
pub mod collision; pub type CollisionWorld = ncollide2d::world::CollisionWorld<f32, hecs::Entity>; pub type PhysHandle = ncollide2d::pipeline::CollisionObjectSlabHandle; pub use ncollide2d::{pipeline::CollisionGroups, shape::Cuboid}; use crate::Game; use glsp::FromVal; /// Collision Group Constants #[derive(serde::Deserialize, serde::Serialize, Copy, Clone, PartialEq, Eq, Hash, Debug)] #[repr(u32)] pub enum Collide { Player, Weapon, Enemy, /// Fences, Terrain, etc. World, Creature, } impl FromVal for Collide { fn from_val(val: &glsp::Val) -> glsp::GResult<Self> { let sym = glsp::Sym::from_val(val)?; Ok(match &*sym.name() { "Player" => Self::Player, "Weapon" => Self::Weapon, "Enemy" => Self::Enemy, "World" => Self::World, "Creature" => Self::Creature, _ => glsp::bail!("Not a valid Collision marker: {}", sym), }) } } #[cfg(feature = "confui")] const ALL_COLLIDE: &[Collide] = { use Collide::*; &[Player, Weapon, Enemy, World, Creature] }; /// A collision relationship :P #[derive(serde::Deserialize, serde::Serialize, Default, Clone, PartialEq, Debug)] #[serde(deny_unknown_fields)] pub struct Collisionship { collision_static: Option<collision::CollisionStatic>, #[serde(default)] pub blacklist: std::collections::HashSet<Collide>, #[cfg(feature = "confui")] #[serde(skip)] adding_blacklist: Option<Collide>, #[serde(default)] pub whitelist: std::collections::HashSet<Collide>, #[cfg(feature = "confui")] #[serde(skip)] adding_whitelist: Option<Collide>, #[serde(default)] pub membership: std::collections::HashSet<Collide>, #[cfg(feature = "confui")] #[serde(skip)] adding_membership: Option<Collide>, } impl Collisionship { #[cfg(feature = "confui")] /// Returns `true` if "dirty" i.e. meaningful outward-facing changes to the data occured. pub fn dev_ui(&mut self, ui: &mut egui::Ui) -> bool { let mut dirty = false; let mut stat = self.collision_static.is_some(); if ui.checkbox("Immovable", &mut stat).clicked { self.collision_static = if stat { Some(collision::CollisionStatic) } else { None }; dirty = true; } fn list_edit( ui: &mut egui::Ui, title: &str, adding: &mut Option<Collide>, list: &mut std::collections::HashSet<Collide>, dirty: &mut bool, ) { ui.collapsing(title, |ui| { *adding = adding.take().and_then(|mut to_add| { for collide in ALL_COLLIDE.iter() { ui.radio_value(format!("{:?}", collide), &mut to_add, *collide); } if ui.button("Add").clicked { *dirty = true; list.insert(to_add); None } else if ui.button("Back").clicked { None } else { Some(to_add) } }); if adding.is_none() { let mut to_remove: Option<Collide> = None; for collide in list.iter() { ui.horizontal(|ui| { ui.label(format!("{:?}", collide)); if ui.button("Remove").clicked { to_remove = Some(collide.clone()); } }); } if ui.button("Add").clicked { *adding = Some(Collide::World); } if let Some(c) = to_remove { *dirty = true; list.remove(&c); } } }); } list_edit( ui, "Membership", &mut self.adding_membership, &mut self.membership, &mut dirty, ); list_edit( ui, "Whitelist", &mut self.adding_whitelist, &mut self.whitelist, &mut dirty, ); list_edit( ui, "Blacklist", &mut self.adding_blacklist, &mut self.blacklist, &mut dirty, ); dirty } pub fn into_groups(self) -> CollisionGroups { let (_, groups): (Option<collision::CollisionStatic>, CollisionGroups) = self.into(); groups } } impl Into<(Option<collision::CollisionStatic>, CollisionGroups)> for Collisionship { fn into(self) -> (Option<collision::CollisionStatic>, CollisionGroups) { let Self { blacklist, whitelist, membership, .. } = self; let m = |l: std::collections::HashSet<Collide>| { l.into_iter().map(|c| c as usize).collect::<Vec<_>>() }; ( self.collision_static, CollisionGroups::new() .with_membership(&m(membership)) .with_whitelist(&m(whitelist)) .with_blacklist(&m(blacklist)), ) } } pub fn phys_components( phys: &mut CollisionWorld, entity: hecs::Entity, iso: na::Isometry2<f32>, cuboid: Cuboid<f32>, groups: CollisionGroups, ) -> (PhysHandle, collision::Contacts) { let (h, _) = phys.add( iso, ncollide2d::shape::ShapeHandle::new(cuboid), groups, ncollide2d::pipeline::GeometricQueryType::Contacts(0.0, 0.0), entity, ); (h, collision::Contacts::new()) } pub fn phys_insert( ecs: &mut hecs::World, phys: &mut CollisionWorld, entity: hecs::Entity, iso: na::Isometry2<f32>, cuboid: Cuboid<f32>, groups: CollisionGroups, ) -> PhysHandle { let comps = phys_components(phys, entity, iso, cuboid, groups); let h = comps.0; ecs.insert(entity, comps).unwrap_or_else(|e| { panic!( "Couldn't add comps for Entity[{:?}] for phys[handle: {:?}] insertion: {}", entity, h, e ) }); h } pub fn phys_remove( ecs: &mut hecs::World, phys: &mut CollisionWorld, entity: hecs::Entity, h: PhysHandle, ) { phys.remove(&[h]); ecs.remove::<(collision::Contacts, PhysHandle)>(entity) .unwrap_or_else(|e| { panic!( "Couldn't remove Contacts and PhysHandle for Entity[{:?}] when removing phys: {}", entity, e ) }); } /// DragTowards moves an Entity towards the supplied location (`goal_loc`) until the /// Entity's Iso2's translation's `vector` is within the supplied speed (`speed`) of the /// given location, at which point the DragTowards component is removed from the Entity /// at the end of the next frame. pub struct DragTowards { pub goal_loc: na::Vector2<f32>, pub speed: f32, speed_squared: f32, } impl DragTowards { pub fn new(goal_loc: na::Vector2<f32>, speed: f32) -> Self { Self { goal_loc, speed, speed_squared: speed.powi(2), } } } /// Chase moves an Entity's Iso2's translation's `vector` field towards another Entity's, /// at the supplied rate (`speed`), removing the Chase component from the entity when /// their positions are within `speed` of each other (if `remove_when_reached` is true). /// /// # Panics /// This will panic if either entity doesn't have `PhysHandle`s/`CollisionObject`s. /// Having an Entity chase itself might work but I wouldn't recommend it. pub struct Chase { pub goal_ent: hecs::Entity, pub speed: f32, pub remove_when_reached: bool, speed_squared: f32, } impl Chase { /// Continues chasing even when the goal entity is reached. pub fn determined(goal_ent: hecs::Entity, speed: f32) -> Self { Self { goal_ent, speed, remove_when_reached: false, speed_squared: speed.powi(2), } } } /// LurchChase applies a force to an entity, in the direction of another entity (`goal_ent`), /// whenever no forces are found on the entity. /// /// # Panics /// This will panic if either entity doesn't have `PhysHandle`s/`CollisionObject`s. /// Having an Entity chase itself might work but I wouldn't recommend it. pub struct LurchChase { pub goal_ent: hecs::Entity, pub magnitude: f32, pub decay: f32, } impl LurchChase { /// Continues chasing even when the goal entity is reached. pub fn new(goal_ent: hecs::Entity, magnitude: f32, decay: f32) -> Self { Self { goal_ent, magnitude, decay, } } } /// Entities with a Charge component will go forward in the direction they are facing, /// at the designated speed. pub struct Charge { pub speed: f32, } impl Charge { pub fn new(speed: f32) -> Self { Self { speed } } } pub struct KnockBack { pub groups: CollisionGroups, pub force_decay: f32, pub force_magnitude: f32, /// Whether or not the direction of any Force affecting the object should be used /// for the direction for the knock back. pub use_force_direction: bool, /// If the entity has a Force and the magnitude of the Force's `vec` field isn't at least /// this high, no knockback will be administered. pub minimum_speed: Option<f32>, } /// A Force is applied to an Entity every frame and decays a bit, /// eventually reaching 0 and being removed. Unlike a Velocity, a Force /// is only temporary, eventually fading away. #[derive(Clone)] pub struct Force { pub vec: na::Vector2<f32>, /// Domain [0, 1] unless you want the velocity to increase exponentially :thinking: pub decay: f32, /// Whether or not to remove the component from the entity when the Force isn't really /// having an effect any more. pub clear: bool, } impl Force { /// A new Force that is cleared when the velocity decays down to extremely small decimals. pub fn new(vec: na::Vector2<f32>, decay: f32) -> Self { Self { vec, decay, clear: true, } } /// A new Force that is NOT cleared when the velocity decays down to extremely small decimals. pub fn new_no_clear(vec: na::Vector2<f32>, decay: f32) -> Self { Self { vec, decay, clear: false, } } } /// Sphereically interpolates the rotation of an Entity with this component towards the /// position of the Entity provided. /// /// # Panics /// This will panic if either entity doesn't have `PhysHandle`s/`CollisionObject`s. /// Having an Entity look at itself might work but I wouldn't recommend it. pub struct LookChase { pub look_at_ent: hecs::Entity, pub speed: f32, } impl LookChase { pub fn new(look_at_ent: hecs::Entity, speed: f32) -> Self { Self { look_at_ent, speed } } } #[inline] /// The result `.is_some()` if progress has been made wrt. the dragging, /// and is `Some(true)` if the goal has been reached. fn drag_goal( h: PhysHandle, phys: &mut CollisionWorld, goal: &na::Vector2<f32>, speed: f32, speed_squared: f32, ) -> Option<bool> { let obj = phys.get_mut(h)?; let mut iso = obj.position().clone(); let loc = &mut iso.translation.vector; let delta = *loc - *goal; Some(if delta.magnitude_squared() < speed_squared { *loc = *goal; obj.set_position_with_prediction(iso, iso); true } else { let vel = delta.normalize() * speed; *loc -= vel; obj.set_position_with_prediction(iso.clone(), { iso.translation.vector -= vel; iso }); false }) } pub struct Velocity(na::Vector2<f32>); /// Also applies Forces and KnockBack. pub fn velocity(world: &mut Game) { let ecs = &world.ecs; let l8r = &mut world.l8r; let phys = &mut world.phys; for (_, (h, &Velocity(vel))) in &mut world.ecs.query::<(&PhysHandle, &Velocity)>() { (|| { let obj = phys.get_mut(*h)?; let mut iso = obj.position().clone(); iso.translation.vector += vel; obj.set_position_with_prediction(iso.clone(), { iso.translation.vector += vel; iso }); Some(()) })(); } for (ent, (&h, knock_back, contacts, force)) in &mut world .ecs .query::<(&_, &KnockBack, &collision::Contacts, Option<&Force>)>() { if let (Some(force), Some(minimum_speed)) = (force, knock_back.minimum_speed) { if force.vec.magnitude() < minimum_speed { continue; } } let loc = phys .collision_object(h) .unwrap_or_else(|| { panic!( "Entity[{:?}] has PhysHandle[{:?}] but no Collision Object!", ent, h ) }) .position() .translation .vector; for &o_ent in contacts.iter() { (|| { ecs.get::<collision::CollisionStatic>(o_ent).err()?; let o_h = *ecs.get::<PhysHandle>(o_ent).ok()?; /*.unwrap_or_else(|e| panic!( "Entity[{:?}] stored in Contacts[{:?}] but no PhysHandle: {}", o_ent, ent, e ));*/ let o_obj = phys.collision_object(o_h)?; /* .unwrap_or_else(|| panic!( "Entity[{:?}] stored in Contacts[{:?}] with PhysHandle[{:?}] but no Collision Object!", ent, o_ent, o_h ));*/ if knock_back .groups .can_interact_with_groups(o_obj.collision_groups()) { let delta = force .map(|f| f.vec) .filter(|_| knock_back.use_force_direction) .unwrap_or_else(|| o_obj.position().translation.vector - loc) .normalize(); l8r.insert_one( o_ent, Force::new(delta * knock_back.force_magnitude, knock_back.force_decay), ); } Some(()) })(); } } for (force_ent, (&h, force)) in &mut world.ecs.query::<(&PhysHandle, &mut Force)>() { (|| { let obj = phys.get_mut(h)?; let mut iso = obj.position().clone(); iso.translation.vector += force.vec; force.vec *= force.decay; obj.set_position_with_prediction(iso.clone(), { iso.translation.vector += force.vec; iso }); if force.clear && force.vec.magnitude_squared() < 0.0005 { l8r.remove_one::<Force>(force_ent); } Some(()) })(); } for (drag_ent, (hnd, drag)) in ecs.query::<(&PhysHandle, &DragTowards)>().iter() { // if the dragging is successful and the goal is reached... if let Some(true) = drag_goal(*hnd, phys, &drag.goal_loc, drag.speed, drag.speed_squared) { l8r.remove_one::<DragTowards>(drag_ent); } } } /// Note: Also does the calculations for LurchChase, LookChase, and Charge pub fn chase(world: &mut Game) { let ecs = &world.ecs; let l8r = &mut world.l8r; let phys = &mut world.phys; let loc_of_ent = |goal_ent, phys: &mut CollisionWorld| -> Option<na::Vector2<f32>> { let goal_h = *ecs.get::<PhysHandle>(goal_ent).ok()?; Some(phys.collision_object(goal_h)?.position().translation.vector) }; for (chaser_ent, (hnd, chase)) in ecs.query::<(&PhysHandle, &Chase)>().iter() { (|| { let goal_loc = loc_of_ent(chase.goal_ent, phys)?; let within_range = drag_goal(*hnd, phys, &goal_loc, chase.speed, chase.speed_squared)?; if within_range && chase.remove_when_reached { l8r.remove_one::<Chase>(chaser_ent); } Some(()) })(); } for (chaser_ent, (_, lurch)) in ecs .query::<hecs::Without<Force, (&PhysHandle, &LurchChase)>>() .iter() { (|| { let goal_loc = loc_of_ent(lurch.goal_ent, phys)?; let chaser_loc = loc_of_ent(chaser_ent, phys)?; let delta = (goal_loc - chaser_loc).normalize(); l8r.insert_one(chaser_ent, Force::new(delta * lurch.magnitude, lurch.decay)); Some(()) })(); } for (_, (&h, &Charge { speed })) in ecs.query::<(&PhysHandle, &Charge)>().iter() { (|| { let obj = phys.get_mut(h)?; let mut iso = obj.position().clone(); iso.translation.vector -= iso.rotation * -na::Vector2::y() * speed; obj.set_position(iso); Some(()) })(); } for (_, (&h, look_chase)) in ecs.query::<(&PhysHandle, &LookChase)>().iter() { (|| { let look_at_loc = loc_of_ent(look_chase.look_at_ent, phys)?; let obj = phys.get_mut(h)?; let mut iso = obj.position().clone(); let delta = na::Unit::new_normalize(iso.translation.vector - look_at_loc); let current = na::Unit::new_unchecked(iso.rotation * na::Vector2::x()); iso.rotation *= na::UnitComplex::from_angle(look_chase.speed * delta.dot(&current).signum()); obj.set_position(iso); Some(()) })(); } }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::error::Error; use std::fmt; use serde::Deserialize; use serde::Serialize; /// Returned by a failed integrity-check on a slab, indicating one way in which /// the given bytes form a corrupt or otherwise invalid slab. #[derive(Debug, Deserialize, PartialEq, Serialize)] pub enum SlabIntegrityError { InvalidBasePointer(usize), InvalidBlockSize(usize), InvalidPointer(usize), InvalidRootValueOffset(usize), NotInitialized, TooSmall(usize), } impl fmt::Display for SlabIntegrityError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl Error for SlabIntegrityError {}
use std::ops::AddAssign; #[derive(Debug)] pub enum Opcode { Load(u8), LoadConst(u8), LoadImmediate(i8), Store(u8), Add, Sub, Mul, Div, Print } #[derive(Debug)] pub struct Chunk { pub code: Vec<Opcode>, pub constants: Vec<i64> } impl Chunk{ pub fn new() -> Chunk{ Chunk{code:vec![], constants:vec![]} } } impl AddAssign<Opcode> for Chunk{ fn add_assign(&mut self, rhs: Opcode) { self.code.push(rhs) } }
#[doc = "Register `GPIOJ_SIDR` reader"] pub type R = crate::R<GPIOJ_SIDR_SPEC>; #[doc = "Field `SIDR` reader - SIDR"] pub type SIDR_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - SIDR"] #[inline(always)] pub fn sidr(&self) -> SIDR_R { SIDR_R::new(self.bits) } } #[doc = "GPIO size identification register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gpioj_sidr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GPIOJ_SIDR_SPEC; impl crate::RegisterSpec for GPIOJ_SIDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gpioj_sidr::R`](R) reader structure"] impl crate::Readable for GPIOJ_SIDR_SPEC {} #[doc = "`reset()` method sets GPIOJ_SIDR to value 0xa3c5_dd01"] impl crate::Resettable for GPIOJ_SIDR_SPEC { const RESET_VALUE: Self::Ux = 0xa3c5_dd01; }
fn main() { let nums: Vec<i32> = Vec::new(); let mut nums = vec![1,2,3]; nums.push(4); nums.remove(2); for num in &nums { println!("{}",num); } enum Value { Int(i32), Float(f32) }; let random = vec![Value::Int(3), Value::Float(4.56)]; for val in &random { println!("{}", val); } //This should return an error because Value::Int // and Value::Float are custom types without // standard formatting IO methods }
#[macro_use] extern crate clap; #[macro_use] extern crate log; use std::env; use std::path::*; use std::process; use clap::App; use log::{LogRecord, LogLevel, LogLevelFilter}; use env_logger::LogBuilder; use console::style; mod config; mod build; mod erl; fn handle_command(bin_path: PathBuf) { let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let (config_file, config) = match matches.value_of("config") { Some(file) => (file.to_owned(), config::read_config(file.to_owned())), None => config::home_config() }; debug!("config_file: {}", config_file); match matches.subcommand() { ("fetch", Some(sub_m)) => { build::fetch(sub_m, config); }, ("tags", Some(sub_m)) => { build::tags(sub_m, config); }, ("build", Some(sub_m)) => { build::run(bin_path, sub_m, &config_file, config); }, ("delete", Some(sub_m)) => { build::delete(bin_path, sub_m, &config_file, config); }, ("update_links", _) => { let dir = &config::lookup_cache_dir(&config); let links_dir = Path::new(dir).join("bin"); build::update_bins(bin_path.as_path(), links_dir.as_path()); }, ("list", _) => { config::list(); }, ("switch", Some(sub_m)) => { let id = sub_m.value_of("ID").unwrap(); config::switch(id); }, ("repo", Some(sub_m)) => { match sub_m.value_of("CMD") { Some("add") => { let repo_id = sub_m.value_of("NAME").unwrap_or_else(|| { error!("Bad command: `repo add` command must be given a repo name and url"); process::exit(1) }); let repo_url = sub_m.value_of("REPO").unwrap_or_else(|| { error!("Bad command: `repo add` command must be given a repo name and url"); process::exit(1) }); config::add_repo(repo_id, repo_url, &config_file, config); }, Some("ls") => { let repos = config::get_repos(&config); for (id, url) in repos { println!("{} -> {}", id, url); } }, Some("rm") => { let repo_id = sub_m.value_of("NAME").unwrap_or_else(|| { error!("Bad command: `repo add` command must be given a repo name and url"); process::exit(1) }); config::delete_repo(repo_id, &config_file, config); }, Some(cmd) => { error!("Bad command: unknown repo subcommand `{}`", cmd); error!("repo command must be given subcommand `add` or `rm`"); process::exit(1) }, None => { error!("Bad command: `repo` command must be given subcommand `add`, `ls` or `rm`"); process::exit(1) } } }, ("default", Some(sub_m)) => { let id = sub_m.value_of("ID").unwrap(); config::set_default(id); }, _ => { let _ = App::from_yaml(yaml).print_help(); }, } } fn setup_logging() { let format = |record: &LogRecord| { if record.level() == LogLevel::Error { style(format!("{}", record.args())).red().to_string() } else if record.level() == LogLevel::Info { format!("{}", record.args()) } else { style(format!("{}", record.args())).blue().to_string() } }; let mut builder = LogBuilder::new(); let key = "DEBUG"; let level = match env::var(key) { Ok(_) => LogLevelFilter::Debug, _ => LogLevelFilter::Info, }; builder.format(format).filter(None, level); builder.init().unwrap(); } fn main() { setup_logging(); let mut args = env::args(); let binname = args.nth(0).unwrap(); let f = Path::new(&binname).file_name().unwrap(); if f.eq("erlup") { match env::current_exe() { Ok(bin_path) => { debug!("current bin path: {}", bin_path.display()); handle_command(bin_path) }, Err(e) => { println!("failed to get current bin path: {}", e); process::exit(1) }, } } else { match build::BINS.iter().find(|&&x| f.eq(Path::new(x).file_name().unwrap())) { Some(x) => { let bin = Path::new(x).file_name().unwrap(); erl::run(bin.to_str().unwrap(), args); }, None => { error!("No such command: {}", f.to_str().unwrap()); process::exit(1) }, } } }
use colored::Colorize; use regex::Regex; use std::process::{Command, Stdio}; use std::thread; const URL: &str = "https://google.com"; // Here you put the url fn threads() { const NTHREADS: u32 = 1; // number of threads let mut children = vec![]; for _i in 0..NTHREADS { children.push(thread::spawn(move || { let ou = Command::new("curl") .arg(URL) .stdout(Stdio::piped()) .output() .expect("Failed to execute command"); let re = Regex::new(r"(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|jpeg|png)").unwrap(); let output = String::from_utf8(ou.stdout).unwrap(); let formated = re.find_iter(&output).collect::<Vec<_>>(); if formated.is_empty() { println!("No matches from: {}", URL.red()); } else { for i in formated { println!("{}", i.as_str().green()) } } })); } for child in children { let _ = child.join(); } } fn main() { println!("scraping: {}", URL.blue()); threads(); }
use crate::rdata::*; /// The enumeration that represents implemented types of DNS resource records data #[derive(Debug, PartialEq)] pub enum RData<'a> { A(A), AAAA(Aaaa), CNAME(Cname<'a>), MX(Mx<'a>), NS(Ns<'a>), PTR(Ptr<'a>), SOA(Soa<'a>), SRV(Srv<'a>), TXT(Txt<'a>), OPT(&'a [u8]), }
use super::orientation::{Orientation, Rotation, MatingSide}; pub fn invert_side(width: u32, side: u32) -> u32 { (0..width).fold(0, |total, n| (total << 1) + ((side >> n) & 1) ) } #[derive(Debug)] pub struct Tile { pub label: u32, pub data: Vec<bool>, pub width: u32, pub sides: [u32; 4] } impl From<&str> for Tile { fn from(input: &str) -> Self { let mut line_iter = input.lines(); let label_line = line_iter.next().unwrap(); let label: u32 = label_line[5..label_line.len()-1].parse().unwrap(); let mut data = Vec::new(); let mut width: u32 = 0; for row in line_iter { width = row.len() as u32; row.chars().for_each(|c| data.push(c == '#')) } let top = (0..width) .map(|i| if data[i as usize] { 1 } else { 0 }) .fold(0, |total, n| (total << 1) + n); let right = (0..width) .map(|i| if data[((i + 1) * width - 1) as usize] { 1 } else { 0 }) .fold(0, |total, n| (total << 1) + n); let bottom = (0..width) .map(|i| if data[data.len() - (i + 1) as usize] { 1 } else { 0 }) .fold(0, |total, n| (total << 1) + n); let left = (0..width) .map(|i| if data[data.len() - (width * (i + 1)) as usize] { 1 } else { 0 }) .fold(0, |total, n| (total << 1) + n); let sides = [top, right, bottom, left]; Tile { label, data, sides, width } } } impl Tile { pub fn inverse_sides(&self) -> [u32; 4] { [ invert_side(10, self.sides[0]), invert_side(10, self.sides[1]), invert_side(10, self.sides[2]), invert_side(10, self.sides[3]), ] } pub fn side_with_translations(&self, index: u32, orientation: Orientation) -> u32 { let zero_indexed_side = 4 + orientation.index_zero_side(); let indexed_rotation = match orientation.flipped { true => (zero_indexed_side - index) % 4, false => (zero_indexed_side + index) % 4 }; let raw_value = self.sides[indexed_rotation as usize]; if orientation.flipped { invert_side(10, raw_value) } else { raw_value } } pub fn mates(&self, edge: u32) -> Option<MatingSide> { for (side_index, &side) in self.sides.iter().enumerate() { let inverted = invert_side(10, side); match side_index { 0 => { if side == edge { return Some(MatingSide::FlippedTop) } else if inverted == edge { return Some(MatingSide::NormalTop) } } 1 => { if side == edge { return Some(MatingSide::FlippedLeft) } else if inverted == edge { return Some(MatingSide::NormalRight) } } 2 => { if side == edge { return Some(MatingSide::FlippedBottom) } else if inverted == edge { return Some(MatingSide::NormalBottom) } } 3 => { if side == edge { return Some(MatingSide::FlippedRight) } else if inverted == edge { return Some(MatingSide::NormalLeft) } } _ => panic!() } } None } pub fn index(&self, x: usize, y: usize, orientation: Orientation) -> bool { let (x, y) = super::index_rotated_grid( x, y, self.width as usize - 2, self.width as usize - 2, orientation ); self.data[(y + 1) * self.width as usize + (x + 1)] } pub fn show(&self, orientation: Orientation) { for y in 0..8 { for x in 0..8 { print!("{}", if self.index(x, y, orientation) { "#" } else { "." }); } println!(""); } } pub fn trues(&self) -> usize { let mut true_count = 0; for y in 0..8 { for x in 0..8 { if self.index(x, y, Orientation { rotation: Rotation::RightSideUp, flipped: false }) { true_count += 1; } } } true_count } }
/// Various representations of a variable name. /// /// Note that the use of the cached! macro is safe here because this structure is /// immutable after initialization. pub struct ScalarName { /// Any string representation of the variable pub canonical: String } /// Naively cache the first return value of the expression. /// /// Note that this does not support functions that use the 'return' keyword macro_rules! cached { (pub fn $name:ident (&$self:ident) -> $ret:ty $body:block) => { pub fn $name(&$self) -> &$ret { static mut cached: Option<$ret> = None; unsafe { if let Some(ref c) = cached { return c; } } let val = $body; unsafe { cached = Some(val); cached.as_ref().unwrap() } } }; } impl ScalarName { /// Returns the CamelCase representation of canonical cached! { pub fn camel_case(&self) -> String { let mut output = String::new(); for token in self.tokens() { for (i, c) in token.chars().enumerate() { match i { 0 => output.extend(c.to_uppercase()), _ => output.extend(c.to_lowercase()), } } } output } } /// Returns the lowerCamelCase representation of canonical cached! { pub fn lower_camel_case(&self) -> String { let mut output = String::new(); for (i, token) in self.tokens().enumerate() { for (j, c) in token.chars().enumerate() { match (i, j) { (0, _) => output.extend(c.to_lowercase()), (_, 0) => output.extend(c.to_uppercase()), _ => output.extend(c.to_lowercase()), } } } output } } /// Returns the snake_case representation of canonical cached! { pub fn snake_case(&self) -> String { self.tokens() .map(|s| s.to_lowercase()) .intersperse(String::from("_")) .collect() } } /// Returns an iterator for the tokens of canonical pub fn tokens<'a>(&'a self) -> impl Iterator<Item = &'a str> { self.canonical.split_whitespace() .flat_map(|w| w.split(&['_', '-'][..])) .flat_map(|w| w.chars().split_camel_case()) } } use std::str::Chars; pub trait SplitCamelCaseExt<'a>: Iterator + Sized { fn split_camel_case(self) -> SplitCamelCase<'a>; } impl<'a> SplitCamelCaseExt<'a> for Chars<'a> { fn split_camel_case(self) -> SplitCamelCase<'a> { let value = self.as_str().clone(); SplitCamelCase { iter: self, value: value, start: 0, end: 0 } } } /// Iterate over the tokens of a camelcase. pub struct SplitCamelCase<'a> { iter: Chars<'a>, value: &'a str, start: usize, end: usize, } impl<'a> Iterator for SplitCamelCase<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { // Check for end and assume a token size of atleast 1. if let None = self.iter.next() { return None; } self.start = self.end; let token_len = 1 + self.iter.clone().take_while(|c| !c.is_uppercase()).count(); self.end += token_len; // token_len includes an extra char, so we pop one less. for _ in 1..token_len { self.iter.next().unwrap(); } Some(&self.value[self.start..self.end]) } }
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use Cancellable; use Error; use File; use IOStream; use Icon; use InputStream; use Resource; use ResourceLookupFlags; use ffi; use glib; use glib::object::IsA; use glib::translate::*; use std; use std::mem; use std::ptr; //pub fn bus_get<'a, 'b, P: Into<Option<&'a Cancellable>>, Q: Into<Option<&'b /*Unimplemented*/AsyncReadyCallback>>, R: Into<Option</*Unimplemented*/Fundamental: Pointer>>>(bus_type: /*Ignored*/BusType, cancellable: P, callback: Q, user_data: R) { // unsafe { TODO: call ffi::g_bus_get() } //} //pub fn bus_get_sync<'a, P: Into<Option<&'a Cancellable>>>(bus_type: /*Ignored*/BusType, cancellable: P) -> Result</*Ignored*/DBusConnection, Error> { // unsafe { TODO: call ffi::g_bus_get_sync() } //} //pub fn bus_own_name<'a, 'b, 'c, 'd, P: Into<Option<&'a /*Unimplemented*/BusAcquiredCallback>>, Q: Into<Option<&'b /*Unimplemented*/BusNameAcquiredCallback>>, R: Into<Option<&'c /*Unimplemented*/BusNameLostCallback>>, S: Into<Option</*Unimplemented*/Fundamental: Pointer>>, T: Into<Option<&'d /*Ignored*/glib::DestroyNotify>>>(bus_type: /*Ignored*/BusType, name: &str, flags: /*Ignored*/BusNameOwnerFlags, bus_acquired_handler: P, name_acquired_handler: Q, name_lost_handler: R, user_data: S, user_data_free_func: T) -> u32 { // unsafe { TODO: call ffi::g_bus_own_name() } //} //pub fn bus_own_name_on_connection<'a, 'b, 'c, P: Into<Option<&'a /*Unimplemented*/BusNameAcquiredCallback>>, Q: Into<Option<&'b /*Unimplemented*/BusNameLostCallback>>, R: Into<Option</*Unimplemented*/Fundamental: Pointer>>, S: Into<Option<&'c /*Ignored*/glib::DestroyNotify>>>(connection: /*Ignored*/&DBusConnection, name: &str, flags: /*Ignored*/BusNameOwnerFlags, name_acquired_handler: P, name_lost_handler: Q, user_data: R, user_data_free_func: S) -> u32 { // unsafe { TODO: call ffi::g_bus_own_name_on_connection() } //} //pub fn bus_own_name_on_connection_with_closures<'a, 'b, P: Into<Option<&'a /*Ignored*/glib::Closure>>, Q: Into<Option<&'b /*Ignored*/glib::Closure>>>(connection: /*Ignored*/&DBusConnection, name: &str, flags: /*Ignored*/BusNameOwnerFlags, name_acquired_closure: P, name_lost_closure: Q) -> u32 { // unsafe { TODO: call ffi::g_bus_own_name_on_connection_with_closures() } //} //pub fn bus_own_name_with_closures<'a, 'b, 'c, P: Into<Option<&'a /*Ignored*/glib::Closure>>, Q: Into<Option<&'b /*Ignored*/glib::Closure>>, R: Into<Option<&'c /*Ignored*/glib::Closure>>>(bus_type: /*Ignored*/BusType, name: &str, flags: /*Ignored*/BusNameOwnerFlags, bus_acquired_closure: P, name_acquired_closure: Q, name_lost_closure: R) -> u32 { // unsafe { TODO: call ffi::g_bus_own_name_with_closures() } //} pub fn bus_unown_name(owner_id: u32) { unsafe { ffi::g_bus_unown_name(owner_id); } } pub fn bus_unwatch_name(watcher_id: u32) { unsafe { ffi::g_bus_unwatch_name(watcher_id); } } //pub fn bus_watch_name<'a, 'b, 'c, P: Into<Option<&'a /*Unimplemented*/BusNameAppearedCallback>>, Q: Into<Option<&'b /*Unimplemented*/BusNameVanishedCallback>>, R: Into<Option</*Unimplemented*/Fundamental: Pointer>>, S: Into<Option<&'c /*Ignored*/glib::DestroyNotify>>>(bus_type: /*Ignored*/BusType, name: &str, flags: /*Ignored*/BusNameWatcherFlags, name_appeared_handler: P, name_vanished_handler: Q, user_data: R, user_data_free_func: S) -> u32 { // unsafe { TODO: call ffi::g_bus_watch_name() } //} //pub fn bus_watch_name_on_connection<'a, 'b, 'c, P: Into<Option<&'a /*Unimplemented*/BusNameAppearedCallback>>, Q: Into<Option<&'b /*Unimplemented*/BusNameVanishedCallback>>, R: Into<Option</*Unimplemented*/Fundamental: Pointer>>, S: Into<Option<&'c /*Ignored*/glib::DestroyNotify>>>(connection: /*Ignored*/&DBusConnection, name: &str, flags: /*Ignored*/BusNameWatcherFlags, name_appeared_handler: P, name_vanished_handler: Q, user_data: R, user_data_free_func: S) -> u32 { // unsafe { TODO: call ffi::g_bus_watch_name_on_connection() } //} //pub fn bus_watch_name_on_connection_with_closures<'a, 'b, P: Into<Option<&'a /*Ignored*/glib::Closure>>, Q: Into<Option<&'b /*Ignored*/glib::Closure>>>(connection: /*Ignored*/&DBusConnection, name: &str, flags: /*Ignored*/BusNameWatcherFlags, name_appeared_closure: P, name_vanished_closure: Q) -> u32 { // unsafe { TODO: call ffi::g_bus_watch_name_on_connection_with_closures() } //} //pub fn bus_watch_name_with_closures<'a, 'b, P: Into<Option<&'a /*Ignored*/glib::Closure>>, Q: Into<Option<&'b /*Ignored*/glib::Closure>>>(bus_type: /*Ignored*/BusType, name: &str, flags: /*Ignored*/BusNameWatcherFlags, name_appeared_closure: P, name_vanished_closure: Q) -> u32 { // unsafe { TODO: call ffi::g_bus_watch_name_with_closures() } //} pub fn content_type_can_be_executable(type_: &str) -> bool { unsafe { from_glib(ffi::g_content_type_can_be_executable(type_.to_glib_none().0)) } } pub fn content_type_equals(type1: &str, type2: &str) -> bool { unsafe { from_glib(ffi::g_content_type_equals(type1.to_glib_none().0, type2.to_glib_none().0)) } } pub fn content_type_from_mime_type(mime_type: &str) -> Option<String> { unsafe { from_glib_full(ffi::g_content_type_from_mime_type(mime_type.to_glib_none().0)) } } pub fn content_type_get_description(type_: &str) -> Option<String> { unsafe { from_glib_full(ffi::g_content_type_get_description(type_.to_glib_none().0)) } } #[cfg(any(feature = "v2_34", feature = "dox"))] pub fn content_type_get_generic_icon_name(type_: &str) -> Option<String> { unsafe { from_glib_full(ffi::g_content_type_get_generic_icon_name(type_.to_glib_none().0)) } } pub fn content_type_get_icon(type_: &str) -> Option<Icon> { unsafe { from_glib_full(ffi::g_content_type_get_icon(type_.to_glib_none().0)) } } pub fn content_type_get_mime_type(type_: &str) -> Option<String> { unsafe { from_glib_full(ffi::g_content_type_get_mime_type(type_.to_glib_none().0)) } } #[cfg(any(feature = "v2_34", feature = "dox"))] pub fn content_type_get_symbolic_icon(type_: &str) -> Option<Icon> { unsafe { from_glib_full(ffi::g_content_type_get_symbolic_icon(type_.to_glib_none().0)) } } pub fn content_type_guess<'a, P: Into<Option<&'a str>>>(filename: P, data: &[u8]) -> (String, bool) { let filename = filename.into(); let filename = filename.to_glib_none(); let data_size = data.len() as usize; unsafe { let mut result_uncertain = mem::uninitialized(); let ret = from_glib_full(ffi::g_content_type_guess(filename.0, data.to_glib_none().0, data_size, &mut result_uncertain)); (ret, from_glib(result_uncertain)) } } pub fn content_type_guess_for_tree<P: IsA<File>>(root: &P) -> Vec<String> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_content_type_guess_for_tree(root.to_glib_none().0)) } } pub fn content_type_is_a(type_: &str, supertype: &str) -> bool { unsafe { from_glib(ffi::g_content_type_is_a(type_.to_glib_none().0, supertype.to_glib_none().0)) } } #[cfg(any(feature = "v2_52", feature = "dox"))] pub fn content_type_is_mime_type(type_: &str, mime_type: &str) -> bool { unsafe { from_glib(ffi::g_content_type_is_mime_type(type_.to_glib_none().0, mime_type.to_glib_none().0)) } } pub fn content_type_is_unknown(type_: &str) -> bool { unsafe { from_glib(ffi::g_content_type_is_unknown(type_.to_glib_none().0)) } } pub fn content_types_get_registered() -> Vec<String> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_content_types_get_registered()) } } #[cfg(any(feature = "v2_36", feature = "dox"))] pub fn dbus_address_escape_value(string: &str) -> Option<String> { unsafe { from_glib_full(ffi::g_dbus_address_escape_value(string.to_glib_none().0)) } } //pub fn dbus_address_get_for_bus_sync<'a, P: Into<Option<&'a Cancellable>>>(bus_type: /*Ignored*/BusType, cancellable: P) -> Result<String, Error> { // unsafe { TODO: call ffi::g_dbus_address_get_for_bus_sync() } //} //pub fn dbus_address_get_stream<'a, 'b, P: Into<Option<&'a Cancellable>>, Q: Into<Option<&'b /*Unimplemented*/AsyncReadyCallback>>, R: Into<Option</*Unimplemented*/Fundamental: Pointer>>>(address: &str, cancellable: P, callback: Q, user_data: R) { // unsafe { TODO: call ffi::g_dbus_address_get_stream() } //} pub fn dbus_address_get_stream_sync<'a, P: Into<Option<&'a Cancellable>>>(address: &str, cancellable: P) -> Result<(IOStream, String), Error> { let cancellable = cancellable.into(); let cancellable = cancellable.to_glib_none(); unsafe { let mut out_guid = ptr::null_mut(); let mut error = ptr::null_mut(); let ret = ffi::g_dbus_address_get_stream_sync(address.to_glib_none().0, &mut out_guid, cancellable.0, &mut error); if error.is_null() { Ok((from_glib_full(ret), from_glib_full(out_guid))) } else { Err(from_glib_full(error)) } } } pub fn dbus_generate_guid() -> Option<String> { unsafe { from_glib_full(ffi::g_dbus_generate_guid()) } } //pub fn dbus_gvalue_to_gvariant(gvalue: /*Ignored*/&glib::Value, type_: &glib::VariantTy) -> Option<glib::Variant> { // unsafe { TODO: call ffi::g_dbus_gvalue_to_gvariant() } //} //pub fn dbus_gvariant_to_gvalue(value: &glib::Variant, out_gvalue: /*Ignored*/glib::Value) { // unsafe { TODO: call ffi::g_dbus_gvariant_to_gvalue() } //} pub fn dbus_is_address(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_address(string.to_glib_none().0)) } } pub fn dbus_is_guid(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_guid(string.to_glib_none().0)) } } pub fn dbus_is_interface_name(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_interface_name(string.to_glib_none().0)) } } pub fn dbus_is_member_name(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_member_name(string.to_glib_none().0)) } } pub fn dbus_is_name(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_name(string.to_glib_none().0)) } } pub fn dbus_is_supported_address(string: &str) -> Result<(), Error> { unsafe { let mut error = ptr::null_mut(); let _ = ffi::g_dbus_is_supported_address(string.to_glib_none().0, &mut error); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } pub fn dbus_is_unique_name(string: &str) -> bool { unsafe { from_glib(ffi::g_dbus_is_unique_name(string.to_glib_none().0)) } } //pub fn io_error_from_errno(err_no: i32) -> /*Ignored*/IOErrorEnum { // unsafe { TODO: call ffi::g_io_error_from_errno() } //} //pub fn io_error_quark() -> /*Ignored*/glib::Quark { // unsafe { TODO: call ffi::g_io_error_quark() } //} //pub fn io_modules_load_all_in_directory<P: AsRef<std::path::Path>>(dirname: P) -> /*Ignored*/Vec<IOModule> { // unsafe { TODO: call ffi::g_io_modules_load_all_in_directory() } //} //pub fn io_modules_load_all_in_directory_with_scope<P: AsRef<std::path::Path>>(dirname: P, scope: /*Ignored*/&mut IOModuleScope) -> /*Ignored*/Vec<IOModule> { // unsafe { TODO: call ffi::g_io_modules_load_all_in_directory_with_scope() } //} pub fn io_modules_scan_all_in_directory<P: AsRef<std::path::Path>>(dirname: P) { unsafe { ffi::g_io_modules_scan_all_in_directory(dirname.as_ref().to_glib_none().0); } } //pub fn io_modules_scan_all_in_directory_with_scope<P: AsRef<std::path::Path>>(dirname: P, scope: /*Ignored*/&mut IOModuleScope) { // unsafe { TODO: call ffi::g_io_modules_scan_all_in_directory_with_scope() } //} pub fn io_scheduler_cancel_all_jobs() { unsafe { ffi::g_io_scheduler_cancel_all_jobs(); } } //pub fn io_scheduler_push_job<'a, 'b, P: Into<Option</*Unimplemented*/Fundamental: Pointer>>, Q: Into<Option<&'a /*Ignored*/glib::DestroyNotify>>, R: Into<Option<&'b Cancellable>>>(job_func: /*Unknown conversion*//*Unimplemented*/IOSchedulerJobFunc, user_data: P, notify: Q, io_priority: i32, cancellable: R) { // unsafe { TODO: call ffi::g_io_scheduler_push_job() } //} //pub fn keyfile_settings_backend_new<'a, P: Into<Option<&'a str>>>(filename: &str, root_path: &str, root_group: P) -> /*Ignored*/Option<SettingsBackend> { // unsafe { TODO: call ffi::g_keyfile_settings_backend_new() } //} //pub fn memory_settings_backend_new() -> /*Ignored*/Option<SettingsBackend> { // unsafe { TODO: call ffi::g_memory_settings_backend_new() } //} #[cfg(any(feature = "v2_36", feature = "dox"))] pub fn networking_init() { unsafe { ffi::g_networking_init(); } } //pub fn null_settings_backend_new() -> /*Ignored*/Option<SettingsBackend> { // unsafe { TODO: call ffi::g_null_settings_backend_new() } //} pub fn pollable_source_new<P: IsA<glib::Object>>(pollable_stream: &P) -> Option<glib::Source> { unsafe { from_glib_full(ffi::g_pollable_source_new(pollable_stream.to_glib_none().0)) } } #[cfg(any(feature = "v2_34", feature = "dox"))] pub fn pollable_source_new_full<'a, 'b, P: IsA<glib::Object>, Q: Into<Option<&'a glib::Source>>, R: Into<Option<&'b Cancellable>>>(pollable_stream: &P, child_source: Q, cancellable: R) -> Option<glib::Source> { let child_source = child_source.into(); let child_source = child_source.to_glib_none(); let cancellable = cancellable.into(); let cancellable = cancellable.to_glib_none(); unsafe { from_glib_full(ffi::g_pollable_source_new_full(pollable_stream.to_glib_none().0, child_source.0, cancellable.0)) } } pub fn resources_enumerate_children(path: &str, lookup_flags: ResourceLookupFlags) -> Result<Vec<String>, Error> { unsafe { let mut error = ptr::null_mut(); let ret = ffi::g_resources_enumerate_children(path.to_glib_none().0, lookup_flags.to_glib(), &mut error); if error.is_null() { Ok(FromGlibPtrContainer::from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } pub fn resources_get_info(path: &str, lookup_flags: ResourceLookupFlags) -> Result<(usize, u32), Error> { unsafe { let mut size = mem::uninitialized(); let mut flags = mem::uninitialized(); let mut error = ptr::null_mut(); let _ = ffi::g_resources_get_info(path.to_glib_none().0, lookup_flags.to_glib(), &mut size, &mut flags, &mut error); if error.is_null() { Ok((size, flags)) } else { Err(from_glib_full(error)) } } } pub fn resources_lookup_data(path: &str, lookup_flags: ResourceLookupFlags) -> Result<glib::Bytes, Error> { unsafe { let mut error = ptr::null_mut(); let ret = ffi::g_resources_lookup_data(path.to_glib_none().0, lookup_flags.to_glib(), &mut error); if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } pub fn resources_open_stream(path: &str, lookup_flags: ResourceLookupFlags) -> Result<InputStream, Error> { unsafe { let mut error = ptr::null_mut(); let ret = ffi::g_resources_open_stream(path.to_glib_none().0, lookup_flags.to_glib(), &mut error); if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } pub fn resources_register(resource: &Resource) { unsafe { ffi::g_resources_register(resource.to_glib_none().0); } } pub fn resources_unregister(resource: &Resource) { unsafe { ffi::g_resources_unregister(resource.to_glib_none().0); } } //#[cfg_attr(feature = "v2_46", deprecated)] //pub fn simple_async_report_error_in_idle<'a, 'b, P: IsA<glib::Object> + 'a, Q: Into<Option<&'a P>>, R: Into<Option<&'b /*Unimplemented*/AsyncReadyCallback>>, S: Into<Option</*Unimplemented*/Fundamental: Pointer>>>(object: Q, callback: R, user_data: S, domain: /*Ignored*/glib::Quark, code: i32, format: &str, : /*Unknown conversion*//*Unimplemented*/Fundamental: VarArgs) { // unsafe { TODO: call ffi::g_simple_async_report_error_in_idle() } //} //#[cfg_attr(feature = "v2_46", deprecated)] //pub fn simple_async_report_gerror_in_idle<'a, 'b, P: IsA<glib::Object> + 'a, Q: Into<Option<&'a P>>, R: Into<Option<&'b /*Unimplemented*/AsyncReadyCallback>>, S: Into<Option</*Unimplemented*/Fundamental: Pointer>>>(object: Q, callback: R, user_data: S, error: &Error) { // unsafe { TODO: call ffi::g_simple_async_report_gerror_in_idle() } //} //#[cfg_attr(feature = "v2_46", deprecated)] //pub fn simple_async_report_take_gerror_in_idle<'a, 'b, P: IsA<glib::Object> + 'a, Q: Into<Option<&'a P>>, R: Into<Option<&'b /*Unimplemented*/AsyncReadyCallback>>, S: Into<Option</*Unimplemented*/Fundamental: Pointer>>>(object: Q, callback: R, user_data: S, error: &mut Error) { // unsafe { TODO: call ffi::g_simple_async_report_take_gerror_in_idle() } //} #[cfg(any(unix, feature = "dox"))] pub fn unix_is_mount_path_system_internal<P: AsRef<std::path::Path>>(mount_path: P) -> bool { unsafe { from_glib(ffi::g_unix_is_mount_path_system_internal(mount_path.as_ref().to_glib_none().0)) } } //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_at<P: AsRef<std::path::Path>>(mount_path: P) -> (/*Ignored*/UnixMountEntry, u64) { // unsafe { TODO: call ffi::g_unix_mount_at() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_compare(mount1: /*Ignored*/&mut UnixMountEntry, mount2: /*Ignored*/&mut UnixMountEntry) -> i32 { // unsafe { TODO: call ffi::g_unix_mount_compare() } //} //#[cfg(any(unix, feature = "dox"))] //#[cfg(any(feature = "v2_54", feature = "dox"))] //pub fn unix_mount_copy(mount_entry: /*Ignored*/&mut UnixMountEntry) -> /*Ignored*/Option<UnixMountEntry> { // unsafe { TODO: call ffi::g_unix_mount_copy() } //} //#[cfg(any(unix, feature = "dox"))] //#[cfg(any(feature = "v2_52", feature = "dox"))] //pub fn unix_mount_for<P: AsRef<std::path::Path>>(file_path: P) -> (/*Ignored*/UnixMountEntry, u64) { // unsafe { TODO: call ffi::g_unix_mount_for() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_free(mount_entry: /*Ignored*/&mut UnixMountEntry) { // unsafe { TODO: call ffi::g_unix_mount_free() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_get_device_path(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<std::path::PathBuf> { // unsafe { TODO: call ffi::g_unix_mount_get_device_path() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_get_fs_type(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<String> { // unsafe { TODO: call ffi::g_unix_mount_get_fs_type() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_get_mount_path(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<std::path::PathBuf> { // unsafe { TODO: call ffi::g_unix_mount_get_mount_path() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_guess_can_eject(mount_entry: /*Ignored*/&mut UnixMountEntry) -> bool { // unsafe { TODO: call ffi::g_unix_mount_guess_can_eject() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_guess_icon(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<Icon> { // unsafe { TODO: call ffi::g_unix_mount_guess_icon() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_guess_name(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<String> { // unsafe { TODO: call ffi::g_unix_mount_guess_name() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_guess_should_display(mount_entry: /*Ignored*/&mut UnixMountEntry) -> bool { // unsafe { TODO: call ffi::g_unix_mount_guess_should_display() } //} //#[cfg(any(unix, feature = "dox"))] //#[cfg(any(feature = "v2_34", feature = "dox"))] //pub fn unix_mount_guess_symbolic_icon(mount_entry: /*Ignored*/&mut UnixMountEntry) -> Option<Icon> { // unsafe { TODO: call ffi::g_unix_mount_guess_symbolic_icon() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_is_readonly(mount_entry: /*Ignored*/&mut UnixMountEntry) -> bool { // unsafe { TODO: call ffi::g_unix_mount_is_readonly() } //} //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_is_system_internal(mount_entry: /*Ignored*/&mut UnixMountEntry) -> bool { // unsafe { TODO: call ffi::g_unix_mount_is_system_internal() } //} #[cfg(any(unix, feature = "dox"))] pub fn unix_mount_points_changed_since(time: u64) -> bool { unsafe { from_glib(ffi::g_unix_mount_points_changed_since(time)) } } //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mount_points_get() -> (/*Ignored*/Vec<UnixMountPoint>, u64) { // unsafe { TODO: call ffi::g_unix_mount_points_get() } //} #[cfg(any(unix, feature = "dox"))] pub fn unix_mounts_changed_since(time: u64) -> bool { unsafe { from_glib(ffi::g_unix_mounts_changed_since(time)) } } //#[cfg(any(unix, feature = "dox"))] //pub fn unix_mounts_get() -> (/*Ignored*/Vec<UnixMountEntry>, u64) { // unsafe { TODO: call ffi::g_unix_mounts_get() } //}
//! The `parser` module contains types and functions useful for parsing Parallisp. use nom; use nom::{digit, IResult, multispace, space}; use std::convert::From; use std::error::Error; use std::{fmt, i64, iter, num, string}; use std::iter::FromIterator; use std::str::FromStr; use super::Expr; /// `ParseError`s are errors that may be encountered in this module. #[derive(Debug)] pub enum ParseError { /// `FromUtf8Error` occurs when the source code is not UTF-8. FromUtf8Error(string::FromUtf8Error), /// `IncompleteInputError` occurs when the source code does not contain a complete expression. IncompleteInputError(nom::Needed), /// `ParseError` occurs when a parse error occurs. ParseError(nom::Err<String>), /// `ParseFloatError` occurs when a floating-point number is improperly parsed. ParseFloatError(num::ParseFloatError), /// `ParseIntError` occurs when an integer is improperly parsed. ParseIntError(num::ParseIntError), /// `UnparsedInput` occurs when there is unparsed input during parsing. UnparsedInput(String), } impl fmt::Display for ParseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { ParseError::FromUtf8Error(ref e) => e.fmt(fmt), ParseError::IncompleteInputError(_) => write!(fmt, "incomplete input"), ParseError::ParseError(ref e) => e.fmt(fmt), ParseError::ParseFloatError(ref e) => e.fmt(fmt), ParseError::ParseIntError(ref e) => e.fmt(fmt), ParseError::UnparsedInput(ref v) => write!(fmt, "unparsed input: {:?}", v), } } } impl Error for ParseError { fn description(&self) -> &str { match *self { ParseError::FromUtf8Error(_) => "invalid utf-8", ParseError::IncompleteInputError(_) => "incomplete input", ParseError::ParseError(ref e) => e.description(), ParseError::ParseFloatError(ref e) => e.description(), ParseError::ParseIntError(ref e) => e.description(), ParseError::UnparsedInput(_) => "unparsed input", } } } impl From<string::FromUtf8Error> for ParseError { fn from(err: string::FromUtf8Error) -> ParseError { ParseError::FromUtf8Error(err) } } impl<'a> From<nom::Err<&'a [u8]>> for ParseError { fn from(err: nom::Err<&[u8]>) -> ParseError { fn convert_err(err: nom::Err<&[u8]>) -> nom::Err<String> { match err { nom::Err::Code(err) => nom::Err::Code(err), nom::Err::Node(err, next) => nom::Err::Node(err, Box::new(convert_err(*next))), nom::Err::Position(err, pos) => nom::Err::Position(err, String::from_utf8_lossy(pos).into_owned().to_string()), nom::Err::NodePosition(err, pos, next) => { let next2 = Box::new(convert_err(*next)); nom::Err::NodePosition(err, String::from_utf8_lossy(pos).into_owned().to_string(), next2) } } } ParseError::ParseError(convert_err(err)) } } impl From<num::ParseFloatError> for ParseError { fn from(err: num::ParseFloatError) -> ParseError { ParseError::ParseFloatError(err) } } impl From<num::ParseIntError> for ParseError { fn from(err: num::ParseIntError) -> ParseError { ParseError::ParseIntError(err) } } named!(integer<Expr>, map_res!( digit, |digits| -> Result<Expr, ParseError> { let string = try!(String::from_utf8(From::from(digits))); let number = try!(i64::from_str(&string)); Ok(Expr::Integer(number)) } )); named!(floating<Expr>, map_res!(chain!( i: digit ~ char!('.') ~ d: digit , || -> Result<Expr, ParseError> { let istr = try!(String::from_utf8(From::from(i))); let dstr = try!(String::from_utf8(From::from(d))); let string = format!("{}.{}", istr, dstr); let number = try!(f64::from_str(&string)); Ok(Expr::Floating(number)) }), |res| res )); named!(string<Expr>, map!(delimited!( char!('"'), many0!(none_of!("\"")), char!('"')), |s: Vec<char>| Expr::String(String::from_iter(s.into_iter())) )); const SYMBOL_START_CHARS: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-*/%!=<>@&:?"; const SYMBOL_CHARS: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-*/%!=<>@&:?0123456789."; named!(symbol<Expr>, chain!( first: one_of!(SYMBOL_START_CHARS) ~ rest: many0!(one_of!(SYMBOL_CHARS)) , || Expr::Symbol(String::from_iter(iter::once(first).chain(rest))) )); named!(list<Expr>, map!(delimited!( char!('('), exprs, char!(')') ), |l: Vec<Expr>| Expr::make_list(&l))); named!(vector<Expr>, map!(delimited!( char!('['), exprs, char!(']') ), |l| Expr::Vector(l))); named!(quote<Expr>, chain!( char!('\'') ~ expr: expr , || Expr::make_list(&vec![Expr::Symbol("quote".to_string()), expr]) )); named!(quasiquote<Expr>, chain!( char!('`') ~ expr: expr , || Expr::make_list(&vec![Expr::Symbol("quasiquote".to_string()), expr]) )); named!(unquote<Expr>, chain!( char!(',') ~ expr: expr , || Expr::make_list(&vec![Expr::Symbol("unquote".to_string()), expr]) )); named!(unquote_splicing<Expr>, chain!( tag!(",@") ~ expr: expr , || Expr::make_list(&vec![Expr::Symbol("unquote-splicing".to_string()), expr]) )); named!(expr<Expr>, alt!( unquote_splicing | unquote | quasiquote | quote | list | vector | floating | integer | string | symbol )); named!(exprs< Vec<Expr> >, delimited!( many0!(space), separated_list!(multispace, expr), many0!(space) )); /// `parse` attempts to parse expressions from source code. pub fn parse(src_raw: &str) -> Result<Vec<Expr>, ParseError> { let mut uncommented_lines = vec![]; for line in src_raw.lines() { let uncommented = line.split(';').next().unwrap(); uncommented_lines.push(uncommented); } let src = uncommented_lines.join("\n").trim().bytes().collect::<Vec<u8>>(); match exprs(&src) { IResult::Done(remaining, out) => { if String::from_utf8_lossy(remaining).trim().len() == 0 { Ok(out) } else { Err(ParseError::UnparsedInput(String::from_utf8_lossy(remaining).into_owned().to_string())) } } IResult::Error(err) => Err(From::from(err)), IResult::Incomplete(i) => Err(ParseError::IncompleteInputError(i)), } }
use header::{self, HdrVal}; use headers::parse::CommaDelimited; use std::fmt; /// A value to represent an encoding used in `Transfer-Encoding` /// or `Accept-Encoding` header. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Encoding<T> { kind: Kind<T>, } /// Represents one or more encodings #[derive(Clone, Debug)] pub struct Encodings<T> { kind: Kind<T>, } /// Iterate encodings pub struct Iter<'a> { // TODO: unbox inner: Option<Kind<Box<Iterator<Item = Encoding<&'a HdrVal>> + 'a>>>, } /// Encoding kinds #[derive(Clone, PartialEq, Eq, Debug)] enum Kind<T> { Chunked, Brotli, Gzip, Deflate, Compress, Identity, Trailers, Ext(T), } // ===== impl Encoding ===== impl<T> Encoding<T> { /// Chunked encoding pub const CHUNKED: Encoding<T> = Encoding { kind: Kind::Chunked, }; /// Convert an `Encoding` from the provided bytes. pub fn parse(src: T) -> Encoding<T> where T: AsRef<HdrVal>, { use self::Kind::*; match src.as_ref().as_bytes() { b"chunked" => Chunked.into(), b"br" => Brotli.into(), b"deflate" => Deflate.into(), b"gzip" => Gzip.into(), b"compress" => Compress.into(), b"identity" => Identity.into(), b"trailers" => Trailers.into(), _ => Ext(src).into(), } } } impl<T: fmt::Display> fmt::Display for Encoding<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use self::Kind::*; match self.kind { Chunked => fmt.write_str("chunked"), Brotli => fmt.write_str("br"), Gzip => fmt.write_str("gzip"), Deflate => fmt.write_str("deflate"), Compress => fmt.write_str("compress"), Identity => fmt.write_str("identity"), Trailers => fmt.write_str("trailers"), Ext(ref s) => s.fmt(fmt), } } } impl<T> From<Kind<T>> for Encoding<T> { fn from(kind: Kind<T>) -> Self { Encoding { kind } } } // ===== impl Encodings ===== impl<T> Encodings<T> where T: header::Encoded, { /// Create a new `Encodings` pub fn new(inner: T) -> Self { Encodings { kind: Kind::Ext(inner) } } pub fn is_empty(&self) -> bool { use self::Kind::*; match self.kind { Ext(ref ext) => ext.is_empty(), _ => false, } } pub fn iter(&self) -> Iter { use self::Kind::*; let kind = match self.kind { Chunked => Chunked, Brotli => Brotli, Gzip => Gzip, Deflate => Deflate, Compress => Compress, Identity => Identity, Trailers => Trailers, Ext(ref ext) => { let inner = ext.iter() .flat_map(CommaDelimited::new) .map(Encoding::parse); Ext(Box::new(inner) as Box<Iterator<Item = Encoding<&HdrVal>>>) } }; Iter { inner: Some(kind) } } } // ===== impl Iter ===== impl<'a> Iterator for Iter<'a> { type Item = Encoding<&'a HdrVal>; fn next(&mut self) -> Option<Self::Item> { use self::Kind::*; match self.inner { Some(Chunked) => { self.inner = None; Some(Encoding { kind: Chunked }) } Some(Brotli) => { self.inner = None; Some(Encoding { kind: Brotli }) } Some(Gzip) => { self.inner = None; Some(Encoding { kind: Gzip }) } Some(Deflate) => { self.inner = None; Some(Encoding { kind: Deflate }) } Some(Compress) => { self.inner = None; Some(Encoding { kind: Compress }) } Some(Identity) => { self.inner = None; Some(Encoding { kind: Identity }) } Some(Trailers) => { self.inner = None; Some(Encoding { kind: Trailers }) } Some(Ext(ref mut ext)) => { ext.next() } None => { None } } } }
// 有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。 // 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。 // 为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。 // 最后返回经过上色渲染后的图像。 // // ## 示例 1: // // 输入: // image = [[1,1,1],[1,1,0],[1,0,1]] // sr = 1, sc = 1, newColor = 2 // 输出: [[2,2,2],[2,2,0],[2,0,1]] // 解析: // 在图像的正中间,(坐标(sr,sc)=(1,1)), // 在路径上所有符合条件的像素点的颜色都被更改成2。 // 注意,右下角的像素没有更改为2, // 因为它不是在上下左右四个方向上与初始点相连的像素点。 // // 注意: // - image 和 image[0] 的长度在范围 [1, 50] 内。 // - 给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。 // - image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。 // // 来源:力扣(LeetCode) // 链接:https://leetcode-cn.com/problems/flood-fill // 题目描述著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 use std::collections::VecDeque; pub fn flood_fill(mut image: Vec<Vec<i32>>, sr: i32, sc: i32, new_color: i32) -> Vec<Vec<i32>> { let (rows, cols) = (image.len(), image[0].len()); let (sr, sc) = (sr as usize, sc as usize); let mut que = VecDeque::<(usize, usize)>::new(); let init_color = image[sr][sc]; // 注意如果色块已经是新颜色,且新颜色和旧颜色相同,则不需要重复渲染 que.push_back((sr, sc)); while !que.is_empty() { let (sr, sc) = que.pop_front().unwrap(); if sr >= 1 && image[sr - 1][sc] == init_color && image[sr - 1][sc] != new_color { que.push_back((sr - 1, sc)); } if sr + 1 < rows && image[sr + 1][sc] == init_color && image[sr + 1][sc] != new_color { que.push_back((sr + 1, sc)); } if sc >= 1 && image[sr][sc - 1] == init_color && image[sr][sc - 1] != new_color { que.push_back((sr, sc - 1)); } if sc + 1 < cols && image[sr][sc + 1] == init_color && image[sr][sc + 1] != new_color { que.push_back((sr, sc + 1)); } image[sr][sc] = new_color; } image } #[cfg(test)] mod test { use super::*; #[test] fn test_example() { let mut v: Vec<Vec<i32>> = vec![ vec![1,1,1], vec![1,1,0], vec![1,0,1], ]; v = flood_fill(v, 1, 1, 2); assert_eq!(v, vec![ vec![2, 2, 2], vec![2, 2, 0], vec![2, 0, 1], ]); } #[test] fn test_already_new_color() { let mut v: Vec<Vec<i32>> = vec![ vec![0,0,0], vec![0,1,1], ]; v = flood_fill(v, 1, 1, 1); assert_eq!(v, vec![ vec![0,0,0], vec![0,1,1], ]); } }
extern crate ggez; extern crate nalgebra; extern crate rand; extern crate hsluv; use ggez::*; use ggez::event::{self, Keycode, Mod, MouseButton, MouseState}; use ggez::graphics::{DrawParam, DrawMode, Mesh, Rect, Point2, Vector2, Matrix4}; use nalgebra::{Real}; use std::fs::File; mod entities; mod star_system_gen; use entities::{G, CelestialObject, Spaceship}; use star_system_gen::*; struct Orbit { pub body_center: Point2, pub e: Vector2, pub p: f32, } impl Orbit { fn new(body_center: Point2, e: Vector2, p: f32) -> Self { Orbit { body_center, e, p } } fn ellipse_axes(&self) -> Option<(f32, f32)> { let e2 = self.e.norm_squared(); if e2 < 1. { let a = self.p / (1. - e2); let b = a * (1. - e2).sqrt(); Some((a, b)) } else { None } } } impl Default for Orbit { fn default() -> Self { Orbit::new(Point2::origin(), Vector2::x(), 0.) } } struct MainState { bodies: Vec<CelestialObject>, player: Spaceship, camera: DrawParam, mouse: Point2, mouse_down: bool, orbit: Orbit, } impl MainState { fn new(_ctx: &mut Context) -> GameResult<MainState> { let sun = random_star(); let mut bodies = vec![]; for _ in 0..4 { bodies.push(random_rocky_planet(&sun)); } for _ in 0..4 { bodies.push(random_gas_giant_planet(&sun)); } let player = Spaceship::new_in_orbit( &sun, Point2::new(250., 0.), true, 1. ); bodies.push(sun); let camera = DrawParam { src: Rect::one(), dest: Point2::origin(), rotation: 0.0, scale: Point2::new(1.0, 1.0), offset: Point2::new(0., 0.), shear: Point2::new(0.0, 0.0), color: None, }; let s = MainState { bodies, player, camera, mouse: Point2::origin(), mouse_down: false, orbit: Orbit::default(), }; Ok(s) } } fn mouse_to_screen_coordinates(ctx: &Context, x: i32, y: i32) -> (f32, f32) { let (w, h) = graphics::get_size(ctx); let screen = graphics::get_screen_coordinates(ctx); (screen.x + (x as f32 / w as f32) * screen.w, screen.y + (y as f32 / h as f32) * screen.h) } impl event::EventHandler for MainState { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { const DESIRED_FPS: u32 = 60; while timer::check_update_time(ctx, DESIRED_FPS) { let seconds = 1. / (DESIRED_FPS as f32); for i in 0..self.bodies.len() { let (object, rest) = self.bodies.split_at_mut(i+1); let object = object.last_mut().unwrap(); for other in rest { object.body.apply_gravity(&other.body, seconds); other.body.apply_gravity(&object.body, seconds); } self.player.body.apply_gravity(&object.body, seconds); object.update(seconds)?; } let mut min_rad = std::f32::INFINITY; self.orbit = Orbit::default(); for object in self.bodies.iter() { let body = &object.body; let player = &self.player.body; let r = player.pos - body.pos; let v = player.vel - body.vel; let h = r.perp(&v); let mu = G * body.mass; let e = Vector2::new(v.y * h, -v.x * h) / mu - r.normalize(); if e.norm() < 1. && r.norm() < min_rad { min_rad = r.norm(); self.orbit = Orbit::new(body.pos, e, h*h / mu); } } let mouse_rel = self.mouse - Point2::new(400., 300.); let angle = Real::atan2(mouse_rel.y, mouse_rel.x); self.player.rot = angle; if self.mouse_down { let ACC: f32 = 10.; self.player.body.vel += seconds * ACC * Vector2::new(angle.cos(), angle.sin()); } self.player.update(seconds)?; self.camera.dest = -self.player.body.pos + Vector2::new(400., 300.); self.camera.offset = self.player.body.pos; } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::clear(ctx); graphics::push_transform(ctx, Some(self.camera.into_matrix())); //graphics::push_transform(ctx, Some(Matrix4::new_scaling(self.camera.scale.x))); //graphics::push_transform(ctx, None); graphics::apply_transformations(ctx)?; let scale = self.camera.scale.x; let inv_scale = Point2::new(1./scale, 1./scale); if let Some((a, b)) = self.orbit.ellipse_axes() { let c = (a*a - b*b).sqrt(); let center = self.orbit.body_center - self.orbit.e.normalize() * c; graphics::set_color(ctx, [1.0, 0.0, 0.0, 1.].into())?; let ellipse = Mesh::new_ellipse( ctx, DrawMode::Line(2.), Point2::origin(), a*scale, b*scale, 1.)?; // TODO idk why this works let angle = if self.orbit.e.y >= 0. { self.orbit.e.angle(&Vector2::x()) } else { f32::pi() - self.orbit.e.angle(&Vector2::x()) }; graphics::draw_ex( ctx, &ellipse, DrawParam { dest: center, rotation: angle, scale: inv_scale, ..Default::default() })?; }; //graphics::pop_transform(ctx); //graphics::apply_transformations(ctx)?; for body in &mut self.bodies { body.draw(ctx)?; } self.player.draw(ctx)?; graphics::pop_transform(ctx); graphics::apply_transformations(ctx)?; self.player.draw_ui(ctx)?; graphics::present(ctx); timer::yield_now(); Ok(()) } fn mouse_button_down_event(&mut self, _ctx: &mut Context, _button: MouseButton, _x: i32, _y: i32) { self.mouse_down = true; } fn mouse_button_up_event(&mut self, _ctx: &mut Context, _button: MouseButton, _x: i32, _y: i32) { self.mouse_down = false; } fn mouse_motion_event( &mut self, ctx: &mut Context, _state: MouseState, x: i32, y: i32, _xrel: i32, _yrel: i32, ) { let (x, y) = mouse_to_screen_coordinates(ctx, x, y); self.mouse = Point2::new(x, y); } fn mouse_wheel_event(&mut self, _ctx: &mut Context, _x: i32, y: i32) { if y > 0 { self.camera.scale *= 1.1; } else if y < 0 { self.camera.scale /= 1.1; } } /*fn key_down_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) { println!( "Key pressed: {:?}, modifier {:?}, repeat: {}", keycode, keymod, repeat ); } fn key_up_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) { println!( "Key released: {:?}, modifier {:?}, repeat: {}", keycode, keymod, repeat ); }*/ } const SCALING_FACTOR: f32 = 2.; pub fn main() { // TODO handle errors let mut config_file = File::open("config.toml").unwrap(); let c = conf::Conf::from_toml_file(&mut config_file).unwrap(); let ctx = &mut Context::load_from_conf("super_simple", "ggez", c).unwrap(); let state = &mut MainState::new(ctx).unwrap(); // High-DPI stuff // TODO pull that into a config file let (w, h) = graphics::get_size(ctx); graphics::set_resolution(ctx, (SCALING_FACTOR * w as f32) as u32, (SCALING_FACTOR * h as f32) as u32).unwrap(); event::run(ctx, state).unwrap(); }
/// AnnotatedTagObject contains meta information of the tag object #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct AnnotatedTagObject { pub sha: Option<String>, #[serde(rename = "type")] pub type_: Option<String>, pub url: Option<String>, } impl AnnotatedTagObject { /// Create a builder for this object. #[inline] pub fn builder() -> AnnotatedTagObjectBuilder { AnnotatedTagObjectBuilder { body: Default::default(), } } } impl Into<AnnotatedTagObject> for AnnotatedTagObjectBuilder { fn into(self) -> AnnotatedTagObject { self.body } } /// Builder for [`AnnotatedTagObject`](./struct.AnnotatedTagObject.html) object. #[derive(Debug, Clone)] pub struct AnnotatedTagObjectBuilder { body: self::AnnotatedTagObject, } impl AnnotatedTagObjectBuilder { #[inline] pub fn sha(mut self, value: impl Into<String>) -> Self { self.body.sha = Some(value.into()); self } #[inline] pub fn type_(mut self, value: impl Into<String>) -> Self { self.body.type_ = Some(value.into()); self } #[inline] pub fn url(mut self, value: impl Into<String>) -> Self { self.body.url = Some(value.into()); self } }
#[doc = "Register `OR` reader"] pub type R = crate::R<OR_SPEC>; #[doc = "Register `OR` writer"] pub type W = crate::W<OR_SPEC>; #[doc = "Field `OR_` reader - Option register bit 1"] pub type OR__R = crate::FieldReader<OR__A>; #[doc = "Option register bit 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum OR__A { #[doc = "0: Input 1 is connected to I/O"] Io = 0, #[doc = "1: Input 1 is connected to COMP1_OUT"] Comp1Out = 1, #[doc = "2: Input 1 is connected to COMP2_OUT"] Comp2Out = 2, #[doc = "3: Input 1 is connected to COMP1_OUT OR COMP2_OUT"] OrComp1Comp2 = 3, } impl From<OR__A> for u8 { #[inline(always)] fn from(variant: OR__A) -> Self { variant as _ } } impl crate::FieldSpec for OR__A { type Ux = u8; } impl OR__R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OR__A { match self.bits { 0 => OR__A::Io, 1 => OR__A::Comp1Out, 2 => OR__A::Comp2Out, 3 => OR__A::OrComp1Comp2, _ => unreachable!(), } } #[doc = "Input 1 is connected to I/O"] #[inline(always)] pub fn is_io(&self) -> bool { *self == OR__A::Io } #[doc = "Input 1 is connected to COMP1_OUT"] #[inline(always)] pub fn is_comp1_out(&self) -> bool { *self == OR__A::Comp1Out } #[doc = "Input 1 is connected to COMP2_OUT"] #[inline(always)] pub fn is_comp2_out(&self) -> bool { *self == OR__A::Comp2Out } #[doc = "Input 1 is connected to COMP1_OUT OR COMP2_OUT"] #[inline(always)] pub fn is_or_comp1_comp2(&self) -> bool { *self == OR__A::OrComp1Comp2 } } #[doc = "Field `OR_` writer - Option register bit 1"] pub type OR__W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, OR__A>; impl<'a, REG, const O: u8> OR__W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "Input 1 is connected to I/O"] #[inline(always)] pub fn io(self) -> &'a mut crate::W<REG> { self.variant(OR__A::Io) } #[doc = "Input 1 is connected to COMP1_OUT"] #[inline(always)] pub fn comp1_out(self) -> &'a mut crate::W<REG> { self.variant(OR__A::Comp1Out) } #[doc = "Input 1 is connected to COMP2_OUT"] #[inline(always)] pub fn comp2_out(self) -> &'a mut crate::W<REG> { self.variant(OR__A::Comp2Out) } #[doc = "Input 1 is connected to COMP1_OUT OR COMP2_OUT"] #[inline(always)] pub fn or_comp1_comp2(self) -> &'a mut crate::W<REG> { self.variant(OR__A::OrComp1Comp2) } } impl R { #[doc = "Bits 0:1 - Option register bit 1"] #[inline(always)] pub fn or_(&self) -> OR__R { OR__R::new((self.bits & 3) as u8) } } impl W { #[doc = "Bits 0:1 - Option register bit 1"] #[inline(always)] #[must_use] pub fn or_(&mut self) -> OR__W<OR_SPEC, 0> { OR__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 = "option register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`or::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 [`or::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct OR_SPEC; impl crate::RegisterSpec for OR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`or::R`](R) reader structure"] impl crate::Readable for OR_SPEC {} #[doc = "`write(|w| ..)` method takes [`or::W`](W) writer structure"] impl crate::Writable for OR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets OR to value 0"] impl crate::Resettable for OR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::io::Write; use crossterm::{ cursor::{self}, style::{self, Colorize, StyledContent}, QueueableCommand, Result, }; #[derive(Clone, Copy, Debug)] pub enum GameContent { SnakeHead(usize), SnakeBody(usize), Food, Border, Empty, Character(char), CharacterOnBorder(char), } fn map_game_content_to_color(gc: &GameContent, is_padded_char: bool) -> StyledContent<String> { // \u{2588} is a full block symbol match gc { GameContent::SnakeHead(player_idx) => { if *player_idx == 0_usize { "\u{2588}".to_string().dark_green() } else { "\u{2588}".to_string().dark_yellow() } } GameContent::SnakeBody(player_idx) => { if *player_idx == 0_usize { "\u{2588}".to_string().green() } else { "\u{2588}".to_string().yellow() } } GameContent::Food => "\u{2588}".to_string().red(), GameContent::Border => "\u{2588}".to_string().dark_blue(), GameContent::Empty => "\u{2588}".to_string().black(), GameContent::Character(some_char) => { if is_padded_char { "\u{2588}".to_string().black() } else { some_char.to_string().white().on_black() } } GameContent::CharacterOnBorder(some_char) => { if is_padded_char { "\u{2588}".to_string().dark_blue() } else { some_char.to_string().white().on_dark_blue() } } } } #[derive(PartialEq, Clone, Copy, Debug)] pub struct Coordinate { pub row: usize, pub col: usize, } pub struct ScreenBuffer { screen_width: usize, screen_height: usize, buffer: Vec<GameContent>, } impl ScreenBuffer { pub fn new( screen_width: usize, screen_height: usize, initial_content: GameContent, ) -> ScreenBuffer { ScreenBuffer { screen_height, screen_width, buffer: vec![initial_content; screen_height * screen_width], } } pub fn set_all(&mut self, content: GameContent) { for screen_char in &mut self.buffer { *screen_char = content; } } pub fn set_centered_text_at_row(&mut self, target_row: usize, message: &str) { let str_chars = message.chars(); let str_len = str_chars.clone().count(); let header_start_idx = ((self.screen_width - str_len) / 2usize).max(0); let mut col_idx = header_start_idx; for sym in str_chars { let gc = if target_row == 0 { GameContent::CharacterOnBorder(sym) } else { GameContent::Character(sym) }; self.set_at(target_row, col_idx, gc); col_idx += 1; } } pub fn get_at(&self, row: usize, col: usize) -> GameContent { self.buffer[col + row * self.screen_width] } pub fn set_at(&mut self, row: usize, col: usize, content: GameContent) { self.buffer[col + row * self.screen_width] = content; } pub fn add_border(&mut self, border_symbol: GameContent) { for row in 0..self.screen_height { self.set_at(row, 0, border_symbol); self.set_at(row, self.screen_width - 1, border_symbol); } for col in 0..self.screen_width { self.set_at(0, col, border_symbol); self.set_at(self.screen_height - 1, col, border_symbol); } } pub fn draw(&self, stdout: &mut std::io::Stdout) -> Result<()> { for row_idx in 0..self.screen_height { for col_idx_buffer in 0..self.screen_width { let content = self.get_at(row_idx, col_idx_buffer); // draw each element twice horizontally, so that we get square "pixels" for i in 0..2 { let col_idx = 2 * col_idx_buffer + i; let styled_content = map_game_content_to_color(&content, i != 0); stdout .queue(cursor::MoveTo(col_idx as u16, row_idx as u16))? .queue(style::PrintStyledContent(styled_content))?; } } } stdout.flush()?; Ok(()) } }
pub fn run() { let groups: Vec<&str> = include_str!("input.txt").split("\n\n").collect(); let mut some = 0; let mut all = 0; for g in groups.iter() { let a = count_answers_in_group(g); some += a.0; all += a.1; } println!("Day06 - Part 1: {}", some); println!("Day06 - Part 2: {}", all); } fn count_answers_in_group(forms: &str) -> (i32, i32) { let chars: Vec<char> = forms.chars().collect(); let mut count: [i32; 26] = [0; 26]; let mut num_of_groups = 1; for c in chars.iter() { if c.is_whitespace() { num_of_groups += 1; } else { count[(*c as usize)-97] += 1; } } let mut some = 0; let mut all = 0; for c in count.iter() { if *c > 0 { some += 1; } if *c == num_of_groups { all += 1; } } (some, all) } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_answers_in_group() { let count = count_answers_in_group("ab ac"); assert_eq!(3, count.0); assert_eq!(1, count.1); } }
use lazy_static::lazy_static; use regex::Regex; use serde::{Deserialize, Serialize}; lazy_static! { /// Check if a wikipedia anchor links to an external resource. static ref EXT_LINK : Regex = Regex::new("^[A-Za-z]+:").unwrap(); } /// Wikipedia anchor, representing a link between pages, optionally with a /// surface realisation. #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum Anchor { Direct(String), Label { surface: String, page: String }, } impl Anchor { /// Parse an anchor string, returning an Anchor. /// /// We consider two forms: /// - [[abc]] is seen as "abc" in text and links to page "abc". /// - [[a|b]] is labelled "b" but links to page "a". pub fn parse(anchor: &str) -> Self { match anchor.find('|') { Some(index) => { let page = anchor[..index].trim(); let page = match page.find('#') { None => page.to_owned(), Some(index) => page[..index].to_owned(), }; let surface = anchor[index + 1..].trim().trim_matches('\''); if surface.is_empty() { Anchor::Direct(page) } else { Anchor::Label { page, surface: surface.to_owned(), } } } None => match anchor.find('#') { None => Anchor::Direct(anchor.trim().to_owned()), Some(index) => Anchor::Direct(anchor.trim()[..index].to_owned()), }, } } /// Extract the text of an anchor, given a start index within a string /// slice. pub fn pare_anchor_match(page: &str, begin: usize) -> Option<&str> { let initial = &page[begin + 2..]; if initial.starts_with("#") { return None; } if EXT_LINK.is_match(initial) { return None; } page[begin..] .find("]]") .and_then(|end| Some(&page[begin + 2..begin + end])) } /// Check if an anchor string points to a file. pub fn is_file(anchor: &str) -> bool { anchor.starts_with("File:") || anchor.starts_with("Image:") } /// Check if an anchor points to Wiktionary. pub fn is_wiktionary(anchor: &str) -> bool { anchor.starts_with("wikt:") || anchor.starts_with("wiktionary:") } /// Check if an anchor points to Wikisource. pub fn is_wikisource(anchor: &str) -> bool { anchor.starts_with("s:") } /// Check if an anchor points to Wikiversity. pub fn is_wikiversity(anchor: &str) -> bool { anchor.starts_with("v:") } /// Check if an anchor points to handle.net. pub fn is_handle(anchor: &str) -> bool { anchor.starts_with("hdl:") } } #[cfg(test)] mod test { use super::*; #[test] fn test_anchor_lowercases_labels() { let anchor = Anchor::parse(" page"); assert_eq!(anchor, Anchor::Direct("page".to_owned())); } #[test] fn test_direct_anchor_trims_whitespace() { let anchor = Anchor::parse(" page"); assert_eq!(anchor, Anchor::Direct("page".to_owned())); } #[test] fn test_label_anchor_trims_whitespace() { let anchor = Anchor::parse(" page | label "); assert_eq!( anchor, Anchor::Label { surface: "label".to_owned(), page: "page".to_owned(), } ); } #[test] fn test_anchor_trims_page_anchor() { let anchor = Anchor::parse("page#anchor"); assert_eq!(anchor, Anchor::Direct("page".to_owned())); let anchor = Anchor::parse("page#anchor| label "); assert_eq!( anchor, Anchor::Label { surface: "label".to_owned(), page: "page".to_owned(), } ); } }
use super::*; use super::{Highlight, Select}; use std::sync::atomic::Ordering; use std::sync::Arc; use tokio::sync::RwLock; #[derive(Clone)] pub enum FocusedWidget<'a> { DownloadTable(Arc<RwLock<DownloadTable<'a>>>), FileTable(Arc<RwLock<FileTable<'a>>>), MessageList(Arc<RwLock<MessageList<'a>>>), } /* I couldn't figure out how to avoid copypasting here. All the enum members implement the Highlight and Select * trait, which have the methods we need here. */ impl<'a> FocusedWidget<'a> { pub async fn change_to(&mut self, mut selected: FocusedWidget<'a>) { match self { FocusedWidget::DownloadTable(current) => { current.write().await.unfocus().await; selected.focus().await; *self = selected; } FocusedWidget::FileTable(current) => { current.write().await.unfocus().await; selected.focus().await; *self = selected; } FocusedWidget::MessageList(current) => { current.write().await.unfocus().await; selected.focus().await; *self = selected; } } } pub async fn next(&mut self) { match self { Self::DownloadTable(dt) => { let mut table_lock = dt.write().await; let dls = table_lock.downloads.clone(); let tasks_lock = dls.tasks.read().await; table_lock.next(tasks_lock.len()); table_lock.needs_redraw.store(true, Ordering::Relaxed); } Self::FileTable(ft) => { let mut table_lock = ft.write().await; let file_index = table_lock.file_index.clone(); let files_lock = file_index.file_id_map.read().await; table_lock.next(files_lock.len()); table_lock.needs_redraw.store(true, Ordering::Relaxed); } Self::MessageList(ml) => { let mut list_lock = ml.write().await; let msgs = list_lock.msgs.clone(); let msgs_lock = msgs.messages.read().await; list_lock.next(msgs_lock.len()); list_lock.needs_redraw.store(true, Ordering::Relaxed); } } } pub async fn previous(&mut self) { match self { Self::DownloadTable(dt) => { let mut table_lock = dt.write().await; let dls = table_lock.downloads.clone(); let tasks_lock = dls.tasks.read().await; table_lock.previous(tasks_lock.len()); table_lock.needs_redraw.store(true, Ordering::Relaxed); } Self::FileTable(ft) => { let mut table_lock = ft.write().await; let file_index = table_lock.file_index.clone(); let files_lock = file_index.file_id_map.read().await; table_lock.previous(files_lock.len()); table_lock.needs_redraw.store(true, Ordering::Relaxed); } Self::MessageList(ml) => { let mut list_lock = ml.write().await; let msgs = list_lock.msgs.clone(); let msgs_lock = msgs.messages.read().await; list_lock.previous(msgs_lock.len()); list_lock.needs_redraw.store(true, Ordering::Relaxed); } } } pub async fn focus(&mut self) { match self { FocusedWidget::DownloadTable(current) => { current.write().await.focus().await; } FocusedWidget::FileTable(current) => { current.write().await.focus().await; } FocusedWidget::MessageList(current) => { current.write().await.focus().await; } } } }
use std::marker::PhantomData; use super::Pusherator; pub struct ForEach<Func, In> { func: Func, _marker: PhantomData<fn(In)>, } impl<Func, In> Pusherator for ForEach<Func, In> where Func: FnMut(In), { type Item = In; fn give(&mut self, item: Self::Item) { (self.func)(item) } } impl<Func, In> ForEach<Func, In> where Func: FnMut(In), { pub fn new(func: Func) -> Self { Self { func, _marker: PhantomData, } } }