text
stringlengths
8
4.13M
use std::{collections::HashSet, fmt, mem}; const INPUT: &str = include_str!("../input"); #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)] struct Coordinate { y: usize, x: usize, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Direction { Up, Left, Right, Down, } impl Direction { fn from_character(c: char) -> Option<Self> { match c { '^' => Some(Direction::Up), '<' => Some(Direction::Left), '>' => Some(Direction::Right), 'v' => Some(Direction::Down), _ => None, } } fn to_character(&self) -> char { match self { Direction::Up => '^', Direction::Down => 'v', Direction::Left => '<', Direction::Right => '>', } } fn turn_right(&self) -> Self { match self { Direction::Up => Direction::Right, Direction::Down => Direction::Left, Direction::Left => Direction::Up, Direction::Right => Direction::Down, } } fn turn_left(&self) -> Self { match self { Direction::Up => Direction::Left, Direction::Down => Direction::Right, Direction::Left => Direction::Down, Direction::Right => Direction::Up, } } fn curve(&self, curve_direction: &CurveDirection) -> Self { match curve_direction { CurveDirection::Right => { match self { // /- to >- // ^ | Direction::Up => self.turn_right(), // v to | // -/ -< Direction::Down => self.turn_right(), // | to | // >/ -^ Direction::Right => self.turn_left(), // /< to v- // | | Direction::Left => self.turn_left(), } } CurveDirection::Left => { match self { // -\ to -< // ^ | Direction::Up => self.turn_left(), // v to | // \- >- Direction::Down => self.turn_left(), // >\ to -v // | | Direction::Right => self.turn_right(), // | to | // \< ^- Direction::Left => self.turn_right(), } } } } } impl fmt::Display for Direction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_character()) } } #[derive(Debug, Clone)] enum TrackOrientation { Vertical, Horizontal, } /// Curve directions are based on the direction a cart moving up or down would turn. /// A cart moving left or right would turn the opposite way. /// /// Examples: /// - current direction up, turn right -> right /// - current direction down, turn right -> left /// - current direction right, turn right -> up /// - current direction left, turn right -> down #[derive(Debug, Clone)] enum CurveDirection { Left, Right, } #[derive(Debug, Clone)] enum Track { Intersection, Curve(CurveDirection), Straight(TrackOrientation), } impl Track { fn from_character(c: char) -> Option<Self> { match c { '|' => Some(Track::Straight(TrackOrientation::Vertical)), '-' => Some(Track::Straight(TrackOrientation::Horizontal)), '\\' => Some(Track::Curve(CurveDirection::Left)), '/' => Some(Track::Curve(CurveDirection::Right)), '+' => Some(Track::Intersection), '^' | 'v' => Some(Track::Straight(TrackOrientation::Vertical)), '<' | '>' => Some(Track::Straight(TrackOrientation::Horizontal)), _ => None, } } fn to_character(&self) -> char { match *self { Track::Straight(TrackOrientation::Vertical) => '|', Track::Straight(TrackOrientation::Horizontal) => '-', Track::Curve(CurveDirection::Left) => '\\', Track::Curve(CurveDirection::Right) => '/', Track::Intersection => '+', } } } impl fmt::Display for Track { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_character()) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct Cart { direction: Direction, position: Coordinate, intersections_hit: u32, } impl Cart { fn new(position: Coordinate, direction: Direction) -> Self { Self { position, direction, intersections_hit: 0, } } fn move_forward(&mut self) { match self.direction { Direction::Up => self.position.y -= 1, Direction::Down => self.position.y += 1, Direction::Right => self.position.x += 1, Direction::Left => self.position.x -= 1, } } fn reorient(&mut self, track: &Track) { let current_direction = mem::replace(&mut self.direction, Direction::Up); self.direction = match track { Track::Curve(curve_direction) => current_direction.curve(curve_direction), Track::Intersection => { let new_direction = match self.intersections_hit % 3 { 0 => current_direction.turn_left(), 1 => current_direction, 2 => current_direction.turn_right(), _ => unreachable!(), }; self.intersections_hit += 1; new_direction } Track::Straight(_) => current_direction, } } } impl fmt::Display for Cart { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.direction) } } #[derive(Debug, Clone)] struct Map { tracks: Vec<Vec<Option<Track>>>, carts: Vec<Cart>, } impl Map { fn from_input(input: &str) -> Self { let mut carts = vec![]; let mut tracks = vec![]; for (i, line) in input.lines().enumerate() { let mut track_row = vec![]; for (j, c) in line.chars().enumerate() { if let Some(d) = Direction::from_character(c) { carts.push(Cart::new(Coordinate { x: j, y: i }, d)); } track_row.push(Track::from_character(c)); } tracks.push(track_row); } Self { carts, tracks } } fn find_first_crash(&mut self) -> Coordinate { loop { self.carts.sort_by_key(|c| c.position); let mut cart_positions: HashSet<_> = self.carts.iter().map(|c| c.position).collect(); for cart in self.carts.iter_mut() { cart_positions.remove(&cart.position); cart.move_forward(); let track = &self.tracks[cart.position.y][cart.position.x]; let track = track.as_ref().expect("Cart off the rails!!!"); cart.reorient(track); if !cart_positions.insert(cart.position) { return cart.position; } } } } fn find_last_cart(&mut self) -> Coordinate { loop { self.carts.sort_by_key(|c| c.position); let mut cart_positions: HashSet<_> = self.carts.iter().map(|c| c.position).collect(); let mut crash_positions = HashSet::new(); for cart in self.carts.iter_mut() { if crash_positions.contains(&cart.position) { continue; } cart_positions.remove(&cart.position); cart.move_forward(); let track = &self.tracks[cart.position.y][cart.position.x]; let track = track.as_ref().expect("Cart off the rails!!!"); cart.reorient(track); if !cart_positions.insert(cart.position) { crash_positions.insert(cart.position); } } self.carts .retain(|c| !crash_positions.contains(&c.position)); if self.carts.len() == 1 { return self.carts[0].position; } if self.carts.is_empty() { panic!("All carts removed"); } } } } impl fmt::Display for Map { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, row) in self.tracks.iter().enumerate() { for (j, track) in row.iter().enumerate() { let carts_at_current_position: Vec<_> = self .carts .iter() .filter(|c| c.position.x == j && c.position.y == i) .collect(); if carts_at_current_position.len() == 1 { write!(f, "{}", carts_at_current_position[0])?; } else if carts_at_current_position.len() > 1 { write!(f, "{}", 'X')?; } else { let out: Box<dyn fmt::Display> = match track { Some(t) => Box::new(t), None => Box::new(' '), }; write!(f, "{}", out)?; } } writeln!(f)?; } Ok(()) } } fn main() { let m = Map::from_input(INPUT); let Coordinate { x, y } = m.clone().find_first_crash(); println!("{},{}", x, y); let Coordinate { x, y } = m.clone().find_last_cart(); println!("{},{}", x, y); } #[cfg(test)] mod test { use super::*; const SAMPLE_INPUT: &str = include_str!("../sample-input"); const PART_TWO_SAMPLE_INPUT: &str = include_str!("../part-two-sample-input"); #[test] fn it_parses_input_correctly() { let m = Map::from_input(SAMPLE_INPUT); // relies on display impls being correct as well assert_eq!(format!("{}", m), SAMPLE_INPUT); } #[test] fn it_finds_correct_first_crash_coordinate() { let mut m = Map::from_input(SAMPLE_INPUT); let coord = m.find_first_crash(); assert_eq!((coord.x, coord.y), (7, 3)); let mut m = Map::from_input(INPUT); let coord = m.find_first_crash(); assert_eq!((coord.x, coord.y), (82, 104)); } #[test] fn it_finds_correct_last_cart_coordinate() { let mut m = Map::from_input(PART_TWO_SAMPLE_INPUT); let coord = m.find_last_cart(); assert_eq!((coord.x, coord.y), (6, 4)); let mut m = Map::from_input(INPUT); let coord = m.find_last_cart(); assert_eq!((coord.x, coord.y), (121, 22)); } }
extern crate getopts; extern crate simple_error; use getopts::Options; use simple_error::require_with; use std::cmp::min; use std::env; use std::error::Error; use std::process; mod runtime; mod cgroup; mod filesystem; mod mount; mod namespace; mod network; fn print_usage(program: &str, opts: &Options) { let brief = format!("Usage: {} [options] [-- <command> <argument>...]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optopt("r", "rootfs", "Path to root file-system \ndefault: --rootfs ../rootfs", ""); opts.optopt("c", "command", "Command to be executed \neg. --command `curl http://google.com`", ""); opts.optopt("n", "hostname", "Customize the name of your container \ndefault: --hostname dokka", ""); opts.optopt("q", "quota", "The quota of CGroup for your process \neg. --quota cpu:cpu.cfs_quota_us:50000", ""); opts.optopt("m", "mount", "Mount directory to container \neg. --mount /root:/mnt", ""); opts.optopt("k", "network", "Add the hostname of the container that you wish to set the network up for \n eg. --network dokka", ""); opts.optflag("h", "help", "Print this help menu"); // Find the conventional "--" that separates out remaing arguments. let end_processable = args.iter().position(|s| s == "--").unwrap_or_else(|| args.len()); let begin_unprocessable = min(end_processable + 1, args.len()); let matches = opts.parse(&args[1..end_processable]).ok().unwrap_or_else(|| { println!("Error: Unrecognzied options"); print_usage(&program, &opts); process::exit(7); }); // Exits early, but doesn't lead to non-zero exit. if matches.opt_present("h") { print_usage(&program, &opts); return; } let rootfs = if matches.opt_present("r") {matches.opt_str("r").unwrap()} else {String::from("../images/rootfs")}; let mnt = if matches.opt_present("m") {matches.opt_str("m").unwrap()} else {String::from("-1")}; let name = if matches.opt_present("n") {matches.opt_str("n").unwrap()} else {String::from("dokka")}; if matches.opt_present("k") { let check = matches.opt_str("k").unwrap_or("dokka-container".to_owned()); network::net_main(&check); return; }; let quota = match matches.opt_str("quota") { Some(s) => s, None => String::from("-1"), }; let c = matches.opt_str("c"); // NB: Seperate let binding for lifetime. let (command, args) = determine_command_tuple(&c, &args[begin_unprocessable..args.len()]).ok().unwrap_or_else(|| { println!("Error: Please pass `--command <shell command>` or `-- <command> <argument>...`"); print_usage(&program, &opts); process::exit(7); }); let a: &str; let b: &str; if mnt != "-1" { let param: Vec<&str> = mnt.split(":").collect(); a = param[0]; b = param[1]; } else { a = "-1"; b = "-1"; } let cylinder = runtime::Runtime::new(&name, &rootfs, &command, &quota, a, b, args); cylinder.run_container(); } /// Determines based on the inputs whether we are going to invoke a shell, with /// shell interpretation, or a simple unescaped argument vector. /// Rearranges arguments as needed, but doesn't reallocate. fn determine_command_tuple<'a, T: AsRef<str> + 'a>(shell_command: &'a Option<T>, argv: &'a [T]) -> Result<(&'a str, Vec<&'a str>), Box<dyn Error>> { let mut vec: Vec<&str> = vec![]; // Prepend shell and command string if a command string is given. if let Some(shell_command) = shell_command { vec.push("/bin/sh"); vec.push("-c"); vec.push(shell_command.as_ref()); } // The args given will be the whole command if there's no shell string; // otherwise, they'll be added to the argument vector. vec.extend(argv.iter().map(|item| item.as_ref())); // Shift off the first word as the command, erroring out if no command is // given. vec.reverse(); let command = require_with!(vec.pop(), "Empty command!"); vec.reverse(); return Ok((command, vec)); }
#![deny(clippy::all, clippy::pedantic)] pub fn raindrops(n: u32) -> String { let mut iter = [(3, "Pling"), (5, "Plang"), (7, "Plong")] .iter() .filter_map(|(factor, label)| if n % factor == 0 { Some(*label) } else { None }) .peekable(); match iter.peek() { Some(_) => iter.collect::<String>(), None => n.to_string(), } }
use rsvm::objectmemory::{ ImageFormat, dist_format::DistFormat, text_format::TextFormat }; fn main() -> Result<(), Box<std::error::Error>> { let args = std::env::args().collect::<Vec<_>>(); let memory = DistFormat::load(&args[1])?; TextFormat::save(&args[2], &memory)?; Ok(()) }
//! Adjust and view Do Not Disturb settings for team members. use rtm::Team; /// Ends the current user's Do Not Disturb session immediately. /// /// Wraps https://api.slack.com/methods/dnd.endDnd /// Ends the current user's snooze mode immediately. /// /// Wraps https://api.slack.com/methods/dnd.endSnooze #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct EndSnoozeResponse { ok: bool, pub dnd_enabled: Option<bool>, pub next_dnd_end_ts: Option<f32>, pub next_dnd_start_ts: Option<f32>, pub snooze_enabled: Option<bool>, } /// Retrieves a user's current Do Not Disturb status. /// /// Wraps https://api.slack.com/methods/dnd.info #[derive(Clone, Debug, Serialize, new)] pub struct InfoRequest { /// User to fetch status for (defaults to current user) #[new(default)] pub user: Option<::UserId>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct InfoResponse { ok: bool, pub dnd_enabled: Option<bool>, pub next_dnd_end_ts: Option<f32>, pub next_dnd_start_ts: Option<f32>, pub snooze_enabled: Option<bool>, pub snooze_endtime: Option<f32>, pub snooze_remaining: Option<f32>, } /// Turns on Do Not Disturb mode for the current user, or changes its duration. /// /// Wraps https://api.slack.com/methods/dnd.setSnooze #[derive(Clone, Debug, Serialize, new)] pub struct SetSnoozeRequest { /// Number of minutes, from now, to snooze until. pub num_minutes: u32, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct SetSnoozeResponse { ok: bool, pub snooze_enabled: Option<bool>, pub snooze_endtime: Option<f32>, pub snooze_remaining: Option<f32>, } /// Retrieves the Do Not Disturb status for users on a team. /// /// Wraps https://api.slack.com/methods/dnd.teamInfo #[derive(Clone, Debug, Serialize, new)] pub struct TeamInfoRequest<'a> { /// Comma-separated list of users to fetch Do Not Disturb status for #[new(default)] #[serde(serialize_with = "::serialize_comma_separated")] pub users: &'a [::UserId], } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct TeamInfoResponse { ok: bool, pub team: Team, }
use std::collections::HashMap; use uuid::Uuid; use crate::{Command, CommandResult, Result}; #[derive(Default)] pub struct CommandBatch { commands_by_device: HashMap<Uuid, Vec<Command>>, } impl CommandBatch { pub fn new() -> Self { Self::default() } pub fn add(&mut self, command: Command) { self.commands_by_device .entry(command.device_id) .or_default() .push(command); } pub async fn execute(self) -> Result<HashMap<Uuid, Vec<CommandResult>>> { let mut result = HashMap::with_capacity(self.commands_by_device.len()); for (device_id, commands) in self.commands_by_device { let client = commands .first() .expect("invariant: must have at least one command") .client .clone(); let url = format!( "https://api.smartthings.com/v1/devices/{}/commands", device_id ); let commands = dbg!(serde_json::json!({ "commands": commands })); let response = dbg!(client.http().post(&url).json(&commands).send().await?); let results: crate::command::CommandResults = dbg!(response.json().await?); result.insert(device_id, results.results); } Ok(result) } }
use crate::rerrs::{ErrorKind, SteelErr}; use crate::rvals::{Result, SteelVal}; use crate::stop; use crate::values::contracts::*; pub struct ContractOperations {} impl ContractOperations { pub fn make_c() -> SteelVal { SteelVal::FuncV(|args: &[SteelVal]| -> Result<SteelVal> { if args.is_empty() { stop!(ArityMismatch => "make/c given no arguments"); } let contract = args[0].clone(); if contract.is_contract() { return Ok(contract); } if args.len() == 2 { let function = args[0].clone(); let name = args[1].clone(); if function.is_function() { return FlatContract::new_from_steelval(function, name.to_string()); // if let SteelVal::SymbolV(s) = name.as_ref() { // return FlatContract::new_from_steelval(function, s.to_string()); // } else { // stop!(TypeMismatch => "make/c attempted to make a flat contract, expected a symbol for the name in the second position"); // } } } if let Some((last, elements)) = args.split_last() { let last = last.clone(); FunctionContract::new_from_steelval(elements, last) } else { stop!(ArityMismatch => "function contract missing range position") } }) } pub fn make_flat_contract() -> SteelVal { SteelVal::FuncV(|args: &[SteelVal]| -> Result<SteelVal> { if args.len() != 2 { stop!(ArityMismatch => "make/c requires 2 argments, the contract and the name") } let function = args[0].clone(); let name = args[1].clone(); if let SteelVal::SymbolV(s) = name { FlatContract::new_from_steelval(function, s.to_string()) } else { stop!(TypeMismatch => "make-flat/c requires a symbol for the name in the second position") } }) } pub fn make_function_contract() -> SteelVal { SteelVal::FuncV(|args: &[SteelVal]| -> Result<SteelVal> { if let Some((last, elements)) = args.split_last() { let last = last.clone(); FunctionContract::new_from_steelval(elements, last) } else { stop!(ArityMismatch => "function contract missing range position") } }) } pub fn bind_contract_to_function() -> SteelVal { SteelVal::FuncV(|args: &[SteelVal]| -> Result<SteelVal> { if args.len() < 2 || args.len() > 4 { stop!(ArityMismatch => "bind/c requires 2 arguments, a contract and a function") } let contract = args[0].clone(); let function = args[1].clone(); let name = args.get(2).map(|x| x.clone()); ContractedFunction::new_from_steelvals(contract, function, name) }) } }
extern crate gcc; fn main() { let tool = gcc::Config::new() .opt_level(1) .host("x86_64-pc-windows-msvc") .target("x86_64-pc-windows-msvc") .debug(false) .get_compiler(); println!("64-bit MSVC path: {:?}", tool.path()); let tool = gcc::Config::new() .opt_level(1) .host("x86_64-pc-windows-msvc") .target("i686-pc-windows-msvc") .debug(false) .get_compiler(); println!("32-bit MSVC path: {:?}", tool.path()); }
//! Provides channel message queue communciation for coordinating threads use std::sync::mpsc::{Receiver, Sender}; /// Message types #[derive(Debug, Clone)] pub enum Message { LogError(String), LogInfo(String), KbdScanCode(String), KbdUnicode(String), RemoteTrace(String), RemoteTerm(String), TxReady(bool, u32), } /// Type for event loop inbound channel's Sender pub type EventLoopTx = Sender<Message>; /// Type for event loop inbound channel's Receiver pub type EventLoopRx = Receiver<Message>; /// Type for HTTP Server-Sent Event (SSE) channel's Receiver pub type SseRx = Receiver<Message>; /// Mq can model: /// 1. Channel endpoint from Event loop thread's point of view: /// - Outbound tx to server thread needs flow control /// 2. Channel endpoint from Server thread's point of view: /// - Outbound tx flow control to event loop is always ready pub struct Mq { /// Outbound to queue from owning thread tx: Sender<Message>, /// Flow control for outbound messages tx_ready: bool, /// Identifier for this thread (used in tx flow control) tid: u32, } impl Mq { /// Initialize pub fn new(tx: Sender<Message>, tx_ready: bool, tid: u32) -> Mq { Mq { tx, tx_ready, tid } } /// Send a message subject to flow control pub fn send(&self, msg: Message) { if self.tx_ready { let _ = self.tx.send(msg); } } /// Send keyboard scancode message to keyboard scancode sink pub fn kbd_scancode(&self, scancode: &str) { self.send(Message::KbdScanCode(String::from(scancode))); } /// Send string to the error log sink pub fn error(&self, message: &str) { self.send(Message::LogError(String::from(message))); } /// Send string to the info log sink pub fn info(&self, message: &str) { self.send(Message::LogInfo(String::from(message))); } /// Send flow control status to tx_ready sink. /// Subtle point: Possible confusion here about point of view. tx_ready() /// has nothing to do with self.tx_ready. The purpose is to inform the /// thread on the other end of the channel that it should update its value /// of Mq.tx_ready in the struct associated with thread of id=self.tid pub fn tx_ready(&self, ready: bool) { self.send(Message::TxReady(ready, self.tid)); } /// Get thread id for owner of this Mq (self) pub fn tid(&self) -> u32 { self.tid } /// Update self.tx_ready (intended for responding to Message::TxReady) pub fn set_tx_ready(&mut self, ready: bool) { self.tx_ready = ready; } }
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. #[repr(C)] #[derive(Debug, Copy)] pub struct mxm_ud_ep_opts { pub ib: mxm_ib_ep_opts_t, pub ack_timeout: f64, pub fast_ack_timeout: f64, pub fast_timer_res: f64, pub window_size: c_uint, pub ca: mxm_ud_ca_t, pub ca_low_window: c_int, pub chk_max_size: c_uint, pub timeout: f64, pub rx: mxm_ud_ep_opts__bindgen_ty_1, pub zcopy_rndv: mxm_ud_ep_opts__bindgen_ty_2, }
use specs::*; use types::*; use component::time::{MobSpawnTime, ThisFrame}; use dispatch::SystemInfo; use airmash_protocol::server::MobDespawn; use airmash_protocol::{to_bytes, ServerPacket}; use websocket::OwnedMessage; pub struct MissileCull; #[derive(SystemData)] pub struct MissileCullData<'a> { pub ents: Entities<'a>, pub spawntime: ReadStorage<'a, MobSpawnTime>, pub mob: ReadStorage<'a, Mob>, pub config: Read<'a, Config>, pub thisframe: Read<'a, ThisFrame>, pub conns: Read<'a, Connections>, } impl<'a> System<'a> for MissileCull { type SystemData = MissileCullData<'a>; fn run(&mut self, data: MissileCullData<'a>) { (&*data.ents, &data.mob, &data.spawntime) .join() .filter_map(|(ent, mob, spawntime)| { let ref info = data.config.mobs[*mob]; let dt = data.thisframe.0 - spawntime.0; if dt > info.lifetime { Some((ent, *mob)) } else { None } }) .for_each(|(ent, mob)| { data.ents.delete(ent).unwrap(); let packet = MobDespawn { id: ent, ty: mob }; data.conns.send_to_all(OwnedMessage::Binary( to_bytes(&ServerPacket::MobDespawn(packet)).unwrap(), )); }); } } impl SystemInfo for MissileCull { type Dependencies = (); fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self {} } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use benchmarks::sync::SyncBencher; use criterion::{criterion_group, criterion_main, Benchmark, Criterion}; fn full_sync(c: &mut Criterion) { ::logger::init_for_test(); for i in vec![10u64, 20, 50].into_iter() { c.bench( "full_sync", Benchmark::new(format!("full_sync_{:?}", i), move |b| { let sync_bencher = SyncBencher {}; sync_bencher.bench_full_sync(b, i) }) .sample_size(10), ); } } criterion_group!(starcoin_sync_benches, full_sync); criterion_main!(starcoin_sync_benches);
/// Type implementing arbitrary-precision decimal arithmetic extern crate num_bigint; extern crate num_traits; extern crate num; use core::cmp::Ordering; use crate::num_bigint::ToBigInt; use num_bigint::BigInt; use std::ops::Add; use std::ops::Sub; use std::ops::Mul; #[derive(Debug, Clone)] pub struct Decimal { i: BigInt, dot_index: i64 } impl Decimal { pub fn try_from(input: &str) -> Option<Decimal> { let mut dot_index_input: i64 = 0; let mut input_string = input.clone().to_string(); input_string = match input.find(".") { Some(_idx) => { input_string .trim_start_matches("0") .trim_end_matches("0") .to_string() }, None => { input_string } }; match input_string.chars().last() { Some('.') => { input_string.push('0'); }, Some(_) => { }, None => { } }; match input_string.chars().next() { Some('.') => { input_string.insert(0, '0'); }, Some(_) => { }, None => { } }; dot_index_input = match input_string.find(".") { Some(idx) => { (input_string.len() - 1 - idx) as i64 }, None => { input_string.push_str(".0"); 1 } }; if dot_index_input > 0 { input_string.remove(input_string.len() - 1 - dot_index_input as usize); } if input_string.is_empty() { input_string.push('0'); } let i_d_bigint = input_string.parse::<BigInt>().unwrap(); Some(Decimal { i: i_d_bigint, dot_index: dot_index_input }) } } impl PartialOrd for Decimal { fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> { let ten_to_power = 10_i32.to_bigint().unwrap(); let self_i = self.i.clone(); let other_i = other.i.clone(); let mut self_i_modified: BigInt = self_i.clone(); let mut output_i_modified: BigInt = other_i.clone(); match self.dot_index < other.dot_index { true => { self_i_modified = self_i * num::pow(ten_to_power, (other.dot_index - self.dot_index) as usize); }, false => { if self.dot_index == other.dot_index { } else { output_i_modified = other_i * num::pow(ten_to_power, (self.dot_index - other.dot_index) as usize); } } }; if self_i_modified < output_i_modified { Some(Ordering::Less) } else if self_i_modified == output_i_modified { Some(Ordering::Equal) } else { Some(Ordering::Greater) } } } impl PartialEq for Decimal { fn eq(&self, other: &Self) -> bool { let ten_to_power = 10_i32.to_bigint().unwrap(); let self_i = self.i.clone(); let other_i = other.i.clone(); match self.dot_index < other.dot_index { true => { let self_i_modified = self_i * num::pow(ten_to_power, (other.dot_index - self.dot_index) as usize); self_i_modified == other.i }, false => { if self.dot_index == other.dot_index { other.i == self.i } else { let output_i_modified = other_i * num::pow(ten_to_power, (self.dot_index - other.dot_index) as usize); output_i_modified == self.i } } } } } impl Add for Decimal { type Output = Self; fn add(self, other: Self) -> Self { let mut dot_index: i64 = 0; let mut output_i = self.i.clone(); let ten_to_power = 10_i32.to_bigint().unwrap(); let _value = match self.dot_index < other.dot_index { true => { dot_index = other.dot_index; output_i = other.i + (self.i * num::pow(ten_to_power, (other.dot_index - self.dot_index) as usize)); }, false => { if self.dot_index == other.dot_index { dot_index = self.dot_index; output_i = self.i + other.i; } else { dot_index = self.dot_index; output_i = self.i + (other.i * num::pow(ten_to_power, (self.dot_index - other.dot_index) as usize)); } } }; Decimal { i: output_i, dot_index: dot_index } } } impl Sub for Decimal { type Output = Self; fn sub(self, other: Self) -> Self { let mut dot_index: i64 = 0; let mut output_i = self.i.clone(); let ten_to_power = 10_i32.to_bigint().unwrap(); let _value = match self.dot_index < other.dot_index { true => { dot_index = other.dot_index; output_i = (self.i * num::pow(ten_to_power, (other.dot_index - self.dot_index) as usize)) - other.i; }, false => { if self.dot_index == other.dot_index { dot_index = self.dot_index; output_i = self.i - other.i; } else { dot_index = self.dot_index; output_i = self.i - (other.i * num::pow(ten_to_power, (self.dot_index - other.dot_index) as usize)); } } }; Decimal { i: output_i, dot_index: dot_index } } } impl Mul for Decimal { type Output = Self; fn mul(self, other: Self) -> Self { let output_calc = self.i.clone() * other.i.clone(); let output_calc_string = output_calc.clone().to_string(); let output_calc_string_trimmed = output_calc_string.trim_end_matches('0'); let chopped_zeros_length = (output_calc_string.len() - output_calc_string_trimmed.len()) as i64; let dot_index_output = match other.dot_index { 0 => { 0 }, rest => rest }; Decimal { i: output_calc_string_trimmed.parse::<BigInt>().unwrap(), dot_index: self.dot_index + dot_index_output - chopped_zeros_length } } }
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. extern "C" { pub fn rdma_freeaddrinfo(res: *mut rdma_addrinfo); pub fn rdma_getaddrinfo(node: *const c_char, service: *const c_char, hints: *const rdma_addrinfo, res: *mut *mut rdma_addrinfo) -> c_int; }
use quote::quote_spanned; use syn::parse_quote; use super::{ DelayType, FlowProperties, FlowPropertyVal, OpInstGenerics, OperatorCategory, OperatorConstraints, OperatorInstance, OperatorWriteOutput, Persistence, WriteContextArgs, RANGE_0, RANGE_1, }; use crate::diagnostic::{Diagnostic, Level}; /// > 2 input streams of type `V1` and `V2`, 1 output stream of type `itertools::EitherOrBoth<V1, V2>` /// /// Zips the streams together, forming paired tuples of the inputs. Note that zipping is done /// per-tick. Excess items are returned as `EitherOrBoth::Left(V1)` or `EitherOrBoth::Right(V2)`. /// If you intead want to discard the excess, use [`zip`](#zip) instead. /// /// ```hydroflow /// source_iter(0..2) -> [0]my_zip_longest; /// source_iter(0..3) -> [1]my_zip_longest; /// my_zip_longest = zip_longest() /// -> assert_eq([ /// itertools::EitherOrBoth::Both(0, 0), /// itertools::EitherOrBoth::Both(1, 1), /// itertools::EitherOrBoth::Right(2)]); /// ``` pub const ZIP_LONGEST: OperatorConstraints = OperatorConstraints { name: "zip_longest", categories: &[OperatorCategory::MultiIn], hard_range_inn: &(2..=2), soft_range_inn: &(2..=2), hard_range_out: RANGE_1, soft_range_out: RANGE_1, num_args: 0, persistence_args: &(0..=1), type_args: RANGE_0, is_external_input: false, ports_inn: Some(|| super::PortListSpec::Fixed(parse_quote! { 0, 1 })), ports_out: None, properties: FlowProperties { // TODO(mingwei): review these. deterministic: FlowPropertyVal::Preserve, monotonic: FlowPropertyVal::Preserve, inconsistency_tainted: false, }, input_delaytype_fn: |_| Some(DelayType::Stratum), write_fn: |&WriteContextArgs { root, op_span, ident, is_pull, inputs, op_name, op_inst: OperatorInstance { generics: OpInstGenerics { persistence_args, .. }, .. }, .. }, diagnostics| { assert!(is_pull); let persistence = match persistence_args[..] { [] => Persistence::Tick, [a] => a, _ => unreachable!(), }; if Persistence::Tick != persistence { diagnostics.push(Diagnostic::spanned( op_span, Level::Error, format!("`{}()` can only have `'tick` persistence.", op_name), )); // Fall-thru to still generate code. } let lhs = &inputs[0]; let rhs = &inputs[1]; let write_iterator = quote_spanned! {op_span=> let #ident = #root::itertools::Itertools::zip_longest(#lhs, #rhs); }; Ok(OperatorWriteOutput { write_iterator, ..Default::default() }) }, };
use regex::Regex; use std::collections::HashMap; use std::convert::TryInto; use std::time::Instant; const INPUT: &str = include_str!("../input.txt"); #[derive(Default)] struct Mask { mask_str: Box<[u8]>, and_mask: u64, or_mask: u64, } impl Mask { fn apply(&self, n: u64) -> u64 { n & self.and_mask | self.or_mask } } impl From<&[u8]> for Mask { fn from(bytes: &[u8]) -> Self { let mut and_mask = 0; let mut or_mask = 0; for c in bytes { and_mask <<= 1; or_mask <<= 1; match c { b'X' => and_mask |= 1, b'0' => (), b'1' => or_mask |= 1, _ => unreachable!(), } } Self { mask_str: bytes.into(), and_mask, or_mask, } } } enum Command { SetMask(&'static [u8]), Write(usize, u64), } fn read_commands() -> impl Iterator<Item = Command> { let mask_re = Regex::new(r"mask = (.+)").unwrap(); let mem_re = Regex::new(r"mem\[(?P<addr>\d+)\] = (?P<val>\d+)").unwrap(); INPUT.lines().map(move |line| { if let Some(cap) = mask_re.captures(line) { let mask_str = cap.get(1).unwrap().as_str(); Command::SetMask(mask_str.as_bytes()) } else if let Some(cap) = mem_re.captures(line) { let addr: usize = cap.name("addr").unwrap().as_str().parse().unwrap(); let val: u64 = cap.name("val").unwrap().as_str().parse().unwrap(); Command::Write(addr, val) } else { unreachable!() } }) } fn part1() -> u64 { let mut mem: HashMap<usize, u64> = HashMap::new(); let mut mask = Mask::default(); for command in read_commands() { match command { Command::SetMask(new_mask) => mask = new_mask.into(), Command::Write(addr, val) => { mem.insert(addr, mask.apply(val)); } } } mem.values().sum() } fn addresses_from_mask(orig_mask: &[u8]) -> impl Iterator<Item = usize> { // Get the positions of each of the floating bits let floating_positions: Vec<_> = orig_mask .iter() .rev() .enumerate() .filter_map(|(i, c)| if *c == b'X' { Some(i) } else { None }) .collect(); let mask_max = 1 << floating_positions.len(); // Apply the address mask to 0 so all Xs are eliminated and replaced by 0s let base_address: usize = Mask::from(orig_mask).apply(0).try_into().unwrap(); // Generate numbers that take on all the possible values for the number of floating bits we have // and apply them toe the base address in the floating positions. (0..mask_max).map(move |mut i| { let mut address = base_address; for masked_pos in &floating_positions { if i & 1 == 1 { address |= 1 << masked_pos; } else { address &= !(1 << masked_pos); } i >>= 1; } address }) } fn generate_mask_from_address(address: usize, mask: &Mask) -> Vec<u8> { let mut mask = mask.mask_str.to_vec(); let mut cur_address = address; for mask_offset in (0..mask.len()).rev() { if cur_address == 0 { break; } match mask[mask_offset] { b'X' | b'1' => (), b'0' => mask[mask_offset] = if (cur_address & 1) == 1 { b'1' } else { b'0' }, _ => unreachable!(), } cur_address >>= 1; } mask } fn part2() -> u64 { let mut mem: HashMap<usize, u64> = HashMap::new(); let mut cur_mask = Mask::default(); for command in read_commands() { match command { Command::SetMask(new_mask) => cur_mask = new_mask.into(), Command::Write(addr, val) => { let initial_mask = generate_mask_from_address(addr, &cur_mask); mem.extend(addresses_from_mask(&initial_mask).map(|new_addr| (new_addr, val))); } } } mem.values().sum() } fn main() { let start = Instant::now(); println!("part 1: {}", part1()); println!("part 1 took {}ms", (Instant::now() - start).as_millis()); let start = Instant::now(); println!("part 2: {}", part2()); println!("part 2 took {}ms", (Instant::now() - start).as_millis()); } #[cfg(test)] mod tests { use super::{part1, part2}; #[test] fn test_part1() { assert_eq!(part1(), 11884151942312); } #[test] fn test_part2() { assert_eq!(part2(), 2625449018811); } }
use std::ops::{Neg, Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Index, IndexMut}; use num::Zero; use alga::general::{ClosedNeg, ClosedAdd, ClosedSub, ClosedMul, ClosedDiv}; use core::{Scalar, ColumnVector, Matrix, ColumnVectorSum}; use core::dimension::{Dim, DimName, U1}; use core::constraint::{ShapeConstraint, SameNumberOfRows, SameNumberOfColumns, AreMultipliable}; use core::storage::{Storage, StorageMut}; use core::allocator::{SameShapeAllocator, Allocator}; use geometry::{PointBase, OwnedPoint, PointMul}; /* * * Indexing. * */ impl<N, D: DimName, S> Index<usize> for PointBase<N, D, S> where N: Scalar, S: Storage<N, D, U1> { type Output = N; #[inline] fn index(&self, i: usize) -> &Self::Output { &self.coords[i] } } impl<N, D: DimName, S> IndexMut<usize> for PointBase<N, D, S> where N: Scalar, S: StorageMut<N, D, U1> { #[inline] fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.coords[i] } } /* * Neg. * */ impl<N, D: DimName, S> Neg for PointBase<N, D, S> where N: Scalar + ClosedNeg, S: Storage<N, D, U1> { type Output = OwnedPoint<N, D, S::Alloc>; #[inline] fn neg(self) -> Self::Output { PointBase::from_coordinates(-self.coords) } } impl<'a, N, D: DimName, S> Neg for &'a PointBase<N, D, S> where N: Scalar + ClosedNeg, S: Storage<N, D, U1> { type Output = OwnedPoint<N, D, S::Alloc>; #[inline] fn neg(self) -> Self::Output { PointBase::from_coordinates(-&self.coords) } } /* * * Subtraction & Addition. * */ // PointBase - PointBase add_sub_impl!(Sub, sub, ClosedSub; (D, U1), (D, U1) for D: DimName; self: &'a PointBase<N, D, SA>, right: &'b PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>; &self.coords - &right.coords; 'a, 'b); add_sub_impl!(Sub, sub, ClosedSub; (D, U1), (D, U1) for D: DimName; self: &'a PointBase<N, D, SB>, right: PointBase<N, D, SA>, Output = ColumnVectorSum<N, D, D, SA>; &self.coords - right.coords; 'a); add_sub_impl!(Sub, sub, ClosedSub; (D, U1), (D, U1) for D: DimName; self: PointBase<N, D, SA>, right: &'b PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>; self.coords - &right.coords; 'b); add_sub_impl!(Sub, sub, ClosedSub; (D, U1), (D, U1) for D: DimName; self: PointBase<N, D, SA>, right: PointBase<N, D, SB>, Output = ColumnVectorSum<N, D, D, SA>; self.coords - right.coords; ); // PointBase - Vector add_sub_impl!(Sub, sub, ClosedSub; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: &'a PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(&self.coords - right); 'a, 'b); add_sub_impl!(Sub, sub, ClosedSub; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: &'a PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(&self.coords - &right); 'a); // FIXME: should not be a ref to `right`. add_sub_impl!(Sub, sub, ClosedSub; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(self.coords - right); 'b); add_sub_impl!(Sub, sub, ClosedSub; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(self.coords - right); ); // PointBase + Vector add_sub_impl!(Add, add, ClosedAdd; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: &'a PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(&self.coords + right); 'a, 'b); add_sub_impl!(Add, add, ClosedAdd; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: &'a PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(&self.coords + &right); 'a); // FIXME: should not be a ref to `right`. add_sub_impl!(Add, add, ClosedAdd; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: PointBase<N, D1, SA>, right: &'b ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(self.coords + right); 'b); add_sub_impl!(Add, add, ClosedAdd; (D1, U1), (D2, U1) -> (D1) for D1: DimName, D2: Dim; self: PointBase<N, D1, SA>, right: ColumnVector<N, D2, SB>, Output = OwnedPoint<N, D1, SA::Alloc>; Self::Output::from_coordinates(self.coords + right); ); // XXX: replace by the shared macro: add_sub_assign_impl macro_rules! op_assign_impl( ($($TraitAssign: ident, $method_assign: ident, $bound: ident);* $(;)*) => {$( impl<'b, N, D1: DimName, D2: Dim, SA, SB> $TraitAssign<&'b ColumnVector<N, D2, SB>> for PointBase<N, D1, SA> where N: Scalar + $bound, SA: StorageMut<N, D1, U1>, SB: Storage<N, D2, U1>, ShapeConstraint: SameNumberOfRows<D1, D2> { #[inline] fn $method_assign(&mut self, right: &'b ColumnVector<N, D2, SB>) { self.coords.$method_assign(right) } } impl<N, D1: DimName, D2: Dim, SA, SB> $TraitAssign<ColumnVector<N, D2, SB>> for PointBase<N, D1, SA> where N: Scalar + $bound, SA: StorageMut<N, D1, U1>, SB: Storage<N, D2, U1>, ShapeConstraint: SameNumberOfRows<D1, D2> { #[inline] fn $method_assign(&mut self, right: ColumnVector<N, D2, SB>) { self.coords.$method_assign(right) } } )*} ); op_assign_impl!( AddAssign, add_assign, ClosedAdd; SubAssign, sub_assign, ClosedSub; ); /* * * Matrix × PointBase * */ md_impl_all!( Mul, mul; (R1, C1), (D2, U1) for R1: DimName, C1: Dim, D2: DimName where SA::Alloc: Allocator<N, R1, U1> where ShapeConstraint: AreMultipliable<R1, C1, D2, U1>; self: Matrix<N, R1, C1, SA>, right: PointBase<N, D2, SB>, Output = PointMul<N, R1, C1, SA>; [val val] => PointBase::from_coordinates(self * right.coords); [ref val] => PointBase::from_coordinates(self * right.coords); [val ref] => PointBase::from_coordinates(self * &right.coords); [ref ref] => PointBase::from_coordinates(self * &right.coords); ); /* * * PointBase ×/÷ Scalar * */ macro_rules! componentwise_scalarop_impl( ($Trait: ident, $method: ident, $bound: ident; $TraitAssign: ident, $method_assign: ident) => { impl<N, D: DimName, S> $Trait<N> for PointBase<N, D, S> where N: Scalar + $bound, S: Storage<N, D, U1> { type Output = OwnedPoint<N, D, S::Alloc>; #[inline] fn $method(self, right: N) -> Self::Output { PointBase::from_coordinates(self.coords.$method(right)) } } impl<'a, N, D: DimName, S> $Trait<N> for &'a PointBase<N, D, S> where N: Scalar + $bound, S: Storage<N, D, U1> { type Output = OwnedPoint<N, D, S::Alloc>; #[inline] fn $method(self, right: N) -> Self::Output { PointBase::from_coordinates((&self.coords).$method(right)) } } impl<N, D: DimName, S> $TraitAssign<N> for PointBase<N, D, S> where N: Scalar + $bound, S: StorageMut<N, D, U1> { #[inline] fn $method_assign(&mut self, right: N) { self.coords.$method_assign(right) } } } ); componentwise_scalarop_impl!(Mul, mul, ClosedMul; MulAssign, mul_assign); componentwise_scalarop_impl!(Div, div, ClosedDiv; DivAssign, div_assign); macro_rules! left_scalar_mul_impl( ($($T: ty),* $(,)*) => {$( impl<D: DimName, S> Mul<PointBase<$T, D, S>> for $T where S: Storage<$T, D, U1> { type Output = OwnedPoint<$T, D, S::Alloc>; #[inline] fn mul(self, right: PointBase<$T, D, S>) -> Self::Output { PointBase::from_coordinates(self * right.coords) } } impl<'b, D: DimName, S> Mul<&'b PointBase<$T, D, S>> for $T where S: Storage<$T, D, U1> { type Output = OwnedPoint<$T, D, S::Alloc>; #[inline] fn mul(self, right: &'b PointBase<$T, D, S>) -> Self::Output { PointBase::from_coordinates(self * &right.coords) } } )*} ); left_scalar_mul_impl!( u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64 );
/// Xor two equally long byte slices. pub fn xor_bytes(a: &[u8], b: &[u8]) -> Vec<u8> { assert_eq!(a.len(), b.len()); // TODO: ??? a.iter().zip(b.iter()).map(|(x, y)| x ^ y).collect() }
use crate::command::CommandBuilder; use clap::{App, Arg, ArgMatches, SubCommand}; use core::convert::TryFrom; use failure::{format_err, Error}; use log::trace; use relative_path::RelativePathBuf; use std::{collections::HashMap, env::current_dir, fs::OpenOptions, io::Read}; use valis::{ interpret::{value::FnValue, ExprEvaluator, FunctionGatherer}, syntax::{ ast::{AstVisitor, Identifier, SourceFile}, parser::FromParser, }, ValisDatabase, }; #[derive(Debug)] pub(crate) struct InterpretCommand { pub(crate) filename: String, pub(crate) entry_func: String, } #[derive(Debug)] pub(crate) struct InterpretCommandBuilder; impl CommandBuilder for InterpretCommandBuilder { fn dependencies(&self) -> Box<[Box<dyn CommandBuilder>]> { Box::new([]) } fn build_initial<'a: 'b, 'b>(&self) -> App<'a, 'b> { SubCommand::with_name(self.name()) .arg( Arg::with_name("input") .help("Sets the input file to use") .required(true) .index(1), ) .arg( Arg::with_name("entry_func") .help("Which function to run on start. Function must have no arguments.") .required(true) .index(2), ) } fn name(&self) -> &'static str { "interpret" } } impl<'a> TryFrom<&ArgMatches<'a>> for InterpretCommand { type Error = Error; fn try_from(m: &ArgMatches<'a>) -> Result<Self, Self::Error> { let filename = m .value_of("input") .ok_or_else(|| format_err!("Parameter 'input' was not found."))? .into(); let entry_func = m .value_of("input") .ok_or_else(|| format_err!("Parameter 'entry_func' was not found."))? .into(); Ok(InterpretCommand { filename, entry_func, }) } } impl InterpretCommand { pub(crate) fn run(self, mut db: ValisDatabase) -> Result<(), Error> { let InterpretCommand { filename, entry_func, } = self; trace!("Get the current working directory"); let cwd = current_dir()?; let path: RelativePathBuf = filename.into(); trace!("Open provided file"); let mut file = OpenOptions::new().read(true).open(path.to_path(cwd))?; trace!("Read source contents"); let mut contents = String::new(); let _ = file.read_to_string(&mut contents)?; let ast = SourceFile::parse(&contents).map_err(|e| format_err!("{}", e))?; let mut functions = FunctionGatherer::default(); functions.visit_source_file(&ast); let (main, items) = functions .into_main_and_others(entry_func.as_str().into()) .unwrap(); let eval = ExprEvaluator { bindings: HashMap::new(), visible_items: items, stack: Vec::new(), }; let val = FnValue { inner: main }; val.call(Vec::new(), &eval); Ok(()) } }
extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; use std::env; use std::fs::File; use std::io::{BufReader,BufRead}; fn main() { let args: Vec<String> = env::args().collect(); let file = &args[1]; read_file(file); } #[derive(Default, Serialize, Deserialize, Debug, Copy, Clone)] struct Demographic { jurisdiction_name: usize, count_participants: usize, count_female: usize, percent_female: f64, count_male: usize, percent_male: f64, count_gender_unknown: usize, percent_gender_unknown: f64, } impl Demographic { fn new() -> Self { Default::default() } } fn read_file(filename: &str) { let f = File::open(filename).unwrap(); let file = BufReader::new(&f); let mut demographic: Demographic = Demographic::new(); let mut keys = vec![String::from("")]; let mut list: Vec<Demographic> = vec![]; for (num, line) in file.lines().enumerate() { if num == 0 { let l = line.unwrap(); let v = l.split(',') .map(|field| field.to_lowercase().replace(" ", "_")) .collect(); keys = v; } else { let l = line.unwrap(); let values: Vec<String> = l.split(',') .map(|val| val.to_string()) .collect(); for item in keys.iter() { match &item as &str { "jurisdiction_name" => { demographic.jurisdiction_name = values[0].parse().unwrap(); }, "count_participants" => { demographic.count_participants = values[1].parse().unwrap(); }, "count_female" => { demographic.count_female = values[2].parse().unwrap(); }, "percent_female" => { demographic.percent_female = values[3].parse().unwrap(); }, "count_male" => { demographic.count_male = values[4].parse().unwrap(); }, "percent_male" => { demographic.percent_male = values[5].parse().unwrap(); }, "count_gender_unknown" => { demographic.count_gender_unknown = values[6].parse().unwrap(); }, "percent_gender_unknown" => { demographic.percent_gender_unknown = values[7].parse().unwrap(); }, _ => (), } } list.push(demographic); } } // Serialize it to a JSON string. let j = serde_json::to_string(&list).expect("could not serialize demographics"); // Print, write to a file, or send to an HTTP server. println!("{:?}", j); }
use std::time::Duration; use std::sync::Arc; use hyper::Client; use futures::future; use tokio::time::delay_for; use tokio::sync::RwLock; use anyhow::{ Result, Context }; use slog::Logger; use kube::{ config, client::APIClient }; use serde::{Deserialize}; use schemars::JsonSchema; use super::ServiceCoordinates; use super::kubernetes; use super::protocol::SingularEndpoint; #[derive(Clone, Debug, Deserialize, JsonSchema)] pub struct DiscoveryOptions { pub interval_secs: u32, pub consecutive_error_threshold: u32, pub svc_coords: ServiceCoordinates, pub query_path: String, } pub async fn run_endpoint_discovery(opts: DiscoveryOptions, log: Logger, forward_uri_lock: Arc<RwLock<String>>) -> Result<()> { let config = config::load_kube_config().await .map_err(kubernetes::to_anyhow) .context("failed loading kube config")?; let client = APIClient::new(config); info!(log, "singular running"); let mut consecutive_err_count: u32 = 0; loop { debug!(log, "retrieving endpoint..."); let res = get_singular_endpoint(client.clone(), opts.clone(), log.clone()).await; match res { Err(e) => { consecutive_err_count += 1; if consecutive_err_count > opts.consecutive_error_threshold { return Err(e).context("failed retrieving singular endpoint"); } warn!(log, "failed retrieving singular endpoint: {}", e); }, Ok(endpoint) => { consecutive_err_count = 0; // notify proxy about new endpoint (if it changed at all) let new_endpoint_uri = endpoint.to_string(); let old_endpoint_uri = { forward_uri_lock.read().await }; if new_endpoint_uri == *old_endpoint_uri { let mut w = forward_uri_lock.write().await; *w = new_endpoint_uri; } } }; let interval = Duration::from_secs(opts.interval_secs.into()); delay_for(interval).await; } } async fn get_singular_endpoint(client: APIClient, opts: DiscoveryOptions, log: Logger) -> anyhow::Result<SingularEndpoint> { let endpoints = kubernetes::get_service_endpoint(client, &opts.svc_coords).await?; // Query all endpoints if they think they are the one let singular_queries = endpoints.iter() .map(|e| query_singular_endpoint(e, &opts.query_path)); let singular_results = future::join_all(singular_queries).await; // Ignore failed queries let responses: Vec<&(SingularEndpoint, bool)> = singular_results.iter() .filter(|res| res.is_ok()) .map(|res| res.as_ref().unwrap()) .collect(); // Sanity: Any responses at all? if responses.is_empty() { return Err(anyhow!("0/{} singular queries successful.", endpoints.len())); } // Filter by positive responses, e.g. which endpoints deemed themselves in charge let positive_response: Vec<&(SingularEndpoint, bool)> = responses.iter() .filter(|r| r.1) .cloned() .collect(); match positive_response.len() { 0 => { Err(anyhow!("none of the singular endpoints felt responsible!")) }, 1 => { let (endpoint, _) = positive_response.first().unwrap(); Ok(endpoint.clone()) }, _ => { let all_endpoints_str = positive_response.iter() .map(|e| format!("{}", e.0)) .collect::<Vec<String>>() .join(", "); warn!(log, "more than 1 singular endpoint felt responsible [{}], chosing first.", all_endpoints_str); let (endpoint, _) = positive_response.first().unwrap(); Ok(endpoint.clone()) } } } async fn query_singular_endpoint(endpoint: &SingularEndpoint, path: &str) -> anyhow::Result<(SingularEndpoint, bool)> { let uri = format!("http://{}{}", endpoint, path).parse()?; let client = Client::new(); let response = client.get(uri).await?; Ok((endpoint.clone(), response.status() == 200)) }
#[doc = "Register `GNPTXFSIZ_Device` reader"] pub type R = crate::R<GNPTXFSIZ_DEVICE_SPEC>; #[doc = "Register `GNPTXFSIZ_Device` writer"] pub type W = crate::W<GNPTXFSIZ_DEVICE_SPEC>; #[doc = "Field `TX0FSA` reader - Endpoint 0 transmit RAM start address"] pub type TX0FSA_R = crate::FieldReader<u16>; #[doc = "Field `TX0FSA` writer - Endpoint 0 transmit RAM start address"] pub type TX0FSA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; #[doc = "Field `TX0FD` reader - Endpoint 0 TxFIFO depth"] pub type TX0FD_R = crate::FieldReader<u16>; #[doc = "Field `TX0FD` writer - Endpoint 0 TxFIFO depth"] pub type TX0FD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; impl R { #[doc = "Bits 0:15 - Endpoint 0 transmit RAM start address"] #[inline(always)] pub fn tx0fsa(&self) -> TX0FSA_R { TX0FSA_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - Endpoint 0 TxFIFO depth"] #[inline(always)] pub fn tx0fd(&self) -> TX0FD_R { TX0FD_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Endpoint 0 transmit RAM start address"] #[inline(always)] #[must_use] pub fn tx0fsa(&mut self) -> TX0FSA_W<GNPTXFSIZ_DEVICE_SPEC, 0> { TX0FSA_W::new(self) } #[doc = "Bits 16:31 - Endpoint 0 TxFIFO depth"] #[inline(always)] #[must_use] pub fn tx0fd(&mut self) -> TX0FD_W<GNPTXFSIZ_DEVICE_SPEC, 16> { TX0FD_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "OTG_FS non-periodic transmit FIFO size register (Device mode)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gnptxfsiz_device::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 [`gnptxfsiz_device::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GNPTXFSIZ_DEVICE_SPEC; impl crate::RegisterSpec for GNPTXFSIZ_DEVICE_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gnptxfsiz_device::R`](R) reader structure"] impl crate::Readable for GNPTXFSIZ_DEVICE_SPEC {} #[doc = "`write(|w| ..)` method takes [`gnptxfsiz_device::W`](W) writer structure"] impl crate::Writable for GNPTXFSIZ_DEVICE_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets GNPTXFSIZ_Device to value 0x0200"] impl crate::Resettable for GNPTXFSIZ_DEVICE_SPEC { const RESET_VALUE: Self::Ux = 0x0200; }
mod math; fn main() { let v = math::Vec3::new(1.0, 2.0, 3.0); println!("Hello, world!"); }
//The sum of the squares of the first ten natural numbers is, // //1^2 + 2^2 + ... + 10^2 = 385 // //The square of the sum of the first ten natural numbers is, // //(1 + 2 + ... + 10)^2 = 55^2 = 3025 // //Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. // //Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. //test commit fn solve(setbound: u64) -> u64 { let mut sumofsquares = 0; let mut squareofsum = 0; if setbound == 0 { panic!(); } for i in 1..(setbound + 1) { sumofsquares += i * i; squareofsum += i; } (squareofsum * squareofsum) - sumofsquares } fn main() { println!("{}", solve(100).to_string()); } #[cfg(test)] mod tests { #[test] #[should_panic] fn sum_square_diff_badbound() { super::solve(0); } #[test] fn sum_square_diff_10() { assert_eq!(2640, super::solve(10)); } #[test] fn sum_square_diff_100() { assert_eq!(25164150, super::solve(100)); } }
use std::collections::HashMap; use std::net::SocketAddr; use anyhow::Result; use async_trait::async_trait; use tokio::net::UdpSocket; pub struct Proxy { socket: UdpSocket, conn_track: HashMap<SocketAddr, UdpSocket>, } #[async_trait] impl super::Proxy for Proxy { async fn listen(bind: SocketAddr) -> Result<Self> { let socket = UdpSocket::bind(bind).await?; return Ok(Self { socket, conn_track: HashMap::new(), }); } async fn run(mut self: Box<Self>, target: SocketAddr) -> Result<()> { unimplemented!() } }
use super::responses::GetNodeInfoResponse; use crate::Result; use reqwest::Client; /// Gets information about the specified node pub async fn get_node_info(client: Client, uri: String) -> Result<GetNodeInfoResponse> { let body = json!({ "command": "getNodeInfo", }); Ok(client .post(&uri) .header("ContentType", "application/json") .header("X-IOTA-API-Version", "1") .body(body.to_string()) .send()? .json()?) }
// SPDX-License-Identifier: GPL-2.0 #[cfg(test)] mod tests { use std::error::Error; #[test] fn open_and_create() -> Result<(), Box<dyn Error>> { const NAME: &str = "open_and_create"; let tests = [ "test.txt", "test1.txt", "test2.txt", "test3.txt", "test4.txt", ]; for t in &tests { use std::fs::{self, File}; use std::io::ErrorKind; let file = format!("{}-{}", NAME, t); let _f = match File::open(&file) { Ok(f) => f, Err(err) => match err.kind() { ErrorKind::NotFound => match File::create(&file) { Ok(f) => f, Err(err) => panic!("{}: create: {:?}", file, err), }, other_error => panic!("{}: open: {:?}", file, other_error), }, }; let msg = format!("{}: remove_file", file); fs::remove_file(&file).expect(&msg); } Ok(()) } #[test] fn open_and_create_unwrap_or_else() -> Result<(), Box<dyn Error>> { const NAME: &str = "open_and_create_unwrap_or_else"; let tests = [ "test.txt", "test1.txt", "test2.txt", "test3.txt", "test4.txt", ]; for t in &tests { use std::fs::{self, File}; use std::io::ErrorKind; let file = format!("{}-{}", NAME, t); let _f = File::open(&file).unwrap_or_else(|err| { assert_eq!(ErrorKind::NotFound, err.kind(), "{}", file); File::create(&file).unwrap_or_else(|err| { panic!(format!("{}: {:?}", file, err)); }) }); let msg = format!("{}: remove_file", file); fs::remove_file(&file).expect(&msg); } Ok(()) } #[test] fn create_write_and_read() -> Result<(), Box<dyn Error>> { const NAME: &str = "create_and_write"; struct Test { name: &'static str, data: u8, bufsiz: usize, } let tests = [ Test { name: "1 bytes 'a'", data: b'a', bufsiz: 1, }, Test { name: "100 bytes 'b'", data: b'b', bufsiz: 100, }, Test { name: "1024 bytes 'x'", data: b'x', bufsiz: 1024, }, Test { name: "1MiB bytes 'y'", data: b'y', bufsiz: 1024 * 1024, }, Test { name: "4MiB 'z'", data: b'z', bufsiz: 4 * 1024 * 1024, }, ]; for t in &tests { use std::fs::File; use std::io::prelude::*; let file = format!("{}-{}", NAME, t.data); let f = File::create(&file)?; { // Use blocks, so that the BufWriter will flushes the buffer // before removing the file below. let mut w = std::io::BufWriter::new(f); let data = vec![t.data; t.bufsiz]; w.write(&data)?; } let mut f = File::open(&file)?; // Initialize the buffer with 0 so that f.read() will be happy. let mut got = vec![0u8; t.bufsiz]; let n = f.read(&mut got)?; assert_eq!(t.bufsiz, n, "{}: unexpected read length", t.name); for got in &got { assert_eq!(t.data, *got, "{}: unexpected read data", t.name); } std::fs::remove_file(&file)?; } Ok(()) } }
use std::collections::HashMap; use std::thread; use std::time::Duration; pub fn closure_simple_test() { println!( "{}", "------------closure_simple_test start-------------------" ); let expensive_closure = |num: u32| -> u32 { println!("calculating slowly..."); thread::sleep(Duration::from_secs(1)); num }; let closure_test = |number1, number2| { println!("find biggest number..."); if number1 > number2 { number1 } else { number2 } }; println!("{}", expensive_closure(20)); println!("{}", closure_test(20, 50)); } pub fn closure_complex_test() { println!( "{}", "------------closure_complex_test start-------------------" ); /* This will cause a error in the future warning: this error has been downgraded to a warning for backwards compatibility with previous releases warning: this represents potential undefined behavior in your code and this warning will become a hard error in the future let _closure_test = |str1: &str, str2: &str| -> &str { if str1.len() > str2.len() { str1 } else { str2 } }; let _string1 = String::from("closure"); let _string2 = String::from("demo"); */ /* It will meet the following error if we want to use it "cannot infer an appropriate lifetime due to conflicting requirements" And this error couldn't be solved */ //println!("{}",closure_test(string1.as_str(),string2.as_str())) } struct Cacher<T> where T: Fn(u32) -> u32, { calculation: T, value: HashMap<u32, u32>, } impl<T> Cacher<T> where T: Fn(u32) -> u32, { fn new(calculation: T) -> Cacher<T> { Cacher { calculation, value: HashMap::new(), } } fn value(&mut self, arg: u32) -> u32 { match self.value.get(&arg) { Some(v) => { println!("we have it"); return *v; } None => { println!("{}", "not existed"); } } println!("insert couldn't be include in get"); println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); let v = (self.calculation)(arg); self.value.insert(arg, v); v } } pub fn generic_closure_test() { println!( "{}", "------------generic_closure_test start-------------------" ); let mut expensive_result = Cacher::new(|num| num); let intensity = 20; let random_number = 1; if intensity < 25 { println!("Today, do {} pushups!", expensive_result.value(intensity)); println!("Next, do {} situps!", expensive_result.value(intensity)); println!("Next, do {} situps!", expensive_result.value(intensity + 1)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_result.value(intensity) ); } } } //闭包会捕获其环境 pub fn closure_environment_demo() { println!( "{}", "------------closure_environment_demo start-------------------" ); let x = 4; let equal_to_x = |z| z == x; let y = 4; println!("{}", equal_to_x(y)); /* 当闭包从环境中捕获一个值,闭包会在闭包体中储存这个值以供使用。这会使用内存并产生额外的开销, 在更一般的场景中,当我们不需要闭包来捕获环境时,我们不希望产生这些开销。 因为函数从未允许捕获环境,定义和使用函数也就从不会有这些额外开销。 闭包可以通过三种方式捕获其环境,他们直接对应函数的三种获取参数的方式:获取所有权,可变借用和不可变借用。 */ } pub fn closure_trait_demo() { println!( "{}", "------------closure_trait_demo start-------------------" ); //FnMut 获取可变的借用值所以可以改变其环境 //Fn 从其环境获取不可变的借用值 /* It will report: value moved (into closure) here let x = vec![1, 2, 3]; let equal_to_x = move |z:Vec<i32>| z == x; println!("can't use x here: {:?}", x); let y = vec![1, 2, 3]; */ }
#![allow(clippy::identity_op)] use std::fs; fn do_the_thing(input: &str) -> u64 { input .lines() .into_iter() .map(|line| { match line { // A = Rock // B = Paper // C = Scissors // X = Rock (1 point) // Y = Paper (2 points) // Z = Scissors (3 points) // Win = 6, draw = 3, loss = 0 "A X" => 1 + 3, "A Y" => 2 + 6, "A Z" => 3 + 0, "B X" => 1 + 0, "B Y" => 2 + 3, "B Z" => 3 + 6, "C X" => 1 + 6, "C Y" => 2 + 0, "C Z" => 3 + 3, _ => panic!("invalid input") } }) .sum() } fn main() { let input = fs::read_to_string("input.txt").unwrap(); println!("{:?}", do_the_thing(&input)); } #[cfg(test)] mod tests { use super::*; use test_case::test_case; #[test_case("A Y B X C Z " => 15)] fn first(input: &str) -> u64 { do_the_thing(&input) } }
/* Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? */ use std::time::Instant; fn main() { let now = Instant::now(); println!("e:{:?}, {:?} seconds", _better_e(), now.elapsed()); } //use std::thread; use itertools::Itertools; fn e() { // get next pentagonal number let pent_clos = |i: i64| i * (i * 3 - 1) / 2; // turns out membership checks is pretty damn slow, much better to just have a predicate // could maybe do this better with a hash map if I /had/ to do this though // let first_1000_pentagonals = (1..2500).map(|x| pent_clos(x)).collect::<Vec<i64>>(); let first_1000_it = (1..2500_i64).map(|x| pent_clos(x)); let it_clone = first_1000_it.clone(); // create the cartesian product of the first 1000 pentagonals, filter by conditions, collect into result. let res_it = first_1000_it .cartesian_product(it_clone) .filter(|(x, y)| is_pentagonal(x + y) && is_pentagonal(x - y)); let res = res_it.collect::<Vec<(i64, i64)>>(); println!("{:?}", res); } //predicates predicates fn is_pentagonal(p: i64) -> bool { // p is pentagonal if p = n(3n-1)/2 has a whole number solution for n; or rather // (3/2)n^2 - (1/2)n - p = 0; apply quad formula // 3n^2 - n - 2p = 0; only want positive soln // n = (1/6)*(1+ sqrt(1 +4*3*2*p)) <- if that exists let n = (1.0 + (1.0 + 24.0 * p as f64).sqrt()) / 6.0; // the .0 bit is important here // fun fact, the f64 std lib is great use std::f64::EPSILON; n - n.floor() < EPSILON } fn _better_e() { // a better solution wouldn't have an upper bound of 2500, would just stop when it found a value. // let pent_clos = |i: i64| i * (i * 3 - 1) / 2; for (i, j) in (1..).map(|x| (x, pent_clos(x))) { // i = index, j = ith pentagonal. for k in (1..i).map(|x| pent_clos(x)) { // if is_pentagonal(j - k) && is_pentagonal(k + j) { println!("{}", j - k); return; } } } } // Here begins some unrelated practice with structs and stuff #[derive(Debug)] struct Pentagonal { i: usize, // 0,1,2, 3, 4.. n: usize, // 0,1,5,12,22.. } impl Pentagonal { #[allow(dead_code)] fn from(i: usize) -> Self { Pentagonal { i: i + 1, n: i * (i * 3 - 1) / 2, } } #[allow(dead_code)] fn new() -> Self { Pentagonal { i: 1, n: 1 } } #[allow(dead_code)] fn is_sum_and_diff_pent(&self, rhs: &Pentagonal) -> bool { Pentagonal::is_pentagonal((self.n - rhs.n) as isize) && Pentagonal::is_pentagonal((self.n + rhs.n) as isize) } fn is_pentagonal(n: isize) -> bool { let (x0, x1) = Pentagonal::factor_quadratic(3, -1, -2 * n); // check roots let zero = |x| 3 * x * x - x - 2 * n == 0; zero(x0) || zero(x1) } fn factor_quadratic(a: isize, b: isize, c: isize) -> (isize, isize) { // sign is +-1 let quad = |sign: isize| { (b * -1 + sign * f64::sqrt((b * b - 4 * a * c) as f64) as isize) / (2 * a) }; (quad(1), quad(-1)) } #[allow(dead_code)] fn are_unseen_pent_sum_and_diff( self, seen: Vec<Pentagonal>, ) -> Option<(Pentagonal, Pentagonal)> { // if sum AND diff of new pent and any old pent are both pent, return tuple let res = seen .iter() .map(|i| { ( seen.contains(&(self + *i)) && seen.contains(&(self - *i)), i.i, ) }) .fold((false, 0), |acc, (x, i)| (x || acc.0, i)); match res.0 { false => None, true => Some((self, Pentagonal::from(res.1))), } } } impl Iterator for Pentagonal { type Item = Pentagonal; fn next(&mut self) -> Option<Self::Item> { Some(Pentagonal { i: self.i + 1, n: self.i * (self.i * 3 - 1) / 2, }) } } impl PartialEq for Pentagonal { fn eq(&self, other: &Self) -> bool { self.n == other.n } } impl Copy for Pentagonal {} impl Clone for Pentagonal { fn clone(&self) -> Self { *self } } use std::ops::Add; impl Add for Pentagonal { type Output = Self; fn add(self, other: Self) -> Self { Self { i: self.i + other.i, n: self.n + other.n, } } } use std::ops::Sub; impl Sub for Pentagonal { type Output = Self; fn sub(self, other: Self) -> Self { Self { i: self.i - other.i, n: self.n - other.n, } } }
pub fn collect_strings(file_path: &str) -> Vec<String> { let reader = fasta::Reader::from_file(file_path.to_string()).unwrap(); let mut string_vec = Vec::new(); for (i, mut result) in enumerate(reader.records()) { let mut rec = result.unwrap(); string_vec.push(rec.seq_string()) } string_vec }
extern crate postgres; extern crate uuid; use dotenv::dotenv; use self::postgres::{Connection, SslMode}; use std::env; #[derive(RustcDecodable, RustcEncodable)] pub struct Invite { uuid: Option<uuid::Uuid>, pub name: String, pub email: String, invited: bool, confirmed: bool, } impl Invite { fn new(uuid: Option<uuid::Uuid>, name: String, email: String) -> Invite { Invite { uuid: uuid, name: name, email: email, invited: false, confirmed: false, } } } fn env_var(var: &str) -> String { match env::var(var) { Ok(x) => x, _ => "".to_string(), } } fn connection() -> Connection { dotenv().ok(); let conn_string: &str = &env_var("POSTGRES_CONNECTION_STRING"); Connection::connect(conn_string, SslMode::None).unwrap() } pub fn pending() -> Vec<Invite> { let conn = connection(); let mut invites: Vec<Invite> = Vec::new(); let query: &str = "SELECT uuid, name, email, invited, confirmed FROM invites WHERE invited = false"; for row in &conn.query(query, &[]).unwrap() { let invite = Invite::new(Some(row.get(0)), row.get(1), row.get(2)); invites.push(invite); } invites } pub fn invited(email: String) { let conn = connection(); let query = "UPDATE invites SET invited = true WHERE email = $1"; conn.execute(query, &[&email]).unwrap(); } pub fn create(name: String, email: String) { let conn = connection(); let query: &str = "INSERT INTO invites (uuid, name, email, invited, confirmed) VALUES ($1, $2, $3, false, false)"; let id = uuid::Uuid::new_v4(); conn.execute(query, &[&id, &name, &email]); } pub fn confirm(id: uuid::Uuid) { let conn = connection(); let query: &str = "UPDATE invites SET confirmed = true WHERE uuid = $1"; conn.execute(query, &[&id]).unwrap(); }
use std::fmt::{ self, Display, Write, Formatter }; use std::rc::Rc; use std::collections::HashMap; use super::super::error::Response::Wrong; use super::*; use super::TokenElement; #[derive(Debug, Clone)] pub enum TypeNode<'t> { Int, Float, Bool, Str, Char, Nil, Id(String), Array(Rc<Type<'t>>, usize), Func(Vec<Type<'t>>, Rc<Type<'t>>, Vec<String>, Option<&'t ExpressionNode<'t>>), } impl<'t> TypeNode<'t> { pub fn check_expression(&self, other: &'t ExpressionNode<'t>) -> bool { use self::TypeNode::*; match *other { ExpressionNode::Int(_) => match *self { Int | Float => true, _ => false, }, ExpressionNode::Array(ref content) => { let array_content = if let &Array(ref array_content, ref len) = self { if *len != content.len() { return false } array_content } else { return false }; for element in content { if !array_content.node.check_expression(&element.node) { return false } } true }, _ => false } } } impl<'t> PartialEq for TypeNode<'t> { fn eq(&self, other: &Self) -> bool { use self::TypeNode::*; match (self, other) { (&Int, &Int) => true, (&Str, &Str) => true, (&Float, &Float) => true, (&Char, &Char) => true, (&Bool, &Bool) => true, (&Nil, &Nil) => true, (&Array(ref a, ref la), &Array(ref b, ref lb)) => a == b && la == lb, (&Id(ref a), &Id(ref b)) => a == b, (&Func(ref a_params, ref a_retty, ..), &Func(ref b_params, ref b_retty, ..)) => a_params == b_params && a_retty == b_retty, _ => false, } } } #[derive(Debug, Clone)] pub enum TypeMode { Undeclared, Immutable, Optional, Regular, Splat(Option<usize>), Unwrap(usize), } impl<'t> Display for TypeNode<'t> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use self::TypeNode::*; match *self { Int => write!(f, "int"), Float => write!(f, "float"), Bool => write!(f, "bool"), Str => write!(f, "str"), Char => write!(f, "char"), Nil => write!(f, "nil"), Array(ref n, l) => write!(f, "[{}; {}]", n, l), Id(ref n) => write!(f, "{}", n), Func(ref params, ref return_type, ..) => { write!(f, "("); for (index, element) in params.iter().enumerate() { if index < params.len() - 1 { write!(f, "{}, ", element)? } else { write!(f, "{}", element)? } } write!(f, ") -> {}", return_type) }, } } } impl PartialEq for TypeMode { fn eq(&self, other: &TypeMode) -> bool { use self::TypeMode::*; match (self, other) { (&Regular, &Regular) => true, (&Regular, &Immutable) => true, (&Immutable, &Immutable) => true, (&Immutable, &Regular) => true, (_, &Optional) => true, (&Optional, _) => true, (&Undeclared, _) => false, (_, &Undeclared) => false, (&Splat(a), &Splat(b)) => &a == &b, (&Unwrap(_), _) => true, (_, &Unwrap(_)) => true, _ => false, } } } impl Display for TypeMode { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use self::TypeMode::*; match *self { Regular => Ok(()), Immutable => write!(f, "constant "), Undeclared => write!(f, "undeclared "), Optional => write!(f, "optional "), Splat(_) => write!(f, ".."), Unwrap(_) => write!(f, "*"), } } } #[derive(Debug, Clone, PartialEq)] pub struct Type<'t> { pub node: TypeNode<'t>, pub mode: TypeMode, } impl<'t> Type<'t> { pub fn new(node: TypeNode<'t>, mode: TypeMode) -> Self { Self { node, mode, } } pub fn id(id: &str) -> Self { Type::new(TypeNode::Id(id.to_owned()), TypeMode::Regular) } pub fn from(node: TypeNode<'t>) -> Type<'t> { Type::new(node, TypeMode::Regular) } pub fn array(t: Type<'t>, len: usize) -> Type<'t> { Type::new(TypeNode::Array(Rc::new(t), len), TypeMode::Regular) } pub fn function(params: Vec<Type<'t>>, return_type: Type<'t>) -> Self { Type::new(TypeNode::Func(params, Rc::new(return_type), Vec::new(), None), TypeMode::Regular) } } impl<'t> Display for Type<'t> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}{}", self.mode, self.node) } } #[derive(Debug, Clone)] pub enum FlagContext<'f> { Block(Option<Type<'f>>), Nothing, } pub struct Visitor<'v> { pub tabs: Vec<(SymTab, TypeTab<'v>)>, pub tab_frames: Vec<(SymTab, TypeTab<'v>)>, pub source: &'v Source, pub ast: &'v Vec<Statement<'v>>, pub flag: Option<FlagContext<'v>>, } impl<'v> Visitor<'v> { pub fn new(source: &'v Source, ast: &'v Vec<Statement<'v>>) -> Self { Visitor { tabs: vec!((SymTab::global(), TypeTab::global())), tab_frames: Vec::new(), // very intelligent hack source, ast, flag: None, } } pub fn visit(&mut self) -> Result<(), ()> { for statement in self.ast { self.visit_statement(&statement)? } self.tab_frames.push(self.tabs.last().unwrap().clone()); Ok(()) } pub fn visit_statement(&mut self, statement: &'v Statement<'v>) -> Result<(), ()> { use self::StatementNode::*; match statement.node { Expression(ref expression) => self.visit_expression(expression), Variable(..) => self.visit_variable(&statement.node), Assignment(ref left, ref right) => { let left_type = self.type_expression(left)?; let right_type = self.type_expression(right)?; if !left_type.node.check_expression(&Parser::fold_expression(right)?.node) && left_type.node != right_type.node { return Err( response!( Wrong(format!("mismatched types, expected type `{}` got `{}`", left_type.node, right_type)), self.source.file, right.pos ) ) } Ok(()) }, _ => Ok(()) } } fn ensure_no_implicit(&self, expression: &'v Expression<'v>) -> Result<(), ()> { use self::ExpressionNode::*; match expression.node { Block(ref statements) => if let Some(statement) = statements.last() { if let StatementNode::Expression(ref expression) = statement.node { match expression.node { Call(..) => (), Block(..) => { self.ensure_no_implicit(expression)?; } If(_, ref expr, _) => self.ensure_no_implicit(&*expr)?, _ => return Err( response!( Wrong("unexpected expression without context"), self.source.file, expression.pos ) ) } } () } else { () }, Call(..) => (), If(_, ref expr, _) => self.ensure_no_implicit(&*expr)?, _ => return Err( response!( Wrong("unexpected expression without context"), self.source.file, expression.pos ) ) } Ok(()) } fn visit_expression(&mut self, expression: &'v Expression<'v>) -> Result<(), ()> { use self::ExpressionNode::*; match expression.node { Identifier(ref name) => if self.current_tab().0.get_name(name).is_none() { Err( response!( Wrong(format!("no such value `{}` in this scope", name)), self.source.file, expression.pos ) ) } else { Ok(()) }, Unwrap(ref expression) => { self.visit_expression(&**expression)?; if let TypeMode::Splat(_) = self.type_expression(&**expression)?.mode { Ok(()) } else { Err( response!( Wrong("can't unwrap a non-splat value"), self.source.file, expression.pos ) ) } } Block(ref statements) => { self.push_scope(); for (i, statement) in statements.iter().enumerate() { if i < statements.len() - 1 { if let StatementNode::Expression(ref expression) = statement.node { self.ensure_no_implicit(expression)? } } self.visit_statement(statement)? } self.pop_scope(); Ok(()) }, If(ref condition, ref body, ref elses) => { self.visit_expression(&*condition)?; let condition_type = self.type_expression(&*condition)?.node; if condition_type == TypeNode::Bool { self.push_scope(); self.visit_expression(body)?; let body_type = self.type_expression(body)?; self.pop_scope(); if let &Some(ref elses) = elses { for &(ref maybe_condition, ref body, _) in elses { if let Some(ref condition) = *maybe_condition { let condition_type = self.type_expression(condition)?.node; if condition_type != TypeNode::Bool { return Err( response!( Wrong(format!("mismatched condition, must be `bool` got `{}`", condition_type)), self.source.file, condition.pos ) ) } } self.push_scope(); self.visit_expression(body)?; let else_body_type = self.type_expression(body)?; self.pop_scope(); if body_type != else_body_type { return Err( response!( Wrong(format!("mismatched types, expected `{}` got `{}`", body_type, else_body_type)), self.source.file, body.pos ) ) } } } Ok(()) } else { return Err( response!( Wrong(format!("mismatched condition, must be `bool` got `{}`", condition_type)), self.source.file, expression.pos ) ) } }, Call(ref expression, ref args) => { self.visit_expression(expression)?; let expression_type = self.type_expression(expression)?.node; let mut covers = HashMap::new(); let mut corrected_params = Vec::new(); // because functions don't know what's best for them >:() if let TypeNode::Func(ref params, _, ref generics, ref func) = expression_type { let mut actual_arg_len = args.len(); let mut type_buffer: Option<Type<'v>> = None; // for unwraps let mut has_unwrap = false; for (index, param) in params.iter().enumerate() { let arg_type = if index < args.len() { self.type_expression(&args[index])? } else { type_buffer.as_ref().unwrap().clone() }; corrected_params.push(arg_type.clone()); let mode = arg_type.mode.clone(); if let TypeMode::Unwrap(ref len) = mode { has_unwrap = true; type_buffer = Some(arg_type.clone()); actual_arg_len += len } if let TypeNode::Id(ref name) = param.node { if generics.contains(name) { if let Some(kind) = covers.get(name) { if &arg_type == kind { continue } else { return Err( response!( Wrong(format!("mismatched argument, expected `{}` got `{}`", expression_type, arg_type)), self.source.file, expression.pos ) ) } } covers.insert(name.clone(), arg_type.clone()); continue } } if (index < args.len() && !param.node.check_expression(&args[index].node)) && param != &arg_type { return Err( response!( Wrong(format!("mismatched argument, expected `{}` got `{}`", param, arg_type)), self.source.file, args[index].pos ) ) } } if has_unwrap { actual_arg_len -= 0 } if actual_arg_len > params.len() { let last = params.last().unwrap(); if let TypeMode::Splat(_) = last.mode { for splat in &args[params.len()..] { let splat_type = self.type_expression(&splat)?; if let TypeNode::Id(ref name) = last.node { if generics.contains(name) { if let Some(kind) = covers.get(name) { if &splat_type == kind { continue } else { return Err( response!( Wrong(format!("mismatched splat argument, expected `{}` got `{}`", kind, splat_type)), self.source.file, splat.pos ) ) } } } } if !last.node.check_expression(&splat.node) && last != &splat_type { return Err( response!( Wrong(format!("mismatched splat argument, expected `{}` got `{}`", last, splat_type)), self.source.file, splat.pos ) ) } } } } if actual_arg_len > params.len() { match params.last().unwrap().mode { TypeMode::Splat(_) => (), _ => return Err( response!( Wrong(format!("too many arguments, expected {} got {}", params.len(), actual_arg_len)), self.source.file, args.last().unwrap().pos ) ) } } if covers.len() > 0 || actual_arg_len > params.len() { if let Function(ref params, ref return_type, ref body, ref generics) = *func.unwrap() { let mut real_params = Vec::new(); for (i, param) in params.iter().enumerate() { real_params.push( ( param.0.clone(), if let TypeNode::Func(..) = param.1.node { corrected_params[i].clone() } else { param.1.clone() } ) ) } self.visit_function(expression.pos.clone(), &real_params, return_type, body, generics, Some(covers), actual_arg_len - params.len())?; } else { unreachable!() } } } else { return Err( response!( Wrong(format!("expected function, found `{}`", expression_type)), self.source.file, expression.pos ) ) } Ok(()) }, Function(ref params, ref return_type, ref body, ref generics) => self.visit_function(expression.pos.clone(), params, return_type, body, generics, None, 0), Array(ref content) => { let t = self.type_expression(content.first().unwrap())?; for element in content { let element_type = self.type_expression(element)?; if !t.node.check_expression(&Parser::fold_expression(element)?.node) && t.node != element_type.node { return Err( response!( Wrong(format!("mismatched types in array, expected `{}` got `{}`", t, element_type)), self.source.file, element.pos ) ) } } Ok(()) }, Index(ref left, ref index) => { let left_type = self.type_expression(left)?; if let TypeNode::Array(_, ref len) = left_type.node { let index_type = self.type_expression(index)?; match index_type.node { TypeNode::Int => { if let Int(ref a) = Parser::fold_expression(index)?.node { if *a as usize > *len { return Err( response!( Wrong(format!("index out of bounds, len is {} got {}", len, a)), self.source.file, left.pos ) ) } } }, _ => return Err( response!( Wrong(format!("can't index with `{}`, must be positive integer", index_type)), self.source.file, left.pos ) ) } } else { return Err( response!( Wrong(format!("can't index `{}`", left_type)), self.source.file, left.pos ) ) } Ok(()) }, _ => Ok(()) } } fn visit_function( &mut self, pos: TokenElement<'v>, params: &Vec<(String, Type<'v>)>, return_type: &'v Type<'v>, body: &'v Rc<Expression<'v>>, generics: &Option<Vec<String>>, generic_covers: Option<HashMap<String, Type<'v>>>, splat_len: usize ) -> Result<(), ()> { let mut param_names = Vec::new(); let mut param_types = Vec::new(); let mut return_type = return_type; for param in params { param_names.push(param.0.clone()); let kind = if let Some(ref generics) = *generics { if let TypeNode::Id(ref name) = return_type.node { if generics.contains(name) { if let Some(ref covers) = generic_covers { return_type = covers.get(name).unwrap() } } } if let TypeNode::Id(ref name) = param.1.node { if generics.contains(name) { if let Some(ref covers) = generic_covers { Type::new(covers.get(name).unwrap().clone().node, param.1.mode.clone()) } else { param.1.clone() } } else { param.1.clone() } } else { param.1.clone() } } else { param.1.clone() }; param_types.push(kind); } let last_type = param_types.last().unwrap().clone(); if let TypeMode::Splat(_) = last_type.mode { let len = param_types.len(); param_types[len - 1] = Type::new(last_type.node, TypeMode::Splat(Some(splat_len))) } if generics.is_none() != generic_covers.is_none() && splat_len == 0 { return Ok(()) } let parent = self.current_tab().clone(); self.tabs.push( ( SymTab::new(Rc::new(parent.0), &param_names), TypeTab::new(Rc::new(parent.1), &param_types, HashMap::new()) ) ); self.visit_expression(body)?; let body_type = self.type_expression(body)?; self.pop_scope(); if return_type != &body_type { Err( response!( Wrong(format!("mismatched return type, expected `{}` got `{}`", return_type, body_type)), self.source.file, pos ) ) } else { Ok(()) } } fn visit_variable(&mut self, variable: &'v StatementNode) -> Result<(), ()> { use self::ExpressionNode::*; if let &StatementNode::Variable(ref variable_type, ref name, ref right) = variable { let index = if let Some((index, _)) = self.current_tab().0.get_name(name) { index } else { self.current_tab().1.grow(); self.current_tab().0.add_name(name) }; if let &Some(ref right) = right { let right_type = self.type_expression(&right)?; match right.node { Function(..) | Block(_) | If(..) => (), _ => self.visit_expression(right)?, } if variable_type.node != TypeNode::Nil { if !variable_type.node.check_expression(&Parser::fold_expression(right)?.node) && variable_type.node != right_type.node { return Err( response!( Wrong(format!("mismatched types, expected type `{}` got `{}`", variable_type.node, right_type)), self.source.file, right.pos ) ) } else { self.current_tab().1.set_type(index, 0, variable_type.to_owned())?; } } else { self.current_tab().1.set_type(index, 0, right_type)?; } match right.node { Function(..) | Block(_) | If(..) => self.visit_expression(right)?, _ => (), } } else { self.current_tab().1.set_type(index, 0, variable_type.to_owned())?; } Ok(()) } else { unreachable!() } } pub fn type_statement(&mut self, statement: &'v Statement<'v>) -> Result<Type<'v>, ()> { use self::StatementNode::*; let t = match statement.node { Expression(ref expression) => self.type_expression(expression)?, Return(ref expression) => if let Some(ref expression) = *expression { self.type_expression(expression)? } else { Type::from(TypeNode::Nil) } _ => Type::from(TypeNode::Nil) }; Ok(t) } pub fn type_expression(&mut self, expression: &'v Expression<'v>) -> Result<Type<'v>, ()> { use self::ExpressionNode::*; let t = match expression.node { Identifier(ref name) => if let Some((index, env_index)) = self.current_tab().0.get_name(name) { self.current_tab().1.get_type(index, env_index)?.clone() } else { return Err( response!( Wrong(format!("no such value `{}` in this scope", name)), self.source.file, expression.pos ) ) }, Unwrap(ref expr) => { let t = self.type_expression(&**expr)?; if let TypeMode::Splat(ref len) = t.mode { Type::new(t.node, TypeMode::Unwrap(len.unwrap())) } else { unreachable!() } }, Empty => Type::from(TypeNode::Nil), Str(_) => Type::from(TypeNode::Str), Char(_) => Type::from(TypeNode::Char), Bool(_) => Type::from(TypeNode::Bool), Int(_) => Type::from(TypeNode::Int), Float(_) => Type::from(TypeNode::Float), Call(ref expression, _) => { if let TypeNode::Func(_, ref return_type, ..) = self.type_expression(expression)?.node { (**return_type).clone() } else { panic!("accident (submit an issue): called {:#?}", self.type_expression(expression)?.node) } }, Index(ref array, _) => if let TypeNode::Array(ref t, _) = self.type_expression(array)?.node { (**t).clone() } else { unreachable!() }, If(_, ref expression, _) => self.type_expression(expression)?, Array(ref content) => Type::array(self.type_expression(content.first().unwrap())?, content.len()), Cast(_, ref t) => Type::from(t.node.clone()), Binary(ref left, ref op, ref right) => { use self::Operator::*; match (self.type_expression(left)?.node, op, self.type_expression(right)?.node) { (ref a, ref op, ref b) => match **op { Add | Sub | Mul | Div | Pow | Mod => if [a, b] != [&TypeNode::Nil, &TypeNode::Nil] { // real hack here Type::from(if a != &TypeNode::Nil { a.to_owned() } else { b.to_owned() }) } else { return Err( response!( Wrong(format!("can't perform operation `{} {} {}`", a, op, b)), self.source.file, expression.pos ) ) }, Concat => if *a == TypeNode::Str { match *b { TypeNode::Func(..) | TypeNode::Array(..) => return Err( response!( Wrong(format!("can't perform operation `{} {} {}`", a, op, b)), self.source.file, expression.pos ) ), _ => Type::from(TypeNode::Str) } } else { return Err( response!( Wrong(format!("can't perform operation `{} {} {}`", a, op, b)), self.source.file, expression.pos ) ) }, Eq | Lt | Gt | NEq | LtEq | GtEq => if a == b { Type::from(TypeNode::Bool) } else { return Err( response!( Wrong(format!("can't perform operation `{} {} {}`", a, op, b)), self.source.file, expression.pos ) ) }, _ => return Err( response!( Wrong(format!("can't perform operation `{} {} {}`", a, op, b)), self.source.file, expression.pos ) ) }, } }, Function(ref params, ref return_type, _, ref generics) => { let mut param_types = Vec::new(); for param in params { param_types.push(param.1.clone()) } Type::from(TypeNode::Func(param_types, Rc::new(return_type.clone()), generics.clone().unwrap_or(Vec::new()), Some(&expression.node))) }, Block(ref statements) => { let flag_backup = self.flag.clone(); if self.flag.is_none() { self.flag = Some(FlagContext::Block(None)) } let block_type = if statements.len() > 0 { for element in statements { match element.node { StatementNode::Expression(ref expression) => match expression.node { Block(_) | If(..) => { self.type_expression(expression)?; }, _ => (), }, StatementNode::Return(ref return_type) => { let flag = self.flag.clone(); if let Some(ref flag) = flag { if let &FlagContext::Block(ref consistent) = flag { let return_type = if let Some(ref return_type) = *return_type { self.type_expression(&return_type)? } else { Type::from(TypeNode::Nil) }; if let Some(ref consistent) = *consistent { if return_type != *consistent { return Err( response!( Wrong(format!("mismatched types, expected `{}` found `{}`", consistent, return_type)), self.source.file, expression.pos ) ) } } else { self.flag = Some(FlagContext::Block(Some(return_type.clone()))) } } } }, _ => (), } } self.visit_expression(&expression)?; self.tabs.push(self.tab_frames.last().unwrap().clone()); let last = statements.last().unwrap(); let implicit_type = self.type_statement(last)?; self.tabs.pop(); if let Some(flag) = self.flag.clone() { if let FlagContext::Block(ref consistent) = flag { if let Some(ref consistent) = *consistent { if implicit_type != *consistent { return Err( response!( Wrong(format!("mismatched types, expected `{}` found `{}`", consistent, implicit_type)), self.source.file, last.pos ) ) } } else { self.flag = Some(FlagContext::Block(Some(implicit_type.clone()))) } } } implicit_type } else { Type::from(TypeNode::Nil) }; self.flag = flag_backup; block_type }, _ => Type::from(TypeNode::Nil) }; Ok(t) } pub fn current_tab(&mut self) -> &mut (SymTab, TypeTab<'v>) { let len = self.tabs.len() - 1; &mut self.tabs[len] } pub fn push_scope(&mut self) { let local_symtab = SymTab::new(Rc::new(self.current_tab().0.clone()), &[]); let local_typetab = TypeTab::new(Rc::new(self.current_tab().1.clone()), &[], HashMap::new()); self.tabs.push((local_symtab.clone(), local_typetab.clone())); } pub fn pop_scope(&mut self) { self.tab_frames.push(self.tabs.pop().unwrap()); } }
use std::cell::RefCell; use super::super::memory::Memory; pub type TensorMemories<T> = RefCell<Vec<Box<Memory<T>>>>;
//! The file generator. //! //! Unlike the other generators the file generator does not "connect" however //! losely to the target but instead, without coordination, merely writes files //! on disk. use std::{ num::{NonZeroU32, NonZeroUsize}, path::PathBuf, str, sync::{ atomic::{AtomicU32, Ordering}, Arc, }, }; use byte_unit::{Byte, ByteUnit}; use futures::future::join_all; use metrics::{gauge, register_counter}; use rand::{prelude::StdRng, SeedableRng}; use serde::Deserialize; use tokio::{ fs, io::{AsyncWriteExt, BufWriter}, task::{JoinError, JoinHandle}, }; use tracing::info; use crate::{ block::{self, chunk_bytes, construct_block_cache, Block}, payload, signals::Shutdown, throttle::{self, Throttle}, }; #[derive(thiserror::Error, Debug)] /// Errors produced by [`FileGen`]. pub enum Error { /// Wrapper around [`std::io::Error`]. #[error("Io error: {0}")] Io(#[from] ::std::io::Error), /// Creation of payload blocks failed. #[error("Block creation error: {0}")] Block(#[from] block::Error), /// Child sub-task error. #[error("Child join error: {0}")] Child(#[from] JoinError), } fn default_rotation() -> bool { true } #[derive(Debug, Deserialize, PartialEq)] /// Configuration of [`FileGen`] pub struct Config { /// The seed for random operations against this target pub seed: [u8; 32], /// The path template for logs. "%NNN%" will be replaced in the template /// with the duplicate number. pub path_template: String, /// Total number of duplicates to make from this template. pub duplicates: u8, /// Sets the [`lading::payload::Config`] of this template. pub variant: payload::Config, /// Sets the **soft** maximum bytes to be written into the `LogTarget`. This /// limit is soft, meaning a burst may go beyond this limit by no more than /// `maximum_token_burst`. /// /// After this limit is breached the target is closed and deleted. A new /// target with the same name is created to be written to. maximum_bytes_per_file: Byte, /// Defines the number of bytes that are added into the `LogTarget`'s rate /// limiting mechanism per second. This sets the maximum bytes that can be /// written _continuously_ per second from this target. Higher bursts are /// possible as the internal governor accumulates, up to /// `maximum_bytes_burst`. bytes_per_second: Byte, /// The block sizes for messages to this target pub block_sizes: Option<Vec<byte_unit::Byte>>, /// Defines the maximum internal cache of this log target. file_gen will /// pre-build its outputs up to the byte capacity specified here. maximum_prebuild_cache_size_bytes: Byte, /// Determines whether the file generator mimics log rotation or not. If /// true, files will be rotated. If false, it is the responsibility of /// tailing software to remove old files. #[serde(default = "default_rotation")] rotate: bool, /// The load throttle configuration #[serde(default)] pub throttle: throttle::Config, } #[derive(Debug)] /// The file generator. /// /// This generator writes files to disk, rotating them as appropriate. It does /// this without coordination to the target. pub struct FileGen { handles: Vec<JoinHandle<Result<(), Error>>>, shutdown: Shutdown, } impl FileGen { /// Create a new [`FileGen`] /// /// # Errors /// /// Creation will fail if the target file cannot be opened for writing. /// /// # Panics /// /// Function will panic if variant is Static and the `static_path` is not /// set. #[allow(clippy::cast_possible_truncation)] pub fn new(config: Config, shutdown: Shutdown) -> Result<Self, Error> { let mut rng = StdRng::from_seed(config.seed); let block_sizes: Vec<NonZeroUsize> = config .block_sizes .unwrap_or_else(|| { vec![ Byte::from_unit(1_f64, ByteUnit::MB).unwrap(), Byte::from_unit(2_f64, ByteUnit::MB).unwrap(), Byte::from_unit(4_f64, ByteUnit::MB).unwrap(), Byte::from_unit(8_f64, ByteUnit::MB).unwrap(), Byte::from_unit(16_f64, ByteUnit::MB).unwrap(), Byte::from_unit(32_f64, ByteUnit::MB).unwrap(), ] }) .iter() .map(|sz| NonZeroUsize::new(sz.get_bytes() as usize).expect("bytes must be non-zero")) .collect(); let labels = vec![ ("component".to_string(), "generator".to_string()), ("component_name".to_string(), "file_gen".to_string()), ]; let bytes_per_second = NonZeroU32::new(config.bytes_per_second.get_bytes() as u32).unwrap(); gauge!( "bytes_per_second", f64::from(bytes_per_second.get()), &labels ); let maximum_bytes_per_file = NonZeroU32::new(config.maximum_bytes_per_file.get_bytes() as u32).unwrap(); let maximum_prebuild_cache_size_bytes = NonZeroU32::new(config.maximum_prebuild_cache_size_bytes.get_bytes() as u32).unwrap(); let block_chunks = chunk_bytes( &mut rng, NonZeroUsize::new(maximum_prebuild_cache_size_bytes.get() as usize) .expect("bytes must be non-zero"), &block_sizes, )?; let mut handles = Vec::new(); let file_index = Arc::new(AtomicU32::new(0)); let block_cache = construct_block_cache(&mut rng, &config.variant, &block_chunks, &labels); let block_cache = Arc::new(block_cache); for _ in 0..config.duplicates { let throttle = Throttle::new_with_config(config.throttle, bytes_per_second); let child = Child { path_template: config.path_template.clone(), maximum_bytes_per_file, bytes_per_second, throttle, block_cache: Arc::clone(&block_cache), file_index: Arc::clone(&file_index), rotate: config.rotate, shutdown: shutdown.clone(), }; handles.push(tokio::spawn(child.spin())); } Ok(Self { handles, shutdown }) } /// Run [`FileGen`] to completion or until a shutdown signal is received. /// /// In this loop the target file will be populated with lines of the variant /// dictated by the end user. /// /// # Errors /// /// This function will terminate with an error if file permissions are not /// correct, if the file cannot be written to etc. Any error from /// `std::io::Error` is possible. #[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_possible_truncation)] pub async fn spin(mut self) -> Result<(), Error> { self.shutdown.recv().await; info!("shutdown signal received"); for res in join_all(self.handles.drain(..)).await { match res { Ok(Ok(())) => continue, Ok(Err(err)) => return Err(err), Err(err) => return Err(Error::Child(err)), } } Ok(()) } } struct Child { path_template: String, maximum_bytes_per_file: NonZeroU32, bytes_per_second: NonZeroU32, throttle: Throttle, block_cache: Arc<Vec<Block>>, rotate: bool, file_index: Arc<AtomicU32>, shutdown: Shutdown, } impl Child { pub(crate) async fn spin(mut self) -> Result<(), Error> { let bytes_per_second = self.bytes_per_second.get() as usize; let mut total_bytes_written: u64 = 0; let maximum_bytes_per_file: u64 = u64::from(self.maximum_bytes_per_file.get()); let mut file_index = self.file_index.fetch_add(1, Ordering::Relaxed); let mut path = path_from_template(&self.path_template, file_index); let mut fp = BufWriter::with_capacity( bytes_per_second, fs::OpenOptions::new() .create(true) .truncate(true) .write(true) .open(&path) .await?, ); let mut idx = 0; let blocks = self.block_cache; let bytes_written = register_counter!("bytes_written"); loop { let block = &blocks[idx]; let total_bytes = block.total_bytes; tokio::select! { _ = self.throttle.wait_for(total_bytes) => { idx = (idx + 1) % blocks.len(); let total_bytes = u64::from(total_bytes.get()); { fp.write_all(&block.bytes).await?; bytes_written.increment(total_bytes); total_bytes_written += total_bytes; } if total_bytes_written > maximum_bytes_per_file { fp.flush().await?; if self.rotate { // Delete file, leaving any open file handlers intact. This // includes our own `fp` for the time being. fs::remove_file(&path).await?; } // Update `path` to point to the next indexed file. file_index = self.file_index.fetch_add(1, Ordering::Relaxed); path = path_from_template(&self.path_template, file_index); // Open a new fp to `path`, replacing `fp`. Any holders of the // file pointer still have it but the file no longer has a name. fp = BufWriter::with_capacity( bytes_per_second, fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .open(&path) .await?, ); total_bytes_written = 0; } } _ = self.shutdown.recv() => { fp.flush().await?; info!("shutdown signal received"); return Ok(()); }, } } } } #[inline] fn path_from_template(path_template: &str, index: u32) -> PathBuf { let fidx = format!("{index:04}"); let full_path = path_template.replace("%NNN%", &fidx); PathBuf::from(full_path) }
use aoc2019::intcode::IntCodeCpu; use itertools::Itertools; use std::fs; fn run_amplifiers(cpu: &IntCodeCpu) -> i64 { (0..5) .permutations(5) .map(|phase_settings| { let mut output = 0; for phase_setting in phase_settings { let mut amplifier = cpu.clone(); amplifier.input.push_back(phase_setting); amplifier.input.push_back(output); amplifier.run(); output = amplifier.output.pop_front().unwrap(); } output }) .max() .unwrap() } fn run_amplifiers_with_feedback(cpu: &IntCodeCpu) -> i64 { (5..10) .permutations(5) .map(|phase_settings| { let mut amplifiers: Vec<IntCodeCpu> = phase_settings .iter() .map(|phase_setting| { let mut amplifier = cpu.clone(); amplifier.input.push_back(*phase_setting); amplifier.set_running(); amplifier }) .collect(); let mut output = 0; while amplifiers.first().unwrap().running() { for amplifier in &mut amplifiers { amplifier.input.push_back(output); if let Some(out) = amplifier.run_until_output() { output = out; } else { break; } } } output }) .max() .unwrap() } fn main() { let input = fs::read_to_string("./input/day07.in").unwrap(); let cpu = IntCodeCpu::from_code(&input); println!("p1: {}", run_amplifiers(&cpu)); println!("p2: {}", run_amplifiers_with_feedback(&cpu)); } #[cfg(test)] mod tests { use super::*; #[test] fn test_run_amplifiers() { assert_eq!( run_amplifiers(&IntCodeCpu::from_code( "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0" )), 43_210 ); } #[test] fn test_run_amplifiers2() { assert_eq!( run_amplifiers(&IntCodeCpu::from_code( "3,23,3,24,1002,24,10,24,1002,23,-1,23, 101,5,23,23,1,24,23,23,4,23,99,0,0" )), 54_321 ); } #[test] fn test_run_amplifiers3() { assert_eq!( run_amplifiers(&IntCodeCpu::from_code( "3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33, 1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0" )), 65_210 ); } #[test] fn test_run_amplifiers_with_feedback() { assert_eq!( run_amplifiers_with_feedback(&IntCodeCpu::from_code( "3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26, 27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5" )), 139_629_729 ); } #[test] fn test_run_amplifiers_with_feedback2() { assert_eq!( run_amplifiers_with_feedback(&IntCodeCpu::from_code( "3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54, -5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4, 53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10" )), 18_216 ); } }
use itertools::__std_iter::FromIterator; use std::collections::HashMap; pub mod part1; pub mod part2; pub fn default_input() -> &'static str{ include_str!("input") } pub fn run() { part1::run(); part2::run(); } pub fn parse_input(input : &str) -> HashMap<String, Vec<Bag>> { input.split("\n").map(|line| { let split : Vec<_> = line.split("contain").collect(); let mut values: Vec<_> = split[1].split(&[',', '.'][..]).collect(); values.remove(values.len()-1); let bags : Vec<Bag>; if values[0].trim().as_bytes()[0].is_ascii_alphabetic() { bags = Vec::new(); } else { bags = values.iter().map(|s| { let amount = (s.trim().as_bytes()[0] as char).to_digit(10).unwrap(); let name = String::from_iter(s.trim().chars().skip(1)).replace("bags", "").replace("bag", "").trim().to_owned(); Bag { amount, name } }).collect(); } (split[0].replace("bags", "").replace("bag", "").trim().to_owned(), bags) }).collect() } pub struct Bag { pub amount: u32, pub name: String, }
#[allow(unused_imports)] use super::util::prelude::*; use super::util::{Pack, PackDepth}; use super::BlockMut; use crate::libs::color::Pallet; use std::collections::HashSet; block! { [pub Textboard(constructor, pack, component)] (is_bind_to_grid): bool; (position): [f64; 3]; origin: BlockMut<Component> = BlockMut::<Component>::none(); title: String = String::new(); text: String = String::new(); font_size: f64 = 0.5; size: [f64; 2] = [3.0, 4.0]; color: Pallet = Pallet::yellow(0); } impl Textboard { pub fn color(&self) -> &Pallet { &self.color } pub fn set_color(&mut self, color: Pallet) { self.color = color; } pub fn is_bind_to_grid(&self) -> bool { self.is_bind_to_grid } pub fn set_is_bind_to_grid(&mut self, is_bind_to_grid: bool) { self.is_bind_to_grid = is_bind_to_grid; } pub fn position(&self) -> &[f64; 3] { &self.position } pub fn set_position(&mut self, position: [f64; 3]) { self.position = position; } pub fn title(&self) -> &String { &self.title } pub fn set_title(&mut self, title: String) { self.title = title; } pub fn text(&self) -> &String { &self.text } pub fn set_text(&mut self, text: String) { self.text = text; } pub fn font_size(&self) -> f64 { self.font_size } pub fn set_font_size(&mut self, font_size: f64) { self.font_size = font_size; } pub fn size(&self) -> &[f64; 2] { &self.size } pub fn set_size(&mut self, size: [f64; 2]) { self.size = size; } } impl BlockMut<Component> { pub fn create_clone(&self) -> Option<Textboard> { self.map(|component| { let mut cloned = component.origin.clone(); cloned.origin = BlockMut::clone(self); cloned }) } } impl Clone for Textboard { fn clone(&self) -> Self { Self { origin: BlockMut::<Component>::none(), is_bind_to_grid: self.is_bind_to_grid, title: self.title.clone(), text: self.text.clone(), font_size: self.font_size, position: self.position.clone(), size: self.size.clone(), color: self.color.clone(), } } }
#[doc = "Register `ODISR` writer"] pub type W = crate::W<ODISR_SPEC>; #[doc = "Field `TA1ODIS` writer - TA1ODIS"] pub type TA1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TA2ODIS` writer - TA2ODIS"] pub type TA2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TB1ODIS` writer - TB1ODIS"] pub type TB1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TB2ODIS` writer - TB2ODIS"] pub type TB2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TC1ODIS` writer - TC1ODIS"] pub type TC1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TC2ODIS` writer - TC2ODIS"] pub type TC2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TD1ODIS` writer - TD1ODIS"] pub type TD1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TD2ODIS` writer - TD2ODIS"] pub type TD2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TE1ODIS` writer - TE1ODIS"] pub type TE1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TE2ODIS` writer - TE2ODIS"] pub type TE2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TF1ODIS` writer - TF1ODIS"] pub type TF1ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TF2ODIS` writer - TF2ODIS"] pub type TF2ODIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl W { #[doc = "Bit 0 - TA1ODIS"] #[inline(always)] #[must_use] pub fn ta1odis(&mut self) -> TA1ODIS_W<ODISR_SPEC, 0> { TA1ODIS_W::new(self) } #[doc = "Bit 1 - TA2ODIS"] #[inline(always)] #[must_use] pub fn ta2odis(&mut self) -> TA2ODIS_W<ODISR_SPEC, 1> { TA2ODIS_W::new(self) } #[doc = "Bit 2 - TB1ODIS"] #[inline(always)] #[must_use] pub fn tb1odis(&mut self) -> TB1ODIS_W<ODISR_SPEC, 2> { TB1ODIS_W::new(self) } #[doc = "Bit 3 - TB2ODIS"] #[inline(always)] #[must_use] pub fn tb2odis(&mut self) -> TB2ODIS_W<ODISR_SPEC, 3> { TB2ODIS_W::new(self) } #[doc = "Bit 4 - TC1ODIS"] #[inline(always)] #[must_use] pub fn tc1odis(&mut self) -> TC1ODIS_W<ODISR_SPEC, 4> { TC1ODIS_W::new(self) } #[doc = "Bit 5 - TC2ODIS"] #[inline(always)] #[must_use] pub fn tc2odis(&mut self) -> TC2ODIS_W<ODISR_SPEC, 5> { TC2ODIS_W::new(self) } #[doc = "Bit 6 - TD1ODIS"] #[inline(always)] #[must_use] pub fn td1odis(&mut self) -> TD1ODIS_W<ODISR_SPEC, 6> { TD1ODIS_W::new(self) } #[doc = "Bit 7 - TD2ODIS"] #[inline(always)] #[must_use] pub fn td2odis(&mut self) -> TD2ODIS_W<ODISR_SPEC, 7> { TD2ODIS_W::new(self) } #[doc = "Bit 8 - TE1ODIS"] #[inline(always)] #[must_use] pub fn te1odis(&mut self) -> TE1ODIS_W<ODISR_SPEC, 8> { TE1ODIS_W::new(self) } #[doc = "Bit 9 - TE2ODIS"] #[inline(always)] #[must_use] pub fn te2odis(&mut self) -> TE2ODIS_W<ODISR_SPEC, 9> { TE2ODIS_W::new(self) } #[doc = "Bit 10 - TF1ODIS"] #[inline(always)] #[must_use] pub fn tf1odis(&mut self) -> TF1ODIS_W<ODISR_SPEC, 10> { TF1ODIS_W::new(self) } #[doc = "Bit 11 - TF2ODIS"] #[inline(always)] #[must_use] pub fn tf2odis(&mut self) -> TF2ODIS_W<ODISR_SPEC, 11> { TF2ODIS_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 = "ODISR\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`odisr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ODISR_SPEC; impl crate::RegisterSpec for ODISR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`odisr::W`](W) writer structure"] impl crate::Writable for ODISR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ODISR to value 0"] impl crate::Resettable for ODISR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub fn hello() -> String {"dog hello".to_string()}
use std::thread; use std::thread::JoinHandle; use std::sync::{Mutex,Arc,RwLock,Weak}; use std::io::{self, ErrorKind}; use std::rc::Rc; use mio::*; use mio::udp::*; use slab::Slab; use std::net::SocketAddr; use time::{get_time}; use std::time::Duration; use appData::AppData; use server::{Server, DisconnectionReason, DisconnectionSource}; use server::ServerState; use tcpConnection::{TCPConnection, ReadResult, TCPConnectionStage}; use udpConnection::UDPConnection; use player::Player; use packet::{ServerToClientUDPPacket, ClientToServerUDPPacket}; use rand::random; pub const UDP_DATAGRAM_LENGTH_LIMIT:usize = 4*1024; pub struct UDPSocket{ pub socket: UdpSocket, //listening socket pub token: Token, } pub struct UDPServer{ pub appData:Arc<AppData>, pub server:Arc<Server>, pub poll: Poll, pub events: Events, // a list of events to process readBuffer:Vec<u8>, pub sessions:Vec<u64>, tickTime:i64, } impl UDPServer{ pub fn process(&mut self) -> Result<(), &'static str>{ try!(self.server.udpSocket.lock().unwrap().register(&mut self.poll).or(Err( "Can not register server poll" ) ) ); { let mut serverStateGuard=self.server.state.write().unwrap(); if *serverStateGuard==ServerState::Initialization(0) { (*serverStateGuard)=ServerState::Initialization(1); }else if *serverStateGuard==ServerState::Initialization(1) { *serverStateGuard=ServerState::Processing; }else if *serverStateGuard!=ServerState::Processing {//Disconnect кем-то другим return Ok(()); } } while match *self.server.state.read().unwrap() { ServerState::Initialization(_) => true, _=>false} { thread::sleep_ms(10); } self.appData.log.print(format!("[INFO] UDP server is ready")); while {*self.server.state.read().unwrap()}==ServerState::Processing { let eventsNumber=try!(self.poll.poll(&mut self.events, Some(Duration::new(0,100_000_000)) ).or(Err( "Can not get eventsNumber" ) ) ); for i in 0..eventsNumber { let event = try!(self.events.get(i).ok_or( "Can not get event" ) ); try!(self.processEvent(event.token(), event.kind())); } self.disconnectUDPConnectionsFromList(); //try!(self.server.udpSocket.lock().unwrap().reregister(&mut self.poll)); self.processTick(); } Ok(()) } fn disconnectUDPConnectionsFromList(&mut self){ let disconnectUDPConnectionsListGuard=self.server.disconnectUDPConnectionsList.lock().unwrap(); let udpConnectionsGuard=self.server.udpConnections.read().unwrap(); for &(sessionID, ref reason) in (*disconnectUDPConnectionsListGuard).iter(){ match (*udpConnectionsGuard).get( sessionID ) { Some( udpConnectionMutex ) => { let udpConnectionGuard=udpConnectionMutex.lock().unwrap(); (*udpConnectionGuard)._disconnect(reason.clone()); }, None => {}, } } (*disconnectUDPConnectionsListGuard).clear(); } fn processTick(&mut self) { if get_time().sec-self.tickTime>1 { self.tickTime=get_time().sec; self.checkConnections(); } } fn checkConnections(&mut self){ let mut removeConnections = Vec::new(); //create list of connections we need to remove { let udpConnectionsGuard=self.server.udpConnections.read().unwrap(); for connectionMutex in (*udpConnectionsGuard).iter() { let mut connection=connectionMutex.lock().unwrap(); if (*connection).shouldReset { removeConnections.push(( (*connection).session & 0x0000_0000_0000_FFFF) as usize ); } } } if removeConnections.len()>0 { let mut udpConnectionsGuard=self.server.udpConnections.write().unwrap(); for sessionID in removeConnections { self.sessions[sessionID]=0; (*udpConnectionsGuard).remove(sessionID); } } } fn processEvent(&mut self, token: Token, event: Ready) -> Result<(), &'static str> { println!("event!!"); if event.is_readable() { let result=self.server.udpSocket.lock().unwrap().socket.recv_from( &mut self.readBuffer[..] ); match result{ Ok (None) => {} Ok (Some(( length, clientAddr ))) => { if length>=16 && length<UDP_DATAGRAM_LENGTH_LIMIT { let session=ClientToServerUDPPacket::unpackSession(&self.readBuffer); if session==0 { match self.processAccept( clientAddr ){ Ok ( _ ) => {}, Err( e ) => self.appData.log.print( format!("[ERROR] UDP Connection acception error : {}", e) ), } }else{ let playerID=(session & 0x0000_0000_0000_FFFF) as usize; if playerID<self.sessions.len() && session==self.sessions[playerID] { let time=ClientToServerUDPPacket::unpackTime(&self.readBuffer); match ClientToServerUDPPacket::unpack(&self.readBuffer) { Ok ( ref packet ) => { self.server.getSafePlayerAnd(playerID, |player| player.processDatagram(packet, time)); }, Err( e ) => self.appData.log.print( format!("[ERROR] Player {} : {}", playerID, e) ), } } } } }, Err( e ) => return Err( "UDP Socket read error" ), } } Ok(()) } fn processAccept(&mut self, clientAddr:SocketAddr) -> Result<(), &'static str> { //в редкой сетуации, когда TCPConnection есть(прошло более 1 сек), а UDP и Player нет, лучше отказать, пусть попросит еще раз //locks tcp/udp/players at the same time - may cause deadlock, особенно со стороны disconnect, от которого и все лочится let packet=try!( ClientToServerUDPPacket::unpack(&self.readBuffer) ); let sessionID=match packet{ ClientToServerUDPPacket::Initialization( sessionID ) => sessionID, _=>return Err("Expected only ClientToServerUDPPacket::Initialization packet"), }; if sessionID<self.sessions.len(){ return Err("too much sessionID"); } if self.sessions[sessionID]!=0 {//self.sessions и self.server.udpConnections чистятся одним потоком в одной функции, поэтому существование UDPConnection гарантировано let udpConnectionsGuard=self.server.udpConnections.read().unwrap(); let connection=(*udpConnectionsGuard)[sessionID].lock().unwrap(); if !connection.shouldReset{ //send package return Ok(()) }else{ return Err("Inactive UDP Connection still exists"); } } { //GUARD лочим сперва TCP Connections, чтобы всякие trydisconnect если и вызвались, то записались бы в очереди let tcpConnectionsGuard=self.server.tcpConnections.read().unwrap(); match (*tcpConnectionsGuard).get( Token(sessionID) ) { Some( tcpConnectionMutex ) => { let connection=tcpConnectionMutex.lock().unwrap(); if !(*connection).isActive { return Err("no active TCP Connection"); } }, None => return Err("no active TCP Connection"), } let tcpConnectionGuard=(*tcpConnectionsGuard)[ Token(sessionID) ].lock().unwrap(); let (userID, userName) = match (*tcpConnectionGuard).stage{ TCPConnectionStage::UDPConnectionInitialization ( _, ref userID, ref userName) => (*userID, userName.clone()), _=> return Err("stage is no UDP Initialization"), }; { //GUARD let playersGuard=self.server.players.read().unwrap(); if (*playersGuard).contains(sessionID){ return Err("Inactive Player still exists"); } } (*tcpConnectionGuard).stage=TCPConnectionStage::Playing; let randomBytes = (rand::random::<u64>()%0xFFFF_FFFF_FFFE+1)<<16; //>0 let session=randomBytes+sessionID as u64; self.sessions[sessionID]=session; { let udpConnectionsGuard=self.server.udpConnections.write().unwrap(); let udpConnection=UDPConnection::new(session, clientAddr); (*udpConnectionsGuard).insert_at(sessionID,Mutex::new(udpConnection)); } { let playersGuard=self.server.players.write().unwrap(); let player=Player::new(self.server.clone(), sessionID, userID, userName); (*playersGuard).insert_at(sessionID,RwLock::new(player)); } } //send package return Ok(()) } pub fn onServerShutdown(&mut self, sendAbschiedMessage:bool) -> Result<(),String> { self.server.udpSocket.lock().unwrap().deregister(&mut self.poll); Ok(()) } } impl UDPSocket{ pub fn new(addr:SocketAddr) -> Result<UDPSocket, String>{ let socketAddress=String::from("0.0.0.0:1945"); let socketAddr=try!((&socketAddress).parse::<SocketAddr>().or( Err(format!("Can bind udp socket address : {}", &socketAddress)) )); //можно и сокет сервера let udpSocket = match UdpSocket::bind( &socketAddr) { Ok ( socket ) => socket, Err( e ) => return Err( format!("UDP Socket error : {:?}",e) ), }; Ok( UDPSocket{ socket:udpSocket, token:Token(20_000_000), } ) } /* //вообще на стороне клиента должно приниматься сообщение целиком pub fn send(&mut self, msg:&Vec<u8>, important:bool) -> Result<bool,String> { let sent=match self.socket.send_to(&msg[..], &self.serverAddr){ Ok ( s ) => { match s { None => false, Some( n ) => n==msg.len(), } }, Err( e ) => return Err(format!("{:?}",e)), }; if sent { return Ok(true); } println!("not sent"); if important { self.importantMessages.push_front(msg.clone()); } Ok(false) } */ pub fn register(&mut self, poll:&mut Poll) -> Result<(), &'static str> { let interest=Ready::readable();//Ready::readable(); poll.register( &self.socket, self.token, interest, PollOpt::edge() ).or_else(|e| Err("Can not register UDP Server") ) } pub fn deregister(&self, poll:&mut Poll ) { poll.deregister( &self.socket ); } }
use std::{collections::VecDeque, cmp::Ordering}; use nom::{ IResult, character::{ complete::{digit1, multispace0, line_ending, alpha1, alpha0}, }, sequence::{preceded, terminated, tuple}, bytes::complete::{tag, take_till, take_while}, multi::separated_list0, combinator::opt, branch::alt, error::Error, }; fn parse_monkey(input: &str) -> IResult<&str, &str> { terminated( preceded( tuple((multispace0, tag("Monkey"), multispace0)), digit1 ), tuple((tag(":"), opt(line_ending))), )(input) } fn parse_starting_items(input: &str) -> IResult<&str,Vec<&str>> { terminated( preceded( take_till(|c: char| c.is_digit(10)), separated_list0( tuple((tag(","), opt(multispace0))), digit1, ) ), opt(line_ending), )(input) } fn parse_operation(input: &str) -> IResult<&str, Operation> { let (input, (operand1, operator, operand2)) = terminated( preceded( tuple((multispace0, tag("Operation: new ="), multispace0)), tuple(( alt((tag("old"), digit1)), preceded( opt(multispace0), alt((tag("+"), tag("*"))), ), preceded( opt(multispace0), alt((digit1, tag("old"))) ), )), ), opt(line_ending), )(input)?; let o1 = match operand1 { "old" => Operand::Old, n => Operand::Num(n.parse().unwrap_or(0)), }; let o2 = match operand2 { "old" => Operand::Old, n => Operand::Num(n.parse().unwrap_or(0)), }; return match operator { "+" => Ok((input, Operation::Add(o1, o2))), "*" => Ok((input, Operation::Mul(o1, o2))), _ => Err(nom::Err::Incomplete(nom::Needed::Unknown)), } } fn parse_test(input: &str) -> IResult<&str, (&str, &str)> { terminated( preceded( tuple((multispace0, tag("Test:"), multispace0)), tuple(( alpha1, preceded(tuple((opt(multispace0), opt(alpha0), opt(multispace0))), digit1), )), ), opt(line_ending), )(input) } fn parse_test_branch(input: &str) -> IResult<&str, &str> { terminated( preceded( tuple((multispace0, tag("If "), alt((tag("true"), tag("false"))), tag(":"), multispace0, tag("throw to monkey"), multispace0)), digit1 ), opt(line_ending), )(input) } #[derive(Debug, Clone)] enum Operand { Old, Num(i32), } impl PartialEq for Operand { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Num(t0), Self::Num(r0)) => t0 == r0, _ => core::mem::discriminant(self) == core::mem::discriminant(other), } } } #[derive(Debug, Clone)] enum Operation { Add(Operand, Operand), Mul(Operand, Operand), } impl PartialEq for Operation { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Add(t1, t2), Self::Add(r0, r1)) => t1 == r0 && t2 == r1, (Self::Mul(t1, t2), Self::Mul(r0, r1)) => t1 == r0 && t2 == r1, _ => false, } } } #[derive(Debug, Clone)] struct MonekyBehaviour { id: u32, items: VecDeque<u64>, operation: Operation, test: i32, true_receiver: u64, false_receiver: u64, inspected: u64, } #[allow(unused)] fn print_monkeys(monkeys: &Vec<MonekyBehaviour>) { for monkey in monkeys.iter() { println!("Monkey {}: {:?}, inspected {:}", monkey.id, monkey.items, monkey.inspected) } } impl PartialEq for MonekyBehaviour { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.items == other.items && self.operation == other.operation && self.test == other.test && self.true_receiver == other.true_receiver && self.false_receiver == other.false_receiver } } fn parse_single(input: &str) -> IResult<&str, MonekyBehaviour> { let (input, _) = take_while::<_, _, Error<_>>(|c: char| !c.is_alphanumeric())(input)?; let (input, monkey_id) = parse_monkey(input)?; let (input, starting_items) = parse_starting_items(input)?; let (input, operation) = parse_operation(input)?; let (input, (_, test_operand)) = parse_test(input)?; let (input, throw_to_when_true) = parse_test_branch(input)?; let (input, throw_to_when_false) = parse_test_branch(input)?; Ok((input, MonekyBehaviour { id: monkey_id.parse().unwrap(), items: starting_items.iter().map(|item| item.parse().unwrap()).collect(), operation: operation, test: test_operand.parse().unwrap_or(0), true_receiver: throw_to_when_true.parse().unwrap_or(0), false_receiver: throw_to_when_false.parse().unwrap_or(0), inspected: 0, })) } fn parse_input(input: &str) -> IResult<&str, Vec<MonekyBehaviour>> { let mut input = input; let mut result: Vec<MonekyBehaviour> = vec![]; while let Ok((output, monkey)) = parse_single(input) { result.push(monkey); input = output; } return Ok((input, result)); } pub fn process_part1(input: &str) -> String { let (_, mut monkeys) = parse_input(input).unwrap(); for _round in 1..21 { for i in 0..monkeys.len() { let current_monkey = monkeys[i].clone(); while let Some(item) = monkeys[i].items.pop_front() { monkeys[i].inspected+=1; // println!("Monkey {} inspect element {}", current_monkey.id, item); let worry_level = match monkeys[i].operation { Operation::Add(Operand::Old, Operand::Num(interest)) | Operation::Add(Operand::Num(interest), Operand::Old) => item + interest as u64, Operation::Add(Operand::Old, Operand::Old) => item + item, Operation::Mul(Operand::Old, Operand::Num(interest)) | Operation::Mul(Operand::Num(interest), Operand::Old) => item * interest as u64, Operation::Mul(Operand::Old, Operand::Old) => item * item, _ => 0, } / 3; if worry_level % current_monkey.test as u64 == 0 { monkeys[current_monkey.true_receiver as usize].items.push_back(worry_level); } else { monkeys[current_monkey.false_receiver as usize].items.push_back(worry_level); } } } // println!("\nRound {round:}"); // print_monkeys(&monkeys); } let mut inspected = monkeys.iter().map(|monkey| monkey.inspected).collect::<Vec<u64>>(); inspected.sort_by(|v1, v2| { if v1 == v2 { Ordering::Equal } else if v1 > v2 { Ordering::Less } else { Ordering::Greater } }); return (inspected[0] * inspected[1]).to_string() } pub fn process_part2(input: &str) -> String { let (_, mut monkeys) = parse_input(input).unwrap(); let mod_num = monkeys.iter().map(|monkey| monkey.test as u64).product::<u64>(); for _ in 1..10_001 { for i in 0..monkeys.len() { let current_monkey = monkeys[i].clone(); while let Some(item) = monkeys[i].items.pop_front() { monkeys[i].inspected+=1; let worry_level = match monkeys[i].operation { Operation::Add(Operand::Old, Operand::Num(interest)) | Operation::Add(Operand::Num(interest), Operand::Old) => item%mod_num + interest as u64, Operation::Add(Operand::Old, Operand::Old) => item%mod_num + item%mod_num, Operation::Mul(Operand::Old, Operand::Num(interest)) | Operation::Mul(Operand::Num(interest), Operand::Old) => item%mod_num * interest as u64, Operation::Mul(Operand::Old, Operand::Old) => item%mod_num * item%mod_num, _ => 0, }; if worry_level % current_monkey.test as u64 == 0 { monkeys[current_monkey.true_receiver as usize].items.push_back(worry_level); } else { monkeys[current_monkey.false_receiver as usize].items.push_back(worry_level); } } } } let mut inspected = monkeys.iter().map(|monkey| monkey.inspected).collect::<Vec<u64>>(); inspected.sort_by(|v1, v2| { if v1 == v2 { Ordering::Equal } else if v1 > v2 { Ordering::Less } else { Ordering::Greater } }); return (inspected[0] * inspected[1]).to_string() } #[cfg(test)] mod tests { use super::*; const INPUT_SINGLE: &str = "Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3"; const INPUT: &str = "Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1"; #[test] fn part2() { assert_eq!("2713310158", process_part2(INPUT)); } #[test] fn part1() { assert_eq!("10605", process_part1(INPUT)); } #[test] fn parse_all(){ let (_, monkeys) = parse_input(INPUT).unwrap(); assert_eq!(4, monkeys.len()); } #[test] fn parse_sinble_into_struct() { assert_eq!(("", MonekyBehaviour{ id: 0, items: [79, 98].into(), operation: Operation::Mul(Operand::Old, Operand::Num(19)), test: 23, true_receiver: 2, false_receiver: 3, inspected: 0, }), parse_single(INPUT_SINGLE).unwrap()); } #[test] fn parse_single_separated() { let (input, monkey_id) = parse_monkey(INPUT_SINGLE).unwrap(); assert_eq!(input, "Starting items: 79, 98\nOperation: new = old * 19\nTest: divisible by 23\n If true: throw to monkey 2\n If false: throw to monkey 3"); assert_eq!(monkey_id, "0"); let (input, starting_items) = parse_starting_items(input).unwrap(); assert_eq!(input, "Operation: new = old * 19\nTest: divisible by 23\n If true: throw to monkey 2\n If false: throw to monkey 3"); assert_eq!(starting_items, vec!["79", "98"]); let (input,operation) = parse_operation(input).unwrap(); assert_eq!(input, "Test: divisible by 23\n If true: throw to monkey 2\n If false: throw to monkey 3"); assert_eq!(operation, Operation::Mul(Operand::Old, Operand::Num(19))); let (input, (operator, operand)) = parse_test(input).unwrap(); assert_eq!(input, " If true: throw to monkey 2\n If false: throw to monkey 3"); assert_eq!(operator, "divisible"); assert_eq!(operand, "23"); let (input, throw_to) = parse_test_branch(input).unwrap(); assert_eq!(input, " If false: throw to monkey 3"); assert_eq!(throw_to, "2"); let (input, throw_to) = parse_test_branch(input).unwrap(); assert_eq!(input, ""); assert_eq!(throw_to, "3"); } }
extern crate zip; use error::Result; use self::zip::ZipArchive; use std::fmt; use std::fs::File; use std::path::{Path, PathBuf}; use super::Handler; pub struct ZipHandler { path: PathBuf, archive: ZipArchive<File>, } impl ZipHandler { pub fn new<P: Into<PathBuf>>(path: P) -> Result<ZipHandler> { let path = path.into(); let file = handler_try!(File::open(&path)); let archive = handler_try!(ZipArchive::new(file)); Ok(ZipHandler { path: path, archive: archive, }) } } impl fmt::Debug for ZipHandler { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("ZipHandler") .field("path", &self.path) .finish() } } impl Handler for ZipHandler { fn stat(&mut self, path: &Path) -> Result<::fs::stat::Stat> { use super::utils; for index in 0..self.archive.len() { let entry = self.archive.by_index(index).unwrap(); let e_path = Path::new(entry.name()); if e_path.starts_with(path) { // Test the two paths equality (== means it's a file) let stat = if e_path == path { ::fs::stat::Stat { file_type: ::fs::stat::FileType::File, permissions: ::fs::stat::Permissions { read: true, write: false, }, size: entry.size() as usize, } } else { ::fs::stat::Stat { file_type: ::fs::stat::FileType::Directory, permissions: ::fs::stat::Permissions { read: true, write: false, }, size: 0, } }; return Ok(stat); } } Err(utils::error(ZipHandlerError::InvalidPath(path.into()))) } fn read_dir(&mut self, path: &Path) -> Result<::fs::dir::ReadDirIterator> { use std::collections::HashSet; use std::ffi::OsStr; let mut items = HashSet::new(); for index in 0..self.archive.len() { let entry = self.archive.by_index(index).unwrap(); let e_path = Path::new(entry.name()); if let Ok(rel_path) = e_path.strip_prefix(path) { if let Some(name) = rel_path.iter().next().and_then(OsStr::to_str) { items.insert(name.to_owned()); } } } Ok(Box::new(items.into_iter())) } fn open(&mut self, path: &Path) -> Result<::fs::file::File<::fs::file::Read>> { let name = handler_try!(zip_name(path)); let entry = handler_try!(self.archive.by_name(name)); let entry = Box::new(entry); Ok(::fs::file::File::new(entry)) } } fn zip_name(path: &Path) -> ::std::result::Result<&str, ZipHandlerError> { match path.to_str() { Some(name) => Ok(name), None => Err(ZipHandlerError::InvalidPath(path.into())), } } quick_error! { #[derive(Debug)] pub enum ZipHandlerError { InvalidPath(path: PathBuf) { description("Invalid path (non UTF-8)") display("Invalid path `{}`", path.display()) } } }
use std::env; use std::fs; use main_error::MainError; use tf_demo_parser::demo::parser::player_summary_analyzer::PlayerSummaryAnalyzer; pub use tf_demo_parser::{Demo, DemoParser, Parse, ParseError, ParserState, Stream}; #[cfg(feature = "jemallocator")] #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; fn main() -> Result<(), MainError> { #[cfg(feature = "better_panic")] better_panic::install(); #[cfg(feature = "trace")] tracing_subscriber::fmt::init(); let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("1 argument required"); return Ok(()); } let path = args[1].clone(); let all = args.contains(&std::string::String::from("all")); let detailed_summaries = args.contains(&std::string::String::from("detailed_summaries")); let file = fs::read(path)?; let demo = Demo::new(&file); if !detailed_summaries { // Use the default (simple) analyzer to track kills, assists, and deaths let parser = if all { DemoParser::new_all(demo.get_stream()) } else { DemoParser::new(demo.get_stream()) }; let (_, state) = parser.parse()?; println!("{}", serde_json::to_string(&state)?); } else { let parser = DemoParser::new_with_analyser(demo.get_stream(), PlayerSummaryAnalyzer::new()); let (header, state) = parser.parse()?; println!("{:?}", header); let table_header = "Player | Points | Kills | Deaths | Assists | Destruction | Captures | Defenses | Domination | Revenge | Ubers | Headshots | Teleports | Healing | Backstabs | Bonus | Support | Damage Dealt"; let divider = "---------------------------------|------------|------------|------------|------------|-------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|-------------"; println!("{}", table_header); println!("{}", divider); for (user_id, user_data) in state.users { let player_name = user_data.name; if let Some(s) = state.player_summaries.get(&user_id) { let (color_code_start, color_code_end) = if player_name == header.nick { // Give the line for the player a green background with white text // ANSI color codes are in hex, since rust doesn't support octal literals in strings // See: https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 ("\x1b[1;42;37m", "\x1b[0m") } else { ("", "") }; println!( "{}{:32} | {:10} | {:10} | {:10} | {:10} | {:11} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:12}{}", color_code_start, player_name, s.points, s.kills, s.deaths, s.assists, s.buildings_destroyed, s.captures, s.defenses, s.dominations, s.revenges, s.ubercharges, s.headshots, s.teleports, s.healing, s.backstabs, s.bonus_points, s.support, s.damage_dealt, color_code_end, ); } } } Ok(()) }
use std::ops::{Deref, DerefMut}; use components::Blueprint; #[derive(Clone, Debug, Default)] pub struct DeltaTime(pub f32); #[derive(Debug, Default)] pub struct SpawnQueue(pub Vec<Blueprint>); impl Deref for SpawnQueue { type Target = Vec<Blueprint>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for SpawnQueue { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(Clone, Debug, Default)] pub struct PlayerScore(pub u32);
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::account_address::AccountAddress; use crate::block_metadata::BlockMetadata; use crate::transaction::SignedUserTransaction; use starcoin_crypto::{ hash::{CryptoHash, CryptoHasher, PlainCryptoHash}, HashValue, }; use crate::accumulator_info::AccumulatorInfo; use crate::language_storage::CORE_CODE_ADDRESS; use crate::U256; use serde::{Deserialize, Serialize}; use starcoin_accumulator::node::ACCUMULATOR_PLACEHOLDER_HASH; use std::cmp::Ordering; use std::cmp::PartialOrd; /// Type for block number. pub type BlockNumber = u64; /// block timestamp allowed future times pub const ALLOWED_FUTURE_BLOCKTIME: u64 = 15 * 1000; // 15 Second; #[derive( Default, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Serialize, Deserialize, CryptoHasher, CryptoHash, )] pub struct BlockHeader { /// Parent hash. pub parent_hash: HashValue, /// Block timestamp. pub timestamp: u64, /// Block number. pub number: BlockNumber, /// Block author. pub author: AccountAddress, /// auth_key_prefix for create_account pub auth_key_prefix: Option<Vec<u8>>, /// The transaction accumulator root hash after executing this block. pub accumulator_root: HashValue, /// The parent block accumulator root hash. pub parent_block_accumulator_root: HashValue, /// The last transaction state_root of this block after execute. pub state_root: HashValue, /// Gas used for contracts execution. pub gas_used: u64, /// Block gas limit. pub gas_limit: u64, /// Block difficulty pub difficulty: U256, /// Consensus extend header field. pub consensus_header: Vec<u8>, } impl BlockHeader { pub fn new<H>( parent_hash: HashValue, parent_block_accumulator_root: HashValue, timestamp: u64, number: BlockNumber, author: AccountAddress, accumulator_root: HashValue, state_root: HashValue, gas_used: u64, gas_limit: u64, difficulty: U256, consensus_header: H, ) -> BlockHeader where H: Into<Vec<u8>>, { Self::new_with_auth( parent_hash, parent_block_accumulator_root, timestamp, number, author, None, accumulator_root, state_root, gas_used, gas_limit, difficulty, consensus_header, ) } pub fn new_with_auth<H>( parent_hash: HashValue, parent_block_accumulator_root: HashValue, timestamp: u64, number: BlockNumber, author: AccountAddress, auth_key_prefix: Option<Vec<u8>>, accumulator_root: HashValue, state_root: HashValue, gas_used: u64, gas_limit: u64, difficulty: U256, consensus_header: H, ) -> BlockHeader where H: Into<Vec<u8>>, { BlockHeader { parent_hash, parent_block_accumulator_root, number, timestamp, author, auth_key_prefix, accumulator_root, state_root, gas_used, gas_limit, difficulty, consensus_header: consensus_header.into(), } } pub fn id(&self) -> HashValue { self.crypto_hash() } pub fn parent_hash(&self) -> HashValue { self.parent_hash } pub fn timestamp(&self) -> u64 { self.timestamp } pub fn number(&self) -> BlockNumber { self.number } pub fn author(&self) -> AccountAddress { self.author } pub fn accumulator_root(&self) -> HashValue { self.accumulator_root } pub fn state_root(&self) -> HashValue { self.state_root } pub fn gas_used(&self) -> u64 { self.gas_used } pub fn gas_limit(&self) -> u64 { self.gas_limit } pub fn consensus_header(&self) -> &[u8] { self.consensus_header.as_slice() } pub fn into_metadata(self) -> BlockMetadata { BlockMetadata::new( self.parent_hash(), self.timestamp, self.author, self.auth_key_prefix, ) } pub fn difficulty(&self) -> U256 { self.difficulty } pub fn parent_block_accumulator_root(&self) -> HashValue { self.parent_block_accumulator_root } pub fn genesis_block_header( parent_hash: HashValue, timestamp: u64, accumulator_root: HashValue, state_root: HashValue, difficulty: U256, consensus_header: Vec<u8>, ) -> Self { Self { parent_hash, parent_block_accumulator_root: *ACCUMULATOR_PLACEHOLDER_HASH, timestamp, number: 0, author: CORE_CODE_ADDRESS, auth_key_prefix: None, accumulator_root, state_root, gas_used: 0, gas_limit: 0, difficulty, consensus_header, } } pub fn random() -> Self { Self { parent_hash: HashValue::random(), parent_block_accumulator_root: HashValue::random(), timestamp: rand::random(), number: rand::random(), author: AccountAddress::random(), auth_key_prefix: None, accumulator_root: HashValue::random(), state_root: HashValue::random(), gas_used: rand::random(), gas_limit: rand::random(), difficulty: U256::max_value(), consensus_header: vec![], } } } impl Ord for BlockHeader { fn cmp(&self, other: &Self) -> Ordering { match self.number.cmp(&other.number) { Ordering::Equal => {} ordering => return ordering, } match self.timestamp.cmp(&other.timestamp) { Ordering::Equal => self.gas_used.cmp(&other.gas_used).reverse(), ordering => ordering, } } } impl Into<BlockMetadata> for BlockHeader { fn into(self) -> BlockMetadata { self.into_metadata() } } #[derive(Default, Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)] pub struct BlockBody { /// The transactions in this block. transactions: Vec<SignedUserTransaction>, } impl BlockBody { pub fn new(transactions: Vec<SignedUserTransaction>) -> Self { Self { transactions } } } impl Into<BlockBody> for Vec<SignedUserTransaction> { fn into(self) -> BlockBody { BlockBody { transactions: self } } } impl Into<Vec<SignedUserTransaction>> for BlockBody { fn into(self) -> Vec<SignedUserTransaction> { self.transactions } } /// A block, encoded as it is on the block chain. #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize, CryptoHasher, CryptoHash)] pub struct Block { /// The header of this block. pub header: BlockHeader, /// The body of this block. pub body: BlockBody, } impl Block { pub fn new<B>(header: BlockHeader, body: B) -> Self where B: Into<BlockBody>, { Block { header, body: body.into(), } } pub fn id(&self) -> HashValue { self.header.id() } pub fn header(&self) -> &BlockHeader { &self.header } pub fn transactions(&self) -> &[SignedUserTransaction] { self.body.transactions.as_slice() } pub fn into_inner(self) -> (BlockHeader, BlockBody) { (self.header, self.body) } pub fn genesis_block( parent_hash: HashValue, timestamp: u64, accumulator_root: HashValue, state_root: HashValue, difficulty: U256, consensus_header: Vec<u8>, genesis_txn: SignedUserTransaction, ) -> Self { let header = BlockHeader::genesis_block_header( parent_hash, timestamp, accumulator_root, state_root, difficulty, consensus_header, ); Self { header, body: BlockBody::new(vec![genesis_txn]), } } } /// `BlockInfo` is the object we store in the storage. It consists of the /// block as well as the execution result of this block. #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize, CryptoHasher, CryptoHash)] pub struct BlockInfo { /// Block id pub block_id: HashValue, //TODO group txn accumulator's fields. /// Accumulator root hash pub accumulator_root: HashValue, /// Frozen subtree roots of this accumulator. pub frozen_subtree_roots: Vec<HashValue>, /// The total number of leaves in this accumulator. pub num_leaves: u64, /// The total number of nodes in this accumulator. pub num_nodes: u64, /// The total difficulty. pub total_difficulty: U256, /// The block accumulator info. pub block_accumulator_info: AccumulatorInfo, } impl BlockInfo { pub fn new( block_id: HashValue, accumulator_root: HashValue, frozen_subtree_roots: Vec<HashValue>, num_leaves: u64, num_nodes: u64, total_difficulty: U256, block_accumulator_info: AccumulatorInfo, ) -> Self { Self { block_id, accumulator_root, frozen_subtree_roots, num_leaves, num_nodes, total_difficulty, block_accumulator_info, } } pub fn new_with_accumulator_info( block_id: HashValue, txn_accumulator_info: AccumulatorInfo, block_accumulator_info: AccumulatorInfo, total_difficulty: U256, ) -> Self { Self { block_id, accumulator_root: *txn_accumulator_info.get_accumulator_root(), frozen_subtree_roots: txn_accumulator_info.get_frozen_subtree_roots().clone(), num_leaves: txn_accumulator_info.get_num_leaves(), num_nodes: txn_accumulator_info.get_num_nodes(), total_difficulty, block_accumulator_info, } } pub fn into_inner( self, ) -> ( HashValue, HashValue, Vec<HashValue>, u64, u64, U256, AccumulatorInfo, ) { self.into() } pub fn id(&self) -> HashValue { self.crypto_hash() } pub fn get_total_difficulty(&self) -> U256 { self.total_difficulty } pub fn get_block_accumulator_info(&self) -> &AccumulatorInfo { &self.block_accumulator_info } pub fn get_txn_accumulator_info(&self) -> AccumulatorInfo { AccumulatorInfo::new( self.accumulator_root, self.frozen_subtree_roots.clone(), self.num_leaves, self.num_nodes, ) } pub fn block_id(&self) -> &HashValue { &self.block_id } } impl Into<( HashValue, HashValue, Vec<HashValue>, u64, u64, U256, AccumulatorInfo, )> for BlockInfo { fn into( self, ) -> ( HashValue, HashValue, Vec<HashValue>, u64, u64, U256, AccumulatorInfo, ) { ( self.block_id, self.accumulator_root, self.frozen_subtree_roots, self.num_leaves, self.num_nodes, self.total_difficulty, self.block_accumulator_info, ) } } #[derive(Clone)] pub struct BlockTemplate { /// Parent hash. pub parent_hash: HashValue, /// Block timestamp. pub timestamp: u64, /// Block number. pub number: BlockNumber, /// Block author. pub author: AccountAddress, /// auth_key_prefix pub auth_key_prefix: Option<Vec<u8>>, /// The accumulator root hash after executing this block. pub accumulator_root: HashValue, /// The parent block accumulator root hash. pub parent_block_accumulator_root: HashValue, /// The last transaction state_root of this block after execute. pub state_root: HashValue, /// Gas used for contracts execution. pub gas_used: u64, /// Block gas limit. pub gas_limit: u64, pub body: BlockBody, } impl BlockTemplate { pub fn new( parent_hash: HashValue, parent_block_accumulator_root: HashValue, timestamp: u64, number: BlockNumber, author: AccountAddress, auth_key_prefix: Option<Vec<u8>>, accumulator_root: HashValue, state_root: HashValue, gas_used: u64, gas_limit: u64, body: BlockBody, ) -> Self { Self { parent_hash, parent_block_accumulator_root, timestamp, number, author, auth_key_prefix, accumulator_root, state_root, gas_used, gas_limit, body, } } pub fn into_block<H>(self, consensus_header: H, difficulty: U256) -> Block where H: Into<Vec<u8>>, { let header = BlockHeader::new_with_auth( self.parent_hash, self.parent_block_accumulator_root, self.timestamp, self.number, self.author, self.auth_key_prefix, self.accumulator_root, self.state_root, self.gas_used, self.gas_limit, difficulty, consensus_header.into(), ); Block { header, body: self.body, } } pub fn into_block_header<H>(self, consensus_header: H, difficulty: U256) -> BlockHeader where H: Into<Vec<u8>>, { BlockHeader::new_with_auth( self.parent_hash, self.parent_block_accumulator_root, self.timestamp, self.number, self.author, self.auth_key_prefix, self.accumulator_root, self.state_root, self.gas_used, self.gas_limit, difficulty, consensus_header.into(), ) } pub fn from_block(block: Block) -> Self { BlockTemplate { parent_hash: block.header().parent_hash, parent_block_accumulator_root: block.header().parent_block_accumulator_root(), timestamp: block.header().timestamp, number: block.header().number, author: block.header().author, auth_key_prefix: block.header().auth_key_prefix.clone(), accumulator_root: block.header().accumulator_root, state_root: block.header().state_root, gas_used: block.header().gas_used, gas_limit: block.header().gas_limit, body: block.body, } } } #[derive(Clone, Debug, Hash, Serialize, Deserialize, CryptoHasher, CryptoHash)] pub struct BlockDetail { block: Block, total_difficulty: U256, } impl BlockDetail { pub fn new(block: Block, total_difficulty: U256) -> Self { BlockDetail { block, total_difficulty, } } pub fn get_total_difficulty(&self) -> U256 { self.total_difficulty } pub fn get_block(&self) -> &Block { &self.block } pub fn header(&self) -> &BlockHeader { self.block.header() } } #[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)] pub enum BlockState { Executed, Verified, }
use std::fs::{create_dir_all, remove_file, File, OpenOptions}; use std::io::{self, BufReader, BufWriter, Seek, SeekFrom, Write}; use std::ops::Range; use std::path::{Path, PathBuf}; use ropey::{Rope, RopeSlice}; use agda_mode::agda::ReplState; use agda_mode::pos::{InteractionPoint, Interval}; const FAIL_CREATE_DEFAULT: &str = "Failed to create default working file"; pub type Monad<T = ()> = io::Result<T>; pub struct InitModule(pub File, pub PathBuf, pub Rope); pub fn init_module(mut file: String, allow_ex: bool) -> Monad<InitModule> { // Extracted as variable to make the borrow checker happy if !file.ends_with(".agda") { file.push_str(".agda") } let path = Path::new(&file); if path.exists() { if !allow_ex { eprintln!("I don't want to work with existing files, sorry."); std::process::exit(1); } else { let file = OpenOptions::new().read(true).write(true).open(path)?; let mut perms = file.metadata()?.permissions(); perms.set_readonly(false); file.set_permissions(perms)?; let rope = Rope::from_reader(BufReader::new(&file))?; return Ok(InitModule(file, path.to_path_buf().canonicalize()?, rope)); } } let mut f = File::create(path)?; let extension = path.extension().and_then(|s| s.to_str()).unwrap_or(""); let mod_name = path .file_name() .and_then(|s| s.to_str()) .map(|s| s.trim_end_matches(extension)) .map(|s| s.trim_end_matches(".")) .map(|s| s.trim()) .expect("File does not have a name"); // TODO: check if it's a valid module name let first_line = format!("module {} where\n", mod_name); f.write(first_line.as_bytes())?; f.flush()?; Ok(InitModule( f, path.to_path_buf().canonicalize()?, Rope::from(first_line), )) } pub fn find_default_unwrap() -> String { find_default().expect(FAIL_CREATE_DEFAULT) } pub fn config_dir() -> Monad<PathBuf> { let agda_tac_dir = dirs::home_dir() .expect(FAIL_CREATE_DEFAULT) .join(".agda-tac"); create_dir_all(&agda_tac_dir)?; Ok(agda_tac_dir) } pub fn history_file() -> Monad<PathBuf> { Ok(config_dir()?.join(".repl_history")) } pub fn find_default() -> Monad<String> { println!("No input file specified, using default."); let file_path = config_dir()? .join("Nameless.agda") .into_os_string() .into_string() .expect(FAIL_CREATE_DEFAULT); println!("Default to {}", file_path); if Path::new(&file_path).exists() { remove_file(&file_path)?; } Ok(file_path) } pub fn agda_to_rope_range(i: &Interval) -> Range<usize> { i.range_shift_left(1) } pub struct Repl { pub agda: ReplState, pub file: File, pub path: PathBuf, file_buf: Rope, pub is_plain: bool, } impl Repl { pub fn new(agda: ReplState, file: File, path: PathBuf, file_buf: Rope) -> Self { Self { agda, file, path, file_buf, is_plain: false, } } pub fn append_buffer(&mut self, text: &str) { let index = self.file_buf.len_chars(); self.file_buf.insert(index, text) } pub fn remove_last_line_buffer(&mut self) { let line_last = self.file_buf.len_lines() - 2; let line_start = self.file_buf.line_to_char(line_last); let doc_end = self.file_buf.len_chars(); self.file_buf.remove(line_start..doc_end) } pub fn remove_line_buffer(&mut self, line_num: usize) { // Previous line let line_start = self.file_buf.line_to_char(line_num - 1); let line_end = self.file_buf.line_to_char(line_num); self.file_buf.remove(line_start..line_end) } pub fn line_of_offset(&mut self, offset: usize) -> usize { self.file_buf.char_to_line(offset) } pub fn fill_goal_buffer(&mut self, i: InteractionPoint, text: &str) { let interval = i.the_interval(); self.file_buf.remove(agda_to_rope_range(interval)); self.file_buf.insert(interval.start.pos - 1, text); } pub fn intros_in_goal_buffer(&mut self, i: InteractionPoint, text: &str) -> Option<()> { let interval = i.the_interval(); let line_num = interval.start.line - 1; let line_start = self.file_buf.line_to_char(line_num); let line = self.file_buf.line(line_num); let (idx, _) = (line.chars().into_iter().enumerate()).find(|(_, c)| c == &'=')?; self.file_buf.insert_char(line_start + idx, ' '); self.file_buf.insert(line_start + idx, text); Some(()) } pub fn insert_line_buffer(&mut self, line_num: usize, line: &str) { // Previous line let index = self.file_buf.line_to_char(line_num - 1) - 1; self.file_buf.insert(index, line); self.file_buf.insert(index, "\n") } pub fn dump_proof(&mut self) -> Monad { self.file_buf.write_to(BufWriter::new(io::stdout())) } pub fn line_in_buffer(&mut self, line_num: usize) -> RopeSlice { self.file_buf.line(line_num) } fn flush_file(&mut self) -> Monad { self.file.flush() } pub fn line_count(&self) -> usize { self.file_buf.len_lines() } pub fn append(&mut self, text: &str) -> Monad { self.append_buffer(text); Self::append_to_file(&mut self.file, text.as_bytes())?; self.flush_file() } pub fn remove_last_line(&mut self) -> Monad { self.remove_last_line_buffer(); self.sync_buffer() } fn append_to_file(file: &mut File, text: &[u8]) -> Monad<usize> { file.write(text) } fn clear_file(&mut self) -> Monad<u64> { let file = &mut self.file; file.sync_all()?; file.set_len(0)?; file.seek(SeekFrom::Start(0)) } pub fn sync_buffer(&mut self) -> Monad { self.clear_file()?; self.file_buf.write_to(BufWriter::new(&self.file))?; self.flush_file() } }
use amethyst::{ core::nalgebra::Vector2, ecs::prelude::{Component, VecStorage}, }; #[derive(Debug, Clone)] pub struct Dynamics { /// The current velocity, consisting of an x-component and a y-component. /// The vectors length should be limited by the System using this, e.g. implicitely due to the movement equation. pub vel: Vector2<f32,>, /// Current rotational speed around the z-axes in rad/s /// Should be limited by the System using this. pub omega: f32, /// Force applied to a body/entity, has a direction. /// The movement system is responsible for detecting and handeling leverage, /// caused by forces not being applied to the center of mass of an entity. pub force: Vector2<f32,>, /// Torque applied on the z-axis. /// - positive = counter-clock-wise /// - negative = clock-wise pub torque: f32, } impl Dynamics { pub fn new(vel: Vector2<f32,>, omega: f32, force: Vector2<f32,>, torque: f32,) -> Self { Dynamics { vel, omega, force, torque, } } } impl Default for Dynamics { fn default() -> Self { Self::new( Vector2::new(0.0, 0.0,), 0.0, Vector2::new(0.0, 0.0,), 0.0, ) } } impl Component for Dynamics { type Storage = VecStorage<Self,>; }
//! Contains options for ChangeStreams. use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; use std::time::Duration; use typed_builder::TypedBuilder; use crate::{ bson::{Bson, Timestamp}, change_stream::event::ResumeToken, collation::Collation, concern::ReadConcern, options::AggregateOptions, selection_criteria::SelectionCriteria, }; /// These are the valid options that can be passed to the `watch` method for creating a /// [`ChangeStream`](crate::change_stream::ChangeStream). #[skip_serializing_none] #[derive(Clone, Debug, Default, Deserialize, Serialize, TypedBuilder)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ChangeStreamOptions { #[rustfmt::skip] /// Configures how the /// [`ChangeStreamEvent::full_document`](crate::change_stream::event::ChangeStreamEvent::full_document) /// field will be populated. By default, the field will be empty for updates. #[builder(default)] pub full_document: Option<FullDocumentType>, /// Configures how the /// [`ChangeStreamEvent::full_document_before_change`]( /// crate::change_stream::event::ChangeStreamEvent::full_document_before_change) field will be /// populated. By default, the field will be empty for updates. #[builder(default)] pub full_document_before_change: Option<FullDocumentBeforeChangeType>, /// Specifies the logical starting point for the new change stream. Note that if a watched /// collection is dropped and recreated or newly renamed, `start_after` should be set instead. /// `resume_after` and `start_after` cannot be set simultaneously. /// /// For more information on resuming a change stream see the documentation [here](https://www.mongodb.com/docs/manual/changeStreams/#change-stream-resume-after) #[builder(default)] pub resume_after: Option<ResumeToken>, /// The change stream will only provide changes that occurred at or after the specified /// timestamp. Any command run against the server will return an operation time that can be /// used here. #[builder(default)] pub start_at_operation_time: Option<Timestamp>, /// Takes a resume token and starts a new change stream returning the first notification after /// the token. This will allow users to watch collections that have been dropped and /// recreated or newly renamed collections without missing any notifications. /// /// This feature is only available on MongoDB 4.2+. /// /// See the documentation [here](https://www.mongodb.com/docs/master/changeStreams/#change-stream-start-after) for more /// information. #[builder(default)] pub start_after: Option<ResumeToken>, /// If `true`, the change stream will monitor all changes for the given cluster. #[builder(default, setter(skip))] pub(crate) all_changes_for_cluster: Option<bool>, /// The maximum amount of time for the server to wait on new documents to satisfy a change /// stream query. #[builder(default)] #[serde(skip_serializing)] pub max_await_time: Option<Duration>, /// The number of documents to return per batch. #[builder(default)] #[serde(skip_serializing)] pub batch_size: Option<u32>, /// Specifies a collation. #[builder(default)] #[serde(skip_serializing)] pub collation: Option<Collation>, /// The read concern to use for the operation. /// /// If none is specified, the read concern defined on the object executing this operation will /// be used. #[builder(default)] #[serde(skip_serializing)] pub read_concern: Option<ReadConcern>, /// The criteria used to select a server for this operation. /// /// If none is specified, the selection criteria defined on the object executing this operation /// will be used. #[builder(default)] #[serde(skip_serializing)] pub selection_criteria: Option<SelectionCriteria>, /// Tags the query with an arbitrary [`Bson`] value to help trace the operation through the /// database profiler, currentOp and logs. /// /// The comment can be any [`Bson`] value on server versions 4.4+. On lower server versions, /// the comment must be a [`Bson::String`] value. #[builder(default)] pub comment: Option<Bson>, } impl ChangeStreamOptions { pub(crate) fn aggregate_options(&self) -> AggregateOptions { AggregateOptions::builder() .batch_size(self.batch_size) .collation(self.collation.clone()) .max_await_time(self.max_await_time) .read_concern(self.read_concern.clone()) .selection_criteria(self.selection_criteria.clone()) .comment_bson(self.comment.clone()) .build() } } /// Describes the modes for configuring the /// [`ChangeStreamEvent::full_document`]( /// crate::change_stream::event::ChangeStreamEvent::full_document) field. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FullDocumentType { /// The field will be populated with a copy of the entire document that was updated. UpdateLookup, /// The field will be populated for replace and update change events if the post-image for this /// event is available. WhenAvailable, /// The same behavior as `WhenAvailable` except that an error is raised if the post-image is /// not available. Required, /// User-defined other types for forward compatibility. Other(String), } /// Describes the modes for configuring the /// [`ChangeStreamEvent::full_document_before_change`]( /// crate::change_stream::event::ChangeStreamEvent::full_document_before_change) field. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum FullDocumentBeforeChangeType { /// The field will be populated for replace, update, and delete change events if the pre-image /// for this event is available. WhenAvailable, /// The same behavior as `WhenAvailable` except that an error is raised if the pre-image is /// not available. Required, /// Do not send a value. Off, /// User-defined other types for forward compatibility. Other(String), }
use async_std::task::block_on; use criterion::{ black_box, criterion_group, criterion_main, Criterion, }; use flux_lsp::LspServer; use lspower::{lsp, LanguageServer}; fn create_server() -> LspServer { LspServer::new(None) } fn open_file(server: &LspServer, text: String) { let params = lsp::DidOpenTextDocumentParams { text_document: lsp::TextDocumentItem::new( lsp::Url::parse("file:///home/user/file.flux").unwrap(), "flux".to_string(), 1, text, ), }; block_on(server.did_open(params)); } /// Benchmark the response for a package completion fn server_completion_package(c: &mut Criterion) { let fluxscript = r#"import "sql" sql."#; let server = create_server(); open_file(&server, fluxscript.to_string()); let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 2, character: 3, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::TRIGGER_CHARACTER, trigger_character: Some(".".to_string()), }), }; c.bench_function("server completion", |b| { b.iter(|| { block_on(black_box(server.completion(params.clone()))) .unwrap() .unwrap(); }) }); } fn server_completion_variable(c: &mut Criterion) { let fluxscript = r#"import "strings" import "csv" cal = 10 env = "prod01-us-west-2" cool = (a) => a + 1 c errorCounts = from(bucket:"kube-infra/monthly") |> range(start: -3d) |> filter(fn: (r) => r._measurement == "query_log" and r.error != "" and r._field == "responseSize" and r.env == env) |> group(columns:["env", "error"]) |> count() |> group(columns:["env", "_stop", "_start"]) errorCounts |> filter(fn: (r) => strings.containsStr(v: r.error, substr: "AppendMappedRecordWithNulls")) "#; let server = create_server(); open_file(&server, fluxscript.to_string()); let params = lsp::CompletionParams { text_document_position: lsp::TextDocumentPositionParams { text_document: lsp::TextDocumentIdentifier { uri: lsp::Url::parse("file:///home/user/file.flux") .unwrap(), }, position: lsp::Position { line: 8, character: 1, }, }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, context: Some(lsp::CompletionContext { trigger_kind: lsp::CompletionTriggerKind::INVOKED, trigger_character: None, }), }; c.bench_function("server completion", |b| { b.iter(|| { block_on(black_box(server.completion(params.clone()))) .unwrap(); }) }); } criterion_group!( benches, server_completion_package, server_completion_variable ); criterion_main!(benches);
use std::io; use std::collections::{HashMap, HashSet}; use std::net::{SocketAddr, TcpListener, TcpStream}; use derive_more::{From, Error, Display}; use serde::{Serialize, de::DeserializeOwned}; use crate::message::CommMessage; use crate::message; #[derive(From, Error, Debug, Display)] pub enum ServerError { IOError(io::Error), MessageError(message::MessageError), PlayerNotFound } pub struct ServerConn<M: Serialize + DeserializeOwned> { pub stream: TcpStream, buffer: Vec<u8>, pub incoming_msgs: Vec<M>, pub name: Option<String> } pub struct ServerContainer<M: Serialize + DeserializeOwned> { pub listener: TcpListener, pub connections: HashMap<u8, ServerConn<M>>, pub next_player_id: u8, pub max_players: usize } impl<M: Serialize + DeserializeOwned> ServerContainer<M> { pub fn new(port: u16, max_players: usize) -> Result<Self, ServerError> { let listener = TcpListener::bind(SocketAddr::from(([0, 0, 0, 0], port)))?; listener.set_nonblocking(true)?; Ok(Self { listener: listener, connections: HashMap::new(), next_player_id: 1, max_players: max_players }) } pub fn pids(&self) -> HashSet<u8> { self.connections.keys().cloned().collect() } pub fn update(&mut self) { while let Ok((stream, _)) = self.listener.accept() { if self.connections.len() < self.max_players { if let Ok(()) = stream.set_nonblocking(true) { self.player_joined(stream); } } } for pid in self.pids() { let _ = self.receive_from(pid); } } fn player_joined(&mut self, stream: TcpStream) { let pid = self.next_player_id; self.connections.insert(pid, ServerConn::<M> { stream: stream, buffer: Vec::new(), incoming_msgs: Vec::new(), name: None }); self.next_player_id += 1; let _ = self.send_to_internal(pid, &CommMessage::Welcome { client_id: pid, players: self.connections.iter().map(|(pid, conn)| (*pid, conn.name.clone())).collect() }); self.broadcast_internal(&CommMessage::PlayerChange { player_id: pid, joined: true }); } fn player_leave(&mut self, player_id: u8) { self.connections.remove(&player_id); self.broadcast_internal(&CommMessage::PlayerChange { player_id: player_id, joined: false }); } pub fn get_msgs(&mut self, player_id: u8) -> Result<Vec<M>, ServerError> { let conn = self.connections.get_mut(&player_id).ok_or(ServerError::PlayerNotFound)?; let mut result: Vec<M> = Vec::new(); result.append(&mut conn.incoming_msgs); Ok(result) } fn broadcast_internal(&mut self, message: &CommMessage<M>) { for pid in self.pids() { let _ = self.send_to_internal(pid, message); } } pub fn broadcast(&mut self, message: M) { self.broadcast_internal(&CommMessage::App(message)); } fn receive_from(&mut self, player_id: u8) -> Result<(), ServerError> { loop { let conn = self.connections.get_mut(&player_id).ok_or(ServerError::PlayerNotFound)?; let recv_result = message::receive(&mut conn.stream, &mut conn.buffer); match recv_result { Err(e) => { self.player_leave(player_id); return Err(ServerError::from(e)); }, Ok(msg) => { if let Some(msg) = msg { self.process_msg(player_id, msg); } else { break; } } }; } Ok(()) } fn process_msg(&mut self, player_id: u8, msg: CommMessage<M>) { let conn = self.connections.get_mut(&player_id).unwrap(); match msg { CommMessage::PlayerNameStatement { name, .. } => { conn.name = Some(name.clone()); self.broadcast_internal(&CommMessage::PlayerNameStatement { player_id: player_id, name: name }); }, CommMessage::App(msg) => conn.incoming_msgs.push(msg), _ => () }; } fn send_to_internal(&mut self, player_id: u8, message: &CommMessage<M>) -> Result<(), ServerError> { let conn = self.connections.get_mut(&player_id).ok_or(ServerError::PlayerNotFound)?; if let Err(e) = message::send(&mut conn.stream, message) { self.player_leave(player_id); return Err(ServerError::from(e)); } return Ok(()) } pub fn send_to(&mut self, player_id: u8, message: M) -> Result<(), ServerError> { self.send_to_internal(player_id, &CommMessage::App(message)) } }
use std::path::PathBuf; use std::sync::Arc; use anyhow::{anyhow, Context, Result}; use async_std::task::{spawn_blocking, JoinHandle}; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::prelude::*; use indicatif::ProgressBar; use notify::{watcher, DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher}; use crate::build::BuildSystem; use crate::config::RtcWatch; /// A watch system wrapping a build system and a watcher. pub struct WatchSystem { /// The build system progress bar for displaying the state of the build system overall. progress: ProgressBar, /// The build system. build: BuildSystem, /// The current vector of paths to be ignored. ignored_paths: Vec<PathBuf>, /// A channel of FS watch events. watch_rx: Receiver<DebouncedEvent>, /// A channel of new paths to ignore from the build system. build_rx: Receiver<PathBuf>, /// The watch system used for watching the filesystem. _watcher: (JoinHandle<()>, RecommendedWatcher), } impl WatchSystem { /// Create a new instance. pub async fn new(cfg: Arc<RtcWatch>, progress: ProgressBar) -> Result<Self> { // Create a channel for being able to listen for new paths to ignore while running. let (watch_tx, watch_rx) = channel(1); let (build_tx, build_rx) = channel(1); // Process ignore list. let mut ignored_paths = cfg.ignored_paths .iter() .try_fold(Vec::with_capacity(cfg.ignored_paths.len() + 1), |mut acc, path| -> Result<Vec<PathBuf>> { let abs_path = path.canonicalize().map_err(|err| anyhow!("invalid path provided: {}", err))?; acc.push(abs_path); Ok(acc) })?; ignored_paths.push(cfg.build.final_dist.clone()); // Build the watcher. let _watcher = build_watcher(watch_tx, cfg.paths.clone())?; // Build dependencies. let build = BuildSystem::new(cfg.build.clone(), progress.clone(), Some(build_tx)).await?; Ok(Self { progress, build, ignored_paths, watch_rx, build_rx, _watcher, }) } /// Run a build. pub async fn build(&mut self) { if let Err(err) = self.build.build().await { // NOTE WELL: we use debug formatting here to ensure the error chain is displayed. self.progress.println(format!("{:?}", err)); } } /// Run the watch system, responding to events and triggering builds. pub async fn run(mut self) { loop { futures::select! { ign_res = self.build_rx.next() => if let Some(ign) = ign_res { self.update_ignore_list(ign); }, ev_res = self.watch_rx.next() => if let Some(ev) = ev_res { self.handle_watch_event(ev).await; }, } } } async fn handle_watch_event(&mut self, event: DebouncedEvent) { let mut ev_path = match event { DebouncedEvent::Create(path) | DebouncedEvent::Write(path) | DebouncedEvent::Remove(path) | DebouncedEvent::Rename(_, path) => path, _ => return, }; ev_path = match ev_path.canonicalize() { Ok(path) => path, Err(err) => return self.progress.println(format!("could not canonicalize path: {}", err)), }; if ev_path .ancestors() .any(|path| self.ignored_paths.iter().any(|ignored_path| ignored_path == path)) { return; // Don't emit a notification if path is ignored. } if let Err(err) = self.build.build().await { self.progress.println(format!("{}", err)); } } fn update_ignore_list(&mut self, path: PathBuf) { if !self.ignored_paths.contains(&path) { self.ignored_paths.push(path); } } } fn build_watcher(mut watch_tx: Sender<DebouncedEvent>, paths: Vec<PathBuf>) -> Result<(JoinHandle<()>, RecommendedWatcher)> { let (tx, rx) = std::sync::mpsc::channel(); let mut watcher = watcher(tx, std::time::Duration::from_secs(1)).context("failed to build file system watcher")?; for path in paths { watcher .watch( &path.clone().canonicalize().context(format!("failed to canonicalize path: {:?}", &path))?, RecursiveMode::Recursive, ) .context(format!("failed to watch {:?} for file system changes", path))?; } let handle = spawn_blocking(move || loop { if let Ok(event) = rx.recv() { let _ = watch_tx.try_send(event); } }); Ok((handle, watcher)) }
extern crate num_bigint; use std::collections::HashMap; use num_bigint::BigUint; use num_bigint::ToBigUint; pub struct Fib { cache: HashMap<usize, BigUint> } impl Fib { #[inline] pub fn new() -> Self { let mut cache = HashMap::new(); cache.insert(1, 1.to_biguint().unwrap()); cache.insert(2, 1.to_biguint().unwrap()); Fib { cache } } pub fn get_by_idx(&mut self, idx: usize) -> BigUint { match self.cache.get(&idx) { Some(n) => n.clone(), None => { let res = self.get_by_idx(idx - 1) + self.get_by_idx(idx - 2); self.cache.insert(idx, res.clone()); res } } } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Comparator status register"] pub comp_sr: COMP_SR, #[doc = "0x04 - Comparator interrupt clear flag register"] pub comp_icfr: COMP_ICFR, _reserved2: [u8; 0x04], #[doc = "0x0c - Comparator configuration register 1"] pub comp_cfgr1: COMP_CFGR1, #[doc = "0x10 - Comparator configuration register 2"] pub comp_cfgr2: COMP_CFGR2, } #[doc = "COMP_SR (r) register accessor: Comparator status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_sr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`comp_sr`] module"] pub type COMP_SR = crate::Reg<comp_sr::COMP_SR_SPEC>; #[doc = "Comparator status register"] pub mod comp_sr; #[doc = "COMP_ICFR (rw) register accessor: Comparator interrupt clear flag register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_icfr::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 [`comp_icfr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`comp_icfr`] module"] pub type COMP_ICFR = crate::Reg<comp_icfr::COMP_ICFR_SPEC>; #[doc = "Comparator interrupt clear flag register"] pub mod comp_icfr; #[doc = "COMP_CFGR1 (rw) register accessor: Comparator configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_cfgr1::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 [`comp_cfgr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`comp_cfgr1`] module"] pub type COMP_CFGR1 = crate::Reg<comp_cfgr1::COMP_CFGR1_SPEC>; #[doc = "Comparator configuration register 1"] pub mod comp_cfgr1; #[doc = "COMP_CFGR2 (rw) register accessor: Comparator configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_cfgr2::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 [`comp_cfgr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`comp_cfgr2`] module"] pub type COMP_CFGR2 = crate::Reg<comp_cfgr2::COMP_CFGR2_SPEC>; #[doc = "Comparator configuration register 2"] pub mod comp_cfgr2;
use lang_result::*; use datatype::Datatype; use type_info::TypeInfo; //use std::mem::discriminant; use std::boxed::Box; use std::collections::HashMap; use include::read_file_into_ast; use s_expression::SExpression; use std::rc::Rc; use datatype::VariableStore; /// Used for finding the main function. const MAIN_FUNCTION_NAME: &'static str = "main"; /// Abstract Syntax Tree /// A recursive data structure that holds instances of other ASTs. /// It encodes the operations that are defined by the language's syntax. /// Evaluating an Ast will produce either a Datatype or a LangError #[derive(PartialEq, PartialOrd, Debug, Clone)] pub enum Ast { SExpr(SExpression), // Operators that store their operands ExpressionList(Vec<Ast>), // uesd for structuring execution of the AST. Conditional { condition: Box<Ast>, // Resolves to a literal->bool true_expr: Box<Ast>, // Will execute if the condition is true false_expr: Option<Box<Ast>>, // Will execute if the condition is false }, Literal(Datatype), // consider making the Literal another enum with supported default datatypes. Type(TypeInfo), // value in the datatype is useless, just use this to determine parameter type. ValueIdentifier(String), // gets the value mapped to a hashmap } impl Ast { /// Moves functions and structs to the top of the Ast's top level ExpressionList. /// This is done because regardless of where a function is declared, a datatype representing it /// will be encoded in the program map before it is used. /// If the AST doesn't have an Expression list, this will throw an error. pub fn hoist_functions_and_structs(&self) -> Ast { match *self { Ast::ExpressionList(ref expressions) => { // Capture struct declarations and hoist them to the top of the AST let mut struct_declarations: Vec<Ast> = vec![]; // Capture the functions as well and move them to the top of the evaluation list. let mut function_declarations: Vec<Ast> = vec![]; // Keep the ordering of everything else, likely constant assignments. let mut everything_else: Vec<Ast> = vec![]; for ast in expressions { match *ast { Ast::SExpr(ref sexpr) => { match *sexpr { SExpression::CreateStruct { .. } => { let ast = ast.clone(); struct_declarations.push(ast); } SExpression::DeclareFunction { .. } => { let ast = ast.clone(); function_declarations.push(ast); } _ => { //If it isn't a creation of a struct or function, put it in the everything else bucket. let ast = ast.clone(); everything_else.push(ast) } } } _ => { // If it isn't one of the desired expression types, put it in the everything else bucket. let ast = ast.clone(); everything_else.push(ast) } } } // Rearrange the order in which the top level AST node is evaluated let mut eval_list_with_hoists: Vec<Ast> = vec![]; eval_list_with_hoists.append(&mut struct_declarations); eval_list_with_hoists.append(&mut function_declarations); eval_list_with_hoists.append(&mut everything_else); Ast::ExpressionList(eval_list_with_hoists) } _ => panic!("Tried to hoist a non list of expressions."), } } /// Determines if a main function exists. /// This should be used to determine if calling the main function after evaluating the AST is necessary. pub fn main_fn_exists(&self) -> bool { match *self { Ast::ExpressionList(ref expressions) => { for ast in expressions { match *ast { Ast::SExpr(ref sexpr) => { if let SExpression::DeclareFunction { ref identifier, function_datatype: ref _function_datatype, } = *sexpr { if let Ast::ValueIdentifier(ref fn_name) = **identifier { if fn_name.as_str() == MAIN_FUNCTION_NAME { return true; } } } } _ => {} } } } _ => {} } false } /// Calls the main function. /// This should be used if a main function has been determined to exist. pub fn execute_main(&self, map: &mut VariableStore) -> LangResult { let executing_ast = Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier(MAIN_FUNCTION_NAME.to_string())), parameters: Box::new(Ast::ExpressionList(vec![])), }); executing_ast.evaluate(map) } /// Recurse down the AST, evaluating expressions where possible, turning them into Literals that contain Datatypes. /// If no errors are encountered, the whole AST should resolve to become a single Datatype, which is then returned. pub fn evaluate(&self, map: &mut VariableStore) -> LangResult { match *self { Ast::SExpr(ref sexpr) => { match *sexpr { SExpression::Add(ref lhs, ref rhs) => { lhs.evaluate(map)?.as_ref().clone() + rhs.evaluate(map)?.as_ref().clone() } SExpression::Subtract(ref lhs, ref rhs) => { lhs.evaluate(map)?.as_ref().clone() - rhs.evaluate(map)?.as_ref().clone() } SExpression::Multiply(ref lhs, ref rhs) => { lhs.evaluate(map)?.as_ref().clone() * rhs.evaluate(map)?.as_ref().clone() } SExpression::Divide(ref lhs, ref rhs) => { lhs.evaluate(map)?.as_ref().clone() / rhs.evaluate(map)?.as_ref().clone() } SExpression::Modulo(ref lhs, ref rhs) => { lhs.evaluate(map)?.as_ref().clone() % rhs.evaluate(map)?.as_ref().clone() } SExpression::Equals(ref lhs, ref rhs) => { if lhs.evaluate(map)? == rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::NotEquals(ref lhs, ref rhs) => { if lhs.evaluate(map)? != rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::GreaterThan(ref lhs, ref rhs) => { if lhs.evaluate(map)? > rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::LessThan(ref lhs, ref rhs) => { if lhs.evaluate(map)? < rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::GreaterThanOrEqual(ref lhs, ref rhs) => { if lhs.evaluate(map)? >= rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::LessThanOrEqual(ref lhs, ref rhs) => { if lhs.evaluate(map)? <= rhs.evaluate(map)? { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::LogicalAnd(ref lhs, ref rhs) => { let lhs_bool: bool = match *rhs.evaluate(map)? { Datatype::Bool(b) => b, _ => { return Err(LangError::TypeError { expected: (TypeInfo::Bool), found: (TypeInfo::from(lhs.evaluate(&mut map.clone())?.as_ref().clone())), }) } }; let rhs_bool: bool = match *rhs.evaluate(map)? { Datatype::Bool(b) => b, _ => { return Err(LangError::TypeError { expected: (TypeInfo::Bool), found: (TypeInfo::from(rhs.evaluate(&mut map.clone())?.as_ref().clone())), }) } }; if lhs_bool && rhs_bool { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::LogicalOr(ref lhs, ref rhs) => { let lhs_bool: bool = match *rhs.evaluate(map)? { Datatype::Bool(b) => b, _ => { return Err(LangError::TypeError { expected: (TypeInfo::Bool), found: (TypeInfo::from(lhs.evaluate(&mut map.clone())?.as_ref().clone())), }) } }; let rhs_bool: bool = match *rhs.evaluate(map)? { Datatype::Bool(b) => b, _ => { return Err(LangError::TypeError { expected: (TypeInfo::Bool), found: (TypeInfo::from(rhs.evaluate(&mut map.clone())?.as_ref().clone())), }) } }; if lhs_bool || rhs_bool { return Ok(Rc::new(Datatype::Bool(true))); } else { return Ok(Rc::new(Datatype::Bool(false))); } } SExpression::VariableDeclaration { identifier: ref lhs, ast: ref rhs, } | SExpression::ConstDeclaration { identifier: ref lhs, ast: ref rhs, } | SExpression::Assignment { identifier: ref lhs, ast: ref rhs, } | SExpression::TypeAssignment { identifier: ref lhs, type_info: ref rhs, } | SExpression::FieldAssignment { identifier: ref lhs, ast: ref rhs, } | SExpression::DeclareFunction { identifier: ref lhs, function_datatype: ref rhs, } => { if let Ast::ValueIdentifier(ref ident) = **lhs { let mut cloned_map = map.clone(); // since this is a clone, the required righthand expressions will be evaluated in their own 'stack', this modified hashmap will be cleaned up post assignment. let evaluated_right_hand_side = rhs.evaluate(&mut cloned_map)?; let cloned_evaluated_rhs = evaluated_right_hand_side.clone(); map.insert(ident.clone(), evaluated_right_hand_side); return Ok(cloned_evaluated_rhs); } else { Err(LangError::IdentifierDoesntExist) } } SExpression::Loop { ref conditional, ref body, } => { let mut evaluated_loop: Rc<Datatype> = Rc::new(Datatype::None); loop { let condition: &Datatype = &*conditional.evaluate(map)?; match *condition { Datatype::Bool(ref b) => { if *b { evaluated_loop = body.evaluate(map)?; // This doesn't clone the map, so it can mutate the "stack" of its context } else { break; } } _ => { return Err(LangError::ConditionalNotBoolean( TypeInfo::from(condition.clone()), )) } } } return Ok(evaluated_loop); // leave block } SExpression::AccessArray { ref identifier, ref index, } => { let datatype: &Datatype = &*identifier.evaluate(map)?; match *datatype { Datatype::Array { ref value, .. } => { let possible_index: Rc<Datatype> = index.evaluate(map)?; match *possible_index { Datatype::Number(resolved_index) => { if resolved_index >= 0 { match value.get(resolved_index as usize) { Some(indexed_rc_to_value) => Ok(indexed_rc_to_value.clone()), None => Err(LangError::OutOfBoundsArrayAccess), } } else { Err(LangError::NegativeIndex(resolved_index)) } } _ => Err(LangError::InvalidIndexType(possible_index.as_ref().clone())), } } _ => { return Err( LangError::ArrayAccessOnNonArray(TypeInfo::from(datatype.clone())), ) } } } SExpression::GetArrayLength(ref lhs) => { match *lhs.evaluate(map)? { Datatype::Array { ref value, type_: ref _type } => { Ok(Rc::new(Datatype::Number(value.len() as i32))) } _ => Err(LangError::TriedToGetLengthOfNonArray) } } SExpression::Range { ref start, ref end} => { let start_val: i32 = match *start.evaluate(map)? { Datatype::Number(num) => num, _ => return Err(LangError::RangeValueIsntNumber) }; let end_val: i32 = match *end.evaluate(map)? { Datatype::Number(num) => num, _ => return Err(LangError::RangeValueIsntNumber) }; let new_array = (start_val..end_val).map(|x| Rc::new(Datatype::Number(x)) ).collect(); // println!("creating array"); Ok(Rc::new(Datatype::Array { value: new_array, type_: TypeInfo::Number })) }, SExpression::StructDeclaration { identifier: ref lhs, struct_type_info: ref rhs, } => return declare_struct(lhs, rhs, map), SExpression::AccessStructField { identifier: ref lhs, field_identifier: ref rhs, } => return access_struct_field(lhs, rhs, map), SExpression::CreateStruct { identifier: ref lhs, struct_datatype: ref rhs, } => return create_struct(lhs, rhs, map), SExpression::ExecuteFn { ref identifier, ref parameters, } => return execute_function(identifier, parameters, map), SExpression::Print(ref expr) => { let datatype_to_print = expr.evaluate(map)?; if let Ast::ValueIdentifier(ref identifier) = **expr { if let Datatype::Struct { .. } = *datatype_to_print { print!("{}{}", identifier, datatype_to_print) } else { print!("{}", datatype_to_print); } } else { print!("{}", datatype_to_print); } Ok(datatype_to_print) } SExpression::Include(ref expr) => { match *expr.evaluate(map)? { Datatype::String(ref filename) => { let new_ast: Ast = read_file_into_ast(filename.clone())?; new_ast.evaluate(map) // move the new AST into the current AST } _ => Err(LangError::CouldNotReadFile { filename: "Not provided".to_string(), reason: "File name was not a string.".to_string(), }), } } SExpression::Negate(ref expr) => { match *expr.evaluate(map)? { Datatype::Number(num) => Ok(Rc::new(Datatype::Number(-num))), Datatype::Float(float) => Ok(Rc::new(Datatype::Float(-float))), _ => Err(LangError::NegateNotNumber) } } SExpression::Invert(ref expr) => { match *expr.evaluate(map)? { Datatype::Bool(bool) => Ok(Rc::new(Datatype::Bool(!bool))), _ => Err(LangError::InvertNonBoolean), } } SExpression::Increment(ref expr) => { match *expr.evaluate(map)? { Datatype::Number(number) => Ok(Rc::new(Datatype::Number(number + 1))), _ => Err(LangError::IncrementNonNumber), } } SExpression::Decrement(ref expr) => { match *expr.evaluate(map)? { Datatype::Number(number) => Ok(Rc::new(Datatype::Number(number - 1))), _ => Err(LangError::DecrementNonNumber), } } } } //Evaluate multiple expressions and return the result of the last one. Ast::ExpressionList(ref expressions) => { let mut val: Rc<Datatype> = Rc::new(Datatype::None); // TODO, consider making this return an error if the expressions vector is empty for e in expressions { val = e.evaluate(map)?; } Ok(val) // return the last evaluated expression; } Ast::Conditional { ref condition, ref true_expr, ref false_expr, } => { match *condition.evaluate(map)? { Datatype::Bool(bool) => { match bool { true => Ok(true_expr.evaluate(map)?), false => { match *false_expr { Some(ref e) => Ok(e.evaluate(map)?), _ => Ok(Rc::new(Datatype::None)), } } } } _ => Err(LangError::ConditionOnNonBoolean), } } Ast::Literal(ref datatype) => Ok(Rc::new(datatype.clone())), Ast::Type(ref datatype) => Err(LangError::TriedToEvaluateTypeInfo(datatype.clone())), // you shouldn't try to evaluate the datatype, Ast::ValueIdentifier(ref ident) => { match map.get(ident) { Some(value) => Ok(value.clone()), // This produces an Rc<> None => Err(LangError::VariableDoesntExist( format!("Variable `{}` hasn't been assigned yet", ident), )), } } } } } /// Resolve the first expression to a struct. /// Resolve the second expression to an identifier. /// Check if the second expression's identifier is in the struct's map. /// If it is, the get the value associated with that identifier and return it. fn access_struct_field( struct_identifier: &Ast, field_identifier: &Ast, map: &mut VariableStore, ) -> LangResult { // if struct_identifier produces a struct when evaluated if let Datatype::Struct { map: ref struct_map } = *struct_identifier.evaluate(map)? { if let Ast::ValueIdentifier(ref field_identifier) = *field_identifier { match struct_map.get(field_identifier) { Some(struct_field_datatype) => return Ok(Rc::new(struct_field_datatype.clone())), None => return Err(LangError::StructFieldDoesntExist), } } else { return Err(LangError::IdentifierDoesntExist); }/**/ } else { return Err(LangError::TriedToAccessNonStruct); } } /// Given an Identifier, /// and a vector of expressions tha contains only TypeAssignments. /// Create a new map that will represent the binding between the fields in the struct and the types they should have when instansiated. /// Insert into the map these field-type pairs. /// Create a new StructType from the new map and return it. fn declare_struct( identifier: &Ast, struct_type_assignments: &Ast, map: &mut VariableStore, ) -> LangResult { if let Ast::ValueIdentifier(ref struct_type_identifier) = *identifier { if let Ast::ExpressionList(ref expressions) = *struct_type_assignments { let mut struct_map: HashMap<String, TypeInfo> = HashMap::new(); for assignment_expr in expressions { if let &Ast::SExpr(ref sexpr) = assignment_expr { if let SExpression::TypeAssignment { identifier: ref field_identifier_expr, type_info: ref field_type_expr, } = *sexpr { if let Ast::ValueIdentifier(ref field_id) = **field_identifier_expr { if let Ast::Type(ref field_type) = **field_type_expr { struct_map.insert(field_id.clone(), field_type.clone()); } else { return Err(LangError::FieldTypeNotSupplied); } } else { return Err(LangError::FieldIdentifierNotSupplied); } } else { return Err(LangError::NonAssignmentInStructDeclaration); } } else { return Err(LangError::ExpectedExpression); } } let new_struct_type = TypeInfo::Struct { map: struct_map }; let retval = Rc::new(Datatype::StructType{ identifier: struct_type_identifier.clone(), type_information: new_struct_type}); map.insert(struct_type_identifier.clone(), retval.clone()); return Ok(retval); } else { return Err(LangError::StructBodyNotSupplied); } } else { Err(LangError::StructNameNotSupplied) } } /// Given an Ast that resolves to a struct type, /// and a vector of expressions that contains only FieldAssignments. /// Grab the map of identifiers to expected Types for fields. /// Create a new map of identifiers and Datatypes /// Get the expected type for each supplied assignment from the first map and check it against the type of data provided. /// Insert the data into the new map. /// Create a new struct instance from the new map, and return it. fn create_struct(expr1: &Ast, expr2: &Ast, map: &mut VariableStore) -> LangResult { // This expects the expr1 to be an Identifier that resolves to be a struct definition, or the struct definition itself. match *expr1.evaluate(map)? { Datatype::StructType { ref identifier, ref type_information } => { match *type_information { TypeInfo::Struct { map: ref struct_type_map } => { if let Ast::ExpressionList(ref assignment_expressions) = *expr2 { let mut new_struct_map: HashMap<String, Datatype> = HashMap::new(); for assignment_expression in assignment_expressions { if let Ast::SExpr(ref sexpr) = *assignment_expression { if let SExpression::FieldAssignment { identifier: ref assignment_expr1, ast: ref assignment_expr2, } = *sexpr { if let Ast::ValueIdentifier(ref field_identifier) = **assignment_expr1 { // Is the identifier specified in the AST exist in the struct type? check the struct_map let expected_type = match struct_type_map.get(field_identifier) { Some(struct_type) => struct_type, None => return Err(LangError::IdentifierDoesntExist), // todo find better error message }; let value_to_be_assigned: &Datatype = &*assignment_expr2.evaluate(map)?; // check if the value to be assigned matches the expected type let to_be_assigned_type: TypeInfo = TypeInfo::from(value_to_be_assigned.clone()); if expected_type == &to_be_assigned_type { // now add the value to the new struct's map new_struct_map.insert( field_identifier.clone(), value_to_be_assigned.clone(), ); } else { return Err(LangError::TypeError { expected: expected_type.clone(), found: to_be_assigned_type, }); } } else { return Err(LangError::ExpectedIdentifier); } } else { return Err(LangError::NonAssignmentInStructInit); } } else { return Err(LangError::NonAssignmentInStructInit); } } return Ok(Rc::new(Datatype::Struct { map: new_struct_map })); // Return the new struct. } else { return Err(LangError::StructBodyNotSupplied); // not entirely accurate } } _ => { return Err(LangError::ExpectedIdentifier); } } } _ => { return Err(LangError::ExpectedIdentifier); } } // if let Datatype::StructType{ identifier: String, type_information: TypeInfo::Struct { map: ref struct_type_map } } = *expr1.evaluate(map)? { // // It expects that the righthand side should be a series of expressions that assign values to fields (that have already been specified in the StructType) // // } else { // return Err(LangError::ExpectedIdentifier); // } } /// Given an identifier that resolves to a function (with expected parameters, the function body, and return type) and a set of input expressions that resolve to Datatypes, /// Resolve the input input expressions to Datatypes. /// Resolve the identifier to a function. /// Check if the input Datatypes have the same types as the supplied function. /// Map the input datatypes onto the identifiers expected in the function prototype. /// Evaluate the function with the substituted datatypes as input. /// Check if the return type is the same as was expected by the function. /// Return the return value. fn execute_function( identifier: &Ast, function: &Ast, map: &VariableStore, ) -> LangResult { let mut cloned_map: VariableStore = map.clone(); // clone the map, to create a temporary new "stack" for the life of the function //TODO instead of cloning the map, preprocess the ast to determine what values need to be copied from the map, and only copy them into a new map. //TODO This will cut down on the number of clone operations that are required, it may make programs with smaller amounts of allocated memory slower, but bigger stacked programs will be faster. // evaluate the parameters let evaluated_parameters: Vec<Rc<Datatype>> = match *function { Ast::ExpressionList(ref expressions) => { let mut evaluated_expressions: Vec<Rc<Datatype>> = vec![]; for e in expressions { match e.evaluate(&mut cloned_map) { Ok(dt) => evaluated_expressions.push(dt), Err(err) => return Err(err), } } evaluated_expressions } _ => return Err(LangError::FunctionParametersShouldBeExpressionList), }; // Take an existing function by (by grabbing the function using an identifier, which should resolve to a function) match *identifier.evaluate(&mut cloned_map)? { Datatype::Function { ref parameters, ref body, ref return_type, } => { match **parameters { // The parameters should be in the form: ExpressionList(expression_with_fn_assignment, expression_with_fn_assignment, ...) This way, functions should be able to support arbitrary numbers of parameters. Ast::ExpressionList(ref expressions) => { // zip the values of the evaluated parameters into the expected parameters for the function if evaluated_parameters.len() == expressions.len() { // Replace the right hand side of the expression (which should be an Ast::Type with a computed literal. let rhs_replaced_with_evaluated_parameters_results: Vec<Result<Ast, LangError>> = expressions .iter() .zip(evaluated_parameters) .map(|expressions_with_parameters: (&Ast, Rc<Datatype>)| { let (expression, datatype): (&Ast, Rc<Datatype>) = expressions_with_parameters; // assign out of tuple. if let Ast::SExpr( ref sexpr ) = *expression { if let SExpression::TypeAssignment { ref identifier, ref type_info } = *sexpr { let identifier: Box<Ast> = identifier.clone(); //TODO Deprecated run-time type-checking. Not sure If I need this because I have compile-time type checking in the works. // This section was causing 2 tests to fail, so I commented it out, obviously it is not adapted to the new struct system //do run-time type-checking, the supplied value should be of the same type as the specified value // let expected_type: &TypeInfo = match **type_info { // Ast::Type(ref datatype) => datatype, // Ast::ValueIdentifier(ref id) => { // match map.get(id) { // // get what should be a struct out of the stack // Some(datatype) => { // if let Datatype::StructType{ ref identifier, ref type_information } = **datatype { // type_information // The types that are related to this struct type. // } else { // return Err(LangError::ExpectedIdentifierToBeStructType { // found: id.clone(), // }); // } // } // None => return Err(LangError::IdentifierDoesntExist), // } // } // _ => return Err(LangError::ExpectedDataTypeInfo), // }; // // Convert the datatype into a TypeInfo and check it against the expected type // if expected_type != &TypeInfo::from(datatype.as_ref().clone()) { // return Err(LangError::TypeError { // expected: expected_type.clone(), // found: TypeInfo::from(datatype.as_ref().clone()), // }); // } // Return a new FunctionParameterAssignment Expression with the same identifier // pointing to a literal that was reduced from the expression passed in as a parameter. return Ok(Ast::SExpr(SExpression::FieldAssignment { identifier: identifier, ast: Box::new(Ast::Literal(datatype.as_ref().clone())) })) } else { return Err(LangError::InvalidFunctionPrototypeFormatting); } } else { return Err(LangError::InvalidFunctionPrototypeFormatting) } }).collect(); // These functions _should_ all be assignments, per the parser. // So after replacing the Types with Literals that have been derived from the expressions passed in, // they can be associated with the identifiers, and the identifiers can be used in the function body later. for rhs in rhs_replaced_with_evaluated_parameters_results { let rhs = rhs?; // return the error if present rhs.evaluate(&mut cloned_map)?; // create the assignment } } else { return Err(LangError::ParameterLengthMismatch); } // Evaluate the body of the function let output: Rc<Datatype> = body.evaluate(&mut cloned_map)?; // let expected_return_type: TypeInfo = return_type.clone(); let expected_return_type: TypeInfo = match *return_type { TypeInfo::StructType { ref identifier } => { match map.get(identifier) { Some(datatype) => { let datatype: &Datatype = &**datatype; if let &Datatype::StructType{ ref identifier, ref type_information } = datatype { type_information.clone() } else { return Err(LangError::ExpectedIdentifierToBeStructType { found: identifier.clone(), }); } } None => return Err(LangError::IdentifierDoesntExist), } } _ => return_type.clone() }; // { // Ast::Type(ref type_) => type_.clone(), // Ast::ValueIdentifier(ref id) => { // match map.get(id) { // Some(datatype) => { // let datatype: &Datatype = &**datatype; // if let &Datatype::StructType(ref struct_type_info) = datatype { // struct_type_info.clone() // } else { // return Err(LangError::ExpectedIdentifierToBeStructType { // found: id.clone(), // }); // } // } // None => return Err(LangError::IdentifierDoesntExist), // } // } // _ => return Err(LangError::ExpectedDataTypeInfo), // }; if TypeInfo::from(output.as_ref().clone()) == expected_return_type { return Ok(output); } else { return Err(LangError::ReturnTypeDoesNotMatchReturnValue); } } _ => return Err(LangError::ParserShouldHaveRejected), // The parser should have put the parameters in the form ExpressionList(expression_with_assignment, expression_with_assignment, ...) } } _ => Err(LangError::ExecuteNonFunction), } } #[cfg(test)] mod test { use super::*; #[test] fn plus_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Add( Box::new(Ast::Literal(Datatype::Number(3))), Box::new(Ast::Literal(Datatype::Number(6))), )); assert_eq!(Datatype::Number(9), *ast.evaluate(&mut map).unwrap()) } #[test] fn string_plus_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Add( Box::new( Ast::Literal(Datatype::String("Hello".to_string())), ), Box::new( Ast::Literal(Datatype::String(" World!".to_string())), ), )); assert_eq!( Datatype::String("Hello World!".to_string()), *ast.evaluate(&mut map).unwrap() ) } #[test] fn minus_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Subtract( Box::new(Ast::Literal(Datatype::Number(6))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Number(3), *ast.evaluate(&mut map).unwrap()) } #[test] fn minus_negative_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Subtract( Box::new(Ast::Literal(Datatype::Number(3))), Box::new(Ast::Literal(Datatype::Number(6))), )); assert_eq!(Datatype::Number(-3), *ast.evaluate(&mut map).unwrap()) } #[test] fn multiplication_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Multiply( Box::new(Ast::Literal(Datatype::Number(6))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Number(18), *ast.evaluate(&mut map).unwrap()) } #[test] fn division_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Divide( Box::new(Ast::Literal(Datatype::Number(6))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Number(2), *ast.evaluate(&mut map).unwrap()) } #[test] fn integer_division_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Divide( Box::new(Ast::Literal(Datatype::Number(5))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Number(1), *ast.evaluate(&mut map).unwrap()) } #[test] fn division_by_zero_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Divide( Box::new(Ast::Literal(Datatype::Number(5))), Box::new(Ast::Literal(Datatype::Number(0))), )); assert_eq!( LangError::DivideByZero, ast.evaluate(&mut map).err().unwrap() ) } #[test] fn modulo_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Modulo( Box::new(Ast::Literal(Datatype::Number(8))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Number(2), *ast.evaluate(&mut map).unwrap()) } #[test] fn equality_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::Equals( Box::new(Ast::Literal(Datatype::Number(3))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Bool(true), *ast.evaluate(&mut map).unwrap()) } #[test] fn greater_than_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::GreaterThan( Box::new(Ast::Literal(Datatype::Number(4))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Bool(true), *ast.evaluate(&mut map).unwrap()) } #[test] fn less_than_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::LessThan( Box::new(Ast::Literal(Datatype::Number(2))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Bool(true), *ast.evaluate(&mut map).unwrap()) } #[test] fn greater_than_or_equal_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::GreaterThanOrEqual( Box::new(Ast::Literal(Datatype::Number(4))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Bool(true), *ast.evaluate(&mut map).unwrap()); let mut map: VariableStore = VariableStore::new(); let equals_ast = Ast::SExpr(SExpression::GreaterThanOrEqual( Box::new(Ast::Literal(Datatype::Number(5))), Box::new(Ast::Literal(Datatype::Number(5))), )); assert_eq!(Datatype::Bool(true), *equals_ast.evaluate(&mut map).unwrap()); } #[test] fn less_than_or_equal_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::SExpr(SExpression::LessThanOrEqual( Box::new(Ast::Literal(Datatype::Number(2))), Box::new(Ast::Literal(Datatype::Number(3))), )); assert_eq!(Datatype::Bool(true), *ast.evaluate(&mut map).unwrap()); let mut map: VariableStore = VariableStore::new(); let equals_ast = Ast::SExpr(SExpression::LessThanOrEqual( Box::new(Ast::Literal(Datatype::Number(5))), Box::new(Ast::Literal(Datatype::Number(5))), )); assert_eq!(Datatype::Bool(true), *equals_ast.evaluate(&mut map).unwrap()); } /// Assign the value 6 to the identifier "a" /// Recall that identifier and add it to 5 #[test] fn assignment_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(6))), }), Ast::SExpr(SExpression::Add( Box::new(Ast::ValueIdentifier("a".to_string())), Box::new(Ast::Literal(Datatype::Number(5))), )), ]); assert_eq!(Datatype::Number(11), *ast.evaluate(&mut map).unwrap()) } /// Assign the value 6 to "a". /// Copy the value in "a" to "b". /// Recall the value in "b" and add it to 5. #[test] fn variable_copy_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(6))), }), Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("b".to_string())), ast: Box::new(Ast::ValueIdentifier("a".to_string())), }), Ast::SExpr(SExpression::Add( Box::new(Ast::ValueIdentifier("b".to_string())), Box::new(Ast::Literal(Datatype::Number(5))), )), ]); assert_eq!(Datatype::Number(11), *ast.evaluate(&mut map).unwrap()) } /// Assign the value 6 to a. /// Assign the value 3 to a. /// Recall the value in a and add it to 5, the value of a should be 3, equalling 8. #[test] fn reassignment_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(6))), }), Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(3))), }), Ast::SExpr(SExpression::Add( Box::new(Ast::ValueIdentifier("a".to_string())), Box::new(Ast::Literal(Datatype::Number(5))), )), ]); assert_eq!(Datatype::Number(8), *ast.evaluate(&mut map).unwrap()) } #[test] fn conditional_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::Conditional { condition: Box::new(Ast::Literal(Datatype::Bool(true))), true_expr: Box::new(Ast::Literal(Datatype::Number(7))), false_expr: None, }; assert_eq!(Datatype::Number(7), *ast.evaluate(&mut map).unwrap()) } #[test] fn conditional_with_else_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::Conditional { condition: Box::new(Ast::Literal(Datatype::Bool(false))), true_expr: Box::new(Ast::Literal(Datatype::Number(7))), false_expr: Some(Box::new(Ast::Literal(Datatype::Number(2)))), }; assert_eq!(Datatype::Number(2), *ast.evaluate(&mut map).unwrap()) } #[test] fn basic_function_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Function { parameters: Box::new(Ast::ExpressionList(vec![])), // empty parameters body: (Box::new(Ast::Literal(Datatype::Number(32)))), // just return a number return_type: TypeInfo::Number, // expect a number })), }), Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), // get the identifier for a parameters: Box::new(Ast::ExpressionList(vec![])), // provide the function parameters }), ]); assert_eq!(Datatype::Number(32), *ast.evaluate(&mut map).unwrap()) } #[test] fn function_with_parameter_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Function { parameters: Box::new(Ast::ExpressionList(vec![ Ast::SExpr(SExpression::TypeAssignment { identifier: Box::new(Ast::ValueIdentifier("b".to_string())), type_info: Box::new(Ast::Type(TypeInfo::Number)), }), ])), body: (Box::new(Ast::ValueIdentifier("b".to_string()))), // just return the number passed in. return_type: TypeInfo::Number, // expect a number to be returned })), }), Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), // get the identifier for a parameters: Box::new(Ast::ExpressionList(vec![Ast::Literal(Datatype::Number(7))])), }), ]); assert_eq!(Datatype::Number(7), *ast.evaluate(&mut map).unwrap()) } #[test] fn function_with_two_parameters_addition_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("add_two_numbers".to_string())), ast: Box::new(Ast::Literal(Datatype::Function { parameters: Box::new(Ast::ExpressionList(vec![ Ast::SExpr(SExpression::TypeAssignment { identifier: Box::new(Ast::ValueIdentifier("b".to_string())), // the value's name is b type_info: Box::new(Ast::Type(TypeInfo::Number)), // fn takes a number }), Ast::SExpr(SExpression::TypeAssignment { identifier: Box::new(Ast::ValueIdentifier("c".to_string())), // the value's name is b type_info: Box::new(Ast::Type(TypeInfo::Number)), // fn takes a number }), ])), body: (Box::new(Ast::SExpr(SExpression::Add( Box::new(Ast::ValueIdentifier("b".to_string())), Box::new(Ast::ValueIdentifier("c".to_string())), )))), // just return the number passed in. return_type: TypeInfo::Number, // expect a number to be returned })), }), Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier("add_two_numbers".to_string())), // get the identifier for a parameters: Box::new(Ast::ExpressionList(vec![ Ast::Literal(Datatype::Number(7)), Ast::Literal(Datatype::Number(5)), ])), }), ]); assert_eq!(Datatype::Number(12), *ast.evaluate(&mut map).unwrap()) } #[test] fn array_access_test() { let mut map: VariableStore = VariableStore::new(); let ast: Ast = Ast::SExpr(SExpression::AccessArray { identifier: Box::new(Ast::Literal(Datatype::Array { value: vec![ Rc::new(Datatype::Number(12)), Rc::new(Datatype::Number(14)), Rc::new(Datatype::Number(16)), ], type_: TypeInfo::Number, })), index: Box::new(Ast::Literal(Datatype::Number(0))), // get the first element }); assert_eq!(Datatype::Number(12), *ast.evaluate(&mut map).unwrap()) } #[test] fn array_incorrect_access_test() { let mut map: VariableStore = VariableStore::new(); let ast: Ast = Ast::SExpr(SExpression::AccessArray { identifier: Box::new(Ast::Literal(Datatype::Array { value: vec![ Rc::new(Datatype::Number(12)), Rc::new(Datatype::Number(14)), Rc::new(Datatype::Number(16)), ], type_: TypeInfo::Number, })), index: Box::new(Ast::Literal(Datatype::Number(3))), // Array size 3. 0, 1, 2 hold elements. Index 3 doesn't. }); assert_eq!( LangError::OutOfBoundsArrayAccess, ast.evaluate(&mut map).unwrap_err() ) } #[test] fn struct_declaration_test() { let mut map: VariableStore = VariableStore::new(); let ast: Ast = Ast::SExpr(SExpression::StructDeclaration { identifier: Box::new(Ast::ValueIdentifier("MyStruct".to_string())), struct_type_info: Box::new(Ast::ExpressionList(vec![ Ast::SExpr(SExpression::TypeAssignment { identifier: Box::new(Ast::ValueIdentifier("Field1".to_string())), type_info: Box::new(Ast::Type(TypeInfo::Number)), }), ])), }); let _ = ast.evaluate(&mut map); // execute the ast to add the struct entry to the global stack map. let mut expected_map = VariableStore::new(); let mut inner_struct_hash_map = HashMap::new(); inner_struct_hash_map.insert("Field1".to_string(), TypeInfo::Number); expected_map.insert( "MyStruct".to_string(), Rc::new(Datatype::StructType{ identifier: String::from("MyStruct"), type_information: TypeInfo::Struct { map: inner_struct_hash_map }} ), ); assert_eq!(expected_map, map) } #[test] fn struct_creation_test() { let mut map: VariableStore = VariableStore::new(); let declaration_ast: Ast = Ast::SExpr(SExpression::StructDeclaration { identifier: Box::new(Ast::ValueIdentifier("MyStruct".to_string())), struct_type_info: Box::new(Ast::ExpressionList(vec![ Ast::SExpr(SExpression::TypeAssignment { identifier: Box::new(Ast::ValueIdentifier("Field1".to_string())), type_info: Box::new(Ast::Type(TypeInfo::Number)), }), ])), }); let _ = declaration_ast.evaluate(&mut map); // execute the ast to add the struct entry to the global stack map. let creation_ast: Ast = Ast::SExpr(SExpression::CreateStruct { identifier: Box::new(Ast::ValueIdentifier("MyStruct".to_string())), struct_datatype: Box::new(Ast::ExpressionList(vec![ Ast::SExpr(SExpression::FieldAssignment { identifier: Box::new(Ast::ValueIdentifier("Field1".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(8))), // assign 8 to field Field1 }), ])), }); let struct_instance = &*creation_ast.evaluate(&mut map).unwrap(); let mut inner_struct_hash_map = HashMap::new(); inner_struct_hash_map.insert("Field1".to_string(), Datatype::Number(8)); assert_eq!( &Datatype::Struct { map: inner_struct_hash_map }, struct_instance ) } #[test] fn function_hoisting_test() { let mut map: VariableStore = VariableStore::new(); let ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(6))), }), Ast::SExpr(SExpression::DeclareFunction { identifier: Box::new(Ast::ValueIdentifier("fn".to_string())), function_datatype: Box::new(Ast::Literal(Datatype::Function { parameters: Box::new(Ast::ExpressionList(vec![])), // empty parameters body: (Box::new(Ast::Literal(Datatype::Number(32)))), // just return a number return_type: TypeInfo::Number, // expect a number })), }), Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier("fn".to_string())), // get the identifier for a parameters: Box::new(Ast::ExpressionList(vec![])), // provide the function parameters }), ]); let hoisted_ast: Ast = ast.hoist_functions_and_structs(); let expected_hoisted_ast: Ast = Ast::ExpressionList(vec![ Ast::SExpr(SExpression::DeclareFunction { identifier: Box::new(Ast::ValueIdentifier("fn".to_string())), function_datatype: Box::new(Ast::Literal(Datatype::Function { parameters: Box::new(Ast::ExpressionList(vec![])), // empty parameters body: (Box::new(Ast::Literal(Datatype::Number(32)))), // just return a number return_type: TypeInfo::Number, // expect a number })), }), Ast::SExpr(SExpression::Assignment { identifier: Box::new(Ast::ValueIdentifier("a".to_string())), ast: Box::new(Ast::Literal(Datatype::Number(6))), }), Ast::SExpr(SExpression::ExecuteFn { identifier: Box::new(Ast::ValueIdentifier("fn".to_string())), // get the identifier for a parameters: Box::new(Ast::ExpressionList(vec![])), // provide the function parameters }), ]); assert_eq!(hoisted_ast, expected_hoisted_ast); assert_eq!( Datatype::Number(32), *hoisted_ast.evaluate(&mut map).unwrap() ); } }
extern crate B; extern crate C; extern crate animal; use B::Balloon; use C::Cat; fn main() { let balloon = Balloon { b: 90}; // println!("Hello, world! ({})", balloon.b); // println!("B: {}", B::foo()); // println!("C: {}", C::foo()); // println!("B dog: {}", B::get_dog().speak()); // println!("C dog: {}", C::get_dog().speak()); // B::say_hi(C::get_dog()); // C::say_hi(B::get_dog()); B::bar(C::get_animal()); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use std::str::FromStr; use std::time::Duration; use common_base::Runtime; use common_tracing::tracing; use lazy_static::lazy_static; pub const CONF_STORE_RT_TH_NUM: &str = "STORE_RT_TH_NUM"; pub const CONF_STORE_SYNC_CALL_TIMEOUT_SEC: &str = "STORE_SYNC_CALL_TIMEOUT_SEC"; lazy_static! { pub static ref STORE_RUNTIME: common_base::Runtime = build_rt(); pub static ref STORE_SYNC_CALL_TIMEOUT: Option<Duration> = get_sync_call_timeout(); } fn build_rt() -> Runtime { let conf_th_num = std::env::var(CONF_STORE_RT_TH_NUM).ok(); let th_num = if let Some(num_str) = conf_th_num { let num = usize::from_str(&num_str); match num { Ok(v) => Some(v), Err(pe) => { tracing::info!( "invalid configuration of store runtime thread number [{}], ignored. {}", &num_str, pe ); None } } } else { None }; if let Some(num) = th_num { tracing::info!("bring up store api runtime with {} thread", num); common_base::Runtime::with_worker_threads(num) .expect("FATAL, initialize store runtime failure") } else { tracing::info!("bring up store api runtime with default worker threads"); common_base::Runtime::with_default_worker_threads() .expect("FATAL, initialize store runtime failure") } } fn get_sync_call_timeout() -> Option<Duration> { let conf_to = std::env::var(CONF_STORE_SYNC_CALL_TIMEOUT_SEC).ok(); let th_num = if let Some(timeout_str) = conf_to { let num = u64::from_str(&timeout_str); match num { Ok(v) => Some(v), Err(pe) => { tracing::info!( "invalid configuration of store rpc timeout (in sec) [{}], ignored. {}", &timeout_str, pe ); None } } } else { None }; if let Some(num) = th_num { tracing::info!("store sync rpc timeout set to {} sec.", num); Some(Duration::from_secs(num)) } else { None } }
pub fn main() { let mut multiples: Vec<u32> = Vec::new(); let mut sum: u32 = 0; for num in 1..1000 { if num % 3 == 0 || num % 5 == 0 { multiples.push(num); sum += num; } } //println!("{:?}", multiples); println!("Sum of the multiples of 3 and 5 in the range 1 to 1000 = {}", sum); }
/* * Copyright Stalwart Labs Ltd. See the COPYING * file at the top-level directory of this distribution. * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. */ use crate::{core::get::GetObject, Get, Set}; use super::{ Email, EmailAddress, EmailAddressGroup, EmailBodyPart, EmailBodyValue, EmailHeader, GetArguments, Header, HeaderValue, }; impl Email<Get> { pub fn id(&self) -> Option<&str> { self.id.as_deref() } pub fn take_id(&mut self) -> String { self.id.take().unwrap_or_default() } pub fn blob_id(&self) -> Option<&str> { self.blob_id.as_deref() } pub fn take_blob_id(&mut self) -> String { self.blob_id.take().unwrap_or_default() } pub fn thread_id(&self) -> Option<&str> { self.thread_id.as_deref() } pub fn take_thread_id(&mut self) -> Option<String> { self.thread_id.take() } pub fn mailbox_ids(&self) -> Vec<&str> { self.mailbox_ids .as_ref() .map(|m| { m.iter() .filter(|(_, v)| **v) .map(|(k, _)| k.as_str()) .collect() }) .unwrap_or_default() } pub fn keywords(&self) -> Vec<&str> { self.keywords .as_ref() .map(|k| { k.iter() .filter(|(_, v)| **v) .map(|(k, _)| k.as_str()) .collect() }) .unwrap_or_default() } pub fn size(&self) -> usize { self.size.unwrap_or(0) } pub fn received_at(&self) -> Option<i64> { self.received_at.as_ref().map(|r| r.timestamp()) } pub fn message_id(&self) -> Option<&[String]> { self.message_id.as_deref() } pub fn in_reply_to(&self) -> Option<&[String]> { self.in_reply_to.as_deref() } pub fn references(&self) -> Option<&[String]> { self.references.as_deref() } pub fn sender(&self) -> Option<&[EmailAddress]> { self.sender.as_deref() } pub fn take_sender(&mut self) -> Option<Vec<EmailAddress>> { self.sender.take() } pub fn from(&self) -> Option<&[EmailAddress]> { self.from.as_deref() } pub fn take_from(&mut self) -> Option<Vec<EmailAddress>> { self.from.take() } pub fn reply_to(&self) -> Option<&[EmailAddress]> { self.reply_to.as_deref() } pub fn take_reply_to(&mut self) -> Option<Vec<EmailAddress>> { self.reply_to.take() } pub fn to(&self) -> Option<&[EmailAddress]> { self.to.as_deref() } pub fn take_to(&mut self) -> Option<Vec<EmailAddress>> { self.to.take() } pub fn cc(&self) -> Option<&[EmailAddress]> { self.cc.as_deref() } pub fn take_cc(&mut self) -> Option<Vec<EmailAddress>> { self.cc.take() } pub fn bcc(&self) -> Option<&[EmailAddress]> { self.bcc.as_deref() } pub fn take_bcc(&mut self) -> Option<Vec<EmailAddress>> { self.bcc.take() } pub fn subject(&self) -> Option<&str> { self.subject.as_deref() } pub fn take_subject(&mut self) -> Option<String> { self.subject.take() } pub fn sent_at(&self) -> Option<i64> { self.sent_at.as_ref().map(|v| v.timestamp()) } pub fn body_structure(&self) -> Option<&EmailBodyPart> { self.body_structure.as_deref() } pub fn body_value(&self, id: &str) -> Option<&EmailBodyValue> { self.body_values.as_ref().and_then(|v| v.get(id)) } pub fn text_body(&self) -> Option<&[EmailBodyPart]> { self.text_body.as_deref() } pub fn html_body(&self) -> Option<&[EmailBodyPart]> { self.html_body.as_deref() } pub fn attachments(&self) -> Option<&[EmailBodyPart]> { self.attachments.as_deref() } pub fn has_attachment(&self) -> bool { *self.has_attachment.as_ref().unwrap_or(&false) } pub fn header(&self, id: &Header) -> Option<&HeaderValue> { self.headers.get(id).and_then(|v| v.as_ref()) } pub fn has_header(&self, id: &Header) -> bool { self.headers.contains_key(id) } pub fn preview(&self) -> Option<&str> { self.preview.as_deref() } pub fn take_preview(&mut self) -> Option<String> { self.preview.take() } #[cfg(feature = "debug")] pub fn into_test(self) -> super::TestEmail { self.into() } } impl EmailBodyPart<Get> { pub fn part_id(&self) -> Option<&str> { self.part_id.as_deref() } pub fn blob_id(&self) -> Option<&str> { self.blob_id.as_deref() } pub fn size(&self) -> usize { *self.size.as_ref().unwrap_or(&0) } pub fn headers(&self) -> Option<&[EmailHeader]> { self.headers.as_deref() } pub fn header(&self, id: &Header) -> Option<&HeaderValue> { self.header.as_ref().and_then(|v| v.get(id)) } pub fn name(&self) -> Option<&str> { self.name.as_deref() } pub fn charset(&self) -> Option<&str> { self.charset.as_deref() } pub fn content_type(&self) -> Option<&str> { self.type_.as_deref() } pub fn content_disposition(&self) -> Option<&str> { self.disposition.as_deref() } pub fn content_id(&self) -> Option<&str> { self.cid.as_deref() } pub fn content_language(&self) -> Option<&[String]> { self.language.as_deref() } pub fn content_location(&self) -> Option<&str> { self.location.as_deref() } pub fn sub_parts(&self) -> Option<&[EmailBodyPart]> { self.sub_parts.as_deref() } } impl EmailBodyValue<Get> { pub fn value(&self) -> &str { self.value.as_str() } pub fn is_encoding_problem(&self) -> bool { self.is_encoding_problem.unwrap_or(false) } pub fn is_truncated(&self) -> bool { self.is_truncated.unwrap_or(false) } } impl EmailAddress<Get> { pub fn name(&self) -> Option<&str> { self.name.as_deref() } pub fn email(&self) -> &str { self.email.as_str() } pub fn unwrap(self) -> (String, Option<String>) { (self.email, self.name) } } impl EmailAddressGroup<Get> { pub fn name(&self) -> Option<&str> { self.name.as_deref() } pub fn addresses(&self) -> &[EmailAddress] { self.addresses.as_ref() } } impl EmailHeader<Get> { pub fn name(&self) -> &str { self.name.as_str() } pub fn value(&self) -> &str { self.value.as_str() } } impl GetObject for Email<Set> { type GetArguments = GetArguments; } impl GetObject for Email<Get> { type GetArguments = GetArguments; }
pub mod login; pub mod register; pub mod logout; pub mod reset_password; pub mod user; pub mod topic; pub mod topic_list; pub mod comment; pub mod message; pub mod error; pub mod simple_render; pub mod upload; pub mod rss;
#[doc = "Register `RCC_ASSCKSELR` reader"] pub type R = crate::R<RCC_ASSCKSELR_SPEC>; #[doc = "Register `RCC_ASSCKSELR` writer"] pub type W = crate::W<RCC_ASSCKSELR_SPEC>; #[doc = "Field `AXISSRC` reader - AXISSRC"] pub type AXISSRC_R = crate::FieldReader; #[doc = "Field `AXISSRC` writer - AXISSRC"] pub type AXISSRC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `AXISSRCRDY` reader - AXISSRCRDY"] pub type AXISSRCRDY_R = crate::BitReader; impl R { #[doc = "Bits 0:2 - AXISSRC"] #[inline(always)] pub fn axissrc(&self) -> AXISSRC_R { AXISSRC_R::new((self.bits & 7) as u8) } #[doc = "Bit 31 - AXISSRCRDY"] #[inline(always)] pub fn axissrcrdy(&self) -> AXISSRCRDY_R { AXISSRCRDY_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bits 0:2 - AXISSRC"] #[inline(always)] #[must_use] pub fn axissrc(&mut self) -> AXISSRC_W<RCC_ASSCKSELR_SPEC, 0> { AXISSRC_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to select the clock source for the AXI sub-system. If TZEN = , this register can only be modified in secure mode. Write access to this register is not allowed during the clock restore sequence. See Section: The clock restore sequence description for details.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_assckselr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_assckselr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_ASSCKSELR_SPEC; impl crate::RegisterSpec for RCC_ASSCKSELR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_assckselr::R`](R) reader structure"] impl crate::Readable for RCC_ASSCKSELR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_assckselr::W`](W) writer structure"] impl crate::Writable for RCC_ASSCKSELR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_ASSCKSELR to value 0x8000_0000"] impl crate::Resettable for RCC_ASSCKSELR_SPEC { const RESET_VALUE: Self::Ux = 0x8000_0000; }
use std::fs::File; use std::io::{BufRead, BufReader}; pub fn exercise() { let input = File::open("./data/day1.data").unwrap(); let reader = BufReader::new(input); let expenses: Vec<i64> = reader.lines() .map(|l| l.unwrap().parse::<i64>().unwrap()) .collect(); expenses.iter().for_each(|e| { expenses.iter().for_each(|o| { if e != o { //let sum = compute_expense(*e, *o, false); expenses.iter().for_each(|x| { if x != e && x != o { compute_expense(*e, *o, *x, true); } }); } }); }); } fn compute_expense(e1: i64, e2: i64, e3:i64, print_output: bool) -> i64 { let sum = e1 + e2 + e3; let product = e1 * e2 * e3; if sum == 2020 && print_output { println!("Sum of {:?} and {:?} is 2020, product is {:?}.", e1, e2, product); } return sum; }
fn main() { // 0 1 2 -> macro //let mut vector = vec![1, 2, 3]; // estructura let mut vector: Vec<i32> = Vec::new(); //incrementar los elementos vector.push(1); vector.push(2); vector.push(3); vector.push(4); vector.push(5); //Agregar elemento vector.insert(0, -1); vector.insert(1, 0); //eliminar elemento vector.remove(vector.len() -1); vector[0] = -10; let primer_vector = vector[0]; //let ultimo_vector = vector[ vector.len() -1]; let ultimo_vector = vector.pop().unwrap(); // option println!("El valor del vector es: {:?}", vector); println!("El valor es: {}", primer_vector); println!("El valor es: {}", ultimo_vector); }
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::net::ip; use std::mem; use std::rt::task::BlockedTask; use std::sync::Arc; use std::time::Duration; use libc; use homing::{HomingIO, HomeHandle}; use access::Access; use timeout::AccessTimeout; use {raw, uvll, UvResult, UvError, EventLoop}; use raw::{Request, Handle}; pub struct Udp { data: Arc<Data>, // See tcp for what these fields are read_access: AccessTimeout<()>, write_access: Access<()>, } struct Data { handle: raw::Udp, home: HomeHandle, } struct UdpRecvCtx { task: Option<BlockedTask>, buf: Option<uvll::uv_buf_t>, result: Option<(libc::ssize_t, Option<ip::SocketAddr>)>, } struct UdpSendCtx { result: libc::c_int, task: Option<BlockedTask>, } impl Udp { pub fn bind(addr: ip::SocketAddr) -> UvResult<Udp> { Udp::bind_on(&mut *try!(EventLoop::borrow()), addr) } pub fn bind_on(eloop: &mut EventLoop, addr: ip::SocketAddr) -> UvResult<Udp> { let mut udp = Data { home: eloop.make_handle(), handle: unsafe { try!(raw::Udp::new(&eloop.uv_loop())) } }; try!(udp.handle.bind(addr)); Ok(Udp { data: Arc::new(udp), read_access: AccessTimeout::new(()), write_access: Access::new(()), }) } pub fn socket_name(&mut self) -> UvResult<ip::SocketAddr> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.getsockname() } pub fn recv_from(&mut self, buf: &mut [u8]) -> UvResult<(uint, ip::SocketAddr)> { let m = self.data.fire_homing_missile(); let _guard = try!(self.read_access.grant(m)); let mut handle = self.data.handle; let mut cx = UdpRecvCtx { task: None, buf: Some(raw::slice_to_uv_buf(buf)), result: None, }; try!(handle.recv_start(alloc_cb, recv_cb)); handle.set_data(&mut cx as *mut _ as *mut _); ::block(handle.uv_loop(), |task| { cx.task = Some(task); }); handle.set_data(0 as *mut _); return match cx.result.take().unwrap() { (n, _) if n < 0 => Err(UvError(n as libc::c_int)), (n, addr) => Ok((n as uint, addr.unwrap())) }; extern fn alloc_cb(handle: *mut uvll::uv_handle_t, _suggested_size: libc::size_t, buf: *mut uvll::uv_buf_t) { unsafe { let handle = handle as *mut uvll::uv_udp_t; let raw: raw::Udp = Handle::from_raw(handle); let cx: &mut UdpRecvCtx = mem::transmute(raw.get_data()); *buf = cx.buf.take().expect("recv alloc_cb called more than once") } } extern fn recv_cb(handle: *mut uvll::uv_udp_t, nread: libc::ssize_t, buf: *const uvll::uv_buf_t, addr: *const libc::sockaddr, _flags: libc::c_uint) { assert!(nread != uvll::ECANCELED as libc::ssize_t); unsafe { let mut raw: raw::Udp = Handle::from_raw(handle); let cx: &mut UdpRecvCtx = mem::transmute(raw.get_data()); // When there's no data to read the recv callback can be a // no-op. This can happen if read returns EAGAIN/EWOULDBLOCK. // By ignoring this we just drop back to kqueue and wait for the // next callback. if nread == 0 { cx.buf = Some(*buf); return } raw.recv_stop().unwrap(); let addr = if addr.is_null() { None } else { let len = mem::size_of::<libc::sockaddr_storage>(); Some(raw::sockaddr_to_addr(mem::transmute(addr), len)) }; cx.result = Some((nread, addr)); ::wakeup(&mut cx.task); } } } pub fn send_to(&mut self, buf: &[u8], dst: ip::SocketAddr) -> UvResult<()> { let m = self.data.fire_homing_missile(); let _guard = self.write_access.grant(0, m); let mut cx = UdpSendCtx { result: uvll::ECANCELED, task: None, }; unsafe { let mut req: raw::UdpSend = Request::alloc(); req.set_data(&mut cx as *mut _ as *mut _); match req.send(self.data.handle, buf, dst, send_cb) { Ok(()) => {} Err(e) => { req.free(); return Err(e) } } ::block(self.data.handle.uv_loop(), |task| { cx.task = Some(task); }); } return if cx.result < 0 {Err(UvError(cx.result))} else {Ok(())}; extern fn send_cb(req: *mut uvll::uv_udp_send_t, status: libc::c_int) { unsafe { let mut req: raw::UdpSend = Request::from_raw(req); let cx: &mut UdpSendCtx = mem::transmute(req.get_data()); cx.result = status; ::wakeup(&mut cx.task); req.free(); } } } pub fn join_multicast(&mut self, multi: ip::IpAddr) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_membership(multi, uvll::UV_JOIN_GROUP) } pub fn leave_multicast(&mut self, multi: ip::IpAddr) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_membership(multi, uvll::UV_LEAVE_GROUP) } pub fn multicast_locally(&mut self, enable: bool) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_multicast_loop(enable) } pub fn multicast_time_to_live(&mut self, ttl: int) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_multicast_ttl(ttl) } pub fn time_to_live(&mut self, ttl: int) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_ttl(ttl) } pub fn broadcast(&mut self, enable: bool) -> UvResult<()> { let _m = self.data.fire_homing_missile(); let mut handle = self.data.handle; handle.set_broadcast(enable) } pub fn set_read_timeout(&mut self, dur: Option<Duration>) { let _m = self.data.fire_homing_missile(); self.read_access.set_timeout(dur, self.data.handle.uv_loop(), cancel_read, self.data.handle.raw() as uint); fn cancel_read(stream: uint) -> Option<BlockedTask> { // This method is quite similar to StreamWatcher::cancel_read, see // there for more information unsafe { let handle = stream as *mut uvll::uv_udp_t; let mut raw: raw::Udp = Handle::from_raw(handle); raw.recv_stop().unwrap(); if raw.get_data().is_null() { return None } let cx: &mut UdpRecvCtx = mem::transmute(raw.get_data()); cx.result = Some((uvll::ECANCELED as libc::ssize_t, None)); cx.task.take() } } } } impl Clone for Udp { fn clone(&self) -> Udp { Udp { read_access: self.read_access.clone(), write_access: self.write_access.clone(), data: self.data.clone(), } } } impl HomingIO for Data { fn home(&self) -> &HomeHandle { &self.home } } impl Drop for Data { fn drop(&mut self) { let _m = self.fire_homing_missile(); unsafe { self.handle.close_and_free(); } } }
#![deny(unsafe_code)] #![warn( nonstandard_style, rust_2018_idioms, future_incompatible, missing_debug_implementations )] //! Generic types for path-based routing. use std::collections::HashMap; /// A generic path-based routing table, terminating with resources `R`. // // The implementation uses a very simple-minded tree structure. `PathTable` is a node, // with branches corresponding to the next path segment. For concrete segments, the // `next` table gives the available string matches. For the (at most one) wildcard match, // the `wildcard` field contains the branch. // // If the current path itself is a route, the `accept` field says what resource it contains. #[derive(Clone)] pub struct PathTable<R> { accept: Option<R>, next: HashMap<String, PathTable<R>>, wildcard: Option<Box<Wildcard<R>>>, } #[derive(Copy, Clone, PartialEq)] enum WildcardKind { Segment, CatchAll, } impl std::fmt::Display for WildcardKind { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { WildcardKind::Segment => Ok(()), WildcardKind::CatchAll => write!(fmt, "*"), } } } #[derive(Clone)] struct Wildcard<R> { name: String, count_mod: WildcardKind, table: PathTable<R>, } /// For a successful match, this structure says how any wildcard segments were matched. #[derive(Debug)] pub struct RouteMatch<'a> { /// Wildcard matches in the order they appeared in the path. pub vec: Vec<&'a str>, /// Named wildcard matches, indexed by name. pub map: HashMap<&'a str, &'a str>, } impl<R> std::fmt::Debug for PathTable<R> { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { struct Children<'a, R>(&'a HashMap<String, PathTable<R>>, Option<&'a Wildcard<R>>); impl<'a, R> std::fmt::Debug for Children<'a, R> { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut dbg = fmt.debug_map(); dbg.entries(self.0.iter()); if let Some(wildcard) = self.1 { dbg.entry( &format_args!("{{{}}}{}", wildcard.name, wildcard.count_mod), &wildcard.table, ); } dbg.finish() } } fmt.debug_struct("PathTable") .field( "resource", &format_args!( "{}", if self.accept.is_some() { "Some" } else { "None" } ), ) .field( "children", &Children(&self.next, self.wildcard.as_ref().map(|x| &**x)), ) .finish() } } impl<R> Default for PathTable<R> { fn default() -> Self { PathTable::new() } } impl<R> PathTable<R> { /// Create an empty routing table. pub fn new() -> PathTable<R> { PathTable { accept: None, next: HashMap::new(), wildcard: None, } } /// Get the resource of current path. pub fn resource(&self) -> Option<&R> { self.accept.as_ref() } /// Retrieve a mutable reference of the resource. pub fn resource_mut(&mut self) -> &mut Option<R> { &mut self.accept } /// Return an iterator of all resources. pub fn iter(&self) -> Resources<'_, R> { Resources { stack: vec![self] } } /// Return a mutable iterator of all resources. pub fn iter_mut(&mut self) -> ResourcesMut<'_, R> { ResourcesMut { stack: vec![self] } } /// Determine which resource, if any, the concrete `path` should be routed to. pub fn route<'a>(&'a self, path: &'a str) -> Option<(&'a R, RouteMatch<'a>)> { let mut table = self; let mut params = Vec::new(); let mut param_map = HashMap::new(); // Find all segments with their indices. let segment_iter = path .match_indices('/') .chain(std::iter::once((path.len(), ""))) .scan(0usize, |prev_idx, (idx, _)| { let starts_at = *prev_idx; let segment = &path[starts_at..idx]; *prev_idx = idx + 1; Some((starts_at, segment)) }); for (starts_at, mut segment) in segment_iter { if segment.is_empty() { continue; } if let Some(next_table) = table.next.get(segment) { table = next_table; } else if let Some(wildcard) = &table.wildcard { let last = if wildcard.count_mod == WildcardKind::CatchAll { segment = &path[starts_at..]; true } else { false }; params.push(segment); if !wildcard.name.is_empty() { param_map.insert(&*wildcard.name, segment); } table = &wildcard.table; if last { break; } } else { return None; } } if table.accept.is_none() { if let Some(wildcard) = &table.wildcard { if wildcard.count_mod == WildcardKind::CatchAll { params.push(""); if !wildcard.name.is_empty() { param_map.insert(&*wildcard.name, ""); } table = &wildcard.table; } } } table.accept.as_ref().map(|res| { ( res, RouteMatch { vec: params, map: param_map, }, ) }) } fn wildcard_mut(&mut self) -> Option<&mut Wildcard<R>> { self.wildcard.as_mut().map(|b| &mut **b) } /// Return the table of the given routing path (which may contain wildcards). /// /// If it doesn't already exist, this will make a new one. pub fn setup_table(&mut self, path: &str) -> &mut PathTable<R> { let mut table = self; let mut forbid_next = false; for segment in path.split('/') { if segment.is_empty() { continue; } if forbid_next { panic!("No segments are allowed after wildcard with `*` modifier"); } let wildcard_opt = if segment.starts_with('{') { if segment.ends_with('}') { Some((&segment[1..segment.len() - 1], WildcardKind::Segment)) } else if segment.ends_with("}*") { Some((&segment[1..segment.len() - 2], WildcardKind::CatchAll)) } else { None } } else if segment == "*" { Some(("", WildcardKind::CatchAll)) } else { None }; if let Some((name, count_mod)) = wildcard_opt { if count_mod != WildcardKind::Segment { forbid_next = true; } if table.wildcard.is_none() { table.wildcard = Some(Box::new(Wildcard { name: name.to_string(), count_mod, table: PathTable::new(), })); } match table.wildcard_mut().unwrap() { Wildcard { name: n, count_mod: c, .. } if name != n || count_mod != *c => { panic!( "Route {} segment `{{{}}}{}` conflicts with existing wildcard segment `{{{}}}{}`", path, name, count_mod, n, c ); } Wildcard { table: t, .. } => { table = t; } } } else { table = table .next .entry(segment.to_string()) .or_insert_with(PathTable::new); } } table } } impl<R: Default> PathTable<R> { /// Add or access a new resource at the given routing path (which may contain wildcards). pub fn setup(&mut self, path: &str) -> &mut R { let table = self.setup_table(path); if table.accept.is_none() { table.accept = Some(R::default()) } table.accept.as_mut().unwrap() } } /// An iterator over the resources of a `PathTable`. #[derive(Debug)] pub struct Resources<'a, R> { stack: Vec<&'a PathTable<R>>, } impl<'a, R> Iterator for Resources<'a, R> { type Item = &'a R; fn next(&mut self) -> Option<&'a R> { while let Some(table) = self.stack.pop() { self.stack.extend(table.next.values()); if let Some(wildcard) = table.wildcard.as_ref() { self.stack.push(&wildcard.table); } if let Some(res) = &table.accept { return Some(res); } } None } } /// A mutable iterator over the resources of a `PathTable`. #[derive(Debug)] pub struct ResourcesMut<'a, R> { stack: Vec<&'a mut PathTable<R>>, } impl<'a, R> Iterator for ResourcesMut<'a, R> { type Item = &'a mut R; fn next(&mut self) -> Option<&'a mut R> { while let Some(table) = self.stack.pop() { self.stack.extend(table.next.values_mut()); if let Some(wildcard) = table.wildcard.as_mut() { self.stack.push(&mut wildcard.table); } if let Some(res) = &mut table.accept { return Some(res); } } None } } #[cfg(test)] mod tests { use std::collections::HashSet; use super::*; #[test] fn empty_route_no_matches() { let table: PathTable<()> = PathTable::new(); assert!(table.route("").is_none()); assert!(table.route("/").is_none()); assert!(table.route("//").is_none()); assert!(table.route("foo").is_none()); assert!(table.route("foo/bar").is_none()); } #[test] fn root_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("/"); assert!(table.route("").is_some()); assert!(table.route("/").is_some()); assert!(table.route("//").is_some()); assert!(table.route("foo").is_none()); assert!(table.route("foo/bar").is_none()); } #[test] fn one_fixed_segment_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo"); assert!(table.route("").is_none()); assert!(table.route("/").is_none()); assert!(table.route("//").is_none()); assert!(table.route("foo").is_some()); assert!(table.route("/foo").is_some()); assert!(table.route("foo/").is_some()); assert!(table.route("/foo/").is_some()); assert!(table.route("//foo//").is_some()); assert!(table.route("foo/bar").is_none()); assert!(table.route("fo/o").is_none()); } #[test] fn multiple_fixed_segment_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo"); table.setup("bar"); assert!(table.route("").is_none()); assert!(table.route("/").is_none()); assert!(table.route("//").is_none()); assert!(table.route("foo").is_some()); assert!(table.route("bar").is_some()); assert!(table.route("foo/bar").is_none()); assert!(table.route("bar/foo").is_none()) } #[test] fn nested_fixed_segment_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo/bar"); assert!(table.route("").is_none()); assert!(table.route("foo").is_none()); assert!(table.route("foo/bar").is_some()); } #[test] fn multiple_nested_fixed_segment_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo/bar"); table.setup("baz"); table.setup("quux/twiddle/twibble"); assert!(table.route("").is_none()); assert!(table.route("foo").is_none()); assert!(table.route("quux").is_none()); assert!(table.route("foo/bar").is_some()); assert!(table.route("baz").is_some()); assert!(table.route("quux/twiddle/twibble").is_some()); } #[test] fn overlap_nested_fixed_segment_matches() { let mut table: PathTable<i32> = PathTable::new(); *table.setup("") = 0; *table.setup("foo") = 1; *table.setup("foo/bar") = 2; assert_eq!(*table.route("/").unwrap().0, 0); assert_eq!(*table.route("/foo").unwrap().0, 1); assert_eq!(*table.route("/foo/bar").unwrap().0, 2); assert_eq!(*table.route("").unwrap().0, 0); assert_eq!(*table.route("foo").unwrap().0, 1); assert_eq!(*table.route("foo/bar").unwrap().0, 2); } #[test] fn wildcard_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("{}"); assert!(table.route("").is_none()); assert!(table.route("foo/bar").is_none()); assert!(table.route("foo").is_some()); assert!(table.route("bar").is_some()); } #[test] fn nested_wildcard_matches() { let mut table: PathTable<()> = PathTable::new(); table.setup("{}/{}"); assert!(table.route("").is_none()); assert!(table.route("foo").is_none()); assert!(table.route("foo/bar").is_some()); assert_eq!(&table.route("foo/bar").unwrap().1.vec, &["foo", "bar"]); assert!(table.route("foo/bar").unwrap().1.map.is_empty()); } #[test] fn mixed_route() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo/{}/bar"); assert!(table.route("").is_none()); assert!(table.route("foo").is_none()); assert!(table.route("foo/bar").is_none()); assert!(table.route("foo/bar/baz").is_none()); assert!(table.route("foo/baz/bar").is_some()); assert_eq!(&table.route("foo/baz/bar").unwrap().1.vec, &["baz"]); } #[test] fn wildcard_fallback() { let mut table: PathTable<i32> = PathTable::new(); *table.setup("foo") = 0; *table.setup("foo/bar") = 1; *table.setup("foo/{}/bar") = 2; assert!(table.route("").is_none()); assert!(table.route("foo/bar/baz").is_none()); assert!(table.route("foo/bar/bar").is_none()); assert_eq!(*table.route("foo").unwrap().0, 0); assert_eq!(*table.route("foo/bar").unwrap().0, 1); assert_eq!(*table.route("foo/baz/bar").unwrap().0, 2); } #[test] fn named_wildcard() { let mut table: PathTable<()> = PathTable::new(); *table.setup("foo/{foo}"); *table.setup("foo/{foo}/{bar}"); *table.setup("{}"); let (_, params) = table.route("foo/a").unwrap(); assert_eq!(params.vec, &["a"]); assert_eq!(params.map, [("foo", "a")].iter().cloned().collect()); let (_, params) = table.route("foo/a/b").unwrap(); assert_eq!(params.vec, &["a", "b"]); assert_eq!( params.map, [("foo", "a"), ("bar", "b")].iter().cloned().collect() ); let (_, params) = table.route("c").unwrap(); assert_eq!(params.vec, &["c"]); assert!(params.map.is_empty()); } #[test] fn wildcard_count_mod() { let mut table: PathTable<usize> = PathTable::new(); *table.setup("foo/{foo}*") = 0; *table.setup("bar/{}*") = 1; *table.setup("baz/*") = 2; *table.setup("foo/bar") = 3; let (&id, params) = table.route("foo/a/b").unwrap(); assert_eq!(id, 0); assert_eq!(params.vec, &["a/b"]); assert_eq!(params.map, [("foo", "a/b")].iter().cloned().collect()); let (&id, params) = table.route("bar/a/b").unwrap(); assert_eq!(id, 1); assert_eq!(params.vec, &["a/b"]); assert!(params.map.is_empty()); let (&id, params) = table.route("baz/a/b").unwrap(); assert_eq!(id, 2); assert_eq!(params.vec, &["a/b"]); assert!(params.map.is_empty()); let (&id, params) = table.route("foo/bar").unwrap(); assert_eq!(id, 3); assert!(params.vec.is_empty()); assert!(params.map.is_empty()); } #[test] #[should_panic] fn conflicting_wildcard_name_fails() { let mut table: PathTable<()> = PathTable::new(); *table.setup("foo/{foo}"); *table.setup("foo/{bar}"); } #[test] #[should_panic] fn conflicting_wildcard_modifier_fails() { let mut table: PathTable<()> = PathTable::new(); table.setup("foo/{foo}*"); table.setup("foo/{foo}"); } #[test] fn iter() { let mut table: PathTable<usize> = PathTable::new(); *table.setup("foo") = 1; *table.setup("foo/bar") = 2; *table.setup("{}") = 3; let set: HashSet<_> = table.iter().cloned().collect(); assert_eq!(set, [1, 2, 3].iter().cloned().collect()); } #[test] fn iter_mut() { let mut table: PathTable<usize> = PathTable::new(); *table.setup("foo") = 1; *table.setup("foo/bar") = 2; *table.setup("{}") = 3; for res in table.iter_mut() { *res -= 1; } let set: HashSet<_> = table.iter().cloned().collect(); assert_eq!(set, [0, 1, 2].iter().cloned().collect()); } }
// this is for vdr-tools { git = "https://gitlab.com/PatrikStas/vdr-tools", rev = "e364aedaf2e448484ff08722bef167041bad7371" } // extern crate indy; // // use std::{env, thread}; // use std::future::Future; // use std::time::Duration; // // use futures::executor::block_on; // use indy_api_types::domain::wallet::{Config, Credentials, KeyDerivationMethod}; // // use self::indy::domain::anoncreds::schema::SchemaId; // use self::indy::domain::cache::GetCacheOptions; // use self::indy::domain::crypto::did::DidValue; // use self::indy::Locator; use serde_json::Value; use indy_api_types::domain::wallet::{Config, Credentials, KeyDerivationMethod}; use futures::executor::block_on; use indy::future::Future; pub static DEFAULT_WALLET_KEY: &str = "8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY"; pub fn run_libindy_ffi(storage_credentials: Option<Value>, storage_config: Option<Value>) { info!("run_libindy_ffi >>"); // indy::pairwise::create_pairwise() ... create did // // l.ledger_controller.build_get_nym_request(Some(did.clone()), did.clone()); // // info!("run_async going to open pool"); // // let pool_handle = block_on(l.pool_controller.open(String::from("pool1"), None)).unwrap(); // // info!("run_async pool opened, handle={}", pool_handle); // let wallet_cfg = Config { id: "foobar".to_string(), storage_type: Some("postgres_storage".into()), storage_config: storage_config.clone(), cache: None, // field present in vdr-tools }; let wallet_credentials = Credentials { key: DEFAULT_WALLET_KEY.to_string(), rekey: None, storage_credentials, key_derivation_method: KeyDerivationMethod::RAW, rekey_derivation_method: KeyDerivationMethod::RAW, }; indy::wallet::create_wallet( &serde_json::to_string(&wallet_cfg).unwrap(), &serde_json::to_string(&wallet_credentials).unwrap() ).wait().unwrap(); info!("run_async wallet created"); let wh = indy::wallet::open_wallet( &serde_json::to_string(&wallet_cfg).unwrap(), &serde_json::to_string(&wallet_credentials).unwrap() ).wait().unwrap(); info!("Wallet opened, wh={:?}", wh);// // // let schema_id = SchemaId(String::from("StetyxAvHZVH6HLDQ4ym4G:2:MedicalLicense+medical_license:3.0.0")); // // let opts = GetCacheOptions { // // no_cache: None, // // no_update: None, // // no_store: None, // // min_fresh: None, // // }; // // let res = block_on(l.cache_controller.get_schema(pool_handle, wallet_handle, did.clone(), schema_id, opts)); // // info!("res = {:?}", res); // // // // block_on(l.pool_controller.close(pool_handle)).unwrap(); }
mod neural; use neural::*; fn main() { let mut bnn = BNN::new(2, 2, vec![2], 0.01).ok().unwrap(); bnn.layers[0].weights = vec![vec![0.15, 0.20], vec![0.25, 0.30]]; bnn.layers[0].bias = 0.35; bnn.layers[1].weights = vec![vec![0.40, 0.45], vec![0.50, 0.55]]; bnn.layers[1].bias = 0.60; println!("{:?}", bnn.forward(&vec![0.05f32,0.10f32])); }
#[doc = "Register `LPTIM_CR` reader"] pub type R = crate::R<LPTIM_CR_SPEC>; #[doc = "Register `LPTIM_CR` writer"] pub type W = crate::W<LPTIM_CR_SPEC>; #[doc = "Field `ENABLE` reader - ENABLE"] pub type ENABLE_R = crate::BitReader; #[doc = "Field `ENABLE` writer - ENABLE"] pub type ENABLE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SNGSTRT` reader - SNGSTRT"] pub type SNGSTRT_R = crate::BitReader; #[doc = "Field `SNGSTRT` writer - SNGSTRT"] pub type SNGSTRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CNTSTRT` reader - CNTSTRT"] pub type CNTSTRT_R = crate::BitReader; #[doc = "Field `CNTSTRT` writer - CNTSTRT"] pub type CNTSTRT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `COUNTRST` reader - COUNTRST"] pub type COUNTRST_R = crate::BitReader; #[doc = "Field `COUNTRST` writer - COUNTRST"] pub type COUNTRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RSTARE` reader - RSTARE"] pub type RSTARE_R = crate::BitReader; #[doc = "Field `RSTARE` writer - RSTARE"] pub type RSTARE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - ENABLE"] #[inline(always)] pub fn enable(&self) -> ENABLE_R { ENABLE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - SNGSTRT"] #[inline(always)] pub fn sngstrt(&self) -> SNGSTRT_R { SNGSTRT_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - CNTSTRT"] #[inline(always)] pub fn cntstrt(&self) -> CNTSTRT_R { CNTSTRT_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - COUNTRST"] #[inline(always)] pub fn countrst(&self) -> COUNTRST_R { COUNTRST_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - RSTARE"] #[inline(always)] pub fn rstare(&self) -> RSTARE_R { RSTARE_R::new(((self.bits >> 4) & 1) != 0) } } impl W { #[doc = "Bit 0 - ENABLE"] #[inline(always)] #[must_use] pub fn enable(&mut self) -> ENABLE_W<LPTIM_CR_SPEC, 0> { ENABLE_W::new(self) } #[doc = "Bit 1 - SNGSTRT"] #[inline(always)] #[must_use] pub fn sngstrt(&mut self) -> SNGSTRT_W<LPTIM_CR_SPEC, 1> { SNGSTRT_W::new(self) } #[doc = "Bit 2 - CNTSTRT"] #[inline(always)] #[must_use] pub fn cntstrt(&mut self) -> CNTSTRT_W<LPTIM_CR_SPEC, 2> { CNTSTRT_W::new(self) } #[doc = "Bit 3 - COUNTRST"] #[inline(always)] #[must_use] pub fn countrst(&mut self) -> COUNTRST_W<LPTIM_CR_SPEC, 3> { COUNTRST_W::new(self) } #[doc = "Bit 4 - RSTARE"] #[inline(always)] #[must_use] pub fn rstare(&mut self) -> RSTARE_W<LPTIM_CR_SPEC, 4> { RSTARE_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 = "LPTIM control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lptim_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 [`lptim_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 LPTIM_CR_SPEC; impl crate::RegisterSpec for LPTIM_CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`lptim_cr::R`](R) reader structure"] impl crate::Readable for LPTIM_CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`lptim_cr::W`](W) writer structure"] impl crate::Writable for LPTIM_CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets LPTIM_CR to value 0"] impl crate::Resettable for LPTIM_CR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! This module implements a simple "varint" encoding of integers. //! The encoding is: //! - unsigned integers are serialized 7 bits at a time, starting with the //! least significant bits //! - the most significant bit (msb) in each output byte indicates if there //! is a continuation byte (msb = 1) //! - signed integers are mapped to unsigned integers using "zig-zag" encoding: //! Positive values x are written as 2*x + 0, negative values //! are written as 2*(^x) + 1; that is, negative numbers are complemented //! and whether to complement is encoded in bit 0. // MaxVarintLenN is the maximum length of a varint-encoded N-bit integer. pub const MAX_VARINT_LEN16: usize = 3; pub const MAX_VARINT_LEN32: usize = 5; pub const MAX_VARINT_LEN64: usize = 10; pub trait Varint: Sized { fn encode(&self, buf: &mut [u8]) -> usize; fn decode(buf: &[u8]) -> Result<(Self, usize), usize>; // fn read_from<R: std::io::Read>(r: R) -> std::io::Result<(Self, usize)>; } pub fn encode<V: Varint>(buf: &mut [u8], v: &V) -> usize { <V as Varint>::encode(v, buf) } pub fn decode<V: Varint>(buf: &[u8]) -> Result<(V, usize), usize> { <V as Varint>::decode(buf) } // fn invalid_data(msg: &str) -> io::Error { // io::Error::new(io::ErrorKind::InvalidData, msg) // } macro_rules! impl_Varint { ( $( ($u:ty, $i:ty) ),* ) => ($( #[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] impl Varint for $u { /// Encodes self into buf and returns the number of bytes written. /// /// # Panic /// If the buffer is too small, encode will panic. fn encode(&self, buf: &mut [u8]) -> usize { let mut x = *self; let mut i = 0; while x >= 0x80 { buf[i] = x as u8 | 0x80; x >>= 7; i += 1; } buf[i] = x as u8; i + 1 } /// Decodes self from buf and returns a pair of value and the /// number of bytes read (> 0). /// If an error occurred, return the number of bytes only. /// n == 0: the buffer is too small. /// n > 0: overflow. fn decode(buf: &[u8]) -> Result<(Self, usize), usize> { let mut x: $u = 0; let mut s = 0usize; for (i, &b) in buf.iter().enumerate() { if b < 0x80 { if i > 9 || i == 9 && b > 1 { return Err(i + 1); // overflow } return Ok((x | (b as $u) << s, i + 1)); } x |= (b & 0x7f) as $u << s; s += 7; } Err(0) } // fn read_from<R: io::Read>(r: R) -> io::Result<(Self, usize)> { // let mut x: $u = 0; // let mut s = 0usize; // for (i, byte) in r.bytes().enumerate() { // let b = byte?; // if b < 0x80 { // if i > 9 || i == 9 && b > 1 { // return Err(invalid_data("varint overflow")) // } // return Ok((x | (b as $u) << s, i + 1)); // } // x |= (b & 0x7f) as $u << s; // s += 7; // } // Err(invalid_data("buffer too small")) // } } #[cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] impl Varint for $i { /// Encodes self into buf and returns the number of bytes written. /// /// # Panic /// If the buffer is too small, encode will panic. fn encode(&self, buf: &mut [u8]) -> usize { let mut u = (*self as $u) << 1; if *self < 0 { u = !u; } u.encode(buf) } /// Decodes self from buf and returns a pair of value and the /// number of bytes read (> 0). /// If an error occurred, return the number of bytes only. /// n == 0: the buffer is too small. /// n > 0: overflow. fn decode(buf: &[u8]) -> Result<(Self, usize), usize> { <$u as Varint>::decode(buf).map(|(v, n)| { let mut x = (v >> 1) as $i; if v & 1 != 0 { x = !x; } (x, n) }) } // fn read_from<R: io::Read>(r: R) -> io::Result<(Self, usize)> { // <$u as Varint>::read_from(r).map(|(v, n)|{ // let mut x = (v >> 1) as $i; // if v & 1 != 0 { // x = !x; // } // (x, n) // }) // } } )*) } impl_Varint!((u16, i16), (u32, i32), (u64, i64));
use std::fmt; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use networking::peers::ArtificePeer; use manager::Database; use std::marker::PhantomData; /// this structure is a container for a task, or rather an abstraction over a series of steps in the installation process /// this struct is stored and used by the taskschedule struct, that is responsible for running tasks in parrallel /// perhaps it would have been easier to use async await I don't know #[derive(Clone)] pub struct Task<E: std::error::Error + Send + Sync, DB: Database<E> + Send + Sync> { task_id: u16, name: String, task: Arc<Box<dyn Fn(Arc<DB>, Arc<Mutex<Vec<(String, u16)>>>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Send + Sync>>, phantom: PhantomData<E>, } impl<E: std::error::Error + Send + Sync, DB: Database<E> + Send + Sync> fmt::Debug for Task<E, DB> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Task") .field("task id", &self.task_id) .field("name", &self.name) .finish() } } impl<E: std::error::Error + Send + Sync, DB: Database<E> + Send + Sync> Task<E, DB> { /// create a task /// # Arguments /// task id: some number that identifies a task /// name: the name of the task /// func: the closure that handles the code that is run in a given task /// /// # Example /// /// ``` /// let task = Task::new(0, "random task", mvoe |db|{ /// // run some code in here /// Ok(()) /// }); /// task.run().unwrap(); /// ``` pub fn new<F>(task_id: u16, name: &str, func: F) -> Self where F: Fn(Arc<DB>, Arc<Mutex<Vec<(String, u16)>>>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> + 'static + Send + Sync, { Self { task_id, name: name.to_string(), task: Arc::new(Box::new(func)), phantom: PhantomData, } } pub fn run( self, database: Arc<DB>, completed: Arc<Mutex<Vec<(String, u16)>>>, ) -> Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)> { let task = self.task; match task(database, completed) { Ok(()) => Ok((self.name, self.task_id)), Err(e) => Err(((self.name, self.task_id), e)), } } pub fn name(&self) -> String { self.name.clone() } pub fn id(&self) -> u16 { self.task_id } } /// this struct runs the series of jobs or tasks that actually install artifice /// it uses a sender and receiver to dispatch tasks and recieve the result of each of those tasks post execution pub struct TaskSchedule<E: 'static + std::error::Error + Send + Sync + Send + Sync, DB: Database<E> + Send + Sync> { tasks: Vec<Task<E, DB>>, recv: Receiver<Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>>, sender: Sender<Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>>, thread_count: u8, timeout: Duration, } impl<E: 'static + std::error::Error + Send + Sync, DB: 'static + Database<E> + Send + Sync> TaskSchedule<E, DB> { /// allows a task list to be constructed from existing tasks, as appose to creating an empty list /*pub fn from_tasks(task_list: &[Task<E, DB>], thread_count: u8, timeout: Duration) -> Self { let (sender, recv): ( Sender< Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>, >, Receiver< Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>, >, ) = channel(); let mut tasks = Vec::new(); tasks.extend_from_slice(task_list); Self { tasks, recv, sender, thread_count, timeout, } }*/ pub fn new(thread_count: u8, timeout: Duration) -> Self { let tasks = Vec::new(); let (sender, recv): ( Sender< Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>, >, Receiver< Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>, >, ) = channel(); Self { tasks, recv, sender, thread_count, timeout, } } pub fn add_task(&mut self, task: Task<E, DB>) { self.tasks.push(task); } /// consumes the task list and dispateches $thread_count threads to run each task pub fn run( mut self, database: Arc<DB>, ) -> Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)> { let comp: Arc<Mutex<Vec<(String, u16)>>> = Arc::new(Mutex::new(Vec::new())); let mut tasks_complete = 0; let tasks_total = self.tasks.len(); let sender = self.sender.clone(); for _ in 0..self.thread_count { if let Some(task) = self.tasks.pop() { println!("starting task: {} with id: {}", task.name(), task.id()); let newsender = sender.clone(); let db = database.clone(); let completed = comp.clone(); thread::spawn(move || { newsender.send(task.run(db, completed.clone())).unwrap(); }); } } while let Ok(result) = self.recv.recv_timeout(self.timeout) { match result { Ok((name, id)) => { tasks_complete += 1; println!( "task: {}, with id: {} completed successfully, {}/{}", name, id, tasks_complete, tasks_total ); let mut done = comp.lock().unwrap(); done.push((name, id)); std::mem::drop(done); if let Some(task) = self.tasks.pop() { println!("starting task: {} with id: {}", task.name(), task.id()); let nextsender = self.sender.clone(); let db = database.clone(); let completed = comp.clone(); thread::spawn(move || { nextsender.send(task.run(db, completed.clone())).unwrap(); }); } else { return Ok(("".to_string(), 0)); } } Err(e) => return Err(e), } } Ok(("".to_string(), 0)) } } /// selects wether to compile the code from source or use precompiled binaries #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub enum InstallationSrc{ NewCompiled, NewFromSrc, } /// allows for the selection of varying locations for configs, /// configs in this case being ArtificePeers see networking, ArtificeConfig, and ArtificeHost #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub enum ConfigSrc{ Peer(ArtificePeer), CompletePeer(ArtificePeer), UpStream(String), Empty, } /// this struct is used for the operation of the installation process pub struct Installer<E: 'static + std::error::Error + Send + Sync, DB: 'static + Database<E> + Send + Sync> { _install_src: InstallationSrc, schedule: TaskSchedule<E, DB>, config_src: ConfigSrc, installation: DB, error: std::marker::PhantomData<E>, } impl<E: std::error::Error + Send + Sync, DB: Database<E> + Send + Sync> Installer<E, DB> { /// /// # Arguments /// install_src: precompiled, versus compiled /// database: the installation destination, ideally will be passed into the callbacks of each task /// thread count: how many threads to run tasks on in parrellel (means tasks can't be sequential) /// task_duration how long should the task schedule wait before killing a task because it has hung /// /// # Example /// /// ``` /// //note if not in this location any attempt to start the network will fail, because that is the current place that the system will look for configs /// // perhaps in the future the configs will be set to load from an env var /// let database = ArtificeDB::create("/home/user/.artifice"); /// /// let mut installer = Installer::new(InstalllationSrc::NewCompiled, database, 5, Durattion::from_seconds(5000000)); /// /// let task = Task::new(0, "create_dirs", move |db| { /// //some code here to preform a task /// }); /// /// installer.add_task(task); /// installer.run(); /// ``` /// pub fn new(install_src: InstallationSrc, database: DB, thread_count: u8, task_duration: Duration) -> Self{ let schedule = TaskSchedule::new(thread_count, task_duration); Self {_install_src: install_src, schedule, config_src: ConfigSrc::Empty, installation: database, error: std::marker::PhantomData} } /// update the config src from generating new config to using existing configs pub fn config_src(mut self, config_src: ConfigSrc) -> Self{ self.config_src = config_src; self } /// adds a task to the task schedule pub fn add_task(&mut self, task: Task<E, DB>){ self.schedule.add_task(task); } /// used to run the constructed task schedule that performs each step needed for installation pub fn run(self) -> Result<(String, u16), ((String, u16), Box<dyn std::error::Error + Send + Sync>)>{ self.schedule.run(Arc::new(self.installation)) } }
mod from_item; mod schema; use apllodb_shared_components::{ApllodbError, ApllodbResult, Expression, SchemaIndex}; use apllodb_sql_parser::apllodb_ast; use crate::{ aliaser::Aliaser, ast_translator::AstTranslator, condition::Condition, select::ordering::Ordering, }; #[derive(Clone, Debug, new)] pub(crate) struct SelectCommandAnalyzer { select_command: apllodb_ast::SelectCommand, } impl SelectCommandAnalyzer { pub(super) fn aliaser(&self) -> ApllodbResult<Aliaser> { let afns = self.aliased_field_names_in_projection()?; Ok(Aliaser::from(afns)) } pub(super) fn selection_condition(&self) -> ApllodbResult<Option<Condition>> { if let Some(ast_condition) = &self.select_command.where_condition { let from_correlations = self.from_item_correlations()?; let expr = AstTranslator::condition_in_select(ast_condition.clone(), &from_correlations)?; Ok(Some(Condition::new(expr))) } else { Ok(None) } } pub(super) fn sort_index_orderings(&self) -> ApllodbResult<Vec<(SchemaIndex, Ordering)>> { if let Some(ast_order_bys) = &self.select_command.order_bys { let from_correlations = self.from_item_correlations()?; let ast_order_bys = ast_order_bys.clone().into_vec(); let index_orderings: Vec<(SchemaIndex, Ordering)> = ast_order_bys .into_iter() .map(|ast_order_by| { let expression = AstTranslator::expression_in_select( ast_order_by.expression, &from_correlations, )?; let index = if let Expression::SchemaIndexVariant(idx) = expression { Ok(idx) } else { Err(ApllodbError::feature_not_supported( "ORDER BY's expression is supposed to be a SchemaIndex currently", )) }?; let ordering = AstTranslator::ordering(ast_order_by.ordering); Ok((index, ordering)) }) .collect::<ApllodbResult<_>>()?; Ok(index_orderings) } else { Ok(vec![]) } } }
use core::{ffi::c_void, mem::MaybeUninit}; use alloc::sync::Arc; use fermium::{SDL_AudioDeviceID, SDL_AudioSpec, SDL_OpenAudioDevice}; use tinyvec::TinyVec; use crate::{sdl_get_error, Initialization, SdlError}; pub struct AudioDevice { // TODO: NonZeroUWhatever? device_id: SDL_AudioDeviceID, // Note(Lokathor): As long as the device is open, we have to also keep SDL // itself alive. #[allow(dead_code)] init: Arc<Initialization>, } impl Drop for AudioDevice { // Note(Lokathor): The drop for the Arc runs *after* this drop code. fn drop(&mut self) { unsafe { fermium::SDL_CloseAudioDevice(self.device_id) } } } /// The Audio subsystem is the only part of SDL that **is** thread safe. unsafe impl Send for AudioDevice {} unsafe impl Sync for AudioDevice {} pub struct AudioFormat(u16); impl AudioFormat { ///signed 8-bit samples pub const S8: Self = Self(fermium::AUDIO_S8 as _); ///unsigned 8-bit samples pub const U8: Self = Self(fermium::AUDIO_U8 as _); ///signed 16-bit samples in little-endian byte order pub const S16LSB: Self = Self(fermium::AUDIO_S16LSB as _); ///signed 16-bit samples in big-endian byte order pub const S16MSB: Self = Self(fermium::AUDIO_S16MSB as _); ///signed 16-bit samples in native byte order pub const S16SYS: Self = Self(fermium::AUDIO_S16SYS as _); /// AUDIO_S16LSB pub const S16: Self = Self(fermium::AUDIO_S16 as _); /// unsigned 16-bit samples in little-endian byte order pub const U16LSB: Self = Self(fermium::AUDIO_U16LSB as _); /// unsigned 16-bit samples in big-endian byte order pub const U16MSB: Self = Self(fermium::AUDIO_U16MSB as _); /// unsigned 16-bit samples in native byte order pub const U16SYS: Self = Self(fermium::AUDIO_U16SYS as _); /// AUDIO_U16LSB pub const U16: Self = Self(fermium::AUDIO_U16 as _); /// 32-bit integer samples in little-endian byte order pub const S32LSB: Self = Self(fermium::AUDIO_S32LSB as _); /// 32-bit integer samples in big-endian byte order pub const S32MSB: Self = Self(fermium::AUDIO_S32MSB as _); /// 32-bit integer samples in native byte order pub const S32SYS: Self = Self(fermium::AUDIO_S32SYS as _); /// AUDIO_S32LSB pub const S32: Self = Self(fermium::AUDIO_S32 as _); /// 32-bit floating point samples in little-endian byte order pub const F32LSB: Self = Self(fermium::AUDIO_F32LSB as _); /// 32-bit floating point samples in big-endian byte order pub const F32MSB: Self = Self(fermium::AUDIO_F32MSB as _); /// 32-bit floating point samples in native byte order pub const F32SYS: Self = Self(fermium::AUDIO_F32SYS as _); /// AUDIO_F32LSB pub const F32: Self = Self(fermium::AUDIO_F32 as _); } pub struct AllowedAudioChanges(i32); impl AllowedAudioChanges { pub const FREQUENCY: Self = Self(fermium::SDL_AUDIO_ALLOW_FREQUENCY_CHANGE as _); pub const FORMAT: Self = Self(fermium::SDL_AUDIO_ALLOW_FORMAT_CHANGE as _); pub const CHANNELS: Self = Self(fermium::SDL_AUDIO_ALLOW_CHANNELS_CHANGE as _); pub const ANY: Self = Self(fermium::SDL_AUDIO_ALLOW_ANY_CHANGE as _); } pub struct AudioDeviceObtainedSpec { pub frequency: i32, pub format: AudioFormat, pub channels: u8, /// Should be a power of two (4096, etc) pub sample_count: u16, pub silence: u8, /// Buffer size in bytes pub size: usize, } // // // // // // Audio Queue // // // // // pub struct AudioQueueRequestSpec { pub frequency: i32, pub format: AudioFormat, pub channels: u8, /// Should be a power of two (4096, etc) pub sample_count: u16, } pub struct AudioQueueDevice(AudioDevice); impl AudioQueueDevice { pub(crate) fn open( init: Arc<Initialization>, device_name: Option<&str>, capture: bool, spec: &AudioQueueRequestSpec, changes: AllowedAudioChanges, ) -> Result<(Self, AudioDeviceObtainedSpec), SdlError> { let opt_device_null = device_name.map(|s| { s.as_bytes().iter().copied().chain(Some(0)).collect::<TinyVec<[u8; 64]>>() }); let device_null: *const u8 = match opt_device_null.as_ref() { Some(device_null_ref) => device_null_ref.as_ptr(), None => core::ptr::null(), }; let desired = SDL_AudioSpec { freq: spec.frequency, format: spec.format.0, channels: spec.channels, silence: /* calculated */ 0, samples: spec.sample_count, size: /* calculated */ 0, callback: None, userdata: core::ptr::null_mut(), padding: 0, }; let mut obtained = SDL_AudioSpec::default(); let device_id = unsafe { SDL_OpenAudioDevice( device_null.cast(), capture as _, &desired, &mut obtained, changes.0, ) }; if device_id > 0 { let queue = AudioQueueDevice(AudioDevice { device_id, init }); let obtained_spec = AudioDeviceObtainedSpec { frequency: obtained.freq, format: AudioFormat(obtained.format), channels: obtained.channels, sample_count: obtained.samples, silence: obtained.silence, size: obtained.size as usize, }; Ok((queue, obtained_spec)) } else { Err(sdl_get_error()) } } } // // // // // // Audio Callback // // // // // pub struct AudioCallbackRequestSpec { pub frequency: i32, pub format: AudioFormat, pub channels: u8, /// Should be a power of two (4096, etc) pub sample_count: u16, /// Usually runs in a **separate** thread from the main thread. pub callback: unsafe extern "C" fn(*mut c_void, *mut MaybeUninit<u8>, i32), pub userdata: *mut c_void, } pub struct AudioCallbackDevice(AudioDevice); impl AudioCallbackDevice { pub(crate) unsafe fn open( init: Arc<Initialization>, device_name: Option<&str>, capture: bool, spec: &AudioCallbackRequestSpec, changes: AllowedAudioChanges, ) -> Result<(Self, AudioDeviceObtainedSpec), SdlError> { let opt_device_null = device_name.map(|s| { s.as_bytes().iter().copied().chain(Some(0)).collect::<TinyVec<[u8; 64]>>() }); let device_null: *const u8 = match opt_device_null.as_ref() { Some(device_null_ref) => device_null_ref.as_ptr(), None => core::ptr::null(), }; let desired = SDL_AudioSpec { freq: spec.frequency, format: spec.format.0, channels: spec.channels, silence: /* calculated */ 0, samples: spec.sample_count, size: /* calculated */ 0, callback: Some(core::mem::transmute(spec.callback)), userdata: spec.userdata, padding: 0, }; let mut obtained = SDL_AudioSpec::default(); let device_id = SDL_OpenAudioDevice( device_null.cast(), capture as _, &desired, &mut obtained, changes.0, ); if device_id > 0 { let callback = AudioCallbackDevice(AudioDevice { device_id, init }); let obtained_spec = AudioDeviceObtainedSpec { frequency: obtained.freq, format: AudioFormat(obtained.format), channels: obtained.channels, sample_count: obtained.samples, silence: obtained.silence, size: obtained.size as usize, }; Ok((callback, obtained_spec)) } else { Err(sdl_get_error()) } } }
use super::{CARRY_FLAG, DECIMAL_FLAG, INTERRUPT_DISABLE_FLAG, IRQ_VECTOR, NEGATIVE_FLAG, NMI_VECTOR, OVERFLOW_FLAG, ZERO_FLAG, Mode}; // TODO: check unofficial opcodes for page crosses impl super::Cpu { pub fn adc(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); let carry_bit = if self.p & CARRY_FLAG == 0 {0} else {1}; let mut new_val = self.a.wrapping_add(byte); // add the byte at the _address to accum new_val = new_val.wrapping_add(carry_bit); // add carry flag to accumulator // set carry flag if we wrapped around and added something if new_val <= self.a && (byte != 0 || carry_bit != 0) { self.p |= CARRY_FLAG; } else { self.p &= 0xFF - CARRY_FLAG; } self.set_zero_flag(new_val); self.set_negative_flag(new_val); // signed 8-bit overflow can only happen if both signs were positive but result was negative, or if both signs were negative and the result was positive // sign is positive if num & 0x80 == 0, negative if num & 0x80 != 0 // ((sum & 0x80 != 0) && (acc & 0x80 == 0) && (operand & 0x80 == 0)) || ((sum & 0x80 == 0) && (acc & 0x80 != 0) && (operand & 0x80 != 0)) // simplifies to the below, thanks http://www.righto.com/2012/12/the-6502-overflow-flag-explained.html if (byte ^ new_val) & (self.a ^ new_val) & 0x80 != 0 { self.p |= OVERFLOW_FLAG; } else { self.p &= 0xFF - OVERFLOW_FLAG; } self.a = new_val; // actually change the accumulator } pub fn and(&mut self, _address: usize, _mode: Mode) { self.a &= self.read(_address); self.set_zero_flag(self.a); self.set_negative_flag(self.a); } pub fn asl(&mut self, _address: usize, _mode: Mode) { let mut val = match _mode { Mode::ACC => self.a, _ => { self.clock += 2; self.read(_address) }, }; // put top bit in carry flag if val & (1<<7) != 0 { self.p |= CARRY_FLAG; } else { self.p &= 0xFF - CARRY_FLAG; } val <<= 1; match _mode { Mode::ACC => self.a = val, _ => self.write(_address, val), }; self.set_zero_flag(val); self.set_negative_flag(val); } pub fn bcc(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & CARRY_FLAG == 0 { self.branch(byte); } } pub fn bcs(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & CARRY_FLAG != 0 { self.branch(byte); } } pub fn beq(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & ZERO_FLAG != 0 { self.branch(byte); } } pub fn bit(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); let tested = byte & self.a; self.set_zero_flag(tested); let bit6 = byte & (1 << 6); if bit6 != 0 { self.p |= OVERFLOW_FLAG; } else { self.p &= 0xFF - OVERFLOW_FLAG; } let bit7 = byte & (1 << 7); if bit7 != 0 { self.p |= NEGATIVE_FLAG; } else { self.p &= 0xFF - NEGATIVE_FLAG; } } pub fn bmi(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & NEGATIVE_FLAG != 0 { self.branch(byte); } } pub fn bne(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & ZERO_FLAG == 0 { self.branch(byte); } } pub fn bpl(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & NEGATIVE_FLAG == 0 { self.branch(byte); } } pub fn brk(&mut self, _address: usize, _mode: Mode) { // instr_test-v5/rom_singles/15-brk.nes and instr_test-v5/rom_singles/16-special.nes: // using self.pc + 1 in these next two lines allows these tests to pass. // I'm not sure why that's necessary as implied addressing mode is only supposed to consume 1 byte, // but the error message from 16-special.nes said "BRK should push address BRK + 2" // Aha! From http://nesdev.com/the%20%27B%27%20flag%20&%20BRK%20instruction.txt: // Regardless of what ANY 6502 documentation says, BRK is a 2 byte opcode. The // first is #$00, and the second is a padding byte. This explains why interrupt // routines called by BRK always return 2 bytes after the actual BRK opcode, // and not just 1. self.push(((self.pc + 1) >> 8) as u8); // push high byte self.push(((self.pc + 1) & 0xFF) as u8); // push low byte self.push(self.p | 0b00110000); // push status register with break bits set self.p |= INTERRUPT_DISABLE_FLAG; // set interrupt disable flag self.pc = ((self.read(IRQ_VECTOR + 1) as usize) << 8) // set program counter to IRQ/BRK vector, taking high byte + (self.read(IRQ_VECTOR) as usize); // and low byte self.clock += 5; // total of 7 cycles, 2 come from implied() } pub fn bvc(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & OVERFLOW_FLAG == 0 { self.branch(byte); } } pub fn bvs(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); if self.p & OVERFLOW_FLAG != 0 { self.branch(byte); } } pub fn clc(&mut self, _address: usize, _mode: Mode) { self.p &= 0xFF - CARRY_FLAG; } pub fn cld(&mut self, _address: usize, _mode: Mode) { self.p &= 0xFF - DECIMAL_FLAG; } pub fn cli(&mut self, _address: usize, _mode: Mode) { self.p &= 0xFF - INTERRUPT_DISABLE_FLAG; } pub fn clv(&mut self, _address: usize, _mode: Mode) { self.p &= 0xFF - OVERFLOW_FLAG; } pub fn cmp(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.compare(self.a, byte); } pub fn cpx(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.compare(self.x, byte); } pub fn cpy(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.compare(self.y, byte); } pub fn dcp(&mut self, _address: usize, _mode: Mode) { // unofficial let val = self.read(_address).wrapping_sub(1); self.write(_address, val); self.compare(self.a, val); } pub fn dec(&mut self, _address: usize, _mode: Mode) { let val = self.read(_address).wrapping_sub(1); self.write(_address, val); self.set_zero_flag(val); self.set_negative_flag(val); self.clock += 2; // extra cycles for all addressing modes of this instruction } pub fn dex(&mut self, _address: usize, _mode: Mode) { self.x = self.x.wrapping_sub(1); self.set_zero_flag(self.x); self.set_negative_flag(self.x); } pub fn dey(&mut self, _address: usize, _mode: Mode) { self.y = self.y.wrapping_sub(1); self.set_zero_flag(self.y); self.set_negative_flag(self.y); } pub fn eor(&mut self, _address: usize, _mode: Mode) { self.a ^= self.read(_address); self.set_negative_flag(self.a); self.set_zero_flag(self.a); } pub fn inc(&mut self, _address: usize, _mode: Mode) { let val = self.read(_address).wrapping_add(1); self.write(_address, val); self.set_zero_flag(val); self.set_negative_flag(val); self.clock += 2; // extra cycles for all addressing modes of this instruction } pub fn isc(&mut self, _address: usize, _mode: Mode) { // unofficial self.inc(_address, _mode); self.sbc(_address, _mode); } pub fn inx(&mut self, _address: usize, _mode: Mode) { self.x = self.x.wrapping_add(1); self.set_zero_flag(self.x); self.set_negative_flag(self.x); } pub fn iny(&mut self, _address: usize, _mode: Mode) { self.y = self.y.wrapping_add(1); self.set_zero_flag(self.y); self.set_negative_flag(self.y); } pub fn jmp(&mut self, _address: usize, _mode: Mode) { if _mode == Mode::ABS { self.clock -= 1; // this only takes 3.. } self.pc = _address; } pub fn jsr(&mut self, _address: usize, _mode: Mode) { // call to absolute already advances program counter by 3 self.clock += 2; let minus1 = self.pc - 1; // so m1 is the last _byte of the jsr instruction. second _byte of the operand. self.push((minus1 >> 8) as u8); self.push((minus1 & 0xFF) as u8); self.pc = _address; } pub fn lax(&mut self, _address: usize, _mode: Mode) { // unofficial opcode that sets both X and accumulator // TODO: check cycle count? https://wiki.nesdev.com/w/index.php/Programming_with_unofficial_opcodes let byte = self.read(_address); self.a = byte; self.x = byte; self.set_zero_flag(byte); self.set_negative_flag(byte); } pub fn lda(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.a = byte; self.set_zero_flag(byte); self.set_negative_flag(byte); } pub fn ldx(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.x = byte; self.set_zero_flag(byte); self.set_negative_flag(byte); } pub fn ldy(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); self.y = byte; self.set_zero_flag(byte); self.set_negative_flag(byte); } pub fn lsr(&mut self, _address: usize, _mode: Mode) { let mut val = match _mode { Mode::ACC => self.a, _ => { self.clock += 2; self.read(_address) }, }; if val & 0x1 == 0x1 { self.p |= CARRY_FLAG; } else { self.p &= 0xFF - CARRY_FLAG; } val >>= 1; match _mode { Mode::ACC => self.a = val, _ => self.write(_address, val), }; self.set_zero_flag(val); self.set_negative_flag(val); } pub fn nop(&mut self, _address: usize, _mode: Mode) { } pub fn ora(&mut self, _address: usize, _mode: Mode) { self.a |= self.read(_address); self.set_zero_flag(self.a); self.set_negative_flag(self.a); } pub fn pha(&mut self, _address: usize, _mode: Mode) { self.clock += 1; self.push(self.a); } pub fn php(&mut self, _address: usize, _mode: Mode) { self.clock += 1; self.push(self.p | 0b00110000); } pub fn pla(&mut self, _address: usize, _mode: Mode) { self.clock += 2; self.a = self.pop(); self.set_zero_flag(self.a); self.set_negative_flag(self.a); } pub fn plp(&mut self, _address: usize, _mode: Mode) { self.clock += 2; self.p = self.pop(); // TODO: figure out exactly what's supposed to happen here // let status = self.pop(); // // for each bit in the popped status, if it's 1, // // set that bit of self.p to 1. if it's 0, set that // // bit of self.p to 0. // for i in 0..=7 { // if i == 4 || i == 5 { // continue; // ignore B flags // } // let bit = if status & (1 << i) == 0 {0} else {1}; // if bit != 0 { // self.p |= 1 << i; // } else { // self.p &= 0xFF - (1 << i); // } // } // self.p |= 1 << 5; // turn on bit 5 // self.p &= 0xFF - (1 << 4); // and turn off bit 4 because god knows why } pub fn rla(&mut self, _address: usize, _mode: Mode) { // unofficial self.rol(_address, _mode); self.and(_address, _mode); } pub fn rol(&mut self, _address: usize, _mode: Mode) { let mut val = match _mode { Mode::ACC => self.a, _ => { self.clock += 2; self.read(_address) }, }; let carry_flag_bit = if self.p & CARRY_FLAG != 0 {1} else {0}; let new_cfb = if val & 0x80 != 0 {1} else {0}; val <<= 1; val += carry_flag_bit; match _mode { Mode::ACC => self.a = val, _ => self.write(_address, val), }; if new_cfb != 0 { self.p |= CARRY_FLAG; } else { self.p &= 0xFF - CARRY_FLAG; } self.set_zero_flag(val); self.set_negative_flag(val); } pub fn ror(&mut self, _address: usize, _mode: Mode) { let mut val = match _mode { Mode::ACC => self.a, _ => { self.clock += 2; // extra cycles self.read(_address) } }; let cfb = if self.p & CARRY_FLAG != 0 {1} else {0}; let new_cfb = val & 0x1; val >>= 1; val += cfb * 0x80; if new_cfb != 0 { self.p |= CARRY_FLAG; } else { self.p &= 0xFF - CARRY_FLAG; } match _mode { Mode::ACC => self.a = val, _ => self.write(_address, val), }; self.set_zero_flag(val); self.set_negative_flag(val); } pub fn rra(&mut self, _address: usize, _mode: Mode) { // unofficial self.ror(_address, _mode); self.adc(_address, _mode); } pub fn rti(&mut self, _address: usize, _mode: Mode) { self.plp(_address, _mode); // pull and set status reg (2 clock cycles) self.pc = self.pop() as usize; // low byte self.pc += (self.pop() as usize) << 8; // high byte self.clock += 2; // +2 from implied } pub fn rts(&mut self, _address: usize, _mode: Mode) { self.pc = self.pop() as usize; self.pc += ((self.pop() as usize) << 8) + 1; self.clock += 4; } pub fn sax(&mut self, _address: usize, _mode: Mode) { // unofficial combo of stx and sta self.write(_address, self.a & self.x); } pub fn sbc(&mut self, _address: usize, _mode: Mode) { let byte = self.read(_address); let carry_bit = if self.p & CARRY_FLAG == 0 {1} else {0}; let mut new_val = self.a.wrapping_sub(byte); new_val = new_val.wrapping_sub(carry_bit); // if overflow occurs and we subtracted something, CLEAR the carry bit if new_val >= self.a && (byte != 0 || carry_bit != 0) { self.p &= 0xFF - CARRY_FLAG; } else { self.p |= CARRY_FLAG; } self.set_zero_flag(new_val); self.set_negative_flag(new_val); // if acc is positive, mem is negative, and result is negative // or if acc is negative, mem is positive, and result is positive let acc = self.a & 0x80 == 0; let mem = byte & 0x80 == 0; let res = new_val & 0x80 == 0; // if sign is wrong, SET overflow flag if (acc && !mem && !res) || (!acc && mem && res) { self.p |= OVERFLOW_FLAG; } else { self.p &= 0xFF - OVERFLOW_FLAG; } self.a = new_val; // actually change the accumulator } pub fn sec(&mut self, _address: usize, _mode: Mode) { self.p |= CARRY_FLAG; } pub fn sed(&mut self, _address: usize, _mode: Mode) { self.p |= DECIMAL_FLAG; // don't think this is necessary since the NES's 6502 doesn't have decimal _mode but whatever } pub fn sei(&mut self, _address: usize, _mode: Mode) { self.p |= INTERRUPT_DISABLE_FLAG; } pub fn slo(&mut self, _address: usize, _mode: Mode) { self.asl(_address, _mode); self.ora(_address, _mode); // can get away with ignoring that asl handles accumulator addressing mode because slo doesn't handle accumulator addressing mode. } pub fn sre(&mut self, _address: usize, _mode: Mode) { // unofficial self.lsr(_address, _mode); self.eor(_address, _mode); } pub fn sta(&mut self, _address: usize, _mode: Mode) { // PPU Test 17 // STA, $2000,Y **must** issue a dummy read to 2007 if _address == 0x2007 && _mode == Mode::ABY && self.y == 7 { self.read(0x2007); } if _mode == Mode::INY { self.clock = self.before_clock + 6; // Special } else if _mode == Mode::ABY { self.clock = self.before_clock + 5; // Special } self.write(_address, self.a); } pub fn stx(&mut self, _address: usize, _mode: Mode) { self.write(_address, self.x); } pub fn sty(&mut self, _address: usize, _mode: Mode) { self.write(_address, self.y); } pub fn tax(&mut self, _address: usize, _mode: Mode) { self.x = self.a; self.set_zero_flag(self.x); self.set_negative_flag(self.x); } pub fn tay(&mut self, _address: usize, _mode: Mode) { self.y = self.a; self.set_zero_flag(self.y); self.set_negative_flag(self.y); } pub fn tsx(&mut self, _address: usize, _mode: Mode) { self.x = self.s; self.set_zero_flag(self.x); self.set_negative_flag(self.x); } pub fn txa(&mut self, _address: usize, _mode: Mode) { self.a = self.x; self.set_zero_flag(self.a); self.set_negative_flag(self.a); } pub fn txs(&mut self, _address: usize, _mode: Mode) { self.s = self.x; } pub fn tya(&mut self, _address: usize, _mode: Mode) { self.a = self.y; self.set_zero_flag(self.a); self.set_negative_flag(self.a); } pub fn bad(&mut self, _address: usize, _mode: Mode) { panic!("illegal opcode: 0x{:02X}", self.read(self.pc)); // this won't be the illegal opcode because the PC somehow hasn't been updated yet } // Interrupts pub fn nmi(&mut self) { self.push((self.pc >> 8) as u8); // push high byte self.push((self.pc & 0xFF) as u8); // push low byte self.push(self.p | 0b00110000); // push status register with break bits set self.p |= INTERRUPT_DISABLE_FLAG; // set interrupt disable flag self.pc = ((self.read(NMI_VECTOR + 1) as usize) << 8) // set program counter to NMI vector, taking high byte + (self.read(NMI_VECTOR) as usize); // and low byte self.clock += 7; } pub fn irq(&mut self) { self.push((self.pc >> 8) as u8); // push high byte self.push((self.pc & 0xFF) as u8); // push low byte self.push(self.p & 0b11001111); // push status register with break bits cleared self.p |= INTERRUPT_DISABLE_FLAG; // set interrupt disable flag self.pc = ((self.read(IRQ_VECTOR + 1) as usize) << 8) // set program counter to IRQ/BRK vector, taking high byte + (self.read(IRQ_VECTOR) as usize); // and low byte self.clock += 7; } }
#[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate languageserver_types; extern crate drop_bomb; #[macro_use] extern crate crossbeam_channel; extern crate threadpool; #[macro_use] extern crate log; extern crate url_serde; extern crate flexi_logger; extern crate walkdir; extern crate libeditor; extern crate libanalysis; extern crate libsyntax2; extern crate im; mod io; mod caps; mod req; mod dispatch; mod conv; mod main_loop; mod vfs; mod path_map; use threadpool::ThreadPool; use crossbeam_channel::bounded; use flexi_logger::{Logger, Duplicate}; use libanalysis::WorldState; use ::{ io::{Io, RawMsg, RawResponse, RawRequest, RawNotification}, path_map::PathMap, }; pub type Result<T> = ::std::result::Result<T, ::failure::Error>; fn main() -> Result<()> { Logger::with_env() .duplicate_to_stderr(Duplicate::All) .log_to_file() .directory("log") .start()?; info!("lifecycle: server started"); match ::std::panic::catch_unwind(|| main_inner()) { Ok(res) => { info!("lifecycle: terminating process with {:?}", res); res } Err(_) => { error!("server panicked"); bail!("server panicked") } } } fn main_inner() -> Result<()> { let mut io = Io::from_stdio(); let res = initialize(&mut io); info!("shutting down IO..."); let io_res = io.stop(); info!("... IO is down"); match (res, io_res) { (Ok(()), Ok(())) => Ok(()), (res, Ok(())) => res, (Ok(()), io_res) => io_res, (res, Err(io_err)) => { error!("shutdown error: {:?}", io_err); res } } } fn initialize(io: &mut Io) -> Result<()> { match io.recv()? { RawMsg::Notification(n) => bail!("expected initialize request, got {:?}", n), RawMsg::Response(res) => bail!("expected initialize request, got {:?}", res), RawMsg::Request(req) => { let mut req = Some(req); dispatch::handle_request::<req::Initialize, _>(&mut req, |_params, resp| { let res = req::InitializeResult { capabilities: caps::server_capabilities() }; let resp = resp.into_response(Ok(res))?; io.send(RawMsg::Response(resp)); Ok(()) })?; if let Some(req) = req { bail!("expected initialize request, got {:?}", req) } match io.recv()? { RawMsg::Notification(n) => { if n.method != "initialized" { bail!("expected initialized notification"); } } _ => bail!("expected initialized notification"), } } } initialized(io) } enum Task { Respond(RawResponse), Request(RawRequest), Notify(RawNotification), Die(::failure::Error), } fn initialized(io: &mut Io) -> Result<()> { { let mut world = WorldState::new(); let mut pool = ThreadPool::new(4); let (task_sender, task_receiver) = bounded::<Task>(16); let (fs_events_receiver, watcher) = vfs::watch(vec![ ::std::env::current_dir()?, ]); info!("lifecycle: handshake finished, server ready to serve requests"); let res = main_loop::main_loop( io, &mut world, &mut pool, task_sender, task_receiver.clone(), fs_events_receiver, ); info!("waiting for background jobs to finish..."); task_receiver.for_each(drop); pool.join(); info!("...background jobs have finished"); info!("waiting for file watcher to finish..."); watcher.stop()?; info!("...file watcher has finished"); res }?; match io.recv()? { RawMsg::Notification(n) => { if n.method == "exit" { info!("lifecycle: shutdown complete"); return Ok(()); } bail!("unexpected notification during shutdown: {:?}", n) } m => { bail!("unexpected message during shutdown: {:?}", m) } } }
//! Currency service configuration. use serde_json; use exonum::blockchain::Schema; use exonum::crypto::PublicKey; use exonum::encoding::serialize::FromHex; use exonum::storage::Snapshot; use currency; use currency::transactions::components::permissions; encoding_struct! { /// Wallet tx permittion configuration #[derive(Eq, PartialOrd, Ord)] struct WalletPermissions { key: &PublicKey, mask: u64 } } encoding_struct! { /// List of wallets that have permissions. struct TransactionPermissions { wallets: Vec<WalletPermissions>, global_permission_mask: u64, } } impl Default for TransactionPermissions { fn default() -> Self { TransactionPermissions::new( vec![], permissions::ALL_ALLOWED_MASK ) } } encoding_struct! { /// Fixed fees to be paid to the genesis wallet when transaction is executed. #[derive(Eq, PartialOrd, Ord)] struct TransactionFees { recipient: &PublicKey, add_assets: u64, add_assets_per_entry: u64, delete_assets: u64, exchange: u64, trade: u64, transfer: u64, } } impl TransactionFees { pub fn with_default_key( add_assets: u64, add_assets_per_entry: u64, delete_assets: u64, exchange: u64, trade: u64, transfer: u64, ) -> Self { TransactionFees::new( &PublicKey::from_hex(GENESIS_WALLET_PUB_KEY).unwrap(), add_assets, add_assets_per_entry, delete_assets, exchange, trade, transfer, ) } } impl Default for TransactionFees { fn default() -> Self { TransactionFees::new( &PublicKey::from_hex(GENESIS_WALLET_PUB_KEY).unwrap(), 0, 0, 0, 0, 0, 0, ) } } encoding_struct! { /// Currency service configuration. #[derive(Eq, PartialOrd, Ord)] struct Configuration { fees: TransactionFees, permissions: TransactionPermissions } } /// Hexadecimal representation of the public key for genesis wallet. pub const GENESIS_WALLET_PUB_KEY: &str = "36a05e418393fb4b23819753f6e6dd51550ce030d53842c43dd1349857a96a61"; impl Default for Configuration { fn default() -> Configuration { Configuration::new(TransactionFees::default(), TransactionPermissions::default()) } } impl Configuration { /// Extract the `Configuration`. /// /// # Panics /// /// Panics if service configuration is invalid or absent. pub fn extract(snapshot: &Snapshot) -> Configuration { let schema = Schema::new(snapshot); let stored_configuration = schema.actual_configuration(); match stored_configuration.services.get(currency::SERVICE_NAME) { Some(json) => serde_json::from_value(json.clone()) .expect(&format!("Configuration is invalid: {:?}", json)), None => panic!( "No configuration for {} on the blockchain", currency::SERVICE_NAME ), } } }
#[doc = "Reader of register INTR_LVL_SEL"] pub type R = crate::R<u32, super::INTR_LVL_SEL>; #[doc = "Writer for register INTR_LVL_SEL"] pub type W = crate::W<u32, super::INTR_LVL_SEL>; #[doc = "Register INTR_LVL_SEL `reset()`'s with value 0"] impl crate::ResetValue for super::INTR_LVL_SEL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "USB SOF Interrupt level select\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SOF_LVL_SEL_A { #[doc = "0: High priority interrupt"] HI, #[doc = "1: Medium priority interrupt"] MED, #[doc = "2: Low priority interrupt"] LO, #[doc = "3: illegal"] RSVD, } impl From<SOF_LVL_SEL_A> for u8 { #[inline(always)] fn from(variant: SOF_LVL_SEL_A) -> Self { match variant { SOF_LVL_SEL_A::HI => 0, SOF_LVL_SEL_A::MED => 1, SOF_LVL_SEL_A::LO => 2, SOF_LVL_SEL_A::RSVD => 3, } } } #[doc = "Reader of field `SOF_LVL_SEL`"] pub type SOF_LVL_SEL_R = crate::R<u8, SOF_LVL_SEL_A>; impl SOF_LVL_SEL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SOF_LVL_SEL_A { match self.bits { 0 => SOF_LVL_SEL_A::HI, 1 => SOF_LVL_SEL_A::MED, 2 => SOF_LVL_SEL_A::LO, 3 => SOF_LVL_SEL_A::RSVD, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `HI`"] #[inline(always)] pub fn is_hi(&self) -> bool { *self == SOF_LVL_SEL_A::HI } #[doc = "Checks if the value of the field is `MED`"] #[inline(always)] pub fn is_med(&self) -> bool { *self == SOF_LVL_SEL_A::MED } #[doc = "Checks if the value of the field is `LO`"] #[inline(always)] pub fn is_lo(&self) -> bool { *self == SOF_LVL_SEL_A::LO } #[doc = "Checks if the value of the field is `RSVD`"] #[inline(always)] pub fn is_rsvd(&self) -> bool { *self == SOF_LVL_SEL_A::RSVD } } #[doc = "Write proxy for field `SOF_LVL_SEL`"] pub struct SOF_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> SOF_LVL_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SOF_LVL_SEL_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "High priority interrupt"] #[inline(always)] pub fn hi(self) -> &'a mut W { self.variant(SOF_LVL_SEL_A::HI) } #[doc = "Medium priority interrupt"] #[inline(always)] pub fn med(self) -> &'a mut W { self.variant(SOF_LVL_SEL_A::MED) } #[doc = "Low priority interrupt"] #[inline(always)] pub fn lo(self) -> &'a mut W { self.variant(SOF_LVL_SEL_A::LO) } #[doc = "illegal"] #[inline(always)] pub fn rsvd(self) -> &'a mut W { self.variant(SOF_LVL_SEL_A::RSVD) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | ((value as u32) & 0x03); self.w } } #[doc = "Reader of field `BUS_RESET_LVL_SEL`"] pub type BUS_RESET_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `BUS_RESET_LVL_SEL`"] pub struct BUS_RESET_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> BUS_RESET_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2); self.w } } #[doc = "Reader of field `EP0_LVL_SEL`"] pub type EP0_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP0_LVL_SEL`"] pub struct EP0_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP0_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | (((value as u32) & 0x03) << 4); self.w } } #[doc = "Reader of field `LPM_LVL_SEL`"] pub type LPM_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `LPM_LVL_SEL`"] pub struct LPM_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> LPM_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } #[doc = "Reader of field `RESUME_LVL_SEL`"] pub type RESUME_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESUME_LVL_SEL`"] pub struct RESUME_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> RESUME_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Reader of field `ARB_EP_LVL_SEL`"] pub type ARB_EP_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ARB_EP_LVL_SEL`"] pub struct ARB_EP_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> ARB_EP_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Reader of field `EP1_LVL_SEL`"] pub type EP1_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP1_LVL_SEL`"] pub struct EP1_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP1_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `EP2_LVL_SEL`"] pub type EP2_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP2_LVL_SEL`"] pub struct EP2_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP2_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 18)) | (((value as u32) & 0x03) << 18); self.w } } #[doc = "Reader of field `EP3_LVL_SEL`"] pub type EP3_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP3_LVL_SEL`"] pub struct EP3_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP3_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 20)) | (((value as u32) & 0x03) << 20); self.w } } #[doc = "Reader of field `EP4_LVL_SEL`"] pub type EP4_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP4_LVL_SEL`"] pub struct EP4_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP4_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22); self.w } } #[doc = "Reader of field `EP5_LVL_SEL`"] pub type EP5_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP5_LVL_SEL`"] pub struct EP5_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP5_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24); self.w } } #[doc = "Reader of field `EP6_LVL_SEL`"] pub type EP6_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP6_LVL_SEL`"] pub struct EP6_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP6_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 26)) | (((value as u32) & 0x03) << 26); self.w } } #[doc = "Reader of field `EP7_LVL_SEL`"] pub type EP7_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP7_LVL_SEL`"] pub struct EP7_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP7_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 28)) | (((value as u32) & 0x03) << 28); self.w } } #[doc = "Reader of field `EP8_LVL_SEL`"] pub type EP8_LVL_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `EP8_LVL_SEL`"] pub struct EP8_LVL_SEL_W<'a> { w: &'a mut W, } impl<'a> EP8_LVL_SEL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 30)) | (((value as u32) & 0x03) << 30); self.w } } impl R { #[doc = "Bits 0:1 - USB SOF Interrupt level select"] #[inline(always)] pub fn sof_lvl_sel(&self) -> SOF_LVL_SEL_R { SOF_LVL_SEL_R::new((self.bits & 0x03) as u8) } #[doc = "Bits 2:3 - BUS RESET Interrupt level select"] #[inline(always)] pub fn bus_reset_lvl_sel(&self) -> BUS_RESET_LVL_SEL_R { BUS_RESET_LVL_SEL_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bits 4:5 - EP0 Interrupt level select"] #[inline(always)] pub fn ep0_lvl_sel(&self) -> EP0_LVL_SEL_R { EP0_LVL_SEL_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 6:7 - LPM Interrupt level select"] #[inline(always)] pub fn lpm_lvl_sel(&self) -> LPM_LVL_SEL_R { LPM_LVL_SEL_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bits 8:9 - Resume Interrupt level select"] #[inline(always)] pub fn resume_lvl_sel(&self) -> RESUME_LVL_SEL_R { RESUME_LVL_SEL_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bits 14:15 - Arbiter Endpoint Interrupt level select"] #[inline(always)] pub fn arb_ep_lvl_sel(&self) -> ARB_EP_LVL_SEL_R { ARB_EP_LVL_SEL_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bits 16:17 - EP1 Interrupt level select"] #[inline(always)] pub fn ep1_lvl_sel(&self) -> EP1_LVL_SEL_R { EP1_LVL_SEL_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 18:19 - EP2 Interrupt level select"] #[inline(always)] pub fn ep2_lvl_sel(&self) -> EP2_LVL_SEL_R { EP2_LVL_SEL_R::new(((self.bits >> 18) & 0x03) as u8) } #[doc = "Bits 20:21 - EP3 Interrupt level select"] #[inline(always)] pub fn ep3_lvl_sel(&self) -> EP3_LVL_SEL_R { EP3_LVL_SEL_R::new(((self.bits >> 20) & 0x03) as u8) } #[doc = "Bits 22:23 - EP4 Interrupt level select"] #[inline(always)] pub fn ep4_lvl_sel(&self) -> EP4_LVL_SEL_R { EP4_LVL_SEL_R::new(((self.bits >> 22) & 0x03) as u8) } #[doc = "Bits 24:25 - EP5 Interrupt level select"] #[inline(always)] pub fn ep5_lvl_sel(&self) -> EP5_LVL_SEL_R { EP5_LVL_SEL_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bits 26:27 - EP6 Interrupt level select"] #[inline(always)] pub fn ep6_lvl_sel(&self) -> EP6_LVL_SEL_R { EP6_LVL_SEL_R::new(((self.bits >> 26) & 0x03) as u8) } #[doc = "Bits 28:29 - EP7 Interrupt level select"] #[inline(always)] pub fn ep7_lvl_sel(&self) -> EP7_LVL_SEL_R { EP7_LVL_SEL_R::new(((self.bits >> 28) & 0x03) as u8) } #[doc = "Bits 30:31 - EP8 Interrupt level select"] #[inline(always)] pub fn ep8_lvl_sel(&self) -> EP8_LVL_SEL_R { EP8_LVL_SEL_R::new(((self.bits >> 30) & 0x03) as u8) } } impl W { #[doc = "Bits 0:1 - USB SOF Interrupt level select"] #[inline(always)] pub fn sof_lvl_sel(&mut self) -> SOF_LVL_SEL_W { SOF_LVL_SEL_W { w: self } } #[doc = "Bits 2:3 - BUS RESET Interrupt level select"] #[inline(always)] pub fn bus_reset_lvl_sel(&mut self) -> BUS_RESET_LVL_SEL_W { BUS_RESET_LVL_SEL_W { w: self } } #[doc = "Bits 4:5 - EP0 Interrupt level select"] #[inline(always)] pub fn ep0_lvl_sel(&mut self) -> EP0_LVL_SEL_W { EP0_LVL_SEL_W { w: self } } #[doc = "Bits 6:7 - LPM Interrupt level select"] #[inline(always)] pub fn lpm_lvl_sel(&mut self) -> LPM_LVL_SEL_W { LPM_LVL_SEL_W { w: self } } #[doc = "Bits 8:9 - Resume Interrupt level select"] #[inline(always)] pub fn resume_lvl_sel(&mut self) -> RESUME_LVL_SEL_W { RESUME_LVL_SEL_W { w: self } } #[doc = "Bits 14:15 - Arbiter Endpoint Interrupt level select"] #[inline(always)] pub fn arb_ep_lvl_sel(&mut self) -> ARB_EP_LVL_SEL_W { ARB_EP_LVL_SEL_W { w: self } } #[doc = "Bits 16:17 - EP1 Interrupt level select"] #[inline(always)] pub fn ep1_lvl_sel(&mut self) -> EP1_LVL_SEL_W { EP1_LVL_SEL_W { w: self } } #[doc = "Bits 18:19 - EP2 Interrupt level select"] #[inline(always)] pub fn ep2_lvl_sel(&mut self) -> EP2_LVL_SEL_W { EP2_LVL_SEL_W { w: self } } #[doc = "Bits 20:21 - EP3 Interrupt level select"] #[inline(always)] pub fn ep3_lvl_sel(&mut self) -> EP3_LVL_SEL_W { EP3_LVL_SEL_W { w: self } } #[doc = "Bits 22:23 - EP4 Interrupt level select"] #[inline(always)] pub fn ep4_lvl_sel(&mut self) -> EP4_LVL_SEL_W { EP4_LVL_SEL_W { w: self } } #[doc = "Bits 24:25 - EP5 Interrupt level select"] #[inline(always)] pub fn ep5_lvl_sel(&mut self) -> EP5_LVL_SEL_W { EP5_LVL_SEL_W { w: self } } #[doc = "Bits 26:27 - EP6 Interrupt level select"] #[inline(always)] pub fn ep6_lvl_sel(&mut self) -> EP6_LVL_SEL_W { EP6_LVL_SEL_W { w: self } } #[doc = "Bits 28:29 - EP7 Interrupt level select"] #[inline(always)] pub fn ep7_lvl_sel(&mut self) -> EP7_LVL_SEL_W { EP7_LVL_SEL_W { w: self } } #[doc = "Bits 30:31 - EP8 Interrupt level select"] #[inline(always)] pub fn ep8_lvl_sel(&mut self) -> EP8_LVL_SEL_W { EP8_LVL_SEL_W { w: self } } }
#[cfg(target_os = "linux")] mod linux; #[cfg(any(target_os = "macos", target_os = "freebsd"))] mod lsof; #[cfg(any(target_os = "macos", target_os = "freebsd"))] mod lsof_utils; #[cfg(target_os = "windows")] mod windows; mod errors; pub(crate) mod shared; pub use shared::*;
use serde::{Deserialize, Serialize}; /// Constraints that each record must satisfy. #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub(in crate::version) enum VersionConstraintKind { Default(/* TODO: Expr */), Check(/* TODO: Expr (e.g. c1 + c2 < c3) */), ForeignKey(/* TODO: ??? */), }
//! Primitives for working with TCP //! //! The types provided in this module are non-blocking by default and are //! designed to be portable across all supported Mio platforms. As long as the //! [portability guidelines] are followed, the behavior should be identical no //! matter the target platform. //! //! [portability guidelines]: ../struct.Poll.html#portability use std::fmt; use std::io::{self, IoSlice, IoSliceMut, Read, Write}; use std::net::SocketAddr; #[cfg(debug_assertions)] use crate::poll::SelectorId; use crate::{event, sys, Interests, Registry, Token}; /* * * ===== TcpStream ===== * */ /// A non-blocking TCP stream between a local socket and a remote socket. /// /// The socket will be closed when the value is dropped. /// /// # Examples /// /// ``` /// # use std::net::TcpListener; /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _listener = TcpListener::bind("127.0.0.1:34254")?; /// use mio::{Events, Interests, Poll, Token}; /// use mio::net::TcpStream; /// use std::time::Duration; /// /// let stream = TcpStream::connect("127.0.0.1:34254".parse()?)?; /// /// let mut poll = Poll::new()?; /// let mut events = Events::with_capacity(128); /// /// // Register the socket with `Poll` /// poll.registry().register(&stream, Token(0), Interests::WRITABLE)?; /// /// poll.poll(&mut events, Some(Duration::from_millis(100)))?; /// /// // The socket might be ready at this point /// # Ok(()) /// # } /// ``` pub struct TcpStream { sys: sys::TcpStream, #[cfg(debug_assertions)] selector_id: SelectorId, } use std::net::Shutdown; impl TcpStream { /// Create a new TCP stream and issue a non-blocking connect to the /// specified address. pub fn connect(addr: SocketAddr) -> io::Result<TcpStream> { sys::TcpStream::connect(addr).map(|sys| TcpStream { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), }) } /// Returns the socket address of the remote peer of this TCP connection. pub fn peer_addr(&self) -> io::Result<SocketAddr> { self.sys.peer_addr() } /// Returns the socket address of the local half of this TCP connection. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.sys.local_addr() } /// Creates a new independently owned handle to the underlying socket. /// /// The returned `TcpStream` is a reference to the same stream that this /// object references. Both handles will read and write the same stream of /// data, and options set on one stream will be propagated to the other /// stream. pub fn try_clone(&self) -> io::Result<TcpStream> { self.sys.try_clone().map(|s| TcpStream { sys: s, #[cfg(debug_assertions)] selector_id: self.selector_id.clone(), }) } /// Shuts down the read, write, or both halves of this connection. /// /// This function will cause all pending and future I/O on the specified /// portions to return immediately with an appropriate value (see the /// documentation of `Shutdown`). pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { self.sys.shutdown(how) } /// Sets the value of the `TCP_NODELAY` option on this socket. /// /// If set, this option disables the Nagle algorithm. This means that /// segments are always sent as soon as possible, even if there is only a /// small amount of data. When not set, data is buffered until there is a /// sufficient amount to send out, thereby avoiding the frequent sending of /// small packets. pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.sys.set_nodelay(nodelay) } /// Gets the value of the `TCP_NODELAY` option on this socket. /// /// For more information about this option, see [`set_nodelay`][link]. /// /// [link]: #method.set_nodelay pub fn nodelay(&self) -> io::Result<bool> { self.sys.nodelay() } /// Sets the value for the `IP_TTL` option on this socket. /// /// This value sets the time-to-live field that is used in every packet sent /// from this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.sys.set_ttl(ttl) } /// Gets the value of the `IP_TTL` option for this socket. /// /// For more information about this option, see [`set_ttl`][link]. /// /// [link]: #method.set_ttl pub fn ttl(&self) -> io::Result<u32> { self.sys.ttl() } /// Get the value of the `SO_ERROR` option on this socket. /// /// This will retrieve the stored error in the underlying socket, clearing /// the field in the process. This can be useful for checking errors between /// calls. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.sys.take_error() } /// Receives data on the socket from the remote address to which it is /// connected, without removing that data from the queue. On success, /// returns the number of bytes peeked. /// /// Successive calls return the same data. This is accomplished by passing /// `MSG_PEEK` as a flag to the underlying recv system call. pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { self.sys.peek(buf) } } impl Read for TcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (&self.sys).read(buf) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { (&self.sys).read_vectored(bufs) } } impl<'a> Read for &'a TcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (&self.sys).read(buf) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { (&self.sys).read_vectored(bufs) } } impl Write for TcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (&self.sys).write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { (&self.sys).write_vectored(bufs) } fn flush(&mut self) -> io::Result<()> { (&self.sys).flush() } } impl<'a> Write for &'a TcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (&self.sys).write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { (&self.sys).write_vectored(bufs) } fn flush(&mut self) -> io::Result<()> { (&self.sys).flush() } } impl event::Source for TcpStream { fn register(&self, registry: &Registry, token: Token, interests: Interests) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate_selector(registry)?; self.sys.register(registry, token, interests) } fn reregister( &self, registry: &Registry, token: Token, interests: Interests, ) -> io::Result<()> { self.sys.reregister(registry, token, interests) } fn deregister(&self, registry: &Registry) -> io::Result<()> { self.sys.deregister(registry) } } impl fmt::Debug for TcpStream { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.sys, f) } } /* * * ===== TcpListener ===== * */ /// A structure representing a socket server /// /// # Examples /// /// ``` /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// use mio::{Events, Interests, Poll, Token}; /// use mio::net::TcpListener; /// use std::time::Duration; /// /// let listener = TcpListener::bind("127.0.0.1:34255".parse()?)?; /// /// let mut poll = Poll::new()?; /// let mut events = Events::with_capacity(128); /// /// // Register the socket with `Poll` /// poll.registry().register(&listener, Token(0), Interests::READABLE)?; /// /// poll.poll(&mut events, Some(Duration::from_millis(100)))?; /// /// // There may be a socket ready to be accepted /// # Ok(()) /// # } /// ``` pub struct TcpListener { sys: sys::TcpListener, #[cfg(debug_assertions)] selector_id: SelectorId, } impl TcpListener { /// Convenience method to bind a new TCP listener to the specified address /// to receive new connections. /// /// This function will take the following steps: /// /// 1. Create a new TCP socket. /// 2. Set the `SO_REUSEADDR` option on the socket on Unix. /// 3. Bind the socket to the specified address. /// 4. Calls `listen` on the socket to prepare it to receive new connections. pub fn bind(addr: SocketAddr) -> io::Result<TcpListener> { sys::TcpListener::bind(addr).map(|sys| TcpListener { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), }) } /// Accepts a new `TcpStream`. /// /// This may return an `Err(e)` where `e.kind()` is /// `io::ErrorKind::WouldBlock`. This means a stream may be ready at a later /// point and one should wait for an event before calling `accept` again. /// /// If an accepted stream is returned, the remote address of the peer is /// returned along with it. pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { self.sys.accept().map(|(sys, addr)| { ( TcpStream { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), }, addr, ) }) } /// Returns the local socket address of this listener. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.sys.local_addr() } /// Creates a new independently owned handle to the underlying socket. /// /// The returned `TcpListener` is a reference to the same socket that this /// object references. Both handles can be used to accept incoming /// connections and options set on one listener will affect the other. pub fn try_clone(&self) -> io::Result<TcpListener> { self.sys.try_clone().map(|s| TcpListener { sys: s, #[cfg(debug_assertions)] selector_id: self.selector_id.clone(), }) } /// Sets the value for the `IP_TTL` option on this socket. /// /// This value sets the time-to-live field that is used in every packet sent /// from this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.sys.set_ttl(ttl) } /// Gets the value of the `IP_TTL` option for this socket. /// /// For more information about this option, see [`set_ttl`][link]. /// /// [link]: #method.set_ttl pub fn ttl(&self) -> io::Result<u32> { self.sys.ttl() } /// Get the value of the `SO_ERROR` option on this socket. /// /// This will retrieve the stored error in the underlying socket, clearing /// the field in the process. This can be useful for checking errors between /// calls. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.sys.take_error() } } impl event::Source for TcpListener { fn register(&self, registry: &Registry, token: Token, interests: Interests) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate_selector(registry)?; self.sys.register(registry, token, interests) } fn reregister( &self, registry: &Registry, token: Token, interests: Interests, ) -> io::Result<()> { self.sys.reregister(registry, token, interests) } fn deregister(&self, registry: &Registry) -> io::Result<()> { self.sys.deregister(registry) } } impl fmt::Debug for TcpListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.sys, f) } } /* * * ===== UNIX ext ===== * */ #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; #[cfg(unix)] impl IntoRawFd for TcpStream { fn into_raw_fd(self) -> RawFd { self.sys.into_raw_fd() } } #[cfg(unix)] impl AsRawFd for TcpStream { fn as_raw_fd(&self) -> RawFd { self.sys.as_raw_fd() } } #[cfg(unix)] impl FromRawFd for TcpStream { unsafe fn from_raw_fd(fd: RawFd) -> TcpStream { TcpStream { sys: FromRawFd::from_raw_fd(fd), #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } } #[cfg(unix)] impl IntoRawFd for TcpListener { fn into_raw_fd(self) -> RawFd { self.sys.into_raw_fd() } } #[cfg(unix)] impl AsRawFd for TcpListener { fn as_raw_fd(&self) -> RawFd { self.sys.as_raw_fd() } } #[cfg(unix)] impl FromRawFd for TcpListener { unsafe fn from_raw_fd(fd: RawFd) -> TcpListener { TcpListener { sys: FromRawFd::from_raw_fd(fd), #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } }
mod cli; mod parse; mod stdlib; use cli::run_repl; use parse::{interpreter, lexer, parser, Context}; use std::{env, fs}; fn main() { match env::args().nth(1) { Some(filename) => run_file(&filename), None => run_repl(), } } fn run_file(filename: &str) { let source = fs::read_to_string(filename).unwrap(); let tokens = lexer::lex(&source).expect("Failed to lex"); let ast = parser::parse(tokens).expect("Failed to parse"); let mut global_sym_table = Context::new(); interpreter::visit(ast, &mut global_sym_table).expect("Fatal error"); }
use chrono; use log; pub fn setup_logger() -> Result<(), fern::InitError> { fern::Dispatch::new() .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) .level(log::LevelFilter::Debug) .chain(std::io::stdout()) .apply()?; Ok(()) } pub fn bytes_to_u16(data: &[u8]) -> u16 { u16::to_le((data[0] as u16) << 8 | data[1] as u16) } pub fn bytes_to_u32(data: &[u8]) -> u32 { u32::to_le( (data[0] as u32) << 24 | (data[1] as u32) << 16 | (data[2] as u32) << 8 | (data[3] as u32), ) } pub fn u32_ip4_to_str(d: u32) -> String { format!( "{}.{}.{}.{}", (d & 0xff00_0000) >> 24, (d & 0x00ff_0000) >> 16, (d & 0x0000_ff00) >> 8, d & 0x0000_00ff ) } pub fn ipv6_to_str(b: &[u8]) -> String { format!( "{:x}{:x}:{:x}{:x}:{:x}{:x}:{:x}{:x}:{:x}{:x}:{:x}{:x}:{:x}{:x}{:x}{:x}", b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15] ) } pub fn mac_to_str(addr: &[u8; 6]) -> String { format!( "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5] ) } pub fn ipv4_to_str(addr: &[u8; 4]) -> String { format!("{}.{}.{}.{}", addr[0], addr[1], addr[2], addr[3]) }
// Copyright 2020 IOTA Stiftung // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. pub(crate) const BEE_NAME: &str = "Bee"; pub(crate) const BEE_VERSION: &str = "0.1.0"; pub(crate) const BEE_GIT_COMMIT: &str = env!("BEE_GIT_COMMIT");
use std::{cmp::Ordering, fmt::Write, sync::Arc}; use eyre::Report; use futures::stream::{FuturesOrdered, StreamExt}; use hashbrown::{HashMap, HashSet}; use itertools::Itertools; use rosu_v2::prelude::{GameMode, OsuError, Score, Username}; use smallvec::SmallVec; use crate::{ commands::osu::{get_scores, ScoreArgs, UserArgs}, embeds::{CommonEmbed, EmbedData}, pagination::{CommonPagination, Pagination}, tracking::process_osu_tracking, util::{ constants::{GENERAL_ISSUE, OSU_API_ISSUE}, get_combined_thumbnail, MessageExt, }, BotResult, CommandData, Context, MessageBuilder, }; use super::TripleArgs; macro_rules! user_id { ($scores:ident[$idx:literal]) => { $scores[$idx].user.as_ref().unwrap().user_id }; } type CommonUsers = SmallVec<[CommonUser; 3]>; pub(super) async fn _common( ctx: Arc<Context>, data: CommandData<'_>, args: TripleArgs, ) -> BotResult<()> { let TripleArgs { name1, name2, name3, mode, } = args; let name1 = match name1 { Some(name) => name, None => { let content = "Since you're not linked with the `link` command, you must specify two names."; return data.error(&ctx, content).await; } }; let mut names = Vec::with_capacity(3); names.push(name1); names.push(name2); if let Some(name) = name3 { names.push(name); } { let mut unique = HashMap::with_capacity(names.len()); for name in names.iter() { *unique.entry(name.as_str()).or_insert(0) += 1; } if unique.len() == 1 { let content = "Give at least two different names"; return data.error(&ctx, content).await; } } let count = names.len(); // Retrieve each user's top scores let mut scores_futs: FuturesOrdered<_> = names .into_iter() .map(|name| async { let mut user_args = UserArgs::new(name.as_str(), mode); let score_args = ScoreArgs::top(100); let scores_fut = get_scores(&ctx, &user_args, &score_args); if let Some(alt_name) = user_args.whitespaced_name() { match scores_fut.await { Ok(scores) => (name, Ok(scores)), Err(OsuError::NotFound) => { user_args.name = &alt_name; let scores_result = get_scores(&ctx, &user_args, &score_args).await; (alt_name.into(), scores_result) } Err(err) => (name, Err(err)), } } else { let scores_result = scores_fut.await; (name, scores_result) } }) .collect(); let mut all_scores = Vec::<Vec<_>>::with_capacity(count); let mut users = CommonUsers::with_capacity(count); while let Some((mut name, result)) = scores_futs.next().await { match result { Ok(scores) => { let opt = scores .first() .and_then(|s| Some((s.user_id, s.user.as_ref()?.avatar_url.clone()))); if let Some((user_id, avatar_url)) = opt { name.make_ascii_lowercase(); users.push(CommonUser::new(name, avatar_url, user_id)); } else { let content = format!("User `{name}` has no {mode} top scores"); return data.error(&ctx, content).await; } all_scores.push(scores); } Err(OsuError::NotFound) => { let content = format!("User `{name}` was not found"); return data.error(&ctx, content).await; } Err(why) => { let _ = data.error(&ctx, OSU_API_ISSUE).await; return Err(why.into()); } } } drop(scores_futs); // Check if different names that both belong to the same user were given { let unique: HashSet<_> = users.iter().map(CommonUser::id).collect(); if unique.len() == 1 { let content = "Give at least two different users"; return data.error(&ctx, content).await; } } // Process users and their top scores for tracking for scores in all_scores.iter_mut() { process_osu_tracking(&ctx, scores, None).await; } // Consider only scores on common maps let mut map_ids: HashSet<u32> = all_scores .iter() .map(|scores| scores.iter().flat_map(|s| map_id!(s))) .flatten() .collect(); map_ids.retain(|&id| { all_scores.iter().all(|scores| { scores .iter() .filter_map(|s| map_id!(s)) .any(|map_id| map_id == id) }) }); all_scores .iter_mut() .for_each(|scores| scores.retain(|s| map_ids.contains(&map_id!(s).unwrap()))); // Flatten scores, sort by beatmap id, then group by beatmap id let mut all_scores: Vec<Score> = all_scores.into_iter().flatten().collect(); all_scores.sort_unstable_by_key(|score| map_id!(score)); let mut scores_per_map: Vec<SmallVec<[CommonScoreEntry; 3]>> = all_scores .into_iter() .group_by(|score| map_id!(score)) .into_iter() .map(|(_, scores)| { // Sort with respect to order of names let mut scores: Vec<Score> = scores.collect(); if user_id!(scores[0]) != users[0].id() { let target = (user_id!(scores[1]) != users[0].id()) as usize + 1; scores.swap(0, target); } if user_id!(scores[1]) != users[1].id() { scores.swap(1, 2); } let mut scores: SmallVec<[CommonScoreEntry; 3]> = scores.into_iter().map(CommonScoreEntry::new).collect(); // Calculate the index of the pp ordered by their values if (scores[0].pp - scores[1].pp).abs() <= f32::EPSILON { match scores[1].score.score.cmp(&scores[0].score.score) { Ordering::Less => scores[1].pos += 1, Ordering::Equal => { match scores[0].score.created_at.cmp(&scores[1].score.created_at) { Ordering::Less => scores[1].pos += 1, Ordering::Equal => {} Ordering::Greater => scores[0].pos += 1, } } Ordering::Greater => scores[0].pos += 1, } } else if scores[0].pp > scores[1].pp { scores[1].pos += 1; } else { scores[0].pos += 1; } if scores.len() == 3 { if (scores[0].pp - scores[2].pp).abs() <= f32::EPSILON { match scores[2].score.score.cmp(&scores[0].score.score) { Ordering::Less => scores[2].pos += 1, Ordering::Equal => { match scores[0].score.created_at.cmp(&scores[2].score.created_at) { Ordering::Less => scores[2].pos += 1, Ordering::Equal => {} Ordering::Greater => scores[0].pos += 1, } } Ordering::Greater => scores[0].pos += 1, } } else if scores[0].pp > scores[2].pp { scores[2].pos += 1; } else { scores[0].pos += 1; } if (scores[1].pp - scores[2].pp).abs() <= f32::EPSILON { match scores[2].score.score.cmp(&scores[1].score.score) { Ordering::Less => scores[2].pos += 1, Ordering::Equal => { match scores[1].score.created_at.cmp(&scores[2].score.created_at) { Ordering::Less => scores[2].pos += 1, Ordering::Equal => {} Ordering::Greater => scores[1].pos += 1, } } Ordering::Greater => scores[1].pos += 1, } } else if scores[1].pp > scores[2].pp { scores[2].pos += 1; } else { scores[1].pos += 1; } } if scores[0].pos == 0 { users[0].first_count += 1; } else if scores[1].pos == 0 { users[1].first_count += 1; } else { users[2].first_count += 1; } scores }) .collect(); // Sort the maps by their score's avg pp values scores_per_map.sort_unstable_by(|s1, s2| { let s1 = s1.iter().map(|entry| entry.pp).sum::<f32>() / s1.len() as f32; let s2 = s2.iter().map(|entry| entry.pp).sum::<f32>() / s2.len() as f32; s2.partial_cmp(&s1).unwrap_or(Ordering::Equal) }); // Accumulate all necessary data let mut content = String::with_capacity(16); let len = users.len(); let mut iter = users.iter().map(CommonUser::name); if let Some(first) = iter.next() { let last = iter.next_back(); let _ = write!(content, "`{first}`"); for name in iter { let _ = write!(content, ", `{name}`"); } if let Some(name) = last { if len > 2 { content.push(','); } let _ = write!(content, " and `{name}`"); } } let amount_common = scores_per_map.len(); if amount_common == 0 { content.push_str(" have no common scores"); } else { let _ = write!( content, " have {} common beatmap{} in their top 100", amount_common, if amount_common > 1 { "s" } else { "" } ); } // Create the combined profile pictures let urls = users.iter().map(CommonUser::avatar_url); let thumbnail_fut = get_combined_thumbnail(&ctx, urls, users.len() as u32, None); let data_fut = async { let limit = scores_per_map.len().min(10); CommonEmbed::new(&users, &scores_per_map[..limit], 0) }; let (thumbnail_result, embed_data) = tokio::join!(thumbnail_fut, data_fut); let thumbnail = match thumbnail_result { Ok(thumbnail) => Some(thumbnail), Err(why) => { let report = Report::new(why).wrap_err("failed to combine avatars"); warn!("{:?}", report); None } }; // Creating the embed let embed = embed_data.into_builder().build(); let mut builder = MessageBuilder::new().content(content).embed(embed); if let Some(bytes) = thumbnail { builder = builder.file("avatar_fuse.png", bytes); } let response_raw = data.create_message(&ctx, builder).await?; // Skip pagination if too few entries if scores_per_map.len() <= 10 { return Ok(()); } let response = response_raw.model().await?; // Pagination let pagination = CommonPagination::new(response, users, scores_per_map); let owner = data.author()?.id; tokio::spawn(async move { if let Err(err) = pagination.start(&ctx, owner, 60).await { warn!("{:?}", Report::new(err)); } }); Ok(()) } #[command] #[short_desc("Compare maps of players' top100s")] #[long_desc( "Compare the users' top 100 and check which \ maps appear in each top list (up to 3 users)" )] #[usage("[name1] [name2] [name3]")] #[example("badewanne3 \"nathan on osu\" idke")] pub async fn common(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match TripleArgs::args(&ctx, &mut args, msg.author.id, Some(GameMode::STD)).await { Ok(Ok(common_args)) => { let data = CommandData::Message { msg, args, num }; _common(ctx, data, common_args).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_compare(ctx, *command).await, } } #[command] #[short_desc("Compare maps of players' top100s")] #[long_desc( "Compare the mania users' top 100 and check which \ maps appear in each top list (up to 3 users)" )] #[usage("[name1] [name2] [name3]")] #[example("badewanne3 \"nathan on osu\" idke")] #[aliases("commonm")] pub async fn commonmania(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match TripleArgs::args(&ctx, &mut args, msg.author.id, Some(GameMode::MNA)).await { Ok(Ok(common_args)) => { let data = CommandData::Message { msg, args, num }; _common(ctx, data, common_args).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_compare(ctx, *command).await, } } #[command] #[short_desc("Compare maps of players' top100s")] #[long_desc( "Compare the taiko users' top 100 and check which \ maps appear in each top list (up to 3 users)" )] #[usage("[name1] [name2] [name3]")] #[example("badewanne3 \"nathan on osu\" idke")] #[aliases("commont")] pub async fn commontaiko(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match TripleArgs::args(&ctx, &mut args, msg.author.id, Some(GameMode::TKO)).await { Ok(Ok(common_args)) => { let data = CommandData::Message { msg, args, num }; _common(ctx, data, common_args).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_compare(ctx, *command).await, } } #[command] #[short_desc("Compare maps of players' top100s")] #[long_desc( "Compare the ctb users' top 100 and check which \ maps appear in each top list (up to 3 users)" )] #[usage("[name1] [name2] [name3]")] #[example("badewanne3 \"nathan on osu\" idke")] #[aliases("commonc")] pub async fn commonctb(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { match data { CommandData::Message { msg, mut args, num } => { match TripleArgs::args(&ctx, &mut args, msg.author.id, Some(GameMode::CTB)).await { Ok(Ok(common_args)) => { let data = CommandData::Message { msg, args, num }; _common(ctx, data, common_args).await } Ok(Err(content)) => msg.error(&ctx, content).await, Err(why) => { let _ = msg.error(&ctx, GENERAL_ISSUE).await; Err(why) } } } CommandData::Interaction { command } => super::slash_compare(ctx, *command).await, } } pub struct CommonScoreEntry { pub pos: usize, pub pp: f32, pub score: Score, } impl CommonScoreEntry { fn new(score: Score) -> Self { Self { pos: 0, pp: score.pp.unwrap_or_default(), score, } } } pub struct CommonUser { name: Username, avatar_url: String, user_id: u32, pub first_count: usize, } impl CommonUser { fn new(name: Username, avatar_url: String, user_id: u32) -> Self { Self { name, avatar_url, user_id, first_count: 0, } } } impl CommonUser { pub fn id(&self) -> u32 { self.user_id } pub fn name(&self) -> &str { self.name.as_str() } fn avatar_url(&self) -> &str { self.avatar_url.as_str() } }
//! Parse col instructions from characters. //! //! # Example //! //! ``` //! use col::parser::Instruction; //! //! let instr = Instruction::from_char(&'@'); //! //! assert_eq!(instr, Some(Instruction::Terminate)); //! ``` #[derive(Copy, Clone, Debug, PartialEq)] pub enum Instruction { /// Push the index of the column on the left onto the local stack PushLeftIndex, /// Push the index of the column on the right onto the local stack PushRightIndex, /// Push the index of the current column to the local stack. PushCurrentIndex, /// Pop value `a` and begin execution at the `a`th column. SetLocalColumn, /// Pop value `a` and set the remote stack to the `a`th column. SetRemoteStack, /// Pop value `a` from the local stack and push to the remote stack. MoveToRemote, /// Pop value `a` from the remote stack and push to the local stack MoveToLocal, /// Swap the top two values of the local stack. SwapTop, /// Duplicate the top value of the local stack. DuplicateTop, /// Discard the top value of the local stack. Discard, /// Clear the local stack. Clear, /// Swap the local and remote stacks. SwapStacks, /// Reverse the order of the local stack. Reverse, /// Push a value to the local stack. Value(u32), /// Skip past the matching `]` if popped value `a` is zero. LeftBracket, /// Skip back to after the matching `[` if popped value `a` is non-zero. RightBracket, /// Pop values `a` and `b` off the local stack and push the result of `b` plus `a`. Add, /// Pop values `a` and `b` off the local stack and push the result of `b` minus `a`. Subtract, /// Pop values `a` and `b` off the local stack and push the result of `b` times `a`. Multiply, /// Pop values `a` and `b` off the local stack and push the result of `b` divided by `a`. Divide, /// Pop values `a` and `b` off the local stack and push the remainder of the integer division of `b` divided by `a`. Modulo, /// Pop values `a` and `b` and push `1` if `a` equals `b` and `0` otherwise. Equals, /// Pop values `a` and `b` and push `1` if `b` is greater than `a` and `0` otherwise. GreaterThan, /// Pop values `a` and `b` and push the bitwise NAND result of the two. BitwiseNand, /// Pop values `a` and `b` and push one if they're both non-zero, and push zero otherwise. Not a bitwise AND. LogicalAnd, /// Pop values `a` and `b` and push one if at least one is non-zero, and push zero if they are both zero. Not a bitwise OR. LogicalOr, /// Invert the top value of the local stack. If it's `0`, push one, otherwise push `1`; LogicalNot, /// Push a random value to the local stack. Random, /// Toggle string mode. Until a matching "string mode" token is executed, characters will be interpreted as raw values. StringMode, /// Pop a value (interpreted from UTF-8 and push to the stack. If no more are available, push `0`. Input, /// Pop `a` and print its UTF-8 value. PrintChar, /// Pop `a` and print its numeric value. PrintNumber, /// Print all values in stack (from top to bottom) as UTF-8 characters. PrintAll, /// Terminate the entire program. Terminate, } impl Instruction { /// Attempts to convert a single char to a col instruction pub fn from_char(c: &char) -> Option<Instruction> { Some(match c { '<' => Instruction::PushLeftIndex, '>' => Instruction::PushRightIndex, '.' => Instruction::PushCurrentIndex, ';' => Instruction::SetLocalColumn, '~' => Instruction::SetRemoteStack, '^' => Instruction::MoveToRemote, 'v' => Instruction::MoveToLocal, '\\' => Instruction::SwapTop, ':' => Instruction::DuplicateTop, 'x' => Instruction::Discard, 'c' => Instruction::Clear, 's' => Instruction::SwapStacks, 'r' => Instruction::Reverse, '0'..='9' => Instruction::Value(c.to_digit(10).unwrap()), 'A'..='F' => Instruction::Value(*c as u32 - 'A' as u32 + 10), '[' => Instruction::LeftBracket, ']' => Instruction::RightBracket, '+' => Instruction::Add, '-' => Instruction::Subtract, '*' => Instruction::Multiply, '/' => Instruction::Divide, '%' => Instruction::Modulo, '=' => Instruction::Equals, '`' => Instruction::GreaterThan, ',' => Instruction::BitwiseNand, '&' => Instruction::LogicalAnd, '|' => Instruction::LogicalOr, '!' => Instruction::LogicalNot, '?' => Instruction::Random, '"' => Instruction::StringMode, '_' => Instruction::Input, '$' => Instruction::PrintChar, '#' => Instruction::PrintNumber, 'p' => Instruction::PrintAll, '@' => Instruction::Terminate, _ => return None, }) } }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::DR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `OEDATA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OEDATAR { #[doc = "No error on UART OEDATA, overrun error indicator. value."] NOERR, #[doc = "Error on UART OEDATA, overrun error indicator. value."] ERR, } impl OEDATAR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { OEDATAR::NOERR => false, OEDATAR::ERR => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> OEDATAR { match value { false => OEDATAR::NOERR, true => OEDATAR::ERR, } } #[doc = "Checks if the value of the field is `NOERR`"] #[inline] pub fn is_noerr(&self) -> bool { *self == OEDATAR::NOERR } #[doc = "Checks if the value of the field is `ERR`"] #[inline] pub fn is_err(&self) -> bool { *self == OEDATAR::ERR } } #[doc = "Possible values of the field `BEDATA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BEDATAR { #[doc = "No error on UART BEDATA, break error indicator. value."] NOERR, #[doc = "Error on UART BEDATA, break error indicator. value."] ERR, } impl BEDATAR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { BEDATAR::NOERR => false, BEDATAR::ERR => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> BEDATAR { match value { false => BEDATAR::NOERR, true => BEDATAR::ERR, } } #[doc = "Checks if the value of the field is `NOERR`"] #[inline] pub fn is_noerr(&self) -> bool { *self == BEDATAR::NOERR } #[doc = "Checks if the value of the field is `ERR`"] #[inline] pub fn is_err(&self) -> bool { *self == BEDATAR::ERR } } #[doc = "Possible values of the field `PEDATA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PEDATAR { #[doc = "No error on UART PEDATA, parity error indicator. value."] NOERR, #[doc = "Error on UART PEDATA, parity error indicator. value."] ERR, } impl PEDATAR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { PEDATAR::NOERR => false, PEDATAR::ERR => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PEDATAR { match value { false => PEDATAR::NOERR, true => PEDATAR::ERR, } } #[doc = "Checks if the value of the field is `NOERR`"] #[inline] pub fn is_noerr(&self) -> bool { *self == PEDATAR::NOERR } #[doc = "Checks if the value of the field is `ERR`"] #[inline] pub fn is_err(&self) -> bool { *self == PEDATAR::ERR } } #[doc = "Possible values of the field `FEDATA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FEDATAR { #[doc = "No error on UART FEDATA, framing error indicator. value."] NOERR, #[doc = "Error on UART FEDATA, framing error indicator. value."] ERR, } impl FEDATAR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { FEDATAR::NOERR => false, FEDATAR::ERR => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> FEDATAR { match value { false => FEDATAR::NOERR, true => FEDATAR::ERR, } } #[doc = "Checks if the value of the field is `NOERR`"] #[inline] pub fn is_noerr(&self) -> bool { *self == FEDATAR::NOERR } #[doc = "Checks if the value of the field is `ERR`"] #[inline] pub fn is_err(&self) -> bool { *self == FEDATAR::ERR } } #[doc = r" Value of the field"] pub struct DATAR { bits: u8, } impl DATAR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = "Values that can be written to the field `OEDATA`"] pub enum OEDATAW { #[doc = "No error on UART OEDATA, overrun error indicator. value."] NOERR, #[doc = "Error on UART OEDATA, overrun error indicator. value."] ERR, } impl OEDATAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { OEDATAW::NOERR => false, OEDATAW::ERR => true, } } } #[doc = r" Proxy"] pub struct _OEDATAW<'a> { w: &'a mut W, } impl<'a> _OEDATAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: OEDATAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No error on UART OEDATA, overrun error indicator. value."] #[inline] pub fn noerr(self) -> &'a mut W { self.variant(OEDATAW::NOERR) } #[doc = "Error on UART OEDATA, overrun error indicator. value."] #[inline] pub fn err(self) -> &'a mut W { self.variant(OEDATAW::ERR) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `BEDATA`"] pub enum BEDATAW { #[doc = "No error on UART BEDATA, break error indicator. value."] NOERR, #[doc = "Error on UART BEDATA, break error indicator. value."] ERR, } impl BEDATAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { BEDATAW::NOERR => false, BEDATAW::ERR => true, } } } #[doc = r" Proxy"] pub struct _BEDATAW<'a> { w: &'a mut W, } impl<'a> _BEDATAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: BEDATAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No error on UART BEDATA, break error indicator. value."] #[inline] pub fn noerr(self) -> &'a mut W { self.variant(BEDATAW::NOERR) } #[doc = "Error on UART BEDATA, break error indicator. value."] #[inline] pub fn err(self) -> &'a mut W { self.variant(BEDATAW::ERR) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PEDATA`"] pub enum PEDATAW { #[doc = "No error on UART PEDATA, parity error indicator. value."] NOERR, #[doc = "Error on UART PEDATA, parity error indicator. value."] ERR, } impl PEDATAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { PEDATAW::NOERR => false, PEDATAW::ERR => true, } } } #[doc = r" Proxy"] pub struct _PEDATAW<'a> { w: &'a mut W, } impl<'a> _PEDATAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PEDATAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No error on UART PEDATA, parity error indicator. value."] #[inline] pub fn noerr(self) -> &'a mut W { self.variant(PEDATAW::NOERR) } #[doc = "Error on UART PEDATA, parity error indicator. value."] #[inline] pub fn err(self) -> &'a mut W { self.variant(PEDATAW::ERR) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `FEDATA`"] pub enum FEDATAW { #[doc = "No error on UART FEDATA, framing error indicator. value."] NOERR, #[doc = "Error on UART FEDATA, framing error indicator. value."] ERR, } impl FEDATAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { FEDATAW::NOERR => false, FEDATAW::ERR => true, } } } #[doc = r" Proxy"] pub struct _FEDATAW<'a> { w: &'a mut W, } impl<'a> _FEDATAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: FEDATAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No error on UART FEDATA, framing error indicator. value."] #[inline] pub fn noerr(self) -> &'a mut W { self.variant(FEDATAW::NOERR) } #[doc = "Error on UART FEDATA, framing error indicator. value."] #[inline] pub fn err(self) -> &'a mut W { self.variant(FEDATAW::ERR) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DATAW<'a> { w: &'a mut W, } impl<'a> _DATAW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 255; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 11 - This is the overrun error indicator."] #[inline] pub fn oedata(&self) -> OEDATAR { OEDATAR::_from({ const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 10 - This is the break error indicator."] #[inline] pub fn bedata(&self) -> BEDATAR { BEDATAR::_from({ const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 9 - This is the parity error indicator."] #[inline] pub fn pedata(&self) -> PEDATAR { PEDATAR::_from({ const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - This is the framing error indicator."] #[inline] pub fn fedata(&self) -> FEDATAR { FEDATAR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 0:7 - This is the UART data port."] #[inline] pub fn data(&self) -> DATAR { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; DATAR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 11 - This is the overrun error indicator."] #[inline] pub fn oedata(&mut self) -> _OEDATAW { _OEDATAW { w: self } } #[doc = "Bit 10 - This is the break error indicator."] #[inline] pub fn bedata(&mut self) -> _BEDATAW { _BEDATAW { w: self } } #[doc = "Bit 9 - This is the parity error indicator."] #[inline] pub fn pedata(&mut self) -> _PEDATAW { _PEDATAW { w: self } } #[doc = "Bit 8 - This is the framing error indicator."] #[inline] pub fn fedata(&mut self) -> _FEDATAW { _FEDATAW { w: self } } #[doc = "Bits 0:7 - This is the UART data port."] #[inline] pub fn data(&mut self) -> _DATAW { _DATAW { w: self } } }
const MAX_DIVISION: usize = 20; fn color_circle(x: f32) -> [f32; 3] { if x*6.0 < 1.0 { let t = x*6.0; [1.0, t, 0.0] } else if x*6.0 < 2.0 { let t = x*6.0-1.0; [1.0-t, 1.0, 0.0] } else if x*6.0 < 3.0 { let t = x*6.0-2.0; [0.0, 1.0, t] } else if x*6.0 < 4.0 { let t = x*6.0-3.0; [0.0, 1.0-t, 1.0] } else if x*6.0 < 5.0 { let t = x*6.0-4.0; [t, 0.0, 1.0] } else { let t = x*6.0-5.0; [1.0, 0.0, 1.0-t] } } pub fn colors() -> Vec<[f32; 4]> { let mut colors = vec![ [0x00, 0x00, 0x00, 0xff], [0xff, 0xff, 0xff, 0xff], [0xef, 0xc5, 0x73, 0xff], [0x9c, 0x66, 0x3a, 0xff], [0xe5, 0x58, 0x5e, 0xff], [0xcb, 0x1d, 0x05, 0xff], [0x83, 0xd0, 0xe0, 0xff], [0x55, 0x8c, 0xcc, 0xff], [0xfc, 0xce, 0x79, 0xff], [0xff, 0xff, 0x44, 0xff], [0xad, 0xdf, 0x42, 0xff], [0x75, 0xce, 0x38, 0xff], [0xf6, 0xc6, 0xd2, 0xff], [0xc7, 0x5f, 0x7a, 0xff], [0xe2, 0xc5, 0xc9, 0xff], [0x97, 0x5d, 0xb2, 0xff], [0x41, 0x60, 0x70, 0xff], ].into_iter() .map(|color| { let mut out_color = [0f32; 4]; for i in 0..4 { out_color[i] = color[i] as f32 / 255.0; } out_color }) .collect::<Vec<_>>(); assert!(colors.len() == Color::GenPaleBlack as usize); colors.append(&mut generate_colors( ::CONFIG.pale_gen_color_division, ::CONFIG.pale_gen_color_delta, ::CONFIG.pale_gen_color_black, ::CONFIG.pale_gen_color_white )); assert!(colors.len() == Color::GenBlack as usize); colors.append(&mut generate_colors( ::CONFIG.gen_color_division, ::CONFIG.gen_color_delta, ::CONFIG.gen_color_black, ::CONFIG.gen_color_white )); assert!(colors.len() - 1 == Color::Gen19 as usize); colors } fn generate_colors(division: usize, delta: f32, black: f32, white: f32) -> Vec<[f32; 4]> { let mut colors = vec![]; assert!(black < white); assert!(division <= MAX_DIVISION); // Black colors.push([ black, black, black, 1.0 ]); // White colors.push([ white, white, white, 1.0 ]); for i in 0..division { let color = color_circle((i as f32 + delta) / division as f32); colors.push([ color[0]*(white-black)+black, color[1]*(white-black)+black, color[2]*(white-black)+black, 1.0 ]); } for _ in 0..(MAX_DIVISION - division) { colors.push([ 0.0, 0.0, 0.0, 1.0 ]); } colors } #[derive(Serialize, Deserialize, Clone, Copy)] #[repr(C)] pub enum Color { Black, //000000 White, //ffffff PaleBrown, //efc573 Brown, //9c663a PaleRed, //e5585e Red, //cb1d05 PaleBlue, //83d0e0 Blue, //558ccc PaleYellow, //fcce79 Yellow, //ffff44 PaleGreen, //addf42 Green, //75ce38 PalePink, //f6c6d2 Pink, //c75f7a PalePurple, //e2c5c9 Purple, //975db2 DarkBlue, //416070 GenPaleBlack, GenPaleWhite, GenPale0, GenPale1, GenPale2, GenPale3, GenPale4, GenPale5, GenPale6, GenPale7, GenPale8, GenPale9, GenPale10, GenPale11, GenPale12, GenPale13, GenPale14, GenPale15, GenPale16, GenPale17, GenPale18, GenPale19, GenBlack, GenWhite, Gen0, Gen1, Gen2, Gen3, Gen4, Gen5, Gen6, Gen7, Gen8, Gen9, Gen10, Gen11, Gen12, Gen13, Gen14, Gen15, Gen16, Gen17, Gen18, Gen19, }
use chrono::{Datelike, Duration, NaiveDate, Utc}; static DAYS: [&'static str; 7] = [ "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche", ]; static MONTHS: [&'static str; 12] = [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre", ]; pub fn format_date(date: &str) -> String { let date_only = NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap(); let weekday = DAYS .get(date_only.weekday().num_days_from_monday() as usize) .unwrap(); format!( "{} {} {}", weekday, date_only.day(), MONTHS.to_vec().get(date_only.month() as usize - 1).unwrap() ) } pub fn next_seven_days() -> Vec<(String, String)> { let mut seven_days = vec![]; for i in 0..7 { let day = Utc::today() + Duration::days(i); let date_string = day.format("%Y-%m-%d").to_string(); seven_days.push((date_string.clone(), format_date(&date_string))) } seven_days }
#[allow(unused_variables)] //Allows to create variables not used in any function fn main() { //Stack // - Fast memory creation and retrieval... speed, Speed, SPEED! // - Memory is automatically recaptured by the program after variables go out of scope // - Is the default in Rust // - Fixed size variables... Collections CANNOT be stack based (and Strings are a collection of u8's) let stack_i8: i8 = 10; let stack_f32: f32 = 20.;// Ponto por causa de ser float let stack_bool: bool = true; let stack_char: char = 'a'; //Heap // - Flexibility // - Memory tha can grow in size (Vector, HashMap, String, etc) // - Runtime performance cost (speed); // - Memory that can live beyond the scope that created it // - Memory is automatically recaptured when the last OWNER goes out of scope let heap_vector: Vec<i8> = Vec::new(); let heap_string: String = String::from("Howdy"); let heap_i8: Box<i8> = Box::new(30); //Como são variáveis de tamanho fixo, são alocados na stack, //sendo que é criado uma cópia da varíavel original quando a mesma é atribuida a outra var let stack_i8_2 = stack_i8; println!("{}", stack_i8); println!("{}", stack_i8_2); //Como estas vars são de Heap, pois o seu tamanho não é fixo, o proprietário passa a heap_i8_2, (transeferencia de propriedade) //sendo que a heap_i8 perde a propriedade dando erro em compilação let heap_i8_2 = heap_i8.clone(); //heap_i8; Não se pode querer ler desta var pois ela perdeu a propriedade para a outra var //.clone() copia o conteudo para a nova Var, ficando com duas vars independente //.clone() é pesado computacionalmente println!("{}", heap_i8); // Aqui println!("{}", heap_i8_2); }
use crate::page::Page; use quick_xml::{self as qx, events::Event}; use std::io::{BufReader, Read}; /// Iterator yielding Page objects for an XML file. pub struct PageIterator<R: Read> { reader: qx::Reader<BufReader<R>>, buf: Vec<u8>, page_buf: Vec<u8>, title: String, id: String, } impl<R: Read> PageIterator<R> { /// Create a new iterator from an XML source. pub fn new(xml_stream: BufReader<R>) -> Self { PageIterator { reader: qx::Reader::from_reader(xml_stream), buf: vec![], page_buf: vec![], title: String::new(), id: String::new(), } } /// Capture and set the title of the current page. fn extract_title(&mut self) { if let Ok(title) = self.reader.read_text(b"title", &mut self.page_buf) { self.title = title; } } /// Capture and set the id of the current page. fn extract_id(&mut self) { if let Ok(id) = self.reader.read_text(b"id", &mut self.page_buf) { self.id = id; } } // TODO: use regex here, with custom filters. fn is_filtered_title(&self) -> bool { // Skip over files. self.title.starts_with("File:") // Skip over templates. || self.title.starts_with("Template:") // Skip over Wikipedia internal pages. || self.title.starts_with("Wikipedia:") // Skip over User talk. || self.title.starts_with("User talk:") // Skip over File talk. || self.title.starts_with("File talk:") } } impl<R: Read> Iterator for PageIterator<R> { type Item = Page; fn next(&mut self) -> Option<Self::Item> { enum Tag { Id, Text, Title, Redirect, None, } loop { let action = { match self.reader.read_event(&mut self.buf) { Ok(Event::Start(ref tag)) => match tag.name() { b"text" => Tag::Text, b"id" => Tag::Id, b"title" => Tag::Title, _ => Tag::None, }, Ok(Event::Empty(ref tag)) => match tag.name() { b"redirect" => Tag::Redirect, _ => Tag::None, }, Ok(Event::Eof) => break, Ok(_) => Tag::None, Err(_) => break, } }; match action { Tag::Id => self.extract_id(), Tag::Title => self.extract_title(), Tag::Redirect => { // Skip over redirects; these are handled separately. self.reader .read_to_end(b"page", &mut self.page_buf) .unwrap(); } Tag::Text => { // Don't skip Portal pages for now. if self.is_filtered_title() { continue; } match self.reader.read_text(b"text", &mut self.page_buf) { Ok(page) => { return Some(Page::new(self.title.clone(), self.id.clone(), &page)); } Err(_) => return None, } } _ => (), } } None } } /// Iterator yielding String for each page in an XML file. pub struct RawPageIterator<R: Read>(pub PageIterator<R>); impl<R: Read> Iterator for RawPageIterator<R> { type Item = String; fn next(&mut self) -> Option<Self::Item> { loop { match self.0.reader.read_event(&mut self.0.buf) { Ok(Event::Start(ref tag)) => match tag.name() { b"text" => { if self.0.is_filtered_title() { continue; } match self.0.reader.read_text(b"text", &mut self.0.page_buf) { Ok(page) => { return Some(page); } Err(_) => return None, } } _ => (), }, Ok(Event::Empty(ref tag)) => match tag.name() { b"redirect" => { self.0 .reader .read_to_end(b"page", &mut self.0.page_buf) .unwrap(); } _ => (), }, Ok(Event::Eof) => break, Ok(_) => (), Err(_) => break, } } None } } /// Iterator yielding String for each page in an XML file. pub struct TantivyPageIterator<R: Read>(pub PageIterator<R>); impl<R: Read> Iterator for TantivyPageIterator<R> { type Item = (String, String, String); fn next(&mut self) -> Option<Self::Item> { loop { match self.0.reader.read_event(&mut self.0.buf) { Ok(Event::Start(ref tag)) => match tag.name() { b"id" => self.0.extract_id(), b"title" => self.0.extract_title(), b"text" => { if self.0.is_filtered_title() { continue; } match self.0.reader.read_text(b"text", &mut self.0.page_buf) { Ok(page) => { return Some((self.0.id.clone(), self.0.title.clone(), page)); } Err(_) => return None, } } _ => (), }, Ok(Event::Empty(ref tag)) => match tag.name() { b"redirect" => { self.0 .reader .read_to_end(b"page", &mut self.0.page_buf) .unwrap(); } _ => (), }, Ok(Event::Eof) => break, Ok(_) => (), Err(_) => break, } } None } }
use std::fmt; use std::fs; use std::io; use std::ops; extern crate serde_json; extern crate charsheet; use charsheet::dice; fn main() { let mut c = charsheet::CharacterBuilder::new(); loop { println!("Choice (enter ? for help): "); let choice = input(); match choice.trim_right() { "?" => { println!("?: Display this help."); println!("cn: Change name."); println!("cr: Change race."); println!("cc: Change class."); println!("uba: Update base abilities."); println!("p: Display character sheet."); println!("l: Load character."); println!("s: Save character."); println!("q: Quit."); } "cn" => { println!("Enter name:"); c.set_name(input()); } "cr" => { c.set_race(choose_named(&charsheet::RACES_FULL)); } "cc" => { c.set_class(choose_named(&charsheet::CLASSES)); } "uba" => { if let Some(scores) = generate_base_ability_scores() { if let Some(base_abilities) = assign_base_ability_scores(&scores) { c.set_base_abilities(base_abilities) } } } "p" => { println!("Character sheet:\n{}", c); } "l" => { println!("Enter filename"); let filename = input(); match fs::File::open(filename.trim_right()) { Err(e) => { println!("Error opening file: {}", e); continue; } Ok(mut f) => { match serde_json::from_reader(&mut f) { Ok(read_char) => { println!("Read from file successfully."); c = read_char; } Err(e) => { println!("Error reading from file: {}", e); } } } } } "s" => { println!("Enter filename"); let filename = input(); match fs::File::create(filename.trim_right()) { Err(e) => { println!("Error creating file: {}", e); continue; } Ok(mut f) => { match serde_json::to_writer(&mut f, &c) { Ok(_) => { println!("Written to file successfully."); } Err(e) => { println!("Error writing to file: {}", e); } } } } } "q" => { break; } c => { println!("Unknown option: {}", c); } } } } fn generate_base_ability_scores() -> Option<charsheet::UnsortedScores> { let mut last_scores: Option<charsheet::UnsortedScores> = None; println!("Generating base ability scores (enter ? for help)."); loop { if let Some(s) = last_scores { let total = s.iter().fold(0, ops::Add::add); println!("Current scores: {:?} (total: {})", s, total); } let choice = input(); match choice.trim_right() { "?" => { println!("c: cancel"); println!("d: done - accept rolls and start assignment"); println!("s: use standard scores"); println!("r: reroll scores"); } "c" => { return None; } "d" => { return last_scores; } "s" => { last_scores = Some(charsheet::STANDARD_SCORES); } "r" => { let mut scores: charsheet::UnsortedScores = [0; 6]; for s in scores.iter_mut() { // 4d6 take 3 highest let rolls = dice::roll(4, 6); let selected = dice::select(&rolls, 3, dice::RollSelect::High); *s = dice::sum(&selected); } scores.sort(); scores.reverse(); last_scores = Some(scores); continue; } c => { println!("Unknown option: {}", c); } } } } fn assign_base_ability_scores(scores: &charsheet::UnsortedScores) -> Option<charsheet::AbilityScores> { // A displayable Option<i32>. #[derive(Clone,Copy)] enum Assignment { Some(i32), None, } impl Assignment { fn unwrap_or_err(&self) -> Result<i32, &'static str> { match *self { Assignment::Some(v) => Ok(v), Assignment::None => Err("unassigned ability score"), } } } impl fmt::Display for Assignment { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { Assignment::Some(v) => { try!(write!(f, "{}", v)); } Assignment::None => { try!(write!(f, "(unassigned)")); } } Ok(()) } } let mut base_abilities = charsheet::AbilityValues::<Assignment>::new(Assignment::None); let mut scores = scores.to_vec(); println!("Assigning base ability scores (enter ? for help)."); loop { println!("Scores for assignment: {:?}", scores); println!("Current assignments: {}", base_abilities); let choice = input(); let have_scores = scores.len() > 0; match choice.trim_right() { "?" => { println!("c: cancel"); println!("d: done - accept and assign values to character"); if have_scores { println!("a: assign value to ability"); } } "c" => { return None; } "d" => { match base_abilities.map_result(|v| v.unwrap_or_err()) { Ok(ba) => { return Some(ba) } Err(e) => { println!("Could not accept values: {}", e); } } } "a" if have_scores => { println!("Assign which score?"); for (i, n) in scores.iter().enumerate() { println!("{} - {}", i+1, n); } let chosen_score_idx = choose_index(scores.len()); let chosen_score = Assignment::Some(scores.remove(chosen_score_idx)); let chosen_ability = choose_named(&charsheet::ABILITIES); let cur_ability_assignment = base_abilities.ability(chosen_ability); if let Assignment::Some(v) = *cur_ability_assignment { // Ability has been assigned a score already, restore that score to the list of // unassigned scores. scores.push(v); scores.sort(); } *cur_ability_assignment = chosen_score; } // TODO: "u" => unassign an ability score c => { println!("Unknown option: {}", c); } } } } fn choose_named<T: charsheet::Named+Copy>(choices: &[T]) -> T { println!("Choose one of the following options:"); for (i, n) in choices.iter().enumerate() { println!("{} - {}", i+1, n.name()); } choices[choose_index(choices.len())] } fn choose_index(count: usize) -> usize { loop { match input().parse::<i32>() { Ok(n) if n >= 1 && n <= count as i32 => { return n as usize - 1; } _ => { println!("Must be a number between 1 and {}", count); }, } } } fn input() -> String { let mut inp = String::new(); io::stdin().read_line(&mut inp) .ok().expect("Failed to read input"); inp.trim_right().to_string() }
extern crate rusqlite; use self::rusqlite::Connection; #[derive(Debug)] pub struct Fact { pub id: i32, pub fact: String, pub tidbit: String, pub verb: String, pub regex: i32, pub protected: i32, pub mood: i32, pub chance: i32, } pub fn open(fname: &str) -> Connection { let facts_db = Connection::open(fname).unwrap(); let _ = facts_db.execute( "CREATE TABLE IF NOT EXISTS facts ( id INTEGER PRIMARY KEY AUTOINCREMENT, fact TEXT NOT NULL, tidbit TEXT NOT NULL, verb TEXT NOT NULL DEFAULT 'is', regex INTEGER NOT NULL DEFAULT 0, protected INTEGER NOT NULL, mood INTEGER DEFAULT NULL, chance INTEGER DEFAULT NULL, CONSTRAINT unique_fact UNIQUE (fact, tidbit, verb) )", &[], ); facts_db }
//! Defines the `Kelvin` temperature newtype and related trait impls use core::{self, fmt}; use composite::UnitName; use temperature::Fahrenheit; use temperature::Celsius; /// A newtype that wraps around `f64` and provides convenience functions for unit-aware and type-safe manipulation. #[derive(Clone, Copy)] pub struct Kelvin(pub f64); impl_basic_ops!(Kelvin); impl_unit_debug!(Kelvin => "K"); impl_partial_ord!(Kelvin); //since Kelvin is an absolute unit, unlike Celsius and Fahrenheit, we support scalar multiplication and division impl_scalar_ops!(Kelvin); impl_div_same!(Kelvin); impl_from!(Celsius => Kelvin, |c| c + 273.); impl_from!(Fahrenheit => Kelvin, |f| (f + 459.67) * 5. / 9.);
/// PullRequestMeta PR info if an issue is a PR #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct PullRequestMeta { pub merged: Option<bool>, pub merged_at: Option<String>, } impl PullRequestMeta { /// Create a builder for this object. #[inline] pub fn builder() -> PullRequestMetaBuilder { PullRequestMetaBuilder { body: Default::default(), } } } impl Into<PullRequestMeta> for PullRequestMetaBuilder { fn into(self) -> PullRequestMeta { self.body } } /// Builder for [`PullRequestMeta`](./struct.PullRequestMeta.html) object. #[derive(Debug, Clone)] pub struct PullRequestMetaBuilder { body: self::PullRequestMeta, } impl PullRequestMetaBuilder { #[inline] pub fn merged(mut self, value: impl Into<bool>) -> Self { self.body.merged = Some(value.into()); self } #[inline] pub fn merged_at(mut self, value: impl Into<String>) -> Self { self.body.merged_at = Some(value.into()); self } }
//! Format commands. use crate::models::AclId; use crate::requests::{BackendId, ErrorFlag}; use std::io::{Result, Write}; pub fn end<W: Write>(w: &mut W) -> Result<()> { w.write_all(b"\n") } pub fn add_acl<W: Write>(w: &mut W, id: AclId, entry: &str) -> Result<()> { w.write_fmt(format_args!("add acl {} {}", id, entry)) } pub fn show_acl<W: Write>(w: &mut W) -> Result<()> { w.write_all(b"show acl") } pub fn show_acl_entries<W: Write>(w: &mut W, id: AclId) -> Result<()> { w.write_fmt(format_args!("show acl {}", id)) } pub fn show_cli_level<W: Write>(w: &mut W) -> Result<()> { w.write_all(b"show cli level") } pub fn show_cli_sockets<W: Write>(w: &mut W) -> Result<()> { w.write_all(b"show cli sockets") } pub fn show_errors<W: Write>(w: &mut W) -> Result<()> { w.write_all(b"show errors") } pub fn show_errors_backend<W: Write>( w: &mut W, id: BackendId, error_type: ErrorFlag, ) -> Result<()> { let error_type_str = match error_type { ErrorFlag::All => "", ErrorFlag::Request => " request", ErrorFlag::Response => " response", }; w.write_fmt(format_args!("show errors {}{}", id, error_type_str)) }
#![feature(test)] extern crate test; extern crate rss; use test::Bencher; use rss::Channel; #[bench] fn read_rss2sample(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/rss2sample.xml"); b.iter(|| { let _ = Channel::read_from(input).expect("failed to parse feed"); }); } #[bench] fn read_itunes(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/itunes.xml"); b.iter(|| { let _ = Channel::read_from(input).expect("failed to parse feed"); }); } #[bench] fn read_dublincore(b: &mut Bencher) { let input: &[u8] = include_bytes!("../tests/data/dublincore.xml"); b.iter(|| { let _ = Channel::read_from(input).expect("failed to parse feed"); }); }
use std::{ collections::{BTreeMap, HashMap}, iter::FromIterator, net::IpAddr, }; use ratatui::{ backend::Backend, layout::{Constraint, Rect}, style::{Color, Style}, terminal::Frame, widgets::{Block, Borders, Row}, }; use unicode_width::UnicodeWidthChar; use crate::{ display::{Bandwidth, DisplayBandwidth, UIState}, network::{display_connection_string, display_ip_or_host}, }; fn display_upload_and_download(bandwidth: &impl Bandwidth, total: bool) -> String { format!( "{} / {}", DisplayBandwidth { bandwidth: bandwidth.get_total_bytes_uploaded() as f64, as_rate: !total, }, DisplayBandwidth { bandwidth: bandwidth.get_total_bytes_downloaded() as f64, as_rate: !total, }, ) } pub enum ColumnCount { Two, Three, } impl ColumnCount { pub fn as_u16(&self) -> u16 { match &self { ColumnCount::Two => 2, ColumnCount::Three => 3, } } } pub struct ColumnData { column_count: ColumnCount, column_widths: Vec<u16>, } pub struct Table<'a> { title: &'a str, column_names: &'a [&'a str], rows: Vec<Vec<String>>, breakpoints: BTreeMap<u16, ColumnData>, } fn truncate_iter_to_unicode_width<Input, Collect>(iter: Input, width: usize) -> Collect where Input: Iterator<Item = char>, Collect: FromIterator<char>, { let mut chunk_width = 0; iter.take_while(|ch| { chunk_width += ch.width().unwrap_or(0); chunk_width <= width }) .collect() } fn truncate_middle(row: &str, max_length: u16) -> String { if max_length < 6 { truncate_iter_to_unicode_width(row.chars(), max_length as usize) } else if row.len() as u16 > max_length { let split_point = (max_length as usize / 2) - 3; // why 3? 5 is the max size of the truncation text ([...] or [..]), 3 is ~5/2 let first_slice = truncate_iter_to_unicode_width::<_, String>(row.chars(), split_point); let second_slice = truncate_iter_to_unicode_width::<_, Vec<_>>(row.chars().rev(), split_point) .into_iter() .rev() .collect::<String>(); if max_length % 2 == 0 { format!("{first_slice}[...]{second_slice}") } else { format!("{first_slice}[..]{second_slice}") } } else { row.to_string() } } impl<'a> Table<'a> { pub fn create_connections_table(state: &UIState, ip_to_host: &HashMap<IpAddr, String>) -> Self { let connections_rows = state .connections .iter() .map(|(connection, connection_data)| { vec![ display_connection_string( connection, ip_to_host, &connection_data.interface_name, ), connection_data.process_name.to_string(), display_upload_and_download(connection_data, state.cumulative_mode), ] }) .collect(); let connections_title = "Utilization by connection"; let connections_column_names = &["Connection", "Process", "Up / Down"]; let mut breakpoints = BTreeMap::new(); breakpoints.insert( 0, ColumnData { column_count: ColumnCount::Two, column_widths: vec![20, 23], }, ); breakpoints.insert( 70, ColumnData { column_count: ColumnCount::Three, column_widths: vec![30, 12, 23], }, ); breakpoints.insert( 100, ColumnData { column_count: ColumnCount::Three, column_widths: vec![60, 12, 23], }, ); breakpoints.insert( 140, ColumnData { column_count: ColumnCount::Three, column_widths: vec![100, 12, 23], }, ); Table { title: connections_title, column_names: connections_column_names, rows: connections_rows, breakpoints, } } pub fn create_processes_table(state: &UIState) -> Self { let processes_rows = state .processes .iter() .map(|(process_name, data_for_process)| { vec![ (*process_name).to_string(), data_for_process.connection_count.to_string(), display_upload_and_download(data_for_process, state.cumulative_mode), ] }) .collect(); let processes_title = "Utilization by process name"; let processes_column_names = &["Process", "Connections", "Up / Down"]; let mut breakpoints = BTreeMap::new(); breakpoints.insert( 0, ColumnData { column_count: ColumnCount::Two, column_widths: vec![12, 23], }, ); breakpoints.insert( 50, ColumnData { column_count: ColumnCount::Three, column_widths: vec![12, 12, 23], }, ); breakpoints.insert( 100, ColumnData { column_count: ColumnCount::Three, column_widths: vec![40, 12, 23], }, ); breakpoints.insert( 140, ColumnData { column_count: ColumnCount::Three, column_widths: vec![40, 12, 23], }, ); Table { title: processes_title, column_names: processes_column_names, rows: processes_rows, breakpoints, } } pub fn create_remote_addresses_table( state: &UIState, ip_to_host: &HashMap<IpAddr, String>, ) -> Self { let remote_addresses_rows = state .remote_addresses .iter() .map(|(remote_address, data_for_remote_address)| { let remote_address = display_ip_or_host(*remote_address, ip_to_host); vec![ remote_address, data_for_remote_address.connection_count.to_string(), display_upload_and_download(data_for_remote_address, state.cumulative_mode), ] }) .collect(); let remote_addresses_title = "Utilization by remote address"; let remote_addresses_column_names = &["Remote Address", "Connections", "Up / Down"]; let mut breakpoints = BTreeMap::new(); breakpoints.insert( 0, ColumnData { column_count: ColumnCount::Two, column_widths: vec![15, 20], }, ); breakpoints.insert( 70, ColumnData { column_count: ColumnCount::Three, column_widths: vec![30, 12, 23], }, ); breakpoints.insert( 100, ColumnData { column_count: ColumnCount::Three, column_widths: vec![60, 12, 23], }, ); breakpoints.insert( 140, ColumnData { column_count: ColumnCount::Three, column_widths: vec![100, 12, 23], }, ); Table { title: remote_addresses_title, column_names: remote_addresses_column_names, rows: remote_addresses_rows, breakpoints, } } pub fn render(&self, frame: &mut Frame<impl Backend>, rect: Rect) { let mut column_spacing: u16 = 0; let mut widths = &vec![]; let mut column_count: &ColumnCount = &ColumnCount::Three; for (width_breakpoint, column_data) in self.breakpoints.iter() { if *width_breakpoint < rect.width { widths = &column_data.column_widths; column_count = &column_data.column_count; let total_column_width: u16 = widths.iter().sum(); if rect.width < total_column_width - column_count.as_u16() { column_spacing = 0; } else { column_spacing = (rect.width - total_column_width) / column_count.as_u16(); } } } let column_names = match column_count { ColumnCount::Two => { vec![self.column_names[0], self.column_names[2]] // always lose the middle column when needed } ColumnCount::Three => vec![ self.column_names[0], self.column_names[1], self.column_names[2], ], }; let rows = self.rows.iter().map(|row| match column_count { ColumnCount::Two => vec![ truncate_middle(&row[0], widths[0]), truncate_middle(&row[2], widths[1]), ], ColumnCount::Three => vec![ truncate_middle(&row[0], widths[0]), truncate_middle(&row[1], widths[1]), truncate_middle(&row[2], widths[2]), ], }); let table_rows = rows.map(|row| Row::new(row).style(Style::default())); let width_constraints: Vec<Constraint> = widths.iter().map(|w| Constraint::Length(*w)).collect(); let table = ratatui::widgets::Table::new(table_rows) .block(Block::default().title(self.title).borders(Borders::ALL)) .header(Row::new(column_names).style(Style::default().fg(Color::Yellow))) .widths(&width_constraints) .style(Style::default()) .column_spacing(column_spacing); frame.render_widget(table, rect); } }
use std::borrow::{Borrow, Cow}; use std::ffi::{OsStr, OsString}; use std::fmt; use std::fs; use std::io; use std::iter::FusedIterator; use std::ops::Deref; use std::path::*; use std::rc::Rc; use std::sync::Arc; // NB: Internal PathBuf must only contain utf8 data #[derive(Clone, Default, Hash)] #[repr(transparent)] pub struct Utf8PathBuf(PathBuf); impl Utf8PathBuf { pub fn new() -> Utf8PathBuf { Utf8PathBuf(PathBuf::new()) } pub fn from_path_buf(path: PathBuf) -> Result<Utf8PathBuf, PathBuf> { match path.into_os_string().into_string() { Ok(string) => Ok(Utf8PathBuf::from(string)), Err(os_string) => Err(PathBuf::from(os_string)), } } pub fn with_capacity(capacity: usize) -> Utf8PathBuf { Utf8PathBuf(PathBuf::with_capacity(capacity)) } pub fn as_path(&self) -> &Utf8Path { unsafe { Utf8Path::assert_utf8(&*self.0) } } pub fn push(&mut self, path: impl AsRef<Utf8Path>) { self.0.push(&path.as_ref().0) } pub fn pop(&mut self) -> bool { self.0.pop() } pub fn set_file_name(&mut self, file_name: impl AsRef<str>) { self.0.set_file_name(file_name.as_ref()) } pub fn set_extension(&mut self, extension: impl AsRef<str>) -> bool { self.0.set_extension(extension.as_ref()) } pub fn into_string(self) -> String { self.into_os_string().into_string().unwrap() } pub fn into_os_string(self) -> OsString { self.0.into_os_string() } pub fn into_boxed_path(self) -> Box<Utf8Path> { unsafe { Box::from_raw(Box::into_raw(self.0.into_boxed_path()) as *mut Utf8Path) } } pub fn capacity(&self) -> usize { self.0.capacity() } pub fn clear(&mut self) { self.0.clear() } pub fn reserve(&mut self, additional: usize) { self.0.reserve(additional) } pub fn reserve_exact(&mut self, additional: usize) { self.0.reserve_exact(additional) } pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit() } } impl Deref for Utf8PathBuf { type Target = Utf8Path; fn deref(&self) -> &Utf8Path { self.as_path() } } impl fmt::Debug for Utf8PathBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl fmt::Display for Utf8PathBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl<P: AsRef<Utf8Path>> Extend<P> for Utf8PathBuf { fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) { for path in iter { self.push(path); } } } // NB: Internal Path must only contain utf8 data #[repr(transparent)] #[derive(Hash)] pub struct Utf8Path(Path); impl Utf8Path { pub fn new(s: &(impl AsRef<str> + ?Sized)) -> &Utf8Path { unsafe { Utf8Path::assert_utf8(Path::new(s.as_ref())) } } pub fn from_path(path: &Path) -> Option<&Utf8Path> { path.as_os_str().to_str().map(|s| Utf8Path::new(s)) } pub fn as_str(&self) -> &str { unsafe { assert_utf8(self.as_os_str()) } } pub fn as_os_str(&self) -> &OsStr { self.0.as_os_str() } pub fn to_path_buf(&self) -> Utf8PathBuf { Utf8PathBuf(self.0.to_path_buf()) } pub fn is_absolute(&self) -> bool { self.0.is_absolute() } pub fn is_relative(&self) -> bool { self.0.is_relative() } pub fn has_root(&self) -> bool { self.0.has_root() } pub fn parent(&self) -> Option<&Utf8Path> { self.0.parent().map(|path| unsafe { Utf8Path::assert_utf8(path) }) } pub fn ancestors(&self) -> Utf8Ancestors<'_> { Utf8Ancestors(self.0.ancestors()) } pub fn file_name(&self) -> Option<&str> { self.0.file_name().map(|s| unsafe { assert_utf8(s) }) } pub fn strip_prefix(&self, base: impl AsRef<Path>) -> Result<&Utf8Path, StripPrefixError> { self.0.strip_prefix(base).map(|path| unsafe { Utf8Path::assert_utf8(path) }) } pub fn starts_with(&self, base: impl AsRef<Path>) -> bool { self.0.starts_with(base) } pub fn ends_with(&self, base: impl AsRef<Path>) -> bool { self.0.ends_with(base) } pub fn file_stem(&self) -> Option<&str> { self.0.file_stem().map(|s| unsafe { assert_utf8(s) }) } pub fn extension(&self) -> Option<&str> { self.0.extension().map(|s| unsafe { assert_utf8(s) }) } pub fn join(&self, path: impl AsRef<Utf8Path>) -> Utf8PathBuf { Utf8PathBuf(self.0.join(&path.as_ref().0)) } pub fn join_os(&self, path: impl AsRef<Path>) -> PathBuf { self.0.join(path) } pub fn with_file_name(&self, file_name: impl AsRef<str>) -> Utf8PathBuf { Utf8PathBuf(self.0.with_file_name(file_name.as_ref())) } pub fn with_extension(&self, extension: impl AsRef<str>) -> Utf8PathBuf { Utf8PathBuf(self.0.with_extension(extension.as_ref())) } pub fn components(&self) -> Utf8Components { Utf8Components(self.0.components()) } pub fn metadata(&self) -> io::Result<fs::Metadata> { self.0.metadata() } pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> { self.0.symlink_metadata() } pub fn canonicalize(&self) -> io::Result<PathBuf> { self.0.canonicalize() } pub fn read_link(&self) -> io::Result<PathBuf> { self.0.read_link() } pub fn read_dir(&self) -> io::Result<fs::ReadDir> { self.0.read_dir() } pub fn exists(&self) -> bool { self.0.exists() } pub fn is_file(&self) -> bool { self.0.is_file() } pub fn is_dir(&self) -> bool { self.0.is_dir() } pub fn into_path_buf(self: Box<Utf8Path>) -> Utf8PathBuf { unsafe { Utf8PathBuf(Box::from_raw(Box::into_raw(self) as *mut Path).into_path_buf()) } } // invariant: Path must be guaranteed to be utf-8 data unsafe fn assert_utf8(path: &Path) -> &Utf8Path { &*(path as *const Path as *const Utf8Path) } } impl fmt::Display for Utf8Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl fmt::Debug for Utf8Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_str(), f) } } #[derive(Copy, Clone)] #[repr(transparent)] pub struct Utf8Ancestors<'a>(Ancestors<'a>); impl<'a> fmt::Debug for Utf8Ancestors<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl<'a> Iterator for Utf8Ancestors<'a> { type Item = &'a Utf8Path; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|path| unsafe { Utf8Path::assert_utf8(path) }) } } impl<'a> FusedIterator for Utf8Ancestors<'a> { } #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)] pub struct Utf8Components<'a>(Components<'a>); impl<'a> Utf8Components<'a> { pub fn as_path(&self) -> &'a Utf8Path { unsafe { Utf8Path::assert_utf8(self.0.as_path()) } } } impl<'a> Iterator for Utf8Components<'a> { type Item = Utf8Component<'a>; fn next(&mut self) -> Option<Self::Item> { self.0.next().map(|component| unsafe { Utf8Component::new(component) }) } } impl<'a> FusedIterator for Utf8Components<'a> { } impl<'a> DoubleEndedIterator for Utf8Components<'a> { fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back().map(|component| unsafe { Utf8Component::new(component) }) } } impl<'a> fmt::Debug for Utf8Components<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum Utf8Component<'a> { Prefix(Utf8PrefixComponent<'a>), RootDir, CurDir, ParentDir, Normal(&'a str), } impl<'a> Utf8Component<'a> { unsafe fn new(component: Component<'a>) -> Utf8Component<'a> { match component { Component::Prefix(prefix) => Utf8Component::Prefix(Utf8PrefixComponent(prefix)), Component::RootDir => Utf8Component::RootDir, Component::CurDir => Utf8Component::CurDir, Component::ParentDir => Utf8Component::ParentDir, Component::Normal(s) => Utf8Component::Normal(assert_utf8(s)), } } pub fn as_str(&self) -> &'a str { unsafe { assert_utf8(self.as_os_str()) } } pub fn as_os_str(&self) -> &'a OsStr { match *self { Utf8Component::Prefix(prefix) => prefix.as_os_str(), Utf8Component::RootDir => Component::RootDir.as_os_str(), Utf8Component::CurDir => Component::CurDir.as_os_str(), Utf8Component::ParentDir => Component::ParentDir.as_os_str(), Utf8Component::Normal(s) => OsStr::new(s), } } } impl<'a> fmt::Debug for Utf8Component<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_os_str(), f) } } impl<'a> fmt::Display for Utf8Component<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } #[repr(transparent)] #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct Utf8PrefixComponent<'a>(PrefixComponent<'a>); impl<'a> Utf8PrefixComponent<'a> { // TODO kind pub fn as_str(&self) -> &'a str { unsafe { assert_utf8(self.as_os_str()) } } pub fn as_os_str(&self) -> &'a OsStr { self.0.as_os_str() } } impl<'a> fmt::Debug for Utf8PrefixComponent<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl<'a> fmt::Display for Utf8PrefixComponent<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl From<String> for Utf8PathBuf { fn from(string: String) -> Utf8PathBuf { Utf8PathBuf(string.into()) } } impl From<Box<Utf8Path>> for Utf8PathBuf { fn from(path: Box<Utf8Path>) -> Utf8PathBuf { path.into_path_buf() } } impl<'a> From<Cow<'a, Utf8Path>> for Utf8PathBuf { fn from(path: Cow<'a, Utf8Path>) -> Utf8PathBuf { path.into_owned() } } impl From<Utf8PathBuf> for String { fn from(path: Utf8PathBuf) -> String { path.into_string() } } impl From<Utf8PathBuf> for PathBuf { fn from(path: Utf8PathBuf) -> PathBuf { path.0 } } impl From<Utf8PathBuf> for OsString { fn from(path: Utf8PathBuf) -> OsString { path.into_os_string() } } impl<'a> From<Utf8PathBuf> for Cow<'a, Utf8Path> { fn from(path: Utf8PathBuf) -> Cow<'a, Utf8Path> { Cow::Owned(path) } } impl From<Utf8PathBuf> for Arc<Utf8Path> { fn from(path: Utf8PathBuf) -> Arc<Utf8Path> { let arc: Arc<Path> = Arc::from(path.0); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Utf8Path) } } } impl From<Utf8PathBuf> for Rc<Utf8Path> { fn from(path: Utf8PathBuf) -> Rc<Utf8Path> { let rc: Rc<Path> = Rc::from(path.0); unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Utf8Path) } } } impl AsRef<Utf8Path> for Utf8Path { fn as_ref(&self) -> &Utf8Path { self } } impl AsRef<Utf8Path> for Utf8PathBuf { fn as_ref(&self) -> &Utf8Path { self.as_path() } } impl AsRef<Utf8Path> for str { fn as_ref(&self) -> &Utf8Path { Utf8Path::new(self) } } impl AsRef<Utf8Path> for String { fn as_ref(&self) -> &Utf8Path { Utf8Path::new(self) } } impl AsRef<Path> for Utf8Path { fn as_ref(&self) -> &Path { &self.0 } } impl AsRef<Path> for Utf8PathBuf { fn as_ref(&self) -> &Path { &*self.0 } } impl AsRef<str> for Utf8Path { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<str> for Utf8PathBuf { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<OsStr> for Utf8Path { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl AsRef<OsStr> for Utf8PathBuf { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl Borrow<Utf8Path> for Utf8PathBuf { fn borrow(&self) -> &Utf8Path { self.as_path() } } impl ToOwned for Utf8Path { type Owned = Utf8PathBuf; fn to_owned(&self) -> Utf8PathBuf { self.to_path_buf() } } // invariant: OsStr must be guaranteed to be utf8 data unsafe fn assert_utf8(string: &OsStr) -> &str { &*(string as *const OsStr as *const str) }
use super::util::NiceDuration; /// Summary statistics produced at the end of a search. /// /// When statistics are reported by a printer, they correspond to all searches /// executed with that printer. #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Stats { elapsed: NiceDuration, searches: u64, searches_with_match: u64, bytes_searched: u64, bytes_printed: u64, matched_lines: u64, matches: u64, }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Expression { #[serde(rename = "type")] pub type_: expression::Type, pub value: String, } pub mod expression { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Expression, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecureString { #[serde(flatten)] pub secret_base: SecretBase, pub value: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureKeyVaultSecretReference { #[serde(flatten)] pub secret_base: SecretBase, pub store: LinkedServiceReference, #[serde(rename = "secretName")] pub secret_name: serde_json::Value, #[serde(rename = "secretVersion", default, skip_serializing_if = "Option::is_none")] pub secret_version: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecretBase { #[serde(rename = "type")] pub type_: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryListResponse { pub value: Vec<Factory>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeListResponse { pub value: Vec<IntegrationRuntimeResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeReference { #[serde(rename = "type")] pub type_: integration_runtime_reference::Type, #[serde(rename = "referenceName")] pub reference_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterValueSpecification>, } pub mod integration_runtime_reference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { IntegrationRuntimeReference, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeResource { #[serde(flatten)] pub sub_resource: SubResource, pub properties: IntegrationRuntime, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeStatusResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, pub properties: IntegrationRuntimeStatus, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeStatusListResponse { pub value: Vec<IntegrationRuntimeStatusResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateIntegrationRuntimeRequest { #[serde(rename = "autoUpdate", default, skip_serializing_if = "Option::is_none")] pub auto_update: Option<IntegrationRuntimeAutoUpdate>, #[serde(rename = "updateDelayOffset", default, skip_serializing_if = "Option::is_none")] pub update_delay_offset: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateIntegrationRuntimeNodeRequest { #[serde(rename = "concurrentJobsLimit", default, skip_serializing_if = "Option::is_none")] pub concurrent_jobs_limit: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LinkedServiceListResponse { pub value: Vec<LinkedServiceResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DatasetListResponse { pub value: Vec<DatasetResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineListResponse { pub value: Vec<PipelineResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerListResponse { pub value: Vec<TriggerResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CreateRunResponse { #[serde(rename = "runId")] pub run_id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { pub code: String, pub message: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorResponse>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ParameterDefinitionSpecification {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ParameterSpecification { #[serde(rename = "type")] pub type_: parameter_specification::Type, #[serde(rename = "defaultValue", default, skip_serializing_if = "Option::is_none")] pub default_value: Option<serde_json::Value>, } pub mod parameter_specification { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Object, String, Int, Float, Bool, Array, SecureString, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ParameterValueSpecification {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryVstsConfiguration { #[serde(rename = "accountName", default, skip_serializing_if = "Option::is_none")] pub account_name: Option<String>, #[serde(rename = "projectName", default, skip_serializing_if = "Option::is_none")] pub project_name: Option<String>, #[serde(rename = "repositoryName", default, skip_serializing_if = "Option::is_none")] pub repository_name: Option<String>, #[serde(rename = "collaborationBranch", default, skip_serializing_if = "Option::is_none")] pub collaboration_branch: Option<String>, #[serde(rename = "rootFolder", default, skip_serializing_if = "Option::is_none")] pub root_folder: Option<String>, #[serde(rename = "lastCommitId", default, skip_serializing_if = "Option::is_none")] pub last_commit_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryRepoUpdate { #[serde(rename = "factoryResourceId", default, skip_serializing_if = "Option::is_none")] pub factory_resource_id: Option<String>, #[serde(rename = "resourceGroupName", default, skip_serializing_if = "Option::is_none")] pub resource_group_name: Option<String>, #[serde(rename = "vstsConfiguration", default, skip_serializing_if = "Option::is_none")] pub vsts_configuration: Option<FactoryVstsConfiguration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "createTime", default, skip_serializing_if = "Option::is_none")] pub create_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(rename = "vstsConfiguration", default, skip_serializing_if = "Option::is_none")] pub vsts_configuration: Option<FactoryVstsConfiguration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineResource { #[serde(flatten)] pub sub_resource: SubResource, pub properties: Pipeline, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineReference { #[serde(rename = "type")] pub type_: pipeline_reference::Type, #[serde(rename = "referenceName")] pub reference_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } pub mod pipeline_reference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { PipelineReference, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerPipelineReference { #[serde(rename = "pipelineReference", default, skip_serializing_if = "Option::is_none")] pub pipeline_reference: Option<PipelineReference>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterValueSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerResource { #[serde(flatten)] pub sub_resource: SubResource, pub properties: Trigger, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Factory { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<FactoryIdentity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<FactoryProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<FactoryIdentity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FactoryIdentity { #[serde(rename = "type")] pub type_: factory_identity::Type, #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } pub mod factory_identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DatasetReference { #[serde(rename = "type")] pub type_: dataset_reference::Type, #[serde(rename = "referenceName")] pub reference_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterValueSpecification>, } pub mod dataset_reference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { DatasetReference, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DatasetResource { #[serde(flatten)] pub sub_resource: SubResource, pub properties: Dataset, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LinkedServiceReference { #[serde(rename = "type")] pub type_: linked_service_reference::Type, #[serde(rename = "referenceName")] pub reference_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterValueSpecification>, } pub mod linked_service_reference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { LinkedServiceReference, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LinkedServiceResource { #[serde(flatten)] pub sub_resource: SubResource, pub properties: LinkedService, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunFilterParameters { #[serde(rename = "continuationToken", default, skip_serializing_if = "Option::is_none")] pub continuation_token: Option<String>, #[serde(rename = "lastUpdatedAfter")] pub last_updated_after: String, #[serde(rename = "lastUpdatedBefore")] pub last_updated_before: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub filters: Vec<PipelineRunQueryFilter>, #[serde(rename = "orderBy", default, skip_serializing_if = "Vec::is_empty")] pub order_by: Vec<PipelineRunQueryOrderBy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunQueryFilter { pub operand: pipeline_run_query_filter::Operand, pub operator: pipeline_run_query_filter::Operator, pub values: Vec<String>, } pub mod pipeline_run_query_filter { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Operand { PipelineName, Status, RunStart, RunEnd, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Operator { Equals, NotEquals, In, NotIn, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunQueryOrderBy { #[serde(rename = "orderBy")] pub order_by: pipeline_run_query_order_by::OrderBy, pub order: pipeline_run_query_order_by::Order, } pub mod pipeline_run_query_order_by { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OrderBy { RunStart, RunEnd, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Order { #[serde(rename = "ASC")] Asc, #[serde(rename = "DESC")] Desc, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunQueryResponse { pub value: Vec<PipelineRun>, #[serde(rename = "continuationToken", default, skip_serializing_if = "Option::is_none")] pub continuation_token: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRun { #[serde(rename = "runId", default, skip_serializing_if = "Option::is_none")] pub run_id: Option<String>, #[serde(rename = "pipelineName", default, skip_serializing_if = "Option::is_none")] pub pipeline_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<serde_json::Value>, #[serde(rename = "invokedBy", default, skip_serializing_if = "Option::is_none")] pub invoked_by: Option<PipelineRunInvokedBy>, #[serde(rename = "lastUpdated", default, skip_serializing_if = "Option::is_none")] pub last_updated: Option<String>, #[serde(rename = "runStart", default, skip_serializing_if = "Option::is_none")] pub run_start: Option<String>, #[serde(rename = "runEnd", default, skip_serializing_if = "Option::is_none")] pub run_end: Option<String>, #[serde(rename = "durationInMs", default, skip_serializing_if = "Option::is_none")] pub duration_in_ms: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunInvokedBy { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActivityRunsListResponse { pub value: Vec<ActivityRun>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActivityRun { #[serde(rename = "pipelineName", default, skip_serializing_if = "Option::is_none")] pub pipeline_name: Option<String>, #[serde(rename = "pipelineRunId", default, skip_serializing_if = "Option::is_none")] pub pipeline_run_id: Option<String>, #[serde(rename = "activityName", default, skip_serializing_if = "Option::is_none")] pub activity_name: Option<String>, #[serde(rename = "activityType", default, skip_serializing_if = "Option::is_none")] pub activity_type: Option<String>, #[serde(rename = "activityRunId", default, skip_serializing_if = "Option::is_none")] pub activity_run_id: Option<String>, #[serde(rename = "linkedServiceName", default, skip_serializing_if = "Option::is_none")] pub linked_service_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "activityRunStart", default, skip_serializing_if = "Option::is_none")] pub activity_run_start: Option<String>, #[serde(rename = "activityRunEnd", default, skip_serializing_if = "Option::is_none")] pub activity_run_end: Option<String>, #[serde(rename = "durationInMs", default, skip_serializing_if = "Option::is_none")] pub duration_in_ms: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub input: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub output: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerRunListResponse { pub value: Vec<TriggerRun>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerRun { #[serde(rename = "triggerRunId", default, skip_serializing_if = "Option::is_none")] pub trigger_run_id: Option<String>, #[serde(rename = "triggerName", default, skip_serializing_if = "Option::is_none")] pub trigger_name: Option<String>, #[serde(rename = "triggerType", default, skip_serializing_if = "Option::is_none")] pub trigger_type: Option<String>, #[serde(rename = "triggerRunTimestamp", default, skip_serializing_if = "Option::is_none")] pub trigger_run_timestamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<trigger_run::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, #[serde(rename = "triggeredPipelines", default, skip_serializing_if = "Option::is_none")] pub triggered_pipelines: Option<serde_json::Value>, } pub mod trigger_run { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Succeeded, Failed, Inprogress, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OperationProperties>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationProperties { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<OperationServiceSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationServiceSpecification { #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub log_specifications: Vec<OperationLogSpecification>, #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<OperationMetricSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationLogSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationMetricSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(rename = "enableRegionalMdmAccount", default, skip_serializing_if = "Option::is_none")] pub enable_regional_mdm_account: Option<String>, #[serde(rename = "sourceMdmAccount", default, skip_serializing_if = "Option::is_none")] pub source_mdm_account: Option<String>, #[serde(rename = "sourceMdmNamespace", default, skip_serializing_if = "Option::is_none")] pub source_mdm_namespace: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub availabilities: Vec<OperationMetricAvailability>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationMetricAvailability { #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeConnectionInfo { #[serde(rename = "serviceToken", default, skip_serializing_if = "Option::is_none")] pub service_token: Option<String>, #[serde(rename = "identityCertThumbprint", default, skip_serializing_if = "Option::is_none")] pub identity_cert_thumbprint: Option<String>, #[serde(rename = "hostServiceUri", default, skip_serializing_if = "Option::is_none")] pub host_service_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(rename = "publicKey", default, skip_serializing_if = "Option::is_none")] pub public_key: Option<String>, #[serde(rename = "isIdentityCertExprired", default, skip_serializing_if = "Option::is_none")] pub is_identity_cert_exprired: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeRegenerateKeyParameters { #[serde(rename = "keyName", default, skip_serializing_if = "Option::is_none")] pub key_name: Option<integration_runtime_regenerate_key_parameters::KeyName>, } pub mod integration_runtime_regenerate_key_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeyName { #[serde(rename = "authKey1")] AuthKey1, #[serde(rename = "authKey2")] AuthKey2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeAuthKeys { #[serde(rename = "authKey1", default, skip_serializing_if = "Option::is_none")] pub auth_key1: Option<String>, #[serde(rename = "authKey2", default, skip_serializing_if = "Option::is_none")] pub auth_key2: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeRemoveNodeRequest { #[serde(rename = "nodeName", default, skip_serializing_if = "Option::is_none")] pub node_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeMonitoringData { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub nodes: Vec<IntegrationRuntimeNodeMonitoringData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeNodeMonitoringData { #[serde(rename = "nodeName", default, skip_serializing_if = "Option::is_none")] pub node_name: Option<String>, #[serde(rename = "availableMemoryInMB", default, skip_serializing_if = "Option::is_none")] pub available_memory_in_mb: Option<i64>, #[serde(rename = "cpuUtilization", default, skip_serializing_if = "Option::is_none")] pub cpu_utilization: Option<f64>, #[serde(rename = "concurrentJobsLimit", default, skip_serializing_if = "Option::is_none")] pub concurrent_jobs_limit: Option<i64>, #[serde(rename = "concurrentJobsRunning", default, skip_serializing_if = "Option::is_none")] pub concurrent_jobs_running: Option<i64>, #[serde(rename = "maxConcurrentJobs", default, skip_serializing_if = "Option::is_none")] pub max_concurrent_jobs: Option<i64>, #[serde(rename = "sentBytes", default, skip_serializing_if = "Option::is_none")] pub sent_bytes: Option<f64>, #[serde(rename = "receivedBytes", default, skip_serializing_if = "Option::is_none")] pub received_bytes: Option<f64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SelfHostedIntegrationRuntimeNode { #[serde(rename = "nodeName", default, skip_serializing_if = "Option::is_none")] pub node_name: Option<String>, #[serde(rename = "machineName", default, skip_serializing_if = "Option::is_none")] pub machine_name: Option<String>, #[serde(rename = "hostServiceUri", default, skip_serializing_if = "Option::is_none")] pub host_service_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<self_hosted_integration_runtime_node::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capabilities: Option<serde_json::Value>, #[serde(rename = "versionStatus", default, skip_serializing_if = "Option::is_none")] pub version_status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(rename = "registerTime", default, skip_serializing_if = "Option::is_none")] pub register_time: Option<String>, #[serde(rename = "lastConnectTime", default, skip_serializing_if = "Option::is_none")] pub last_connect_time: Option<String>, #[serde(rename = "expiryTime", default, skip_serializing_if = "Option::is_none")] pub expiry_time: Option<String>, #[serde(rename = "lastStartTime", default, skip_serializing_if = "Option::is_none")] pub last_start_time: Option<String>, #[serde(rename = "lastStopTime", default, skip_serializing_if = "Option::is_none")] pub last_stop_time: Option<String>, #[serde(rename = "lastUpdateResult", default, skip_serializing_if = "Option::is_none")] pub last_update_result: Option<self_hosted_integration_runtime_node::LastUpdateResult>, #[serde(rename = "lastStartUpdateTime", default, skip_serializing_if = "Option::is_none")] pub last_start_update_time: Option<String>, #[serde(rename = "lastEndUpdateTime", default, skip_serializing_if = "Option::is_none")] pub last_end_update_time: Option<String>, #[serde(rename = "isActiveDispatcher", default, skip_serializing_if = "Option::is_none")] pub is_active_dispatcher: Option<bool>, #[serde(rename = "concurrentJobsLimit", default, skip_serializing_if = "Option::is_none")] pub concurrent_jobs_limit: Option<i64>, #[serde(rename = "maxConcurrentJobs", default, skip_serializing_if = "Option::is_none")] pub max_concurrent_jobs: Option<i64>, } pub mod self_hosted_integration_runtime_node { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { NeedRegistration, Online, Limited, Offline, Upgrading, Initializing, InitializeFailed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastUpdateResult { Succeed, Fail, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeNodeIpAddress { #[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")] pub ip_address: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntime { #[serde(rename = "type")] pub type_: IntegrationRuntimeType, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IntegrationRuntimeType { Managed, SelfHosted, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IntegrationRuntimeStatus { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<IntegrationRuntimeType>, #[serde(rename = "dataFactoryName", default, skip_serializing_if = "Option::is_none")] pub data_factory_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<IntegrationRuntimeState>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IntegrationRuntimeState { Initial, Stopped, Started, Starting, Stopping, NeedRegistration, Online, Limited, Offline, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum IntegrationRuntimeAutoUpdate { On, Off, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Pipeline { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub activities: Vec<Activity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterDefinitionSpecification>, #[serde(default, skip_serializing_if = "Option::is_none")] pub concurrency: Option<i64>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub annotations: Vec<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Activity { pub name: String, #[serde(rename = "type")] pub type_: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "dependsOn", default, skip_serializing_if = "Vec::is_empty")] pub depends_on: Vec<ActivityDependency>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActivityDependency { pub activity: String, #[serde(rename = "dependencyConditions")] pub dependency_conditions: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Trigger { #[serde(rename = "type")] pub type_: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "runtimeState", default, skip_serializing_if = "Option::is_none")] pub runtime_state: Option<TriggerRuntimeState>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TriggerRuntimeState { Started, Stopped, Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dataset { #[serde(rename = "type")] pub type_: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub structure: Option<serde_json::Value>, #[serde(rename = "linkedServiceName")] pub linked_service_name: LinkedServiceReference, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterDefinitionSpecification>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub annotations: Vec<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LinkedService { #[serde(rename = "type")] pub type_: String, #[serde(rename = "connectVia", default, skip_serializing_if = "Option::is_none")] pub connect_via: Option<IntegrationRuntimeReference>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<ParameterDefinitionSpecification>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub annotations: Vec<serde_json::Value>, }
#[doc = "Register `GTZC1_TZIC_IER2` reader"] pub type R = crate::R<GTZC1_TZIC_IER2_SPEC>; #[doc = "Register `GTZC1_TZIC_IER2` writer"] pub type W = crate::W<GTZC1_TZIC_IER2_SPEC>; #[doc = "Field `FDCAN1IE` reader - illegal access interrupt enable for FDCAN1"] pub type FDCAN1IE_R = crate::BitReader; #[doc = "Field `FDCAN1IE` writer - illegal access interrupt enable for FDCAN1"] pub type FDCAN1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `FDCAN2IE` reader - illegal access interrupt enable for FDCAN2"] pub type FDCAN2IE_R = crate::BitReader; #[doc = "Field `FDCAN2IE` writer - illegal access interrupt enable for FDCAN2"] pub type FDCAN2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UCPDIE` reader - illegal access interrupt enable for UCPD"] pub type UCPDIE_R = crate::BitReader; #[doc = "Field `UCPDIE` writer - illegal access interrupt enable for UCPD"] pub type UCPDIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM1IE` reader - illegal access interrupt enable for TIM1"] pub type TIM1IE_R = crate::BitReader; #[doc = "Field `TIM1IE` writer - illegal access interrupt enable for TIM1"] pub type TIM1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI1IE` reader - illegal access interrupt enable for SPI1"] pub type SPI1IE_R = crate::BitReader; #[doc = "Field `SPI1IE` writer - illegal access interrupt enable for SPI1"] pub type SPI1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM8IE` reader - illegal access interrupt enable for TIM8"] pub type TIM8IE_R = crate::BitReader; #[doc = "Field `TIM8IE` writer - illegal access interrupt enable for TIM8"] pub type TIM8IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART1IE` reader - illegal access interrupt enable for USART1"] pub type USART1IE_R = crate::BitReader; #[doc = "Field `USART1IE` writer - illegal access interrupt enable for USART1"] pub type USART1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM15IE` reader - illegal access interrupt enable for TIM15"] pub type TIM15IE_R = crate::BitReader; #[doc = "Field `TIM15IE` writer - illegal access interrupt enable for TIM15"] pub type TIM15IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM16IE` reader - illegal access interrupt enable for TIM16"] pub type TIM16IE_R = crate::BitReader; #[doc = "Field `TIM16IE` writer - illegal access interrupt enable for TIM16"] pub type TIM16IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM17IE` reader - illegal access interrupt enable for TIM17"] pub type TIM17IE_R = crate::BitReader; #[doc = "Field `TIM17IE` writer - illegal access interrupt enable for TIM17"] pub type TIM17IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI4IE` reader - illegal access interrupt enable for SPI4"] pub type SPI4IE_R = crate::BitReader; #[doc = "Field `SPI4IE` writer - illegal access interrupt enable for SPI4"] pub type SPI4IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI6IE` reader - illegal access interrupt enable for SPI6"] pub type SPI6IE_R = crate::BitReader; #[doc = "Field `SPI6IE` writer - illegal access interrupt enable for SPI6"] pub type SPI6IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SAI1IE` reader - illegal access interrupt enable for SAI1"] pub type SAI1IE_R = crate::BitReader; #[doc = "Field `SAI1IE` writer - illegal access interrupt enable for SAI1"] pub type SAI1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SAI2IE` reader - illegal access interrupt enable for SAI2"] pub type SAI2IE_R = crate::BitReader; #[doc = "Field `SAI2IE` writer - illegal access interrupt enable for SAI2"] pub type SAI2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USBIE` reader - illegal access interrupt enable for USB"] pub type USBIE_R = crate::BitReader; #[doc = "Field `USBIE` writer - illegal access interrupt enable for USB"] pub type USBIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI5IE` reader - illegal access interrupt enable for SPI5"] pub type SPI5IE_R = crate::BitReader; #[doc = "Field `SPI5IE` writer - illegal access interrupt enable for SPI5"] pub type SPI5IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPUART1IE` reader - illegal access interrupt enable for LPUART"] pub type LPUART1IE_R = crate::BitReader; #[doc = "Field `LPUART1IE` writer - illegal access interrupt enable for LPUART"] pub type LPUART1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C3IE` reader - illegal access interrupt enable for I2C3"] pub type I2C3IE_R = crate::BitReader; #[doc = "Field `I2C3IE` writer - illegal access interrupt enable for I2C3"] pub type I2C3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I2C4IE` reader - illegal access interrupt enable for I2C4"] pub type I2C4IE_R = crate::BitReader; #[doc = "Field `I2C4IE` writer - illegal access interrupt enable for I2C4"] pub type I2C4IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM1IE` reader - illegal access interrupt enable for LPTIM1"] pub type LPTIM1IE_R = crate::BitReader; #[doc = "Field `LPTIM1IE` writer - illegal access interrupt enable for LPTIM1"] pub type LPTIM1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM3IE` reader - illegal access interrupt enable for LPTIM3"] pub type LPTIM3IE_R = crate::BitReader; #[doc = "Field `LPTIM3IE` writer - illegal access interrupt enable for LPTIM3"] pub type LPTIM3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM4IE` reader - illegal access interrupt enable for LPTIM4"] pub type LPTIM4IE_R = crate::BitReader; #[doc = "Field `LPTIM4IE` writer - illegal access interrupt enable for LPTIM4"] pub type LPTIM4IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM5IE` reader - illegal access interrupt enable for LPTIM5"] pub type LPTIM5IE_R = crate::BitReader; #[doc = "Field `LPTIM5IE` writer - illegal access interrupt enable for LPTIM5"] pub type LPTIM5IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - illegal access interrupt enable for FDCAN1"] #[inline(always)] pub fn fdcan1ie(&self) -> FDCAN1IE_R { FDCAN1IE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - illegal access interrupt enable for FDCAN2"] #[inline(always)] pub fn fdcan2ie(&self) -> FDCAN2IE_R { FDCAN2IE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - illegal access interrupt enable for UCPD"] #[inline(always)] pub fn ucpdie(&self) -> UCPDIE_R { UCPDIE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 8 - illegal access interrupt enable for TIM1"] #[inline(always)] pub fn tim1ie(&self) -> TIM1IE_R { TIM1IE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - illegal access interrupt enable for SPI1"] #[inline(always)] pub fn spi1ie(&self) -> SPI1IE_R { SPI1IE_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - illegal access interrupt enable for TIM8"] #[inline(always)] pub fn tim8ie(&self) -> TIM8IE_R { TIM8IE_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - illegal access interrupt enable for USART1"] #[inline(always)] pub fn usart1ie(&self) -> USART1IE_R { USART1IE_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - illegal access interrupt enable for TIM15"] #[inline(always)] pub fn tim15ie(&self) -> TIM15IE_R { TIM15IE_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - illegal access interrupt enable for TIM16"] #[inline(always)] pub fn tim16ie(&self) -> TIM16IE_R { TIM16IE_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - illegal access interrupt enable for TIM17"] #[inline(always)] pub fn tim17ie(&self) -> TIM17IE_R { TIM17IE_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - illegal access interrupt enable for SPI4"] #[inline(always)] pub fn spi4ie(&self) -> SPI4IE_R { SPI4IE_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - illegal access interrupt enable for SPI6"] #[inline(always)] pub fn spi6ie(&self) -> SPI6IE_R { SPI6IE_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - illegal access interrupt enable for SAI1"] #[inline(always)] pub fn sai1ie(&self) -> SAI1IE_R { SAI1IE_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - illegal access interrupt enable for SAI2"] #[inline(always)] pub fn sai2ie(&self) -> SAI2IE_R { SAI2IE_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - illegal access interrupt enable for USB"] #[inline(always)] pub fn usbie(&self) -> USBIE_R { USBIE_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 24 - illegal access interrupt enable for SPI5"] #[inline(always)] pub fn spi5ie(&self) -> SPI5IE_R { SPI5IE_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - illegal access interrupt enable for LPUART"] #[inline(always)] pub fn lpuart1ie(&self) -> LPUART1IE_R { LPUART1IE_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - illegal access interrupt enable for I2C3"] #[inline(always)] pub fn i2c3ie(&self) -> I2C3IE_R { I2C3IE_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - illegal access interrupt enable for I2C4"] #[inline(always)] pub fn i2c4ie(&self) -> I2C4IE_R { I2C4IE_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - illegal access interrupt enable for LPTIM1"] #[inline(always)] pub fn lptim1ie(&self) -> LPTIM1IE_R { LPTIM1IE_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - illegal access interrupt enable for LPTIM3"] #[inline(always)] pub fn lptim3ie(&self) -> LPTIM3IE_R { LPTIM3IE_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - illegal access interrupt enable for LPTIM4"] #[inline(always)] pub fn lptim4ie(&self) -> LPTIM4IE_R { LPTIM4IE_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - illegal access interrupt enable for LPTIM5"] #[inline(always)] pub fn lptim5ie(&self) -> LPTIM5IE_R { LPTIM5IE_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - illegal access interrupt enable for FDCAN1"] #[inline(always)] #[must_use] pub fn fdcan1ie(&mut self) -> FDCAN1IE_W<GTZC1_TZIC_IER2_SPEC, 0> { FDCAN1IE_W::new(self) } #[doc = "Bit 1 - illegal access interrupt enable for FDCAN2"] #[inline(always)] #[must_use] pub fn fdcan2ie(&mut self) -> FDCAN2IE_W<GTZC1_TZIC_IER2_SPEC, 1> { FDCAN2IE_W::new(self) } #[doc = "Bit 2 - illegal access interrupt enable for UCPD"] #[inline(always)] #[must_use] pub fn ucpdie(&mut self) -> UCPDIE_W<GTZC1_TZIC_IER2_SPEC, 2> { UCPDIE_W::new(self) } #[doc = "Bit 8 - illegal access interrupt enable for TIM1"] #[inline(always)] #[must_use] pub fn tim1ie(&mut self) -> TIM1IE_W<GTZC1_TZIC_IER2_SPEC, 8> { TIM1IE_W::new(self) } #[doc = "Bit 9 - illegal access interrupt enable for SPI1"] #[inline(always)] #[must_use] pub fn spi1ie(&mut self) -> SPI1IE_W<GTZC1_TZIC_IER2_SPEC, 9> { SPI1IE_W::new(self) } #[doc = "Bit 10 - illegal access interrupt enable for TIM8"] #[inline(always)] #[must_use] pub fn tim8ie(&mut self) -> TIM8IE_W<GTZC1_TZIC_IER2_SPEC, 10> { TIM8IE_W::new(self) } #[doc = "Bit 11 - illegal access interrupt enable for USART1"] #[inline(always)] #[must_use] pub fn usart1ie(&mut self) -> USART1IE_W<GTZC1_TZIC_IER2_SPEC, 11> { USART1IE_W::new(self) } #[doc = "Bit 12 - illegal access interrupt enable for TIM15"] #[inline(always)] #[must_use] pub fn tim15ie(&mut self) -> TIM15IE_W<GTZC1_TZIC_IER2_SPEC, 12> { TIM15IE_W::new(self) } #[doc = "Bit 13 - illegal access interrupt enable for TIM16"] #[inline(always)] #[must_use] pub fn tim16ie(&mut self) -> TIM16IE_W<GTZC1_TZIC_IER2_SPEC, 13> { TIM16IE_W::new(self) } #[doc = "Bit 14 - illegal access interrupt enable for TIM17"] #[inline(always)] #[must_use] pub fn tim17ie(&mut self) -> TIM17IE_W<GTZC1_TZIC_IER2_SPEC, 14> { TIM17IE_W::new(self) } #[doc = "Bit 15 - illegal access interrupt enable for SPI4"] #[inline(always)] #[must_use] pub fn spi4ie(&mut self) -> SPI4IE_W<GTZC1_TZIC_IER2_SPEC, 15> { SPI4IE_W::new(self) } #[doc = "Bit 16 - illegal access interrupt enable for SPI6"] #[inline(always)] #[must_use] pub fn spi6ie(&mut self) -> SPI6IE_W<GTZC1_TZIC_IER2_SPEC, 16> { SPI6IE_W::new(self) } #[doc = "Bit 17 - illegal access interrupt enable for SAI1"] #[inline(always)] #[must_use] pub fn sai1ie(&mut self) -> SAI1IE_W<GTZC1_TZIC_IER2_SPEC, 17> { SAI1IE_W::new(self) } #[doc = "Bit 18 - illegal access interrupt enable for SAI2"] #[inline(always)] #[must_use] pub fn sai2ie(&mut self) -> SAI2IE_W<GTZC1_TZIC_IER2_SPEC, 18> { SAI2IE_W::new(self) } #[doc = "Bit 19 - illegal access interrupt enable for USB"] #[inline(always)] #[must_use] pub fn usbie(&mut self) -> USBIE_W<GTZC1_TZIC_IER2_SPEC, 19> { USBIE_W::new(self) } #[doc = "Bit 24 - illegal access interrupt enable for SPI5"] #[inline(always)] #[must_use] pub fn spi5ie(&mut self) -> SPI5IE_W<GTZC1_TZIC_IER2_SPEC, 24> { SPI5IE_W::new(self) } #[doc = "Bit 25 - illegal access interrupt enable for LPUART"] #[inline(always)] #[must_use] pub fn lpuart1ie(&mut self) -> LPUART1IE_W<GTZC1_TZIC_IER2_SPEC, 25> { LPUART1IE_W::new(self) } #[doc = "Bit 26 - illegal access interrupt enable for I2C3"] #[inline(always)] #[must_use] pub fn i2c3ie(&mut self) -> I2C3IE_W<GTZC1_TZIC_IER2_SPEC, 26> { I2C3IE_W::new(self) } #[doc = "Bit 27 - illegal access interrupt enable for I2C4"] #[inline(always)] #[must_use] pub fn i2c4ie(&mut self) -> I2C4IE_W<GTZC1_TZIC_IER2_SPEC, 27> { I2C4IE_W::new(self) } #[doc = "Bit 28 - illegal access interrupt enable for LPTIM1"] #[inline(always)] #[must_use] pub fn lptim1ie(&mut self) -> LPTIM1IE_W<GTZC1_TZIC_IER2_SPEC, 28> { LPTIM1IE_W::new(self) } #[doc = "Bit 29 - illegal access interrupt enable for LPTIM3"] #[inline(always)] #[must_use] pub fn lptim3ie(&mut self) -> LPTIM3IE_W<GTZC1_TZIC_IER2_SPEC, 29> { LPTIM3IE_W::new(self) } #[doc = "Bit 30 - illegal access interrupt enable for LPTIM4"] #[inline(always)] #[must_use] pub fn lptim4ie(&mut self) -> LPTIM4IE_W<GTZC1_TZIC_IER2_SPEC, 30> { LPTIM4IE_W::new(self) } #[doc = "Bit 31 - illegal access interrupt enable for LPTIM5"] #[inline(always)] #[must_use] pub fn lptim5ie(&mut self) -> LPTIM5IE_W<GTZC1_TZIC_IER2_SPEC, 31> { LPTIM5IE_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "GTZC1 TZIC interrupt enable register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gtzc1_tzic_ier2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gtzc1_tzic_ier2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GTZC1_TZIC_IER2_SPEC; impl crate::RegisterSpec for GTZC1_TZIC_IER2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gtzc1_tzic_ier2::R`](R) reader structure"] impl crate::Readable for GTZC1_TZIC_IER2_SPEC {} #[doc = "`write(|w| ..)` method takes [`gtzc1_tzic_ier2::W`](W) writer structure"] impl crate::Writable for GTZC1_TZIC_IER2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets GTZC1_TZIC_IER2 to value 0"] impl crate::Resettable for GTZC1_TZIC_IER2_SPEC { const RESET_VALUE: Self::Ux = 0; }