text
stringlengths
8
4.13M
use actix_web::http::Method; use actix_web::{fs, server, App}; use failure::Error; use num_cpus::get as cpus; use std::sync::Arc; use crate::configuration::Configuration; use crate::store::Store; mod errors; mod middlewares; mod types; // !! Context holds important values for the server. #[derive(Clone)] pub struct Context<T: 'static + Store + Send + Sync + Clone> { pub configuration: Arc<Configuration>, pub store: Arc<T>, } pub fn server<T: 'static + Store + Send + Sync + Clone>(context: Context<T>) -> Result<(), Error> { let state = context.clone(); let sys = server::new(move || { let context = Arc::new(context.clone()); let state = context.clone(); let folder = fs::StaticFiles::new(state.clone().configuration.clone().server.folder.as_str()) .expect("missing static folder"); App::with_state(state) .resource("/api/v1/entries/new", |r| { r.method(Method::POST).f(middlewares::post_entry) }) .resource("/api/v1/entry/{id}", |r| { r.method(Method::GET).a(middlewares::get_entry) }) .resource("/api/v1/health", |r| { r.method(Method::GET).f(middlewares::health) }) .handler("/", folder) }) .shutdown_timeout(10) // <- Set shutdown timeout to 10 seconds .workers(workers_num()); let socket = format!( "{}:{}", state.clone().configuration.clone().server.address, state.clone().configuration.clone().server.port ); info!( "listening on port: {:?}", state.clone().configuration.clone().server.port ); let reactor = sys .bind(socket.as_str()) .map_err(|err| format_err!("an error occured while setting server {:?}", err))?; Ok(reactor.run()) } fn workers_num() -> usize { cpus() / 2 }
//! Core `yggy` service implementations. mod peer; mod router; mod switch; pub use peer::{Peer, PeerManager}; pub use router::Router; pub use switch::Switch;
//! Search your team's files and messages. use rtm::{File, Message, Paging}; #[derive(Clone, Debug, Serialize)] pub enum SortDirection { #[serde(rename = "asc")] Ascending, #[serde(rename = "desc")] Descending, } #[derive(Clone, Debug, Serialize)] #[serde(rename = "snake_case")] pub enum SortBy { Score, Timestamp, } /// Searches for messages and files matching a query. /// /// Wraps https://api.slack.com/methods/search.all #[derive(Clone, Debug, Serialize, new)] pub struct AllRequest<'a> { /// Search query. May contains booleans, etc. pub query: &'a str, /// Return matches sorted by either score or timestamp. pub sort: Option<SortBy>, /// Change sort direction to ascending (asc) or descending (desc). pub sort_dir: Option<SortDirection>, /// Pass a value of true to enable query highlight markers (see below). pub highlight: Option<bool>, /// Number of items to return per page. pub count: Option<u32>, /// Page number of results to return. pub page: Option<u32>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct AllResponse { ok: bool, pub files: Option<AllResponseFiles>, pub messages: Option<AllResponseMessages>, pub query: Option<String>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct AllResponseFiles { pub matches: Vec<File>, pub paging: Paging, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct AllResponseMessages { pub matches: Vec<Message>, pub paging: Paging, } /// Searches for files matching a query. /// /// Wraps https://api.slack.com/methods/search.files #[derive(Clone, Debug, Serialize, new)] pub struct FilesRequest<'a> { /// Search query. May contain booleans, etc. #[new(default)] pub query: &'a str, /// Return matches sorted by either score or timestamp. #[new(default)] pub sort: Option<SortBy>, /// Change sort direction to ascending (asc) or descending (desc). #[new(default)] pub sort_dir: Option<SortDirection>, /// Pass a value of true to enable query highlight markers (see below). #[new(default)] pub highlight: Option<bool>, /// Number of items to return per page. #[new(default)] pub count: Option<u32>, /// Page number of results to return. #[new(default)] pub page: Option<u32>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct FilesResponse { ok: bool, pub files: Option<FilesResponseFiles>, pub query: Option<String>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct FilesResponseFiles { pub matches: Option<Vec<File>>, pub paging: Option<Paging>, pub total: Option<u32>, } /// Searches for messages matching a query. /// /// Wraps https://api.slack.com/methods/search.messages #[derive(Clone, Debug, Serialize, new)] pub struct MessagesRequest<'a> { /// Search query. May contains booleans, etc. pub query: &'a str, /// Return matches sorted by either score or timestamp. #[new(default)] pub sort: Option<SortBy>, /// Change sort direction to ascending (asc) or descending (desc). #[new(default)] pub sort_dir: Option<SortDirection>, /// Pass a value of true to enable query highlight markers (see below). #[new(default)] pub highlight: Option<bool>, /// Number of items to return per page. #[new(default)] pub count: Option<u32>, /// Page number of results to return. #[new(default)] pub page: Option<u32>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct MessagesResponse { ok: bool, pub messages: Option<MessagesResponseMessages>, pub query: Option<String>, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct MessagesResponseMessages { pub matches: Option<Vec<Message>>, pub paging: Option<Paging>, pub total: Option<u32>, }
use crate::instruction::Instruction; #[derive(Default)] pub struct InterruptController { interrupt: Option<Instruction>, } impl InterruptController { pub fn generate_interrupt(&mut self, instruction: Instruction) { self.interrupt = Some(instruction); } pub fn consume_interrupt(&mut self) -> Option<Instruction> { match self.interrupt { Some(_) => { let ret = self.interrupt; self.interrupt = None; ret } None => None, } } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// AwsTagFilterDeleteRequest : The objects used to delete an AWS tag filter entry. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AwsTagFilterDeleteRequest { /// The unique identifier of your AWS account. #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] pub account_id: Option<String>, #[serde(rename = "namespace", skip_serializing_if = "Option::is_none")] pub namespace: Option<crate::models::AwsNamespace>, } impl AwsTagFilterDeleteRequest { /// The objects used to delete an AWS tag filter entry. pub fn new() -> AwsTagFilterDeleteRequest { AwsTagFilterDeleteRequest { account_id: None, namespace: None, } } }
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use engine::rocks::util::get_cf_handle; use engine::*; use test_raftstore::*; use tikv_util::config::ReadableSize; #[test] fn test_turnoff_titan() { let mut cluster = new_node_cluster(0, 3); cluster.cfg.rocksdb.defaultcf.disable_auto_compactions = true; cluster.cfg.rocksdb.defaultcf.num_levels = 1; configure_for_enable_titan(&mut cluster, ReadableSize::kb(0)); cluster.run(); assert_eq!(cluster.must_get(b"k1"), None); let size = 5; for i in 0..size { assert!(cluster .put( format!("k{:02}0", i).as_bytes(), format!("v{}", i).as_bytes(), ) .is_ok()); } cluster.must_flush_cf(CF_DEFAULT, true); for i in 0..size { assert!(cluster .put( format!("k{:02}1", i).as_bytes(), format!("v{}", i).as_bytes(), ) .is_ok()); } cluster.must_flush_cf(CF_DEFAULT, true); for i in cluster.get_node_ids().into_iter() { let db = cluster.get_engine(i); assert_eq!( db.get_property_int(&"rocksdb.num-files-at-level0").unwrap(), 2 ); assert_eq!( db.get_property_int(&"rocksdb.num-files-at-level1").unwrap(), 0 ); assert_eq!( db.get_property_int(&"rocksdb.titandb.num-live-blob-file") .unwrap(), 2 ); assert_eq!( db.get_property_int(&"rocksdb.titandb.num-obsolete-blob-file") .unwrap(), 0 ); } cluster.shutdown(); // try reopen db when titan isn't properly turned off. configure_for_disable_titan(&mut cluster); assert!(cluster.pre_start_check().is_err()); configure_for_enable_titan(&mut cluster, ReadableSize::kb(0)); assert!(cluster.pre_start_check().is_ok()); cluster.start().unwrap(); assert_eq!(cluster.must_get(b"k1"), None); for i in cluster.get_node_ids().into_iter() { let db = cluster.get_engine(i); let handle = get_cf_handle(&db, CF_DEFAULT).unwrap(); let mut opt = Vec::new(); opt.push(("blob_run_mode", "kFallback")); assert!(db.set_options_cf(handle, &opt).is_ok()); } cluster.compact_data(); let mut all_check_pass = true; for _ in 0..10 { // wait for gc completes. sleep_ms(10); all_check_pass = true; for i in cluster.get_node_ids().into_iter() { let db = cluster.get_engine(i); if db.get_property_int(&"rocksdb.num-files-at-level0").unwrap() != 0 { all_check_pass = false; break; } if db.get_property_int(&"rocksdb.num-files-at-level1").unwrap() != 1 { all_check_pass = false; break; } if db .get_property_int(&"rocksdb.titandb.num-live-blob-file") .unwrap() != 0 { all_check_pass = false; break; } } if all_check_pass { break; } } if !all_check_pass { panic!("unexpected titan gc results"); } cluster.shutdown(); configure_for_disable_titan(&mut cluster); // wait till files are purged, timeout set to purge_obsolete_files_period. for _ in 1..100 { sleep_ms(10); if cluster.pre_start_check().is_ok() { return; } } assert!(cluster.pre_start_check().is_ok()); }
use std::process::Command; use std::{thread, time}; pub struct PACMD { /// Mac Address e.g. AA:11:2B:3F:44:55 pub mac: String, /// Sink Card e.g. bluez_card.AA_11_2B_3F_44_55 pub sink: String, /// Is debug config enabled pub dbg: bool, } impl PACMD { /// Get all cards listed by pacmd pub fn get_card_list() -> String { let output = Command::new("pacmd") .arg("list-cards") .output() .expect("Failed to list cards"); return String::from_utf8_lossy(&output.stdout).to_string(); } /// Restart bluetooth connection pub fn restart(&self) -> bool { let out = Command::new("bluetoothctl") .arg("disconnect") .arg(&self.mac) .output() .expect("Failed to disconnect Bluetooth"); let _disconnected = String::from_utf8_lossy(&out.stdout).contains("Successful disconnected"); self.sleep(7); Command::new("bluetoothctl") .arg("connect") .arg(&self.mac) .spawn() .expect("Failed to connect Bluetooth"); self.sleep(3); let connected = String::from_utf8_lossy(&out.stdout).contains("Connection successful"); return connected; } fn sleep(&self, seconds: u64) { let ten_seconds = time::Duration::from_secs(seconds); thread::sleep(ten_seconds); } /// Force A2DP sink pub fn set_a2dp_sink(&self) -> bool { let out = Command::new("pacmd") .arg("set-card-profile") .arg(&self.sink) .arg("a2dp_sink") .output(); match out { Ok(output) => { let success = output.status.success(); if !success { println!("Failed to update A2DP, restarting Bluetooth"); let success = self.restart(); if !success { println!( "Failed to restart {}", String::from_utf8_lossy(&output.stderr) ); } else { return self.set_a2dp_sink(); } } success } Err(e) => { let success = self.restart(); if !success { println!("Failed to restart {}", e); } else { return self.set_a2dp_sink(); } success } } } }
//! A set of abstraction utilities used by the framework to simplify its code. //! //! Usable outside of the framework. pub mod id_map; pub mod segments; pub use id_map::*; pub use segments::*;
pub mod pc_usage; pub mod python_repo; use crate::{ error::WebsocketError, message::{ResultMessage, TaskMessage, WebsocketMessage}, }; use anyhow::Context; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use tokio::sync::mpsc; #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum WebsocketSystem { PythonRepo, PcUsage, } #[async_trait::async_trait] pub trait Subsystem { type Error; type Task; fn system(&self) -> WebsocketSystem; async fn handle_message( &self, task: Self::Task, payload: serde_json::Value, ) -> Result<serde_json::Value, Self::Error>; #[tracing::instrument( name = "Handling subsystem message", skip(self, internal_receiver, sender), fields(subsystem=tracing::field::Empty) )] async fn handle_messages( &self, mut internal_receiver: mpsc::Receiver<TaskMessage>, sender: mpsc::Sender<WebsocketMessage>, ) -> Result<(), WebsocketError> where Self: Sized, Self::Task: DeserializeOwned + Send, Self::Error: std::error::Error, { tracing::Span::current().record("subsystem", &tracing::field::debug(self.system())); while let Some(msg) = internal_receiver.recv().await { tracing::debug!("Received: {:?}", msg); let result = match serde_json::from_str::<Self::Task>(&format!("{:?}", msg.name)) .context("Failed to deserialize message.") { Ok(task) => match self.handle_message(task, msg.payload).await { Ok(res) => ResultMessage::from_json(res, Some(self.system())), Err(e) => ResultMessage::from_error(e, Some(self.system())), }, Err(e) => ResultMessage::from_error(e, Some(self.system())), }; if sender .send(WebsocketMessage::TaskResult(result)) .await .is_err() { tracing::info!("Websocket receiver dropped."); } } Ok(()) } }
pub mod moves; pub mod characters; pub mod boosters; pub mod outcomes; pub mod streaks; pub mod players; pub mod io; pub mod prfg; pub mod single_player_game; mod helpers;
fn count_diffs(data: &[u32], val: u32) -> u32 { data.windows(2) .map(|s| (s[1] - s[0])) .filter(|diff| *diff == val) .count() as u32 } fn count_permutations(data: &[u32]) -> u64 { let mut amount = 0; let mut ret: u64 = 1; for slice in data.windows(2) { if slice[1] - slice[0] == 1 { amount += 1; } else { match amount { 2 => ret *= 2, 3 => ret *= 4, 4 => ret *= 7, _ => (), } amount = 0; } } ret } fn main() { let mut data: Vec<u32> = std::fs::read_to_string("input") .expect("file not found!") .lines() .map(|x| x.parse().unwrap()) .collect(); data.sort(); data.push(data.last().unwrap() + 3); data.insert(0, 0); println!( "Part 1 answer is {}", count_diffs(&data, 1) * count_diffs(&data, 3) ); println!("Part 2 answer is {}", count_permutations(&data)); }
use std::collections::VecDeque; use crate::geometry::*; #[derive(Debug, Clone)] pub struct QuadTree<T: Clone> { boundary: Rect, points: Vec<Point>, data: Vec<T>, north_west: Option<Box<QuadTree<T>>>, north_east: Option<Box<QuadTree<T>>>, south_west: Option<Box<QuadTree<T>>>, south_east: Option<Box<QuadTree<T>>>, } impl<T: Clone> QuadTree<T> { pub const NODE_CAPACITY: usize = 128; pub fn new(boundary: Rect) -> Self { Self { boundary, points: Vec::new(), data: Vec::new(), north_west: None, north_east: None, south_west: None, south_east: None, } } pub fn boundary(&self) -> Rect { self.boundary } pub fn points(&self) -> &[Point] { &self.points } pub fn data(&self) -> &[T] { &self.data } pub fn elems<'a>(&'a self) -> impl Iterator<Item = (Point, &'a T)> { self.points.iter().copied().zip(self.data.iter()) } pub fn node_len(&self) -> usize { self.points.len() } pub fn is_leaf(&self) -> bool { self.north_west.is_none() } fn can_insert(&self, point: Point) -> bool { if !self.boundary.contains(point) { return false; } true } pub fn insert( &mut self, point: Point, data: T, ) -> std::result::Result<(), T> { log::trace!( "inserting data into quad tree at ({}, {})", point.x, point.y ); if !self.boundary.contains(point) { log::trace!("point is outside tree bounds, aborting"); return Err(data); } if self.node_len() < Self::NODE_CAPACITY && self.is_leaf() { log::trace!("in leaf below capacity, adding to node"); self.points.push(point); self.data.push(data); return Ok(()); } if self.is_leaf() { log::trace!("subdividing node"); self.subdivide(); } let mut deque: VecDeque<&mut Self> = VecDeque::new(); let children = [ self.north_west.as_deref_mut(), self.north_east.as_deref_mut(), self.south_west.as_deref_mut(), self.south_east.as_deref_mut(), ]; for child in children { if let Some(child) = child { deque.push_back(child); } } let mut data = Some(data); while let Some(node) = deque.pop_back() { if node.can_insert(point) { if node.is_leaf() { if let Some(data_) = data { // since we've already checked that the point // can be inserted into the node, this // recursive call won't actually do any // further recursion // // lol match node.insert(point, data_) { Ok(_) => { data = None; break; } Err(d) => data = Some(d), } } } else { if let Some(children) = node.children_mut() { for child in children { deque.push_back(child); } } } } } if let Some(data) = data { Err(data) } else { Ok(()) } } pub fn query_range(&self, range: Rect) -> Vec<(Point, &T)> { let mut results = Vec::new(); if !self.boundary.intersects(range) { return results; } for (point, data) in self.elems() { if range.contains(point) { results.push((point, data)); } } if let Some(children) = self.children() { for child in children { results.extend(Self::child_range(child, range)); } } results } pub fn delete_nearest(&mut self, p: Point) -> bool { if let Some(closest) = self.nearest_mut(p) { closest.delete(); true } else { false } } pub fn nearest_leaf(&self, tgt: Point) -> Option<&QuadTree<T>> { let mut best_dist: Option<f32> = None; let mut best_leaf: Option<&QuadTree<T>> = None; let rect_dist = |rect: Rect| { let l = rect.min().x; let r = rect.max().x; let t = rect.min().y; let b = rect.max().y; let l_ = (l - tgt.x).abs(); let r_ = (r - tgt.x).abs(); let t_ = (t - tgt.y).abs(); let b_ = (b - tgt.y).abs(); l_.min(r_).min(t_).min(b_) }; let mut stack: VecDeque<&QuadTree<T>> = VecDeque::new(); stack.push_back(self); while let Some(node) = stack.pop_back() { let bound = node.boundary(); if let Some(dist) = best_dist { if (tgt.x < bound.min().x - dist) || (tgt.x > bound.max().x + dist) || (tgt.y > bound.min().y - dist) || (tgt.y > bound.max().y + dist) { // } else { continue; } } if node.is_leaf() { // we know it's close enough to check for &point in node.points() { let dist = point.dist(tgt); if let Some(best) = best_dist { if dist < best { best_dist = Some(dist); best_leaf = Some(node); } } else { best_dist = Some(dist); best_leaf = Some(node); } } } else { if let Some(mut children) = node.children() { children.sort_by(|a, b| { let da = rect_dist(a.boundary()); let db = rect_dist(b.boundary()); da.partial_cmp(&db).unwrap() }); for child in children { stack.push_back(child); } } } } best_leaf } pub fn nearest_leaf_mut(&mut self, tgt: Point) -> Option<&mut QuadTree<T>> { let mut best_dist: Option<f32> = None; let mut best_leaf: Option<&mut QuadTree<T>> = None; let rect_dist = |rect: Rect| { let l = rect.min().x; let r = rect.max().x; let t = rect.min().y; let b = rect.max().y; let l_ = (l - tgt.x).abs(); let r_ = (r - tgt.x).abs(); let t_ = (t - tgt.y).abs(); let b_ = (b - tgt.y).abs(); l_.min(r_).min(t_).min(b_) }; let mut stack: VecDeque<&mut QuadTree<T>> = VecDeque::new(); stack.push_back(self); while let Some(node) = stack.pop_back() { let bound = node.boundary(); if let Some(dist) = best_dist { if (tgt.x < bound.min().x - dist) || (tgt.x > bound.max().x + dist) || (tgt.y > bound.min().y - dist) || (tgt.y > bound.max().y + dist) { // } else { continue; } } if node.is_leaf() { // we know it's close enough to check let mut set_best = false; for &point in node.points() { let dist = point.dist(tgt); if let Some(best) = best_dist { if dist < best { best_dist = Some(dist); set_best = true; } } else { best_dist = Some(dist); set_best = true; } } if set_best { best_leaf = Some(node); } } else { if let Some(mut children) = node.children_mut() { children.sort_by(|a, b| { let da = rect_dist(a.boundary()); let db = rect_dist(b.boundary()); da.partial_cmp(&db).unwrap() }); for child in children { stack.push_back(child); } } } } best_leaf } pub fn nearest(&self, p: Point) -> Option<(Point, &T)> { let leaf = self.nearest_leaf(p)?; let mut closest: Option<(Point, &T)> = None; let mut prev_dist: Option<f32> = None; for (point, data) in leaf.elems() { let dist = point.dist_sqr(p); if let Some(prev) = prev_dist { if dist < prev { closest = Some((point, data)); prev_dist = Some(dist); } } else { closest = Some((point, data)); prev_dist = Some(dist); } } closest } pub fn nearest_mut(&mut self, p: Point) -> Option<PointMut<'_, T>> { let leaf = self.nearest_leaf_mut(p)?; let mut closest: Option<usize> = None; let mut prev_dist: Option<f32> = None; for (ix, &point) in leaf.points.iter().enumerate() { let dist = point.dist_sqr(p); if let Some(prev) = prev_dist { if dist < prev { closest = Some(ix); prev_dist = Some(dist); } } else { closest = Some(ix); prev_dist = Some(dist); } } let ix = closest?; let point = leaf.points[ix]; Some(PointMut { node: leaf, ix, point, }) } pub fn rects(&self) -> Vec<Rect> { let mut result = Vec::new(); let mut queue = VecDeque::new(); queue.push_back(self); while let Some(node) = queue.pop_front() { result.push(node.boundary); if let Some(children) = node.children() { for child in children { queue.push_back(child); } } } result } pub fn leaves(&self) -> Leaves<'_, T> { Leaves::new(self) } fn subdivide(&mut self) { let min = self.boundary.min(); let max = self.boundary.max(); let pt = |x, y| Point::new(x, y); let mid_x = min.x + ((max.x - min.x) / 2.0); let mid_y = min.y + ((max.y - min.y) / 2.0); // calculate the boundary rectangles for the children let top_left_bnd = Rect::new(pt(min.x, min.y), pt(mid_x, mid_y)); let top_right_bnd = Rect::new(pt(mid_x, min.y), pt(max.x, mid_y)); let btm_left_bnd = Rect::new(pt(min.x, mid_y), pt(mid_x, max.y)); let btm_right_bnd = Rect::new(pt(mid_x, mid_y), pt(max.x, max.y)); let mut top_left = Self::new(top_left_bnd); let mut top_right = Self::new(top_right_bnd); let mut btm_left = Self::new(btm_left_bnd); let mut btm_right = Self::new(btm_right_bnd); let move_to_child = |child: &mut Self| { let bnd = child.boundary; // TODO this should be done without cloning, but the data // will probably be Copy in most cases so it doesn't // matter for now for (point, data) in self.query_range(bnd) { if let Err(_) = child.insert(point, data.clone()) { panic!("unexpected error when subdividing quadtree"); } } }; move_to_child(&mut top_left); move_to_child(&mut top_right); move_to_child(&mut btm_left); move_to_child(&mut btm_right); self.north_west = Some(Box::new(top_left)); self.north_east = Some(Box::new(top_right)); self.south_west = Some(Box::new(btm_left)); self.south_east = Some(Box::new(btm_right)); } fn children(&self) -> Option<[&QuadTree<T>; 4]> { let nw = self.north_west.as_deref()?; let ne = self.north_east.as_deref()?; let sw = self.south_west.as_deref()?; let se = self.south_east.as_deref()?; let children = [nw, ne, sw, se]; Some(children) } fn children_mut(&mut self) -> Option<[&mut QuadTree<T>; 4]> { let nw = self.north_west.as_deref_mut()?; let ne = self.north_east.as_deref_mut()?; let sw = self.south_west.as_deref_mut()?; let se = self.south_east.as_deref_mut()?; let children = [nw, ne, sw, se]; Some(children) } fn child_range<'a>( child: &'a Self, range: Rect, ) -> impl Iterator<Item = (Point, &'a T)> { child.points.iter().zip(child.data.iter()).filter_map( move |(&point, data)| { if range.contains(point) { Some((point, data)) } else { None } }, ) } } pub struct PointMut<'a, T: Clone> { node: &'a mut QuadTree<T>, ix: usize, point: Point, } impl<'a, T: Clone> PointMut<'a, T> { pub fn point(&self) -> Point { self.point } pub fn data(&self) -> &T { &self.node.data[self.ix] } pub fn data_mut(&mut self) -> &mut T { &mut self.node.data[self.ix] } pub fn delete(self) { self.node.points.remove(self.ix); self.node.data.remove(self.ix); } } pub struct Leaves<'a, T: Clone> { stack: VecDeque<&'a QuadTree<T>>, done: bool, } impl<'a, T: Clone> Leaves<'a, T> { fn new(tree: &'a QuadTree<T>) -> Self { let mut stack = VecDeque::new(); stack.push_back(tree); Self { stack, done: false } } fn next(&mut self) -> Option<&'a QuadTree<T>> { if self.done { return None; } while let Some(next) = self.stack.pop_back() { if next.is_leaf() { return Some(next); } if let Some(children) = next.children() { for child in children { self.stack.push_back(child); } } } self.done = true; None } } impl<'a, T: Clone> Iterator for Leaves<'a, T> { type Item = &'a QuadTree<T>; fn next(&mut self) -> Option<Self::Item> { Leaves::next(self) } }
use std::fmt::{self, Debug}; use line_drawing::{FloatNum, Midpoint, SignedNum}; use renderer::{Coord, Drawable}; use point::Point2; /// Euclidean + barycentric coordinate on a line. pub type Coordinate<T> = (Point2<T>, [T; 2]); impl<T: Copy> Coord<T> for Coordinate<T> { #[inline(always)] fn point(&self) -> Point2<T> { self.0 } #[inline(always)] fn barycentric(&self) -> Option<&[T]> { Some(&self.1) } } #[derive(Clone, Copy, Debug)] pub struct Line<T> { start: Point2<T>, end: Point2<T>, } impl<T: FloatNum + SignedNum> Drawable<T, Coordinate<T>> for Line<T> { #[inline(always)] fn vertices(&self) -> usize { 2 } } impl<T: FloatNum + SignedNum> IntoIterator for Line<T> { type Item = Coordinate<T>; type IntoIter = IntoIter<T>; #[inline] fn into_iter(self) -> Self::IntoIter { let start = self.start; let dx = self.end.0 - self.start.0; let dy = self.end.1 - self.start.1; let len = (dx * dx + dy * dy).sqrt(); let len_recip = len.recip(); let inner = Midpoint::new(self.start, self.end); IntoIter { start, inner, len_recip, } } } pub struct IntoIter<T: FloatNum + SignedNum> { start: Point2<T>, inner: Midpoint<T, T>, len_recip: T, } impl<T: FloatNum + SignedNum> Iterator for IntoIter<T> { type Item = Coordinate<T>; #[inline] fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(x, y)| { let dx = x - self.start.0; let dy = y - self.start.1; let dist = (dx * dx + dy * dy).sqrt(); let f = dist * self.len_recip; ((x, y), [f, T::one() - f]) }) } } impl<T: FloatNum + SignedNum + Debug> Debug for IntoIter<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("IntoIter") .field("start", &self.start) .field("len_recip", &self.len_recip) .field("inner", &"...") .finish() } }
#![cfg_attr(test, allow(dead_code))] use ::scene::{Camera, Scene}; pub mod bunny; pub mod cornell; pub mod cow; pub mod easing; pub mod fresnel; pub mod heptoroid; pub mod lucy; pub mod sibenik; pub mod sierpinski; pub mod sphere; pub mod sponza; pub mod tachikoma; pub mod teapot; pub trait SceneConfig { fn get_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera; fn get_animation_camera(&self, image_width: u32, image_height: u32, fov: f64) -> Camera { self.get_camera(image_width, image_height, fov) } fn get_scene(&self) -> Scene; } pub fn scene_by_name(name: &str) -> Option<Box<SceneConfig>> { Some(match name { "bunny" => Box::new(bunny::BunnyConfig), "cornell" => Box::new(cornell::CornelConfig), "cow" => Box::new(cow::CowConfig), "easing" => Box::new(easing::EasingConfig), "fresnel" => Box::new(fresnel::FresnelConfig), "heptoroid-shiny" => Box::new(heptoroid::HeptoroidConfig::shiny()), "heptoroid-white" => Box::new(heptoroid::HeptoroidConfig::white()), "heptoroid-refractive" => Box::new(heptoroid::HeptoroidConfig::refractive()), "lucy" => Box::new(lucy::LucyConfig), "sibenik" => Box::new(sibenik::SibenikConfig), "sierpinski" => Box::new(sierpinski::SierpinskiConfig), "sphere" => Box::new(sphere::SphereConfig), "sponza" => Box::new(sponza::SponzaConfig), "tachikoma" => Box::new(tachikoma::TachikomaConfig), "teapot" => Box::new(teapot::TeapotConfig), _ => return None, }) }
#![cfg_attr(feature = "cargo-clippy", allow(unreadable_literal, excessive_precision))] use std::cmp::{ min, max }; use physical_constants::{ PLANCK_CONSTANT as h, SPEED_OF_LIGHT_IN_VACUUM as c, BOLTZMANN_CONSTANT as kb, WIEN_WAVELENGTH_DISPLACEMENT_LAW_CONSTANT as b, }; use lazy_static::lazy_static; use super::*; use super::sampled::*; pub enum SpectrumType { Reflectance, Illumination, } pub struct XyzSampledSpectrums { pub x: SampledSpectrum, pub y: SampledSpectrum, pub z: SampledSpectrum, } pub struct RgbSampledSpectrums { pub white: SampledSpectrum, pub cyan: SampledSpectrum, pub magenta: SampledSpectrum, pub yellow: SampledSpectrum, pub red: SampledSpectrum, pub green: SampledSpectrum, pub blue: SampledSpectrum, } lazy_static! { pub static ref XYZ: XyzSampledSpectrums = { let num = float(NUM_SAMPLES as f32); let start = float(LAMBDA_START as f32); let end = float(LAMBDA_END as f32); let mut x = SampledSpectrum::new(0.0); let mut y = SampledSpectrum::new(0.0); let mut z = SampledSpectrum::new(0.0); let cie = |v: [f32; N_CIE_SAMPLES]| CIE_LAMBDA.iter().zip(v.iter()) .map(|(l, v)| (float(*l), float(*v))) .map(|(lambda, value)| SampledSpectrumData { lambda, value }) .collect::<Vec<_>>(); let cie_x = cie(CIE_X); let cie_y = cie(CIE_Y); let cie_z = cie(CIE_Z); for i in 0..NUM_SAMPLES { let wl_0 = start.lerp(end, float(i as f32) / num); let wl_1 = start.lerp(end, float(i as f32 + 1.0) / num); x.c[i] = average_samples(&cie_x, wl_0, wl_1); y.c[i] = average_samples(&cie_y, wl_0, wl_1); z.c[i] = average_samples(&cie_z, wl_0, wl_1); } XyzSampledSpectrums { x, y, z } }; pub static ref RGB_REFL: RgbSampledSpectrums = { let num = float(NUM_SAMPLES as f32); let start = float(LAMBDA_START as f32); let end = float(LAMBDA_END as f32); let mut white = SampledSpectrum::new(0.0); let mut cyan = SampledSpectrum::new(0.0); let mut magenta = SampledSpectrum::new(0.0); let mut yellow = SampledSpectrum::new(0.0); let mut red = SampledSpectrum::new(0.0); let mut green = SampledSpectrum::new(0.0); let mut blue = SampledSpectrum::new(0.0); let cie = |v: [f32; RGB_TO_SPECTRUM_SAMPLES]| RGB_TO_SPECTRUM_LAMBDA.iter().zip(v.iter()) .map(|(l, v)| (float(*l), float(*v))) .map(|(lambda, value)| SampledSpectrumData { lambda, value }) .collect::<Vec<_>>(); let cie_white = cie(RGB_REFL_TO_SPECTRUM_WHITE); let cie_cyan = cie(RGB_REFL_TO_SPECTRUM_CYAN); let cie_magenta = cie(RGB_REFL_TO_SPECTRUM_MAGENTA); let cie_yellow = cie(RGB_REFL_TO_SPECTRUM_YELLOW); let cie_red = cie(RGB_REFL_TO_SPECTRUM_RED); let cie_green = cie(RGB_REFL_TO_SPECTRUM_GREEN); let cie_blue = cie(RGB_REFL_TO_SPECTRUM_BLUE); for i in 0..NUM_SAMPLES { let wl_0 = start.lerp(end, float(i as f32) / num); let wl_1 = start.lerp(end, float(i as f32 + 1.0) / num); white.c[i] = average_samples(&cie_white, wl_0, wl_1); cyan.c[i] = average_samples(&cie_cyan, wl_0, wl_1); magenta.c[i] = average_samples(&cie_magenta, wl_0, wl_1); yellow.c[i] = average_samples(&cie_yellow, wl_0, wl_1); red.c[i] = average_samples(&cie_red, wl_0, wl_1); green.c[i] = average_samples(&cie_green, wl_0, wl_1); blue.c[i] = average_samples(&cie_blue, wl_0, wl_1); } RgbSampledSpectrums { white, cyan, magenta, yellow, red, green, blue } }; pub static ref RGB_ILLUM: RgbSampledSpectrums = { let num = float(NUM_SAMPLES as f32); let start = float(LAMBDA_START as f32); let end = float(LAMBDA_END as f32); let mut white = SampledSpectrum::new(0.0); let mut cyan = SampledSpectrum::new(0.0); let mut magenta = SampledSpectrum::new(0.0); let mut yellow = SampledSpectrum::new(0.0); let mut red = SampledSpectrum::new(0.0); let mut green = SampledSpectrum::new(0.0); let mut blue = SampledSpectrum::new(0.0); let cie = |v: [f32; RGB_TO_SPECTRUM_SAMPLES]| RGB_TO_SPECTRUM_LAMBDA.iter().zip(v.iter()) .map(|(l, v)| (float(*l), float(*v))) .map(|(lambda, value)| SampledSpectrumData { lambda, value }) .collect::<Vec<_>>(); let cie_white = cie(RGB_ILLUM_TO_SPECTRUM_WHITE); let cie_cyan = cie(RGB_ILLUM_TO_SPECTRUM_CYAN); let cie_magenta = cie(RGB_ILLUM_TO_SPECTRUM_MAGENTA); let cie_yellow = cie(RGB_ILLUM_TO_SPECTRUM_YELLOW); let cie_red = cie(RGB_ILLUM_TO_SPECTRUM_RED); let cie_green = cie(RGB_ILLUM_TO_SPECTRUM_GREEN); let cie_blue = cie(RGB_ILLUM_TO_SPECTRUM_BLUE); for i in 0..NUM_SAMPLES { let wl_0 = start.lerp(end, float(i as f32) / num); let wl_1 = start.lerp(end, float(i as f32 + 1.0) / num); white.c[i] = average_samples(&cie_white, wl_0, wl_1); cyan.c[i] = average_samples(&cie_cyan, wl_0, wl_1); magenta.c[i] = average_samples(&cie_magenta, wl_0, wl_1); yellow.c[i] = average_samples(&cie_yellow, wl_0, wl_1); red.c[i] = average_samples(&cie_red, wl_0, wl_1); green.c[i] = average_samples(&cie_green, wl_0, wl_1); blue.c[i] = average_samples(&cie_blue, wl_0, wl_1); } RgbSampledSpectrums { white, cyan, magenta, yellow, red, green, blue } }; } pub fn xyz_to_rgb(xyz: [Float; 3]) -> [Float; 3] { let xyz = [xyz[0].raw(), xyz[1].raw(), xyz[2].raw()]; let mut rgb = [0.0; 3]; rgb[0] = 3.240479 * xyz[0] - 1.537150 * xyz[1] - 0.498535 * xyz[2]; rgb[1] = -0.969256 * xyz[0] + 1.875991 * xyz[1] + 0.041556 * xyz[2]; rgb[2] = 0.055648 * xyz[0] - 0.204043 * xyz[1] + 1.057311 * xyz[2]; [float(rgb[0]), float(rgb[1]), float(rgb[2])] } pub fn rgb_to_xyz(rgb: [Float; 3]) -> [Float; 3] { let rgb = [rgb[0].raw(), rgb[1].raw(), rgb[2].raw()]; let mut xyz = [0.0; 3]; xyz[0] = 0.412453 * rgb[0] + 0.357580 * rgb[1] + 0.180423 * rgb[2]; xyz[1] = 0.212671 * rgb[0] + 0.715160 * rgb[1] + 0.072169 * rgb[2]; xyz[2] = 0.019334 * rgb[0] + 0.119193 * rgb[1] + 0.950227 * rgb[2]; [float(xyz[0]), float(xyz[1]), float(xyz[2])] } pub fn blackbody(lambda: &[Float], temperature: Float) -> Vec<SampledSpectrumData> { let temperature = f64::from(temperature.raw()); lambda.iter() .map(|l| { let l_o = *l; // convert nm to m let l = f64::from(l.raw()) * 1e-9; let l_5 = l.powi(5); let v = (2.0 * h * c.powi(2)) / (l_5 * ((h * c) / (l * kb * temperature)).exp() - 1.0); SampledSpectrumData { lambda: l_o, value: float(v), } }) .collect() } pub fn blackbody_normalized(lambda: &[Float], temperature: Float) -> Vec<SampledSpectrumData> { let temperature_r = f64::from(temperature.raw()); // Wein's displacement law gives λ in m, // this converts to nm for `blackbody()` let lambda_max = (b / temperature_r) * 1e9; let max_l = blackbody(&[float(lambda_max)], temperature); assert!(max_l.len() == 1); let max_l = max_l[0]; blackbody(lambda, temperature) .into_iter() .map(|mut s| { s.value /= max_l.value; s }) .collect() } pub fn interpolate_spectrum_samples(samples: &[SampledSpectrumData], lambda: Float) -> Float { assert!(!samples.is_empty()); let first = samples.first().unwrap(); let last = samples.last().unwrap(); if lambda <= first.lambda { return first.value; } if lambda >= last.lambda { return last.value; } let offset = samples.binary_search_by(|p| p.lambda.cmp(&lambda)); // because in error case it gives us the index where an element // could be placed and preserve order, should also be the closest // index? let offset = match offset { Ok(s) => s, Err(s) => if s <= samples.len() { s } else { samples.len() }, }; let sample = samples[offset]; let sample_1 = samples.get(offset + 1).unwrap_or(last); let t = (lambda - sample.lambda) / (sample_1.lambda - sample.lambda); sample.value.lerp(sample_1.value, t) } pub fn average_samples(samples: &[SampledSpectrumData], lambda_start: Float, lambda_end: Float) -> Float { assert!(!samples.is_empty()); let first = samples.first().unwrap(); let last = samples.last().unwrap(); if samples.len() == 1 { return first.value; } if lambda_end <= samples.first().unwrap().lambda { return first.value; } if lambda_start >= samples.last().unwrap().lambda { return last.value; } let mut sum = float(0.0); // add contributions of constant segments before/after samples if lambda_start < first.lambda { sum += first.value * (first.lambda - lambda_start); } if lambda_end > last.lambda { sum += last.value * (lambda_end - last.lambda); } // advance to first relevant w/v segment let mut i = 0; while lambda_start > samples[i + 1].lambda { i += 1; }; // loop over segments and add contributions let interpolate = |w: Float, i0: &SampledSpectrumData, i1: &SampledSpectrumData| { i0.value.lerp(i1.value, (w - i0.lambda) / (i1.lambda - i0.lambda)) }; for i in samples.windows(2) { if let [i0, i1] = i { if lambda_end < i1.lambda { break; } let seg_start = max(lambda_start, i0.lambda); let seg_end = min(lambda_end, i1.lambda); sum += float(0.5) * (interpolate(seg_start, i0, i1) + interpolate(seg_end, i0, i1)) * (seg_end - seg_start); } } sum / (lambda_start - lambda_end) } pub fn is_sorted(samples: &[SampledSpectrumData]) -> bool { for i in samples.windows(2) { if let [i1, i2] = i { if i1.lambda > i2.lambda { return false; } } } true }
extern crate rand; use rand::random; use std::slice; use std::os::args; use std::io::{print, println}; use std::slice::MutableCloneableVector; fn main() { // get arguments let args = args(); let mut args_iter = args.iter(); args_iter.next(); let size = from_str::<uint>(*args_iter.next().unwrap()).unwrap(); let num_iterations = from_str::<uint>(*args_iter.next().unwrap()).unwrap(); // Initialize arrays let mut current_state = slice::build(Some(size), |push: |v: bool|| { for _ in range(0, size) { push(random::<bool>()); }}); let mut next_state = slice::build(Some(size), |push: |v: bool|| { for _ in range(0, size) { push(false); }}); // Simulate print_state(current_state); for _ in range(0, num_iterations) { iterate_state(current_state, next_state); assert!(current_state.copy_from(next_state) == next_state.len()); print_state(current_state); } } fn iterate_state(current_state:&mut [bool], next_state:&mut [bool]) { next_state[0] = false; for index in range(1, current_state.len() - 1) { if current_state[index] { next_state[index] = false; } else { next_state[index] = current_state[index - 1] != current_state[index + 1]; } } next_state[current_state.len() - 1] = false; } fn print_state(current_state:&[bool]) { for index in range(0, current_state.len()) { if current_state[index] { print("*"); } else { print("."); } } println(""); } fn print_usage(file_name:&str) { writeln!(stderr(), "usage: {} size iterations", file_name); }
use message::*; use vecmath::*; use std::time::{Instant, Duration}; use config::{Config, ControllerMode, GimbalTrackingGain}; use std::collections::HashMap; use controller::velocity::RateLimitedVelocity; pub struct ManualControls { axes: HashMap<ManualControlAxis, f32>, velocity: RateLimitedVelocity, camera_control_active_until_timestamp: Option<Instant>, } impl ManualControls { pub fn new() -> ManualControls { ManualControls { axes: HashMap::new(), velocity: RateLimitedVelocity::new(), camera_control_active_until_timestamp: None, } } pub fn full_reset(&mut self) { *self = ManualControls::new(); } fn lookup_axis(&mut self, axis: ManualControlAxis) -> f32 { self.axes.entry(axis).or_insert(0.0).min(1.0).max(-1.0) } pub fn camera_vector(&mut self) -> Vector2<f32> { vec2_cast([ self.lookup_axis(ManualControlAxis::CameraYaw), self.lookup_axis(ManualControlAxis::CameraPitch), ]) } pub fn camera_vector_in_deadzone(cam_vec: Vector2<f32>, config: &Config) -> bool { let z = config.vision.manual_control_deadzone; vec2_square_len(cam_vec) <= z*z } pub fn tracking_update(&mut self, config: &Config, rect: Vector4<f32>, time_step: f32) -> Vector4<f32> { let vec = self.camera_vector(); let vec = if ManualControls::camera_vector_in_deadzone(vec, config) { [0.0, 0.0] } else { vec }; let velocity = vec2_mul(vec, vec2_scale([1.0, -1.0], config.vision.manual_control_speed)); let restoring_force_axis = |gains: &Vec<GimbalTrackingGain>, lower_dist: f32, upper_dist: f32| { let mut f = 0.0; for index in 0 .. gains.len() { let width = gains[index].width * config.vision.manual_control_restoring_force_width; f += (width - lower_dist).max(0.0) - (width - upper_dist).max(0.0); } f.max(-1.0).min(1.0) * config.vision.manual_control_restoring_force }; let border = config.vision.border_rect; let left_dist = rect_left(rect) - rect_left(border); let top_dist = rect_top(rect) - rect_top(border); let right_dist = rect_right(border) - rect_right(rect); let bottom_dist = rect_bottom(border) - rect_bottom(rect); let restoring_force = [ restoring_force_axis(&config.gimbal.yaw_gains, left_dist, right_dist), restoring_force_axis(&config.gimbal.pitch_gains, top_dist, bottom_dist), ]; let center = vec2_add(rect_center(rect), vec2_scale(vec2_add(velocity, restoring_force), time_step)); let side_len = config.vision.tracking_default_area.sqrt(); let default_rect = rect_centered_on_origin(side_len, side_len); rect_constrain(rect_translate(default_rect, center), config.vision.border_rect) } pub fn camera_control_active(&self) -> bool { match self.camera_control_active_until_timestamp { None => false, Some(timestamp) => Instant::now() < timestamp, } } fn lookup_relative_vec(&mut self) -> Vector3<f32> { [ self.lookup_axis(ManualControlAxis::RelativeX), self.lookup_axis(ManualControlAxis::RelativeY), self.lookup_axis(ManualControlAxis::RelativeZ), ] } fn velocity_target(&mut self, config: &Config) -> Vector3<f32> { let velocity_scale = config.params.manual_control_velocity_m_per_sec; vec3_scale(self.lookup_relative_vec(), velocity_scale) } pub fn limited_velocity(&self) -> Vector3<f32> { self.velocity.get() } pub fn control_tick(&mut self, config: &Config) { match config.mode { ControllerMode::Halted => self.full_reset(), _ => { let v = self.velocity_target(config); self.velocity.tick(config, v); self.camera_control_tick(config); } }; } pub fn camera_control_tick(&mut self, config: &Config) { if !ManualControls::camera_vector_in_deadzone(self.camera_vector(), config) { let timeout = Duration::from_millis((1000.0 * config.vision.manual_control_timeout_sec) as u64); self.camera_control_active_until_timestamp = Some(Instant::now() + timeout); } } pub fn control_value(&mut self, axis: ManualControlAxis, value: f32) { self.axes.insert(axis, value); } pub fn control_reset(&mut self) { self.axes.clear(); } }
//! Tests auto-converted from "sass-spec/spec/values/maps" #[allow(unused)] use super::rsass; // From "sass-spec/spec/values/maps/duplicate-keys.hrx" // Ignoring "duplicate_keys", error tests are not supported yet. // From "sass-spec/spec/values/maps/errors.hrx" // Ignoring "errors", error tests are not supported yet. // From "sass-spec/spec/values/maps/invalid-key.hrx" // Ignoring "invalid_key", error tests are not supported yet. // From "sass-spec/spec/values/maps/key_equality.hrx" mod key_equality { #[allow(unused)] use super::rsass; mod infinity { #[allow(unused)] use super::rsass; #[test] #[ignore] // wrong result fn negative() { assert_eq!( rsass( "a {b: inspect(map-get(((-1/0): b), -1/0))}\ \n" ) .unwrap(), "a {\ \n b: null;\ \n}\ \n" ); } #[test] #[ignore] // wrong result fn positive() { assert_eq!( rsass( "a {b: inspect(map-get(((1/0): b), 1/0))}\ \n" ) .unwrap(), "a {\ \n b: null;\ \n}\ \n" ); } } #[test] fn nan() { assert_eq!( rsass( "a {b: inspect(map-get(((0/0): b), 0/0))}\ \n" ) .unwrap(), "a {\ \n b: null;\ \n}\ \n" ); } } // From "sass-spec/spec/values/maps/length.hrx" #[test] fn length() { assert_eq!( rsass( "$map: (aaa: 100, bbb: 200, ccc: 300);\ \n\ \na {\ \n b: length($map);\ \n}\ \n" ) .unwrap(), "a {\ \n b: 3;\ \n}\ \n" ); } // From "sass-spec/spec/values/maps/map-values.hrx" #[test] fn map_values() { assert_eq!( rsass( "div {\ \n foo: map-values((foo: 1, bar: 2));\ \n foo: map-values((foo: 1, bar: 2, baz: 2));\ \n}\ \n" ) .unwrap(), "div {\ \n foo: 1, 2;\ \n foo: 1, 2, 2;\ \n}\ \n" ); }
use crate::{error::VelociError, persistence::Persistence}; use doc_store::DocStoreWriter; use std::{io::Write, path::Path, str}; #[derive(Debug)] pub(crate) struct DocWriteRes { pub(crate) num_doc_ids: u32, #[allow(dead_code)] pub(crate) bytes_indexed: u64, } pub(crate) fn write_docs<K, S: AsRef<str>>(persistence: &mut Persistence, stream3: K) -> Result<DocWriteRes, VelociError> where K: Iterator<Item = S>, { info_time!("write_docs"); let path = Path::new("data"); let mut file_out = persistence.directory.open_append(path)?; let mut doc_store = DocStoreWriter::new(0); for doc in stream3 { doc_store.add_doc(doc.as_ref(), &mut file_out)?; } doc_store.finish(&mut file_out)?; file_out.flush()?; // create_cache.term_data.current_offset = doc_store.current_offset; persistence.metadata.num_docs = doc_store.curr_id.into(); persistence.metadata.bytes_indexed = doc_store.bytes_indexed; Ok(DocWriteRes { num_doc_ids: doc_store.curr_id, bytes_indexed: doc_store.bytes_indexed, }) }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! A futures-rs executor design specifically for Fuchsia OS. #![deny(warnings)] #![deny(missing_docs)] extern crate bytes; extern crate crossbeam; #[macro_use] pub extern crate futures; extern crate fuchsia_zircon as zx; extern crate libc; extern crate net2; extern crate parking_lot; extern crate slab; // Set the system allocator for anything using this crate extern crate fuchsia_system_alloc; /// A future which can be used by multiple threads at once. pub mod atomic_future; mod channel; pub use channel::{Channel, RecvMsg}; mod on_signals; pub use on_signals::OnSignals; mod rwhandle; pub use rwhandle::RWHandle; mod socket; pub use socket::Socket; mod timer; pub use timer::{Interval, Timer, TimeoutExt, OnTimeout}; mod executor; pub use executor::{Executor, EHandle, spawn, spawn_local}; mod fifo; pub use fifo::{Fifo, FifoEntry, FifoReadable, FifoWritable, ReadEntry, WriteEntry}; pub mod net; #[macro_export] macro_rules! many_futures { ($future:ident, [$first:ident, $($subfuture:ident $(,)*)*]) => { enum $future<$first, $($subfuture,)*> { $first($first), $( $subfuture($subfuture), )* } impl<$first, $($subfuture,)*> $crate::futures::Future for $future<$first, $($subfuture,)*> where $first: $crate::futures::Future, $( $subfuture: $crate::futures::Future<Item = $first::Item, Error = $first::Error>, )* { type Item = $first::Item; type Error = $first::Error; fn poll(&mut self, cx: &mut $crate::futures::task::Context) -> $crate::futures::Poll<Self::Item, Self::Error> { match self { $future::$first(x) => $crate::futures::Future::poll(x, cx), $( $future::$subfuture(x) => $crate::futures::Future::poll(x, cx), )* } } } } }
mod fixtures; use assert_cmd::Command; use fixtures::{server, Error, TestServer, FILES}; use predicates::str::contains; use reqwest::blocking::ClientBuilder; use rstest::rstest; use select::{document::Document, node::Node}; /// Can start the server with TLS and receive encrypted responses. #[rstest] #[case(server(&[ "--tls-cert", "tests/data/cert_rsa.pem", "--tls-key", "tests/data/key_pkcs8.pem", ]))] #[case(server(&[ "--tls-cert", "tests/data/cert_rsa.pem", "--tls-key", "tests/data/key_pkcs1.pem", ]))] #[case(server(&[ "--tls-cert", "tests/data/cert_ec.pem", "--tls-key", "tests/data/key_ec.pem", ]))] fn tls_works(#[case] server: TestServer) -> Result<(), Error> { let client = ClientBuilder::new() .danger_accept_invalid_certs(true) .build()?; let body = client.get(server.url()).send()?.error_for_status()?; let parsed = Document::from_read(body)?; for &file in FILES { assert!(parsed.find(|x: &Node| x.text() == file).next().is_some()); } Ok(()) } /// Wrong path for cert throws error. #[rstest] fn wrong_path_cert() -> Result<(), Error> { Command::cargo_bin("miniserve")? .args(["--tls-cert", "wrong", "--tls-key", "tests/data/key.pem"]) .assert() .failure() .stderr(contains("Error: Couldn't access TLS certificate \"wrong\"")); Ok(()) } /// Wrong paths for key throws errors. #[rstest] fn wrong_path_key() -> Result<(), Error> { Command::cargo_bin("miniserve")? .args(["--tls-cert", "tests/data/cert.pem", "--tls-key", "wrong"]) .assert() .failure() .stderr(contains("Error: Couldn't access TLS key \"wrong\"")); Ok(()) }
// Run with `rust run hello.rs` fn greeter(greeting_text: &str) { println(fmt!("Hello %s!", greeting_text)); } fn main() { greeter("World"); }
// GM/T 0004-2012 SM3密码杂凑算法标准 (中文版本) // https://sca.gov.cn/sca/xwdt/2010-12/17/1002389/files/302a3ada057c4a73830536d03e683110.pdf // // GM/T 0004-2012 SM3 Cryptographic Hash Algorithm (English Version) // http://www.gmbz.org.cn/upload/2018-07-24/1532401392982079739.pdf use core::convert::TryFrom; const INITIAL_STATE: [u32; 8] = [ 0x7380_166f, 0x4914_b2b9, 0x1724_42d7, 0xda8a_0600, 0xa96f_30bc, 0x1631_38aa, 0xe38d_ee4d, 0xb0fb_0e4e, ]; /// GM/T 0004-2012 SM3密码杂凑算法标准 pub fn sm3<T: AsRef<[u8]>>(data: T) -> [u8; Sm3::DIGEST_LEN] { Sm3::oneshot(data) } /// GM/T 0004-2012 SM3密码杂凑算法标准 #[derive(Clone)] pub struct Sm3 { buffer: [u8; Self::BLOCK_LEN], state: [u32; 8], len: u64, // in bytes offset: usize, } impl Sm3 { pub const BLOCK_LEN: usize = 64; pub const DIGEST_LEN: usize = 32; const BLOCK_LEN_BITS: u64 = Self::BLOCK_LEN as u64 * 8; const MLEN_SIZE: usize = core::mem::size_of::<u64>(); const MLEN_SIZE_BITS: u64 = Self::MLEN_SIZE as u64 * 8; const MAX_PAD_LEN: usize = Self::BLOCK_LEN + Self::MLEN_SIZE as usize; pub fn new() -> Self { Self { buffer: [0u8; Self::BLOCK_LEN], state: INITIAL_STATE, len: 0, offset: 0usize, } } pub fn update(&mut self, data: &[u8]) { let mut i = 0usize; while i < data.len() { if self.offset < Self::BLOCK_LEN { self.buffer[self.offset] = data[i]; self.offset += 1; i += 1; } if self.offset == Self::BLOCK_LEN { transform(&mut self.state, &self.buffer); self.offset = 0; self.len += Self::BLOCK_LEN as u64; } } } pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] { let mlen = self.len + self.offset as u64; // in bytes let mlen_bits = mlen * 8; // in bits // pad len, in bits let plen_bits = Self::BLOCK_LEN_BITS - (mlen_bits + Self::MLEN_SIZE_BITS + 1) % Self::BLOCK_LEN_BITS + 1; // pad len, in bytes let plen = plen_bits / 8; debug_assert_eq!(plen_bits % 8, 0); debug_assert!(plen > 1); debug_assert_eq!( (mlen + plen + Self::MLEN_SIZE as u64) % Self::BLOCK_LEN as u64, 0 ); // NOTE: MAX_PAD_LEN 是一个很小的数字,所以这里可以安全的 unwrap. let plen = usize::try_from(plen).unwrap(); let mut padding: [u8; Self::MAX_PAD_LEN] = [0u8; Self::MAX_PAD_LEN]; padding[0] = 0x80; let mlen_octets: [u8; Self::MLEN_SIZE] = mlen_bits.to_be_bytes(); padding[plen..plen + Self::MLEN_SIZE].copy_from_slice(&mlen_octets); let data = &padding[..plen + Self::MLEN_SIZE]; self.update(data); // NOTE: 数据填充完毕后,此时已经处理的消息应该是 BLOCK_LEN 的倍数,因此,offset 此时已被清零。 debug_assert_eq!(self.offset, 0); let mut output = [0u8; Self::DIGEST_LEN]; output[0..4].copy_from_slice(&self.state[0].to_be_bytes()); output[4..8].copy_from_slice(&self.state[1].to_be_bytes()); output[8..12].copy_from_slice(&self.state[2].to_be_bytes()); output[12..16].copy_from_slice(&self.state[3].to_be_bytes()); output[16..20].copy_from_slice(&self.state[4].to_be_bytes()); output[20..24].copy_from_slice(&self.state[5].to_be_bytes()); output[24..28].copy_from_slice(&self.state[6].to_be_bytes()); output[28..32].copy_from_slice(&self.state[7].to_be_bytes()); output } pub fn oneshot<T: AsRef<[u8]>>(data: T) -> [u8; Self::DIGEST_LEN] { let mut m = Self::new(); m.update(data.as_ref()); m.finalize() } } #[inline(always)] fn ff0(x: u32, y: u32, z: u32) -> u32 { x ^ y ^ z } #[inline(always)] fn ff1(x: u32, y: u32, z: u32) -> u32 { (x & y) | (x & z) | (y & z) } #[inline(always)] fn gg0(x: u32, y: u32, z: u32) -> u32 { x ^ y ^ z } #[inline(always)] fn gg1(x: u32, y: u32, z: u32) -> u32 { (x & y) | (!x & z) } #[inline(always)] fn p0(x: u32) -> u32 { x ^ x.rotate_left(9) ^ x.rotate_left(17) } #[inline(always)] fn p1(x: u32) -> u32 { x ^ x.rotate_left(15) ^ x.rotate_left(23) } #[inline] fn transform(state: &mut [u32; 8], block: &[u8; Sm3::BLOCK_LEN]) { // get expend let mut w: [u32; 68] = [0; 68]; let mut w1: [u32; 64] = [0; 64]; for i in 0..16 { let a = block[i * 4 + 0]; let b = block[i * 4 + 1]; let c = block[i * 4 + 2]; let d = block[i * 4 + 3]; w[i] = u32::from_be_bytes([a, b, c, d]); } for i in 16..68 { w[i] = p1(w[i - 16] ^ w[i - 9] ^ w[i - 3].rotate_left(15)) ^ w[i - 13].rotate_left(7) ^ w[i - 6]; } for i in 0..Sm3::BLOCK_LEN { w1[i] = w[i] ^ w[i + 4]; } let mut ra = state[0]; let mut rb = state[1]; let mut rc = state[2]; let mut rd = state[3]; let mut re = state[4]; let mut rf = state[5]; let mut rg = state[6]; let mut rh = state[7]; let mut ss1: u32; let mut ss2: u32; let mut tt1: u32; let mut tt2: u32; for i in 0..16 { ss1 = ra .rotate_left(12) .wrapping_add(re) .wrapping_add(0x79cc_4519u32.rotate_left(i as u32)) .rotate_left(7); ss2 = ss1 ^ ra.rotate_left(12); tt1 = ff0(ra, rb, rc) .wrapping_add(rd) .wrapping_add(ss2) .wrapping_add(w1[i]); tt2 = gg0(re, rf, rg) .wrapping_add(rh) .wrapping_add(ss1) .wrapping_add(w[i]); rd = rc; rc = rb.rotate_left(9); rb = ra; ra = tt1; rh = rg; rg = rf.rotate_left(19); rf = re; re = p0(tt2); } for i in 16..64 { ss1 = ra .rotate_left(12) .wrapping_add(re) .wrapping_add(0x7a87_9d8au32.rotate_left(i as u32)) .rotate_left(7); ss2 = ss1 ^ ra.rotate_left(12); tt1 = ff1(ra, rb, rc) .wrapping_add(rd) .wrapping_add(ss2) .wrapping_add(w1[i]); tt2 = gg1(re, rf, rg) .wrapping_add(rh) .wrapping_add(ss1) .wrapping_add(w[i]); rd = rc; rc = rb.rotate_left(9); rb = ra; ra = tt1; rh = rg; rg = rf.rotate_left(19); rf = re; re = p0(tt2); } state[0] ^= ra; state[1] ^= rb; state[2] ^= rc; state[3] ^= rd; state[4] ^= re; state[5] ^= rf; state[6] ^= rg; state[7] ^= rh; } #[test] fn test_sm3() { // A.1 示例1 // https://sca.gov.cn/sca/xwdt/2010-12/17/1002389/files/302a3ada057c4a73830536d03e683110.pdf let digest = sm3(b"abc"); assert_eq!( &digest[..], &[ 0x66, 0xc7, 0xf0, 0xf4, 0x62, 0xee, 0xed, 0xd9, 0xd1, 0xf2, 0xd4, 0x6b, 0xdc, 0x10, 0xe4, 0xe2, 0x41, 0x67, 0xc4, 0x87, 0x5c, 0xf2, 0xf7, 0xa2, 0x29, 0x7d, 0xa0, 0x2b, 0x8f, 0x4b, 0xa8, 0xe0, ] ); // A.1 示例2 let digest = sm3(b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd"); assert_eq!( &digest[..], &[ 0xde, 0xbe, 0x9f, 0xf9, 0x22, 0x75, 0xb8, 0xa1, 0x38, 0x60, 0x48, 0x89, 0xc1, 0x8e, 0x5a, 0x4d, 0x6f, 0xdb, 0x70, 0xe5, 0x38, 0x7e, 0x57, 0x65, 0x29, 0x3d, 0xcb, 0xa3, 0x9c, 0x0c, 0x57, 0x32, ] ); }
use std::process::{Command, Stdio, Child, ChildStdout}; use assert_cmd::prelude::*; use std::io::{Write}; use std::thread::sleep; use std::time::Duration; use nonblock::NonBlockingReader; use std::ops::{Deref, DerefMut}; use rzmq::{chat, socket}; fn test_push_pull_send_listen() { let test_message = "TEST MESSAGE 12345"; let mut listener = run_instance("listen --address tcp://127.0.0.1:5559 --type PULL --bind").unwrap(); let _send = run_instance(format!("send --message {} --address tcp://127.0.0.1:5559 --type PUSH --connect", test_message).as_str()).unwrap(); assert!(listener.wait_for_message(test_message).is_ok()); } fn test_push_pull_with_json_config() { let test_message = "TEST MESSAGE 12345"; let mut listener = run_instance("listen --config test_config.json").unwrap(); let _send = run_instance(format!("send --message {} --config test_config.json --type PUSH --connect", test_message).as_str()).unwrap(); assert!(listener.wait_for_message(test_message).is_ok()); } fn test_pub_sub() { let test_message_wo_topic = "TEST MESSAGE1"; let test_message_with_topic = "TOPIC1 TEST MESSAGE2"; let mut listener = run_instance("listen --topic TOPIC1 --address tcp://127.0.0.1:5559 --type SUB --bind").unwrap(); let _send1 = run_instance(format!("send --message {} --address tcp://127.0.0.1:5559 --type PUB --connect", test_message_wo_topic).as_str()).unwrap(); assert!(listener.wait_for_message( test_message_wo_topic).is_err()); let _send2 = run_instance(format!("send --message {} --address tcp://127.0.0.1:5559 --type PUB --connect", test_message_with_topic).as_str()).unwrap(); assert!(listener.wait_for_message( test_message_with_topic).is_ok()); } fn test_pair_chat() { let instance1 = chat::Chat::new(&socket::SocketParameters{ address: "tcp://127.0.0.1:5559", association_type: socket::AssociationType::Bind, socket_type: socket::SocketType::PAIR, socket_id: None, topic: None}).unwrap(); let instance2 = chat::Chat::new(&socket::SocketParameters{ address: "tcp://127.0.0.1:5559", association_type: socket::AssociationType::Connect, socket_type: socket::SocketType::PAIR, socket_id: None, topic: None}).unwrap(); instance1.send("Hi!").unwrap(); instance1.send("How are you?").unwrap(); sleep(Duration::from_millis(500)); assert_eq!("Hi!", instance2.receive().unwrap()[0].as_str() ); assert_eq!("How are you?", instance2.receive().unwrap()[0].as_str()); instance2.send("I'm fine").unwrap(); assert_eq!("I'm fine", instance1.receive().unwrap()[0].as_str()); } fn test_router_dealer_chat() { let router = chat::Chat::new(&socket::SocketParameters{ address: "tcp://127.0.0.1:5559", association_type: socket::AssociationType::Bind, socket_type: socket::SocketType::ROUTER, socket_id: None, topic: None}).unwrap(); let dealer = chat::Chat::new(&socket::SocketParameters{ address: "tcp://127.0.0.1:5559", association_type: socket::AssociationType::Connect, socket_type: socket::SocketType::DEALER, socket_id: Some("ID1"), topic: None}).unwrap(); let dealer2 = chat::Chat::new(&socket::SocketParameters{ address: "tcp://127.0.0.1:5559", association_type: socket::AssociationType::Connect, socket_type: socket::SocketType::DEALER, socket_id: Some("ID2"), topic: None}).unwrap(); dealer.send("MSG1").unwrap(); dealer.send("MSG2").unwrap(); sleep(Duration::from_millis(500)); assert_eq!(["ID1", "MSG1"], router.receive().unwrap()[0..2]); assert_eq!(["ID1", "MSG2"], router.receive().unwrap()[0..2]); router.send_with_id("ID1", "MSG3").unwrap(); router.send_with_id("ID2", "MSG4").unwrap(); assert_eq!("MSG3", dealer.receive().unwrap()[0].as_str()); assert_eq!("MSG4", dealer2.receive().unwrap()[0].as_str()); } #[test] fn integration_tests() { test_push_pull_send_listen(); test_push_pull_with_json_config(); test_pub_sub(); test_pair_chat(); test_router_dealer_chat(); } fn run_instance(args: &str) -> Result<Wrapper, String> { let args = args.split_whitespace(); Command::cargo_bin("rzmq") .map_err(|e| e.to_string()) .and_then(|mut command | { command .args(args) .stdout(Stdio::piped()) .stdin(Stdio::piped()) .spawn() .map_err(|e| e.to_string()) }).map(|mut c| { let reader = NonBlockingReader::from_fd(c.stdout.take().unwrap()).unwrap(); Wrapper{ 0: c, 1: reader} }) } struct Wrapper(Child, NonBlockingReader<ChildStdout>); impl Drop for Wrapper { fn drop(&mut self) { self.kill().unwrap(); } } impl DerefMut for Wrapper { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Deref for Wrapper { type Target = Child; fn deref(&self) -> &Self::Target { &self.0 } } impl Wrapper { fn wait_for_message(&mut self, message: &str) -> Result<(), &'static str> { let mut buffer = String::new(); for _ in 1..10 { self.1.read_available_to_string(&mut buffer).unwrap(); println!("OUT: {}", buffer); if buffer.contains(message) { println!("MATCHED: {}", buffer); return Ok(()); } sleep(Duration::from_millis(100)); } Err("Message not received") } fn _write(&mut self, input: &str) { self.stdin.as_mut().unwrap().write(input.as_bytes()).unwrap(); } }
#[doc = "Register `ISR` reader"] pub type R = crate::R<ISR_SPEC>; #[doc = "Field `PE` reader - PE"] pub type PE_R = crate::BitReader; #[doc = "Field `FE` reader - FE"] pub type FE_R = crate::BitReader; #[doc = "Field `NF` reader - NF"] pub type NF_R = crate::BitReader; #[doc = "Field `ORE` reader - ORE"] pub type ORE_R = crate::BitReader; #[doc = "Field `IDLE` reader - IDLE"] pub type IDLE_R = crate::BitReader; #[doc = "Field `RXNE` reader - RXNE"] pub type RXNE_R = crate::BitReader; #[doc = "Field `TC` reader - TC"] pub type TC_R = crate::BitReader; #[doc = "Field `TXE` reader - TXE"] pub type TXE_R = crate::BitReader; #[doc = "Field `CTSIF` reader - CTSIF"] pub type CTSIF_R = crate::BitReader; #[doc = "Field `CTS` reader - CTS"] pub type CTS_R = crate::BitReader; #[doc = "Field `BUSY` reader - BUSY"] pub type BUSY_R = crate::BitReader; #[doc = "Field `CMF` reader - CMF"] pub type CMF_R = crate::BitReader; #[doc = "Field `SBKF` reader - SBKF"] pub type SBKF_R = crate::BitReader; #[doc = "Field `RWU` reader - RWU"] pub type RWU_R = crate::BitReader; #[doc = "Field `WUF` reader - WUF"] pub type WUF_R = crate::BitReader; #[doc = "Field `TEACK` reader - TEACK"] pub type TEACK_R = crate::BitReader; #[doc = "Field `REACK` reader - REACK"] pub type REACK_R = crate::BitReader; #[doc = "Field `TXFF` reader - ??"] pub type TXFF_R = crate::BitReader; #[doc = "Field `RXFF` reader - ??"] pub type RXFF_R = crate::BitReader; #[doc = "Field `RXFT` reader - RXFIFO threshold flag"] pub type RXFT_R = crate::BitReader; #[doc = "Field `TXFT` reader - TXFIFO threshold flag"] pub type TXFT_R = crate::BitReader; impl R { #[doc = "Bit 0 - PE"] #[inline(always)] pub fn pe(&self) -> PE_R { PE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - FE"] #[inline(always)] pub fn fe(&self) -> FE_R { FE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - NF"] #[inline(always)] pub fn nf(&self) -> NF_R { NF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - ORE"] #[inline(always)] pub fn ore(&self) -> ORE_R { ORE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - IDLE"] #[inline(always)] pub fn idle(&self) -> IDLE_R { IDLE_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - RXNE"] #[inline(always)] pub fn rxne(&self) -> RXNE_R { RXNE_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - TC"] #[inline(always)] pub fn tc(&self) -> TC_R { TC_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - TXE"] #[inline(always)] pub fn txe(&self) -> TXE_R { TXE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 9 - CTSIF"] #[inline(always)] pub fn ctsif(&self) -> CTSIF_R { CTSIF_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - CTS"] #[inline(always)] pub fn cts(&self) -> CTS_R { CTS_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 16 - BUSY"] #[inline(always)] pub fn busy(&self) -> BUSY_R { BUSY_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - CMF"] #[inline(always)] pub fn cmf(&self) -> CMF_R { CMF_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - SBKF"] #[inline(always)] pub fn sbkf(&self) -> SBKF_R { SBKF_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - RWU"] #[inline(always)] pub fn rwu(&self) -> RWU_R { RWU_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - WUF"] #[inline(always)] pub fn wuf(&self) -> WUF_R { WUF_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - TEACK"] #[inline(always)] pub fn teack(&self) -> TEACK_R { TEACK_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - REACK"] #[inline(always)] pub fn reack(&self) -> REACK_R { REACK_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - ??"] #[inline(always)] pub fn txff(&self) -> TXFF_R { TXFF_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - ??"] #[inline(always)] pub fn rxff(&self) -> RXFF_R { RXFF_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 26 - RXFIFO threshold flag"] #[inline(always)] pub fn rxft(&self) -> RXFT_R { RXFT_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - TXFIFO threshold flag"] #[inline(always)] pub fn txft(&self) -> TXFT_R { TXFT_R::new(((self.bits >> 27) & 1) != 0) } } #[doc = "Interrupt &amp; status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ISR_SPEC; impl crate::RegisterSpec for ISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`isr::R`](R) reader structure"] impl crate::Readable for ISR_SPEC {} #[doc = "`reset()` method sets ISR to value 0xc0"] impl crate::Resettable for ISR_SPEC { const RESET_VALUE: Self::Ux = 0xc0; }
#![allow(dead_code)] #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #[macro_use] extern crate arrayref; #[macro_use] extern crate bitflags; #[macro_use] extern crate derive_new; #[macro_use] extern crate downcast_rs; #[macro_use] extern crate enum_dispatch; #[macro_use] extern crate num_derive; #[macro_use] extern crate steam_language_gen_derive; use downcast_rs::Downcast; use serde::Serialize; use crate::generated::headers::{ExtendedMessageHeader, StandardMessageHeader}; pub mod generated; pub mod generator; pub mod parser; #[enum_dispatch] #[derive(Clone, Debug, Serialize)] /// This wraps our headers so we can be generic over them over a Msg type. pub enum MessageHeaderWrapper { Std(StandardMessageHeader), Ext(ExtendedMessageHeader), } /// Every implementation has to implement bincode::serialize and deserialize pub trait SerializableBytes: Downcast { fn to_bytes(&self) -> Vec<u8>; } impl_downcast!(SerializableBytes); /// delegate serialization to inner type impl SerializableBytes for MessageHeaderWrapper { fn to_bytes(&self) -> Vec<u8> { match self { MessageHeaderWrapper::Std(hdr) => hdr.to_bytes(), MessageHeaderWrapper::Ext(hdr) => hdr.to_bytes(), } } } pub trait DeserializableBytes { fn from_bytes(packet_data: &[u8]) -> Self; } #[enum_dispatch(MessageHeaderWrapper)] pub trait MessageHeader: Downcast { fn set_target(&mut self, new_target: u64); fn set_source(&mut self, new_source: u64); } impl_downcast!(MessageHeader); // facilities around headers pub trait MessageHeaderExt: Downcast { /// delegate to new fn create() -> Self; /// Returns header on the left, rest on the right fn split_from_bytes(data: &[u8]) -> (&[u8], &[u8]); } pub trait MessageBodyExt: Downcast { fn split_from_bytes(data: &[u8]) -> (&[u8], &[u8]); } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Element { File, Head, Type, Member, } #[derive(PartialEq, Eq)] pub struct Token<'a> { value: String, default: Option<&'a str>, } impl<'a> Token<'a> { fn get_value(&self) -> &String { &self.value } fn get_default(&self) -> Option<&'a str> { self.default } }
use crate::{ component::{ containers::paper::{paper, PaperProps}, text_paper::{text_paper, TextPaperProps}, }, theme::ThemedWidgetProps, }; use raui_core::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TextFieldPaperProps { #[serde(default)] pub hint: String, #[serde(default)] pub width: TextBoxSizeValue, #[serde(default)] pub height: TextBoxSizeValue, #[serde(default)] pub variant: String, #[serde(default)] pub use_main_color: bool, #[serde(default)] pub transform: Transform, #[serde(default)] pub paper_theme: ThemedWidgetProps, #[serde(default = "TextFieldPaperProps::default_padding")] pub padding: Rect, } implement_props_data!(TextFieldPaperProps, "TextFieldPaperProps"); impl TextFieldPaperProps { fn default_padding() -> Rect { Rect { left: 4.0, right: 4.0, top: 4.0, bottom: 4.0, } } } impl Default for TextFieldPaperProps { fn default() -> Self { Self { hint: Default::default(), width: Default::default(), height: Default::default(), variant: Default::default(), use_main_color: Default::default(), transform: Default::default(), paper_theme: Default::default(), padding: Self::default_padding(), } } } widget_component! { text_field_content(key, props) { let ButtonProps { selected, .. } = props.read_cloned_or_default(); let TextFieldPaperProps { hint, width, height, variant, use_main_color, transform, paper_theme, padding, } = props.read_cloned_or_default(); let InputFieldProps { text, cursor_position, .. } = props.read_cloned_or_default(); let text = text.trim(); let text = if text.is_empty() { hint } else if selected { if cursor_position < text.len() { format!("{}|{}", &text[..cursor_position], &text[cursor_position..]) } else { format!("{}|", text) } } else { text.to_owned() }; let paper_variant = props.map_or_default::<PaperProps, _, _>(|p| p.variant.clone()); let paper_props = props.clone().with(PaperProps { variant: paper_variant, ..Default::default() }).with(paper_theme); let props = props.clone().with(TextPaperProps { text, width, height, variant, use_main_color, transform, }).with(ContentBoxItemLayout { margin: padding, ..Default::default() }); widget! { (#{key} paper: {paper_props} [ (#{key} text_paper: {props}) ]) } } } widget_component! { pub text_field_paper(key, props) { widget! { (#{key} input_field: {props.clone()} { content = (#{"text"} text_field_content: {props.clone()}) }) } } }
use actix_web::{middleware, web, App, HttpServer}; use forum_rust::config::MyConfig as Config; use forum_rust::headers; #[actix_web::main] async fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); let config = Config::new(); let pool = r2d2::Pool::new(config.sqlite_manager).unwrap(); HttpServer::new(move || { App::new() .data(pool.clone()) .wrap(middleware::Logger::default()) .route("/", web::get().to(headers::index)) .route("/testdb", web::get().to(headers::testdb)) }) .bind((config.server_address, config.server_port))? .run() .await }
mod crypto_key; mod crypto_read; mod crypto_write; pub use self::crypto_key::*; pub use self::crypto_read::*; pub use self::crypto_write::*; // ex: et ts=2 filetype=rust
use std::fmt; pub struct UserInputLiteral { pub field_name: Option<String>, pub phrase: String, } impl fmt::Debug for UserInputLiteral { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self.field_name { Some(ref field_name) => write!(formatter, "{}:\"{}\"", field_name, self.phrase), None => write!(formatter, "\"{}\"", self.phrase), } } } pub enum UserInputBound { Inclusive(String), Exclusive(String), } impl UserInputBound { fn display_lower(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { UserInputBound::Inclusive(ref word) => write!(formatter, "[\"{}\"", word), UserInputBound::Exclusive(ref word) => write!(formatter, "{{\"{}\"", word), } } fn display_upper(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { UserInputBound::Inclusive(ref word) => write!(formatter, "\"{}\"]", word), UserInputBound::Exclusive(ref word) => write!(formatter, "\"{}\"}}", word), } } pub fn term_str(&self) -> &str { match *self { UserInputBound::Inclusive(ref contents) => contents, UserInputBound::Exclusive(ref contents) => contents, } } } pub enum UserInputAST { Clause(Vec<Box<UserInputAST>>), Not(Box<UserInputAST>), Must(Box<UserInputAST>), Range { field: Option<String>, lower: UserInputBound, upper: UserInputBound, }, All, Leaf(Box<UserInputLiteral>), } impl From<UserInputLiteral> for UserInputAST { fn from(literal: UserInputLiteral) -> UserInputAST { UserInputAST::Leaf(Box::new(literal)) } } impl fmt::Debug for UserInputAST { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { UserInputAST::Must(ref subquery) => write!(formatter, "+({:?})", subquery), UserInputAST::Clause(ref subqueries) => { if subqueries.is_empty() { write!(formatter, "<emptyclause>")?; } else { write!(formatter, "(")?; write!(formatter, "{:?}", &subqueries[0])?; for subquery in &subqueries[1..] { write!(formatter, " {:?}", subquery)?; } write!(formatter, ")")?; } Ok(()) } UserInputAST::Not(ref subquery) => write!(formatter, "-({:?})", subquery), UserInputAST::Range { ref field, ref lower, ref upper, } => { if let &Some(ref field) = field { write!(formatter, "{}:", field)?; } lower.display_lower(formatter)?; write!(formatter, " TO ")?; upper.display_upper(formatter)?; Ok(()) } UserInputAST::All => write!(formatter, "*"), UserInputAST::Leaf(ref subquery) => write!(formatter, "{:?}", subquery), } } }
//! src/handlers.rs use axum::{ extract::{Extension, Json, UrlParams}, response::{self, IntoResponse}, }; use hyper::http::StatusCode; use serde_json::json; use sqlx::{postgres::PgPool, query_as}; use uuid::Uuid; use crate::models; pub async fn get_recipes( Extension(pool): Extension<PgPool>, ) -> response::Json<Vec<models::RecipesOut>> { let recipe = query_as!( models::RecipesOut, r#" SELECT id, title FROM recipes ORDER BY title "# ) .fetch_all(&pool) .await .unwrap(); response::Json(recipe) } pub async fn get_recipe( Extension(pool): Extension<PgPool>, UrlParams((id,)): UrlParams<(Uuid,)>, ) -> response::Json<models::RecipeOut> { let recipe = query_as!( models::RecipeOut, r#" SELECT id, title, content FROM recipes WHERE id = $1 "#, id ) .fetch_one(&pool) .await .unwrap(); response::Json(recipe) } pub async fn create_recipe( Extension(pool): Extension<PgPool>, Json(recipe): Json<models::RecipeIn>, ) -> impl IntoResponse { let recipe_id = Uuid::new_v4(); sqlx::query!( "INSERT INTO recipes (id, title, content, published) VALUES ($1, $2, $3, $4)", recipe_id, recipe.title, recipe.content, recipe.published, ) .execute(&pool) .await .expect("Failed to insert to DB"); ( StatusCode::CREATED, response::Json(json!({ "recipe_id": recipe_id })), ) } pub async fn update_recipe( Extension(pool): Extension<PgPool>, Json(recipe): Json<models::RecipeUpdate>, ) -> impl IntoResponse { todo!() } pub async fn delete_recipe( Extension(pool): Extension<PgPool>, UrlParams((id,)): UrlParams<(Uuid,)>, ) -> impl IntoResponse { sqlx::query!( r#" DELETE FROM recipes WHERE id = $1 "#, id ) .execute(&pool) .await .expect("Failed to delete row from DB"); ( StatusCode::OK, response::Json(json!({ "recipe_id": id })), ) }
use juice_sdk_rs::{client, transports, types, Result}; #[tokio::main] async fn main() -> Result<()> { let transport = transports::http::Http::new("http://10.1.1.40:7009")?; let client = client::Client::new(transport, true); let number = client.block_number(String::from("test")).await?; let block = client .block_by_number(String::from("test"), types::BlockNumber::Number(number)) .await?; let block = block.unwrap(); if block.transactions.len() > 0 { let transaction = client .transaction_by_hash(String::from("test"), block.transactions[0].hash) .await?; println!("{:?}", transaction); } Ok(()) }
#[doc = "Register `HYSCR2` reader"] pub type R = crate::R<HYSCR2_SPEC>; #[doc = "Register `HYSCR2` writer"] pub type W = crate::W<HYSCR2_SPEC>; #[doc = "Field `PC` reader - Port C hysteresis control on/off"] pub type PC_R = crate::FieldReader<u16>; #[doc = "Field `PC` writer - Port C hysteresis control on/off"] pub type PC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; #[doc = "Field `PD` reader - Port D hysteresis control on/off"] pub type PD_R = crate::FieldReader<u16>; #[doc = "Field `PD` writer - Port D hysteresis control on/off"] pub type PD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; impl R { #[doc = "Bits 0:15 - Port C hysteresis control on/off"] #[inline(always)] pub fn pc(&self) -> PC_R { PC_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - Port D hysteresis control on/off"] #[inline(always)] pub fn pd(&self) -> PD_R { PD_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Port C hysteresis control on/off"] #[inline(always)] #[must_use] pub fn pc(&mut self) -> PC_W<HYSCR2_SPEC, 0> { PC_W::new(self) } #[doc = "Bits 16:31 - Port D hysteresis control on/off"] #[inline(always)] #[must_use] pub fn pd(&mut self) -> PD_W<HYSCR2_SPEC, 16> { PD_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 = "RI hysteresis control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hyscr2::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 [`hyscr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HYSCR2_SPEC; impl crate::RegisterSpec for HYSCR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hyscr2::R`](R) reader structure"] impl crate::Readable for HYSCR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`hyscr2::W`](W) writer structure"] impl crate::Writable for HYSCR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets HYSCR2 to value 0"] impl crate::Resettable for HYSCR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn memory_copy( minitrace::TraceDetails { start_time_ns, elapsed_ns, cycles_per_second, spans, properties: minitrace::Properties { span_ids, property_lens, payload, }, }: minitrace::TraceDetails, buf: &mut Vec<u8>, ) { let total_len = std::mem::size_of::<minitrace::TraceDetails>() + std::mem::size_of::<minitrace::Span>() * spans.len() + std::mem::size_of::<minitrace::Properties>() + std::mem::size_of::<u64>() * span_ids.len() + std::mem::size_of::<u64>() * property_lens.len() + std::mem::size_of::<u8>() * payload.len(); buf.reserve(total_len); buf.extend_from_slice(&start_time_ns.to_be_bytes()); buf.extend_from_slice(&elapsed_ns.to_be_bytes()); buf.extend_from_slice(&cycles_per_second.to_be_bytes()); unsafe { let origin = buf.as_mut_ptr(); let mut cur_ptr = origin.add(buf.len()); let c = spans.len() * std::mem::size_of::<minitrace::Span>(); std::ptr::copy_nonoverlapping(spans.as_ptr() as *const u8, cur_ptr, c); cur_ptr = cur_ptr.add(c); let c = span_ids.len() * std::mem::size_of::<u64>(); std::ptr::copy_nonoverlapping(span_ids.as_ptr() as *const u8, cur_ptr, c); cur_ptr = cur_ptr.add(c); let c = property_lens.len() * std::mem::size_of::<u64>(); std::ptr::copy_nonoverlapping(property_lens.as_ptr() as *const u8, cur_ptr, c); cur_ptr = cur_ptr.add(c); let c = payload.len() * std::mem::size_of::<u8>(); std::ptr::copy_nonoverlapping(payload.as_ptr() as *const u8, cur_ptr, c); cur_ptr = cur_ptr.add(c); buf.set_len(cur_ptr as usize - origin as usize); } } #[derive(Debug, Copy, Clone)] enum Type { Memcpy, Flatbuffers, } fn serizalization(c: &mut Criterion) { c.bench_function_over_inputs( "serialization", |b, tp| { b.iter_with_setup( || { let collector = { let (_root, collector) = minitrace::trace_enable(0u32); for i in 1..50u32 { let _guard = minitrace::new_span(i); } let handle = minitrace::trace_crossthread(); let jh = std::thread::spawn(move || { let mut handle = handle; let _guard = handle.trace_enable(50u32); for i in 51..100u32 { let _guard = minitrace::new_span(i); } }); jh.join().unwrap(); collector }; collector.collect() }, |trace_result| match tp { Type::Memcpy => { let mut buf = Vec::with_capacity(8192); memory_copy(trace_result, &mut buf); black_box(buf); } Type::Flatbuffers => { let mut builder = flatbuffers::FlatBufferBuilder::new_with_capacity(8192); black_box( minitrace_fbs::serialize_to_fbs(&mut builder, trace_result).unwrap(), ); } }, ); }, vec![Type::Memcpy, Type::Flatbuffers], ); } criterion_group!(benches, serizalization); criterion_main!(benches);
#[doc = "Register `T0VALR1` reader"] pub type R = crate::R<T0VALR1_SPEC>; #[doc = "Field `TS1_FMT0` reader - Engineering value of the frequency measured at T0 for temperature sensor 1 This value is expressed in 0.1 kHz."] pub type TS1_FMT0_R = crate::FieldReader<u16>; #[doc = "Field `TS1_T0` reader - Engineering value of the T0 temperature for temperature sensor 1. Others: Reserved, must not be used."] pub type TS1_T0_R = crate::FieldReader; impl R { #[doc = "Bits 0:15 - Engineering value of the frequency measured at T0 for temperature sensor 1 This value is expressed in 0.1 kHz."] #[inline(always)] pub fn ts1_fmt0(&self) -> TS1_FMT0_R { TS1_FMT0_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:17 - Engineering value of the T0 temperature for temperature sensor 1. Others: Reserved, must not be used."] #[inline(always)] pub fn ts1_t0(&self) -> TS1_T0_R { TS1_T0_R::new(((self.bits >> 16) & 3) as u8) } } #[doc = "Temperature sensor T0 value register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`t0valr1::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct T0VALR1_SPEC; impl crate::RegisterSpec for T0VALR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`t0valr1::R`](R) reader structure"] impl crate::Readable for T0VALR1_SPEC {} #[doc = "`reset()` method sets T0VALR1 to value 0"] impl crate::Resettable for T0VALR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
// /Users/josiah/github/rustOS/src/serial.rs use uart_16550::SerialPort; // SerialPort implements fmt::Write trait use spin::Mutex; use lazy_static::lazy_static; lazy_static! { // "use lazy_static and a spinlock to create a static writer instance" pub static ref SERIAL1: Mutex<SerialPort> = { // Mutex 'mutual exclusion' locks out a thread // at least, I think it does let mut serial_port = unsafe { SerialPort::new(0x3F8) }; // port 1016/0b0011 1111 1000 serial_port.init(); Mutex::new(serial_port) }; } #[doc(hidden)] // prevent this from entering docs pub fn _print(args: ::core::fmt::Arguments) { // core print function use core::fmt::Write; use x86_64::instructions::interrupts; interrupts::without_interrupts(|| { SERIAL1 .lock() .write_fmt(args) .expect("Printing to serial failed"); }); } /// Prints to the host through the serial interface #[macro_export] macro_rules! serial_print { // define a macro for printing a single line ($($arg:tt)*) => { $crate::serial::_print(format_args!($($arg)*)); }; } /// Prints to the host through the serial interface, appending a newline. #[macro_export] macro_rules! serial_println { () => ($crate::serial_print!("\n")); ($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::serial_print!( concat!($fmt, "\n"), $($arg)*)); }
use kvs::*; use std::process; use structopt::StructOpt; const IO_ERR: i32 = 74; #[derive(Debug, StructOpt)] #[structopt(name = "kvs", about = "Key value storage")] struct Cli { #[structopt(subcommand)] cmd: Command, } #[derive(Debug, StructOpt)] pub enum Command { #[structopt(name = "set")] /// Set and modify key:value pairings Set { key: String, val: String }, #[structopt(name = "get")] /// Access stored key:value pairings Get { key: String }, #[structopt(name = "rm")] /// Remove stored key:value pairings Remove { key: String }, } fn main() -> Result<()> { let mut store = kvs::KvStore::open("~/"); match Cli::from_args().cmd { Command::Get { key } => match store.get(key) { Ok(_) => Ok(()), Err(_) => { process::exit(IO_ERR); } }, Command::Set { key, val } => match store.set(key, val) { Ok(_) => Ok(()), Err(_) => { process::exit(IO_ERR); } }, Command::Remove { key } => match store.remove(key) { Ok(_) => Ok(()), Err(_) => { process::exit(IO_ERR); } }, } }
//! control the interrupt processing use crate::registers::cp0; /// disable all interrupts pub fn disable() { cp0::status::disable_interrupt(); } /// enable all interrupts pub fn enable() { cp0::status::enable_interrupt(); } /// execute a closure in critical section, which means it will not be interrupted /// only works when there is only one processor pub fn critical_section(f: impl FnOnce()) { disable(); f(); enable(); }
use chapter2::basics_nlz; #[cfg(target_arch = "x86_64")] use std::borrow::BorrowMut; #[cfg(target_arch = "riscv64")] use core::borrow::BorrowMut; /// Integer Divisions /* q[0], r[0], u[0], and v[0] contain the LEAST significant halfwords. (The sequence is in little-endian order). This first version is a fairly precise implementation of Knuth's Algorithm D, for a binary computer with base b = 2**16. The caller supplies 1. Space q for the quotient, m - n + 1 halfwords (at least one). 2. Space r for the remainder (optional), n halfwords. 3. The dividend u, m halfwords, m >= 1. 4. The divisor v, n halfwords, n >= 2. The most significant digit of the divisor, v[n-1], must be nonzero. The dividend u may have leading zeros; this just makes the algorithm take longer and makes the quotient contain more leading zeros. A value of NULL may be given for the address of the remainder to signify that the caller does not want the remainder. The program does not alter the input parameters u and v. The quotient and remainder returned may have leading zeros. The function itself returns a value of 0 for success and 1 for invalid parameters (e.g., division by 0). For now, we must have m >= n. Knuth's Algorithm D also requires that the dividend be at least as long as the divisor. (In his terms, m >= 0 (unstated). Therefore m+n >= n.) */ #[allow(overflowing_literals)] #[allow(arithmetic_overflow)] pub fn division_divmnu(q: &mut [u8], r: &mut [u8], u: &[u8], v: &[u8], m: i32, n: i32) -> i32 { let b:u16 = 65536; // Number base (16 bits). if m < n || n <= 0 || v[(n - 1)as usize] == 0 { return 1; // Return if invalid param. } if n == 1 { // Take care of let mut k = 0; // the case of a for j in m - 1..0 { // single-digit q[j as usize] = ((k * b + u[j as usize] as u16) / v[0] as u16) as u8; // divisor here. k = (k * b + u[j as usize] as u16) - q[j as usize] as u16 * v[0] as u16; } if r != &[] { r[0] = k as u8; } return 0; } // Normalize by shifting v left just enough so that // its high-order bit is on, and shift u left the // same amount. We may have to append a high-order // digit on the dividend; we do that unconditionally. let mut s = basics_nlz(v[(n - 1) as usize] as u32) - 16; // 0 <= s <= 15. let mut vn = [0;100000]; for i in n - 1..0 { vn[i as usize] = (v[i as usize] << s) | (v[i as usize - 1] >> 16 - s); } vn[0] = v[0] << s; let mut un = [0;100000]; un[m as usize] = u[m as usize - 1] >> 16 - s; for i in m - 1..0 { un[i as usize] = (u[i as usize] << s) | (u[i as usize - 1] >> 16 - s); } un[0] = u[0] << s; for j in m-n..0 { // Main loop. // Compute estimate qhat of q[j]. let mut qhat = (un[(j + n) as usize] * b as u8 + un[(j + n) as usize - 1]) / vn[n as usize - 1]; let mut rhat = (un[(j + n) as usize] * b as u8 + un[(j + n) as usize - 1]) - qhat * vn[n as usize- 1]; loop { if qhat >= b as u8 || qhat * vn[n as usize - 2] > (b * rhat as u16 + un[(j + n)as usize - 2] as u16)as u8 { qhat = qhat - 1; rhat = rhat + vn[n as usize - 1]; if rhat >= b as u8{ break; } } } // Multiply and subtract. let mut k = 0; for i in 0..n { let p = qhat * vn[i as usize]; let t = un[(i + j) as usize] - k - (p & 0xFFFF); un[(i + j)as usize] = t; k = (p >> 16) - (t >> 16); } let mut t = un[(j + n)as usize] - k; un[(j + n)as usize] = t; q[j as usize] = qhat; // Store quotient digit. if t < 0 { // If we subtracted too q[j as usize] = q[j as usize] - 1; // much, add back. k = 0; for i in 0..n{ t = un[(i + j)as usize] + vn[i as usize] + k; un[(i + j) as usize] = t; k = t >> 16; } un[(j + n)as usize] = un[(j + n)as usize] + k; } } // End j. // If the caller wants the remainder, unnormalize // it and pass it back. if r != &[] { for i in 0..n { r[i as usize] = (un[i as usize] >> s) | (un[i as usize + 1] << 16 - s); } } return 0; } #[cfg_attr(not(target_arch = "x86_64"),test_case)] #[cfg_attr(not(target_arch = "riscv64"),test)] fn test_division_divmnu(){ let mut a: [u8;50] = [0;50]; let mut b: [u8;50] = [0;50]; let mut c: [u8;50] = [0;50]; let mut d: [u8;50] = [0;50]; assert_eq!(division_divmnu(a.borrow_mut(), b.borrow_mut(), c.borrow_mut(), d.borrow_mut(),1,1), 1); }
use super::config; use crate::encoder; use crate::errors::{Error, ErrorKind, Result}; use crate::protos::{xchain, xendorser}; use num_bigint; use num_traits; use num_traits::cast::FromPrimitive; use serde_json; use std::ops::AddAssign; use std::ops::Sub; use std::prelude::v1::*; use std::slice; extern crate sgx_types; use sgx_types::*; #[derive(Default)] pub struct Message { pub to: String, pub amount: String, pub fee: String, pub desc: String, pub frozen_height: i64, pub initiator: String, pub auth_require: Vec<String>, } pub struct Session<'a, 'b, 'c> { pub chain_name: &'a String, account: &'b super::wallet::Account, msg: &'c Message, } impl<'a, 'b, 'c> Session<'a, 'b, 'c> { pub fn new(c: &'a String, w: &'b super::wallet::Account, m: &'c Message) -> Self { Session { msg: m, chain_name: c, account: w, } } pub fn check_resp_code(&self, resp: &[xchain::ContractResponse]) -> Result<()> { for i in resp.iter() { if i.status > 400 { return Err(Error::from(ErrorKind::ContractCodeGT400)); } } Ok(()) } pub fn pre_exec_with_select_utxo( &self, pre_sel_utxo_req: xchain::PreExecWithSelectUTXORequest, ) -> Result<xchain::PreExecWithSelectUTXOResponse> { let request_data = serde_json::to_string(&pre_sel_utxo_req)?; let mut endorser_request = xendorser::EndorserRequest::new(); endorser_request.set_RequestName(String::from("PreExecWithFee")); endorser_request.set_BcName(self.chain_name.to_owned()); endorser_request.set_RequestData(request_data.into_bytes()); let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; let req = serde_json::to_string(&endorser_request)?; let mut output = 0 as *mut sgx_libc::c_void; let mut out_len: usize = 0; let resp = unsafe { crate::ocall_xchain_endorser_call( &mut rt, req.as_ptr() as *const u8, req.len(), &mut output, &mut out_len, ) }; if resp != sgx_status_t::SGX_SUCCESS || rt != sgx_status_t::SGX_SUCCESS { println!( "[-] pre_exec_with_select_utxo ocall_xchain_endorser_call failed: {}, {}!", resp.as_str(), rt.as_str() ); return Err(Error::from(ErrorKind::InvalidArguments)); } unsafe { if sgx_types::sgx_is_outside_enclave(output, out_len) == 0 { println!("[-] alloc error"); return Err(Error::from(ErrorKind::InvalidArguments)); } } let resp_slice = unsafe { slice::from_raw_parts(output as *mut u8, out_len) }; let endorser_resp: xendorser::EndorserResponse = serde_json::from_slice(&resp_slice)?; let pre_exec_with_select_utxo_resp: xchain::PreExecWithSelectUTXOResponse = serde_json::from_slice(&endorser_resp.ResponseData)?; self.check_resp_code( pre_exec_with_select_utxo_resp .get_response() .get_responses(), )?; unsafe { crate::ocall_free(output); } Ok(pre_exec_with_select_utxo_resp) } fn generate_tx_input( &self, utxo_output: &xchain::UtxoOutput, total_need: &num_bigint::BigInt, ) -> Result<(Vec<xchain::TxInput>, xchain::TxOutput)> { let mut tx_inputs = std::vec::Vec::<xchain::TxInput>::new(); for utxo in utxo_output.utxoList.iter() { let mut ti = xchain::TxInput::new(); ti.set_ref_txid(utxo.refTxid.clone()); ti.set_ref_offset(utxo.refOffset); ti.set_from_addr(utxo.toAddr.clone()); ti.set_amount(utxo.amount.clone()); tx_inputs.push(ti); } let utxo_total = crate::consts::str_as_bigint(&utxo_output.totalSelected)?; let mut to = xchain::TxOutput::new(); if utxo_total.cmp(total_need) == std::cmp::Ordering::Greater { let delta = utxo_total.sub(total_need); to.set_to_addr(self.account.address.clone().into_bytes()); to.set_amount(delta.to_bytes_be().1); } return Ok((tx_inputs, to)); } fn generate_tx_output( &self, to: &String, amount: &String, fee: &str, ) -> Result<Vec<xchain::TxOutput>> { let mut tx_outputs = std::vec::Vec::<xchain::TxOutput>::new(); //TODO amount > 0 if !to.is_empty() { let mut t = xchain::TxOutput::new(); t.set_to_addr(to.clone().into_bytes()); let am = crate::consts::str_as_bigint(&amount)?; t.set_amount(am.to_bytes_be().1); tx_outputs.push(t); } if !fee.is_empty() && fee != "0" { let mut t = xchain::TxOutput::new(); t.set_to_addr(String::from("$").into_bytes()); let am = crate::consts::str_as_bigint(&fee)?; t.set_amount(am.to_bytes_be().1); tx_outputs.push(t); } Ok(tx_outputs) } pub fn gen_compliance_check_tx( &self, resp: &mut xchain::PreExecWithSelectUTXOResponse, ) -> Result<xchain::Transaction> { let total_need = num_bigint::BigInt::from_i64( config::CONFIG .read() .unwrap() .compliance_check .compliance_check_endorse_service_fee as i64, ) .ok_or(Error::from(ErrorKind::ParseError))?; let (tx_inputs, tx_output) = self.generate_tx_input(resp.get_utxoOutput(), &total_need)?; let mut tx_outputs = self.generate_tx_output( &config::CONFIG .read() .unwrap() .compliance_check .compliance_check_endorse_service_fee_addr, &config::CONFIG .read() .unwrap() .compliance_check .compliance_check_endorse_service_fee .to_string(), "0", )?; if !tx_output.to_addr.is_empty() { tx_outputs.push(tx_output); } // compose transaction let mut tx = xchain::Transaction::new(); tx.set_desc(String::from("compliance check tx").into_bytes()); tx.set_version(super::consts::TXVersion); tx.set_coinbase(false); tx.set_timestamp(super::consts::now_as_nanos()); tx.set_tx_inputs(protobuf::RepeatedField::from_vec(tx_inputs)); tx.set_tx_outputs(protobuf::RepeatedField::from_vec(tx_outputs)); tx.set_initiator(self.msg.initiator.to_owned()); tx.set_nonce(super::wallet::get_nonce()?); let digest_hash = encoder::make_tx_digest_hash(&tx)?; //sign the digest_hash let sig = self.account.sign(&digest_hash)?; let mut signature_info = xchain::SignatureInfo::new(); signature_info.set_PublicKey(self.account.public_key()?); signature_info.set_Sign(sig); let signature_infos = vec![signature_info; 1]; tx.set_initiator_signs(protobuf::RepeatedField::from_vec(signature_infos)); tx.set_txid(encoder::make_transaction_id(&tx)?); Ok(tx) } pub fn gen_real_tx( &self, resp: &xchain::PreExecWithSelectUTXOResponse, cctx: &xchain::Transaction, ) -> Result<xchain::Transaction> { let mut tx_outputs = self.generate_tx_output(&self.msg.to, &self.msg.amount, &self.msg.fee)?; let mut total_selected: num_bigint::BigInt = num_traits::Zero::zero(); let mut utxo_list = std::vec::Vec::<xchain::Utxo>::new(); let mut index = 0; for tx_output in cctx.tx_outputs.iter() { if tx_output.to_addr == self.msg.initiator.as_bytes() { let mut t = xchain::Utxo::new(); t.set_amount(tx_output.amount.clone()); t.set_toAddr(tx_output.to_addr.clone()); t.set_refTxid(cctx.txid.clone()); t.set_refOffset(index); utxo_list.push(t); let um = num_bigint::BigInt::from_bytes_be( num_bigint::Sign::Plus, &tx_output.amount[..], ); total_selected.add_assign(um); }; index += 1; } let mut utxo_output = xchain::UtxoOutput::new(); utxo_output.set_utxoList(protobuf::RepeatedField::from_vec(utxo_list)); utxo_output.set_totalSelected(total_selected.to_str_radix(10)); let mut total_need = crate::consts::str_as_bigint(&self.msg.amount)?; let fee = crate::consts::str_as_bigint(&self.msg.fee)?; total_need.add_assign(fee); let (tx_inputs, delta_tx_ouput) = self.generate_tx_input(&utxo_output, &total_need)?; if !delta_tx_ouput.to_addr.is_empty() { tx_outputs.push(delta_tx_ouput); } let mut tx = xchain::Transaction::new(); tx.set_desc(vec![]); tx.set_version(super::consts::TXVersion); tx.set_coinbase(false); tx.set_timestamp(super::consts::now_as_nanos()); tx.set_tx_inputs(protobuf::RepeatedField::from_vec(tx_inputs)); tx.set_tx_outputs(protobuf::RepeatedField::from_vec(tx_outputs)); tx.set_initiator(self.msg.initiator.to_owned()); tx.set_nonce(super::wallet::get_nonce()?); tx.set_auth_require(protobuf::RepeatedField::from_vec( self.msg.auth_require.to_owned(), )); tx.set_tx_inputs_ext(resp.get_response().inputs.clone()); tx.set_tx_outputs_ext(resp.get_response().outputs.clone()); tx.set_contract_requests(resp.get_response().requests.clone()); let digest_hash = encoder::make_tx_digest_hash(&tx)?; //sign the digest_hash let sig = self.account.sign(&digest_hash)?; let mut signature_info = xchain::SignatureInfo::new(); signature_info.set_PublicKey(self.account.public_key()?); signature_info.set_Sign(sig); let signature_infos = vec![signature_info; 1]; tx.set_initiator_signs(protobuf::RepeatedField::from_vec(signature_infos.clone())); if !self.account.contract_name.is_empty() { tx.set_auth_require_signs(protobuf::RepeatedField::from_vec(signature_infos)); } tx.set_txid(encoder::make_transaction_id(&tx)?); Ok(tx) } pub fn compliance_check( &self, tx: &xchain::Transaction, fee: &xchain::Transaction, ) -> Result<xchain::SignatureInfo> { let mut tx_status = xchain::TxStatus::new(); tx_status.set_bcname(self.chain_name.to_owned()); tx_status.set_tx(tx.clone()); let request_data = serde_json::to_string(&tx_status)?; let mut endorser_request = xendorser::EndorserRequest::new(); endorser_request.set_RequestName(String::from("ComplianceCheck")); endorser_request.set_BcName(self.chain_name.to_owned()); endorser_request.set_Fee(fee.clone()); endorser_request.set_RequestData(request_data.into_bytes()); let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; let req = serde_json::to_string(&endorser_request)?; let mut output = 0 as *mut sgx_libc::c_void; let mut out_len: usize = 0; let resp = unsafe { crate::ocall_xchain_endorser_call( &mut rt, req.as_ptr() as *const u8, req.len(), &mut output, &mut out_len, ) }; if resp != sgx_status_t::SGX_SUCCESS || rt != sgx_status_t::SGX_SUCCESS { println!( "[-] compliance_check ocall_xchain_endorser_call failed: {}, {}!", resp.as_str(), rt.as_str() ); return Err(Error::from(ErrorKind::InvalidArguments)); } unsafe { if sgx_types::sgx_is_outside_enclave(output, out_len) == 0 { println!("[-] alloc error"); return Err(Error::from(ErrorKind::InvalidArguments)); } } let resp_slice = unsafe { slice::from_raw_parts(output as *mut u8, out_len) }; let result: xendorser::EndorserResponse = serde_json::from_slice(resp_slice).unwrap(); unsafe { crate::ocall_free(output); } Ok(result.EndorserSign.unwrap()) } pub fn gen_complete_tx_and_post( &self, pre_exec_resp: &mut xchain::PreExecWithSelectUTXOResponse, ) -> Result<String> { let cctx = self.gen_compliance_check_tx(pre_exec_resp)?; let mut tx = self.gen_real_tx(&pre_exec_resp, &cctx)?; let end_sign = self.compliance_check(&tx, &cctx)?; tx.auth_require_signs.push(end_sign); tx.set_txid(encoder::make_transaction_id(&tx)?); let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; let tran = serde_json::to_string(&tx)?; let resp = unsafe { crate::ocall_xchain_post_tx(&mut rt, tran.as_ptr() as *const u8, tran.len()) }; if resp != sgx_status_t::SGX_SUCCESS || rt != sgx_status_t::SGX_SUCCESS { println!( "[-] ocall_xchain_post_tx failed: {}, {}!", resp.as_str(), rt.as_str() ); return Err(Error::from(ErrorKind::InvalidArguments)); } Ok(hex::encode(tx.txid)) } #[allow(dead_code)] fn print_tx(&self, tx: &xchain::Transaction) { for i in tx.tx_inputs.iter() { crate::consts::print_bytes_num(&i.amount); } for i in tx.tx_outputs.iter() { crate::consts::print_bytes_num(&i.amount); } } //TODO //pub fn get_balance() -> Result<String> {} }
use std::time::Duration; use std::{env, path::Path}; use std::{str::FromStr, thread}; use anyhow::{bail, Context}; use anyhow::{Ok, Result}; use chrono::prelude::*; use log::debug; use crate::cli::Appearance; use crate::config::Config; use crate::constants::UPDATE_INTERVAL_MINUTES; use crate::heif; use crate::info::ImageInfo; use crate::loader::WallpaperLoader; use crate::schedule::{ current_image_index_h24, current_image_index_solar, get_image_index_order_appearance, get_image_index_order_h24, get_image_index_order_solar, }; use crate::setter::set_wallpaper; use crate::wallpaper::{self, properties::Properties, Wallpaper}; use crate::{cache::LastWallpaper, schedule::current_image_index_appearance}; pub fn info<P: AsRef<Path>>(path: P) -> Result<()> { validate_wallpaper_file(&path)?; print!("{}", ImageInfo::from_image(&path)?); Ok(()) } pub fn unpack<IP: AsRef<Path>, OP: AsRef<Path>>(source: IP, destination: OP) -> Result<()> { validate_wallpaper_file(&source)?; wallpaper::unpack(source, destination) } pub fn set<P: AsRef<Path>>( path: Option<P>, daemon: bool, user_appearance: Option<Appearance>, ) -> Result<()> { if daemon && user_appearance.is_some() { bail!("appearance can't be used in daemon mode!") } let config = Config::find()?; let last_wallpaper = LastWallpaper::find(); let wall_path = if let Some(given_path) = path { validate_wallpaper_file(&given_path)?; last_wallpaper.save(&given_path); given_path.as_ref().to_path_buf() } else if let Some(last_path) = last_wallpaper.get() { debug!("last used wallpaper at {}", last_path.display()); last_path } else { bail!("no image to set given"); }; let wallpaper = WallpaperLoader::new().load(&wall_path); loop { let current_image_index = current_image_index(&wallpaper, &config, user_appearance)?; let current_image_path = wallpaper .images .get(current_image_index) .with_context(|| "missing image specified by metadata")?; debug!("setting wallpaper to {}", current_image_path.display()); set_wallpaper(current_image_path, config.setter_command())?; if !daemon { eprintln!("Wallpaper set!"); break; } debug!("sleeping for {UPDATE_INTERVAL_MINUTES} minutes"); thread::sleep(Duration::from_secs(UPDATE_INTERVAL_MINUTES * 60)); } Ok(()) } pub fn preview<P: AsRef<Path>>(path: P, delay: u64, repeat: bool) -> Result<()> { let config = Config::find()?; validate_wallpaper_file(&path)?; let wallpaper = WallpaperLoader::new().load(&path); let image_order = match wallpaper.properties { Properties::H24(ref props) => get_image_index_order_h24(&props.time_info), Properties::Solar(ref props) => get_image_index_order_solar(&props.solar_info), Properties::Appearance(ref props) => get_image_index_order_appearance(props), }; loop { for image_index in &image_order { let image_path = wallpaper.images.get(*image_index).unwrap(); set_wallpaper(image_path, config.setter_command())?; thread::sleep(Duration::from_millis(delay)); } if !repeat { break; } } Ok(()) } fn validate_wallpaper_file<P: AsRef<Path>>(path: P) -> Result<()> { let path = path.as_ref(); if !path.exists() { bail!("file '{}' is not accessible", path.display()); } if !path.is_file() { bail!("'{}' is not a file", path.display()); } heif::validate_file(path) } fn get_now_time() -> DateTime<Local> { match env::var("TIMEWALL_OVERRIDE_TIME") { Err(_) => Local::now(), Result::Ok(time_str) => DateTime::from_str(&time_str).unwrap(), } } fn current_image_index( wallpaper: &Wallpaper, config: &Config, user_appearance: Option<Appearance>, ) -> Result<usize> { let now = get_now_time(); match wallpaper.properties { ref any_properties if user_appearance.is_some() => match any_properties.appearance() { Some(appearance_props) => { current_image_index_appearance(appearance_props, user_appearance) } None => bail!("wallpaper missing appearance metadata"), }, Properties::Appearance(ref appearance_props) => { current_image_index_appearance(appearance_props, user_appearance) } Properties::H24(ref props) => current_image_index_h24(&props.time_info, &now.time()), Properties::Solar(ref props) => { current_image_index_solar(&props.solar_info, &now, &config.location) } } }
use english_numbers::{Formatting, convert}; // bit o cheating ;) fn main() { let mut form = Formatting::none(); form.conjunctions = true; let sum: u64 = (1..=1000) .map(|x| convert(x, form).len()) .fold(0, |a, b| a + b as u64); println!("{}", sum); }
use std::fs::File; use std::io::{BufRead, BufReader}; use crate::util::{lines_as_i32, time, vecs_i32}; pub fn day1() { println!("== Day 1 =="); let input = "src/day1/input.txt"; // let input = "src/day1/aoc_2022_day01_large_input.txt"; // println!("Part A: {}", part_a(&input)); // println!("Part B: {}", part_b(&input)); time(part_a_3, input, "A"); time(part_b_3, input, "B"); } fn get_input(file: &str) -> Vec<i32> { let input = lines_as_i32(file); let numbers = vecs_i32(&input); let summed: Vec<i32> = numbers.iter().map(|v| v.iter().sum()).collect(); summed } fn part_a(input: &Vec<i32>) -> i32 { *input.iter().max().unwrap() } fn part_b(input: &Vec<i32>) -> i32 { let mut summed = input.clone(); summed.sort(); summed.reverse(); let top_three = vec![summed[0], summed[1], summed[2]]; top_three.iter().sum() } fn part_b_2(input: &Vec<i32>) -> i32 { let mut top_three = vec![0, 0, 0]; let mut index = 0; for v in input { let mut lowest = i32::MAX; for i in 0..top_three.len() { if top_three[i] < lowest { lowest = top_three[i]; index = i; } } if *v > top_three[index.clone()] { top_three[index.clone()] = *v; } } top_three.iter().sum() } fn part_a_3(file: &str) -> i32 { let open = File::open(file).expect("Could not read file"); let mut count = 0; let mut max = 0; for line in BufReader::new(open).lines() { let line = line.unwrap(); if line == "" { max = std::cmp::max(max, count); count = 0; } else { count += line.parse::<i32>().unwrap(); } } max } fn part_b_3(file: &str) -> i32 { let open = File::open(file).expect("Could not read file"); let mut tmp = 0; let mut top_three = vec![0, 0, 0]; for line in BufReader::new(open).lines() { let string = line.unwrap(); if string.is_empty() { let mut lowest = i32::MAX; let mut index = 0; for i in 0..3 { if top_three[i] < lowest { lowest = top_three[i]; index = i; } } if tmp > lowest { top_three[index] = tmp; } tmp = 0; } else { tmp += string.parse::<i32>().unwrap() } } top_three.iter().sum() } #[cfg(test)] mod tests { use std::time::Instant; use super::*; #[ignore] #[test] fn runday() { day1(); } #[ignore] #[test] fn real_a() { let input = get_input("src/day1/input.txt"); assert_eq!(67450, part_a(&input)); } #[ignore] #[test] fn real_b() { let input = get_input("src/day1/input.txt"); assert_eq!(199357, part_b_2(&input)); } #[ignore] #[test] fn uppe_the_ante() { let instant = Instant::now(); let input = get_input("src/day1/aoc_2022_day01_large_input.txt"); let read_input = Instant::now(); println!("Read input in {}ms", read_input.duration_since(instant).as_millis()); print!("Part A: {}", part_a(&input)); let part_a_time = Instant::now(); println!(" took {}ms", part_a_time.duration_since(read_input).as_millis()); print!("Part B: {}", part_b(&input)); let part_b_time = Instant::now(); println!(" took {}ms", part_b_time.duration_since(part_a_time).as_millis()); print!("Part B 2: {}", part_b_2(&input)); let part_b_2_time = Instant::now(); println!(" took {}ms", part_b_2_time.duration_since(part_b_time).as_millis()); } #[ignore] #[test] fn a3() { let instant = Instant::now(); let result = part_a_3("src/day1/aoc_2022_day01_large_input.txt"); let end = Instant::now(); print!("Part a 3: {} took {}ms", result, end.duration_since(instant).as_millis()); assert_eq!(184028272, result); } #[ignore] #[test] fn b3() { let instant = Instant::now(); let result = part_b_3("src/day1/aoc_2022_day01_large_input.txt"); let end = Instant::now(); print!("Part B 3: {} took {}ms", result, end.duration_since(instant).as_millis()); assert_eq!(549010145, result); } #[test] fn part_a_test_input() { let input = get_input("src/day1/test-input.txt"); let result = part_a(&input); assert_eq!(24000, result); } #[test] fn part_b_test_input() { let input = get_input("src/day1/test-input.txt"); let result = part_b(&input); assert_eq!(45000, result); } }
// 2019-07-08 // Un programme avec // un thread qui génère des valeurs et les envoie dans une channel // un thread qui les reçoit et les affiche // mpsc signigie Multiple Producer, Single Consumer // Une channel peut avoir plusieurs extrémités qui produisent des valeurs // mais UNE SEULE extrémité qui les consomme. use std::sync::mpsc; use std::thread; fn main() { // La fonction mpsc::channel() renvoie un n-uplet // premier élément: l'extrémité qui émet (transmitter) // deuxième élément: l'extrémité qui reçoit (receiver) let (tx, rx) = mpsc::channel(); // ENVOYER // Déplaçons l'extrémité émettrice tx dans un nouveau thread thread::spawn(move || { let val = String::from("hi"); // la méthode send() prend la valeur et renvoie Result<T, E> // l'erreur est utile s'il n'y a personne pour recevoir, mais ici on // utilise unwrap() par commodité. tx.send(val).unwrap(); // send() a pris l'ownership. Une fois la valeur envoyée, on ne peut plus // l'utiliser. Ceci est interdit: // println!("{}", val); }); // RECEVOIR // L'extrémité receptrise, rx, a deux méthodes utiles. // recv() blocque l'exécution du thread principal dans l'attente d'une valeur // De même, recv() renvoie Result<T, E> (erreur en cas de channel fermée) // try_recv() n'attends pas, renvoie Ok(valeur) ou Err s'il n'y a rien à // recevoir. let received = rx.recv().unwrap(); println!("Got: {}", received); }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![allow(nonstandard_style)] #[cfg(feature = "std")] use std::io::{Error}; use core::fmt::{self, Display, Debug, Formatter}; pub use crate::kty:: { c_int, EPERM, ENOENT, ESRCH, EINTR, EIO, ENXIO, E2BIG, ENOEXEC, EBADF, ECHILD, EAGAIN, ENOMEM, EACCES, EFAULT, ENOTBLK, EBUSY, EEXIST, EXDEV, ENODEV, ENOTDIR, EISDIR, EINVAL, ENFILE, EMFILE, ENOTTY, ETXTBSY, EFBIG, ENOSPC, ESPIPE, EROFS, EMLINK, EPIPE, EDOM, ERANGE, EDEADLK, ENAMETOOLONG, ENOLCK, ENOSYS, ENOTEMPTY, ELOOP, ENOMSG, EIDRM, ECHRNG, EL2NSYNC, EL3HLT, EL3RST, ELNRNG, EUNATCH, ENOCSI, EL2HLT, EBADE, EBADR, EXFULL, ENOANO, EBADRQC, EBADSLT, EBFONT, ENOSTR, ENODATA, ETIME, ENOSR, ENONET, ENOPKG, EREMOTE, ENOLINK, EADV, ESRMNT, ECOMM, EPROTO, EMULTIHOP, EDOTDOT, EBADMSG, EOVERFLOW, ENOTUNIQ, EBADFD, EREMCHG, ELIBACC, ELIBBAD, ELIBSCN, ELIBMAX, ELIBEXEC, EILSEQ, ERESTART, ESTRPIPE, EUSERS, ENOTSOCK, EDESTADDRREQ, EMSGSIZE, EPROTOTYPE, ENOPROTOOPT, EPROTONOSUPPORT, ESOCKTNOSUPPORT, EOPNOTSUPP, EPFNOSUPPORT, EAFNOSUPPORT, EADDRINUSE, EADDRNOTAVAIL, ENETDOWN, ENETUNREACH, ENETRESET, ECONNABORTED, ECONNRESET, ENOBUFS, EISCONN, ENOTCONN, ESHUTDOWN, ETOOMANYREFS, ETIMEDOUT, ECONNREFUSED, EHOSTDOWN, EHOSTUNREACH, EALREADY, EINPROGRESS, ESTALE, EUCLEAN, ENOTNAM, ENAVAIL, EISNAM, EREMOTEIO, EDQUOT, ENOMEDIUM, EMEDIUMTYPE, ECANCELED, ENOKEY, EKEYEXPIRED, EKEYREVOKED, EKEYREJECTED, EOWNERDEAD, ENOTRECOVERABLE, ERFKILL, EHWPOISON, }; /// A standard error /// /// [field, 1] /// The error number. /// /// = Remarks /// /// Error numbers between 0 and 4096 exclusive are reserved by the kernel. Error numbers /// between 4096 and 9999 inclusive are reserved by lrs. /// /// = See also /// /// * link:man:errno(3) /// * link:lrs::error which contains constants for the error numbers returned by the /// kernel. #[derive(Pod, Copy, Clone, Eq, PartialEq)] #[structural_match] pub struct Errno(pub c_int); #[cfg(feature = "std")] impl From<Errno> for Error { fn from(errno: Errno) -> Error { Error::from_raw_os_error(errno.0) } } impl Display for Errno { fn fmt(&self, f: &mut Formatter) -> fmt::Result { core::write!(f, "{} {} {}", self.name().unwrap_or("?"), self.0, self.desc()) } } impl Debug for Errno { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Display::fmt(self, f) } } macro_rules! create { ($($name:ident = $val:expr, $str:expr,)*) => { $(#[doc = $str] pub const $name: Errno = Errno($val as c_int);)* impl Errno { /// Returns the name of the error in string form. pub fn name(self) -> Option<&'static str> { match self { $($name => Some(stringify!($name)),)* _ => None, } } /// Returns a longer description of the error. pub fn desc(self) -> &'static str { match self { $($name => $str,)* _ => "Unknown error", } } } } } create! { NoError = 0 , "No error", NotPermitted = EPERM , "Operation not permitted", DoesNotExist = ENOENT , "No such file or directory", NoSuchProcess = ESRCH , "No process matches the specified process ID", Interrupted = EINTR , "Function call interrupted", InputOutput = EIO , "Input/Output error", NoSuchDevice = ENXIO , "No such device or address", TooManyArguemnts = E2BIG , "Argument list too long", InvalidExecutable = ENOEXEC , "Invalid executable file format", BadFileDesc = EBADF , "Bad file descriptor", NoChildProcesses = ECHILD , "There are no child processes", WouldBlock = EAGAIN , "Resource temporarily unavailable", NoMemory = ENOMEM , "No memory available", AccessDenied = EACCES , "Permission denied", InvalidPointer = EFAULT , "Invalid pointer", NoBlockSpecialFile = ENOTBLK , "Block special file required", ResourceBusy = EBUSY , "Resource busy", FileExists = EEXIST , "File exists", CrossFileSystemLink = EXDEV , "Attempted to link across filesystems", WrongDeviceType = ENODEV , "Wrong device type for operation", NotADirectory = ENOTDIR , "Directory required for operation", IsADirectory = EISDIR , "Directory not permitted in operation", InvalidArgument = EINVAL , "Invalid argument", SystemFileLimit = ENFILE , "Process file limit reached", ProcessFileLimit = EMFILE , "System file limit reached", NotATerminal = ENOTTY , "Argument is not a terminal", ExecutableBusy = ETXTBSY , "Trying to execute and write a file at the same time", FileTooBig = EFBIG , "File too big", DeviceFull = ENOSPC , "No space left on device", InvalidSeek = ESPIPE , "Invalid seek operation", ReadOnlyFileSystem = EROFS , "Operation not permitted on read-only filesystem", TooManyLinks = EMLINK , "Too many links", BrokenPipe = EPIPE , "Broken pipe", DomainError = EDOM , "Domain error", RangeError = ERANGE , "Range error", DeadlockAvoided = EDEADLK , "Deadlock avoided", PathTooLong = ENAMETOOLONG , "Path too long", NoLocksAvailable = ENOLCK , "No locks available", NotImplemented = ENOSYS , "Function not implemented", NotEmpty = ENOTEMPTY , "Directory not empty", TooManySymlinks = ELOOP , "Too many levels of symbolic links", NoMessageOfType = ENOMSG , "No message of desired type", IdentifierRemoved = EIDRM , "Identifier removed", ChannelOutOfRange = ECHRNG , "Channel number out of range", Level2NotSync = EL2NSYNC , "Level 2 not synchronized", Level3Halted = EL3HLT , "Level 3 halted", Level3Reset = EL3RST , "Level 3 reset", LinkNumberOutOfRange = ELNRNG , "Link number out of range", ProtoDriverNotAttached = EUNATCH , "Protocol driver not attached", NoCSIStructAvailable = ENOCSI , "No CSI structure available", Level2Halted = EL2HLT , "Level 2 halted", InvalidExchange = EBADE , "Invalid exchange", InvalidReqDesc = EBADR , "Invalid request descriptor", ExchangeFull = EXFULL , "Exchange full", NoAnode = ENOANO , "No anode", InvalidRequestCode = EBADRQC , "Invalid request code", InvalidSlot = EBADSLT , "Invalid slot", BadFontFileFormat = EBFONT , "Bad font file format", NotAStream = ENOSTR , "Device not a stream", NoDataAvailable = ENODATA , "No data available", TimerExpired = ETIME , "Timer expired", OutOfStreamsResources = ENOSR , "Out of streams resources", NotOnNetwork = ENONET , "Machine is not on the network", PackageNotInstalled = ENOPKG , "Package not installed", ObjectIsRemote = EREMOTE , "Object is remote", LinkSevered = ENOLINK , "Link has been severed", AdvertiseError = EADV , "Advertise error", SrmountError = ESRMNT , "Srmount error", CommunitacionError = ECOMM , "Communication error on send", ProtocolError = EPROTO , "Protocol error", MultihopAttempted = EMULTIHOP , "Multihop attempted", RFSError = EDOTDOT , "RFS specific error", NotADataMessage = EBADMSG , "Not a data message", Overflow = EOVERFLOW , "Value too large for defined data type", NotUnique = ENOTUNIQ , "Name not unique on network", BadFileDescState = EBADFD , "File descriptor in bad state", RemoteAddrChanged = EREMCHG , "Remote address changed", SharedLibInaccessible = ELIBACC , "Can not access a needed shared library", SharedLibCorrupted = ELIBBAD , "Accessing a corrupted shared library", LibSectionCorrupted = ELIBSCN , ".lib section in a.out corrupted", TooManySharedLibs = ELIBMAX , "Attempting to link in too many shared libraries", SharedLibExec = ELIBEXEC , "Cannot exec a shared library directly", InvalidSequence = EILSEQ , "Invalid sequence", Restart = ERESTART , "Interrupted system call should be restarted", StreamPipeError = ESTRPIPE , "Streams pipe error", TooManyUsers = EUSERS , "Too many users", NotASocket = ENOTSOCK , "Argument is not a socket", NoDefaultDestination = EDESTADDRREQ , "Connectionless socket has no destination", MessageSize = EMSGSIZE , "Message too large", ProtoNotSupported = EPROTOTYPE , "Protocol not supported by socket type", OpNotSupported = ENOPROTOOPT , "Operation not supported by protocol", ProtoNotSupported2 = EPROTONOSUPPORT , "Protocol not supported by socket domain", SocketTypeNotSupported = ESOCKTNOSUPPORT , "Socket type is not supported", NotSupported = EOPNOTSUPP , "Operation not supported", ProtoFamilyNotSupported = EPFNOSUPPORT , "Protocol family not supported", AddrFamilyNotSupported = EAFNOSUPPORT , "Address family not supported", AddressInUse = EADDRINUSE , "Socket address already in use", AddressNotAvailable = EADDRNOTAVAIL , "Socket address is not available", NetworkDown = ENETDOWN , "Network is down", NetworkUnreachable = ENETUNREACH , "Remote network is unreachable", HostCrashed = ENETRESET , "Remote hast crashed", ConnectionAborted = ECONNABORTED , "Connection locally aborted", ConnectionReset = ECONNRESET , "Connection closed", KernelBuffersBusy = ENOBUFS , "All kernel I/O buffers are in use", SocketConnected = EISCONN , "Socket is already connected", SocketNotConnected = ENOTCONN , "Socket is not connected", SocketShutDown = ESHUTDOWN , "Socket has shut down", TooManyReferences = ETOOMANYREFS , "Too many references", TimedOut = ETIMEDOUT , "Operation timed out", ConnectionRefused = ECONNREFUSED , "Remote host is down", HostDown = EHOSTDOWN , "Remote host is unreachable", HostUnreachable = EHOSTUNREACH , "Remote host refused connection", AlreadyInProgress = EALREADY , "Operation already in progress", OperationInitiated = EINPROGRESS , "Operation initiated", StaleFileHandle = ESTALE , "Stale file handle", NeedsCleaning = EUCLEAN , "Structure needs cleaning", NotXENIX = ENOTNAM , "Not a XENIX named type file", NoXENIXSemaphores = ENAVAIL , "No XENIX semaphores available", NamedTypeFile = EISNAM , "Is a named type file", RemoteIOError = EREMOTEIO , "Remote I/O error", DiskQuota = EDQUOT , "Disk quota exceeded", NoMedium = ENOMEDIUM , "No medium found", WrongMediumType = EMEDIUMTYPE , "Wrong medium type", OperationCanceled = ECANCELED , "Asynchronous operation canceled", KeyNotAvailable = ENOKEY , "Required key not available", KeyExpired = EKEYEXPIRED , "Key has expired", KeyRevoked = EKEYREVOKED , "Key has been revoked", KeyRejected = EKEYREJECTED , "Key was rejected by service", OwnerDied = EOWNERDEAD , "Owner died", IrrecoverableState = ENOTRECOVERABLE , "State not recoverable", RFKill = ERFKILL , "Operation not possible due to RF-kill", HardwarePoison = EHWPOISON , "Memory page has hardware error", }
use super::geometry::{Ray, Vector}; use image::{DynamicImage, GenericImageView}; use std::sync::Arc; pub struct Scene { pub objects: Vec<Arc<dyn Traceable>>, pub lights: Vec<Light>, pub environment_color: Vector, pub environment_map: Option<DynamicImage>, } pub struct Light { pub position: Vector, pub intensity: f64, } #[derive(Clone)] pub struct Material { pub diffuse_color: Vector, pub specular_exponent: f64, pub albedo_diffuse: f64, pub albedo_reflect: f64, pub albedo_specular: f64, pub albedo_refract: f64, pub refractive_index: f64, } pub trait Traceable: Send + Sync { fn intersect(&self, ray: &Ray) -> Option<f64>; fn material(&self) -> Arc<Material>; fn normal_at(&self, point: &Vector) -> Vector; } impl Scene { fn intersect(self: &Scene, ray: &Ray) -> (f64, Option<Arc<dyn Traceable>>) { let mut min_dist: f64 = std::f64::MAX; let mut hit_object: Option<Arc<dyn Traceable>> = None; // Find the first object hit by this ray for object in &self.objects { if let Some(distance) = object.intersect(ray) { if distance < min_dist { min_dist = distance; hit_object = Some(object.clone()); } } } (min_dist, hit_object) } fn offset_orig(dir: Vector, point: Vector, n: Vector) -> Vector { if (dir ^ n) < 0.0 { point - (n * 1e-3) } else { point + (n * 1e-3) } } pub fn cast_ray(self: &Scene, ray: &Ray, depth: i32) -> Vector { if depth > 0 { let (min_dist, hit_object) = self.intersect(ray); // Render pixel if let Some(object) = hit_object { let material = object.material(); let point = ray.extend(min_dist); let normal = object.normal_at(&point).normalize(); let mut diffuse_intensity = 0.0; let mut specular_intensity = 0.0; // Determine total light intensity for light in &self.lights { let light_direction = (light.position - point).normalize(); // Shadow let light_distance = (light.position - point).norm(); let shadow_origin = Scene::offset_orig(light_direction, point, normal); let (shadow_distance, shadow_obstacle) = self.intersect(&Ray::new(shadow_origin, light_direction)); if shadow_obstacle.is_none() || shadow_distance > light_distance { // Light is not occluded diffuse_intensity += light.intensity * (light_direction ^ normal).max(0.0); let specularity = (((light_direction * -1.0).reflect(normal) * -1.0) ^ ray.direction()) .max(0.0) .powf(material.specular_exponent); specular_intensity += specularity * light.intensity; } } let diffuse_color = material.diffuse_color * diffuse_intensity * material.albedo_diffuse; let specular_color = Vector { x: 1.0, y: 1.0, z: 1.0, } * specular_intensity * material.albedo_specular; // Reflection let reflect_direction = ray.direction().reflect(normal).normalize(); let reflect_origin = Scene::offset_orig(reflect_direction, point, normal); let reflect_color = self .cast_ray(&Ray::new(reflect_origin, reflect_direction), depth - 1) * material.albedo_reflect; // Refraction let refract_direction = ray .direction() .refract(normal, material.refractive_index) .normalize(); let refract_origin = Scene::offset_orig(refract_direction, point, normal); let refract_color = self .cast_ray(&Ray::new(refract_origin, refract_direction), depth - 1) * material.albedo_refract; // Determine lit pixel color return diffuse_color + specular_color + reflect_color + refract_color; } } // Environment let env_dir = ray.direction(); match &self.environment_map { Some(image) => { let ew = f64::from(image.width()); let eh = f64::from(image.height()); // Spherical /*let m = env_dir.x.powf(2.0) + env_dir.y.powf(2.0) + (env_dir.z + 1.0).powf(2.0); let ex = (((env_dir.x / m) / 2.0 + 0.5) * ew) as u32; let ey = (((-env_dir.y / m) / 2.0 + 0.5) * eh) as u32;*/ // https://stackoverflow.com/questions/39283698/direction-to-environment-map-uv-coordinates let m = env_dir.norm() * 2.0; let ex = ((-env_dir.z / m + 0.5) * ew) as u32; let ey = ((-env_dir.y / m + 0.5) * eh) as u32; let color = image.get_pixel( ex.min(image.width() - 1).max(0), ey.min(image.height() - 1).max(0), ); Vector { x: f64::from(color[0]) / 255.0, y: f64::from(color[1]) / 255.0, z: f64::from(color[2]) / 255.0, } } None => self.environment_color, } } }
//! A description of a widget. use std::any::Any; use std::panic::Location; use druid::widget; use crate::any_widget::{Action, AnyWidget, DruidAppData}; use crate::cx::Cx; use crate::id::Id; pub trait View: AsAny + std::fmt::Debug { fn same(&self, other: &dyn View) -> bool; // This will yield Box<dyn Widget> in the future. fn make_widget(&self, id: Id) -> AnyWidget; } // Could use same AsAnyEqState trick to avoid repetitive eq impls. pub trait AsAny { fn as_any(&self) -> &dyn Any; } impl<T: 'static> AsAny for T { fn as_any(&self) -> &dyn Any { self } } #[derive(Debug)] pub struct Label(pub(crate) String); impl Label { pub fn new(text: impl Into<String>) -> Label { Label(text.into()) } #[track_caller] pub fn build(self, cx: &mut Cx) { cx.leaf_view(self, Location::caller()); } } impl View for Label { fn same(&self, other: &dyn View) -> bool { if let Some(other) = other.as_any().downcast_ref::<Self>() { self.0 == other.0 } else { false } } fn make_widget(&self, _id: Id) -> AnyWidget { AnyWidget::Label(widget::Label::new(self.0.to_string())) } } #[derive(Debug)] pub struct Button(pub(crate) String); impl Button { pub fn new(text: impl Into<String>) -> Button { Button(text.into()) } #[track_caller] pub fn build(self, cx: &mut Cx) -> bool { let id = cx.leaf_view(self, Location::caller()); cx.app_data.dequeue_action(id).is_some() } } impl View for Button { fn same(&self, other: &dyn View) -> bool { if let Some(other) = other.as_any().downcast_ref::<Self>() { self.0 == other.0 } else { false } } fn make_widget(&self, id: Id) -> AnyWidget { let button = widget::Button::new(self.0.clone()) .on_click(move |_, data: &mut DruidAppData, _| data.queue_action(id, Action::Clicked)); AnyWidget::Button(button) } } #[derive(Debug)] pub struct Row; impl Row { pub fn new() -> Row { Row } #[track_caller] pub fn build<T>(self, cx: &mut Cx, f: impl FnOnce(&mut Cx) -> T) -> T { cx.begin_view(Box::new(self), Location::caller()); let result = f(cx); cx.end(); result } } impl View for Row { fn same(&self, other: &dyn View) -> bool { if let Some(_other) = other.as_any().downcast_ref::<Self>() { true } else { false } } fn make_widget(&self, _id: Id) -> AnyWidget { let row = crate::widget::Flex::row(); AnyWidget::Flex(row) } } #[derive(Debug)] pub struct Column; impl Column { pub fn new() -> Column { Column } #[track_caller] pub fn build<T>(self, cx: &mut Cx, f: impl FnOnce(&mut Cx) -> T) -> T { cx.begin_view(Box::new(self), Location::caller()); let result = f(cx); cx.end(); result } } impl View for Column { fn same(&self, other: &dyn View) -> bool { if let Some(_other) = other.as_any().downcast_ref::<Self>() { true } else { false } } fn make_widget(&self, _id: Id) -> AnyWidget { let column = crate::widget::Flex::column(); AnyWidget::Flex(column) } } // TODO: this is commented out because the widget is not written yet. /* /// A wrapper for detecting click gestures. #[derive(Debug)] pub struct Clicked; impl Clicked { pub fn new() -> Clicked { Clicked } #[track_caller] pub fn build<T>(self, cx: &mut Cx, f: impl FnOnce(&mut Cx)) -> bool { let id = cx.begin_view(Box::new(self), Location::caller()); let result = f(cx); cx.end(); cx.app_data.dequeue_action(id).is_some() } } impl View for Clicked { fn same(&self, other: &dyn View) -> bool { if let Some(_other) = other.as_any().downcast_ref::<Self>() { true } else { false } } fn make_widget(&self, _id: Id) -> AnyWidget { let clicked = crate::widget::Clicked::new(); AnyWidget::Clicked(clicked) } } */
mod map_file; mod pp; use plotters::drawing::DrawingAreaErrorKind; use twilight_model::application::interaction::{ApplicationCommand, MessageComponentInteraction}; use twilight_validate::message::MessageValidationError; pub use self::{map_file::MapFileError, pp::PpError}; #[macro_export] macro_rules! bail { ($($arg:tt)*) => { return Err($crate::Error::Custom(format!("{}", format_args!($($arg)*)))) }; } #[derive(Debug, thiserror::Error)] pub enum Error { #[error("error while checking authority status")] Authority(#[source] Box<Error>), #[error("background game error")] BgGame(#[from] crate::bg_game::BgGameError), #[error("missing value in cache")] Cache(#[from] crate::core::CacheMiss), #[error("serde cbor error")] Cbor(#[from] serde_cbor::Error), #[error("error occured on cluster request")] ClusterCommand(#[from] twilight_gateway::cluster::ClusterCommandError), #[error("failed to start cluster")] ClusterStart(#[from] twilight_gateway::cluster::ClusterStartError), #[error("chrono parse error")] ChronoParse(#[from] chrono::format::ParseError), #[error("command error: {1}")] Command(#[source] Box<Error>, String), #[error("{0}")] Custom(String), #[error("custom client error")] CustomClient(#[from] crate::custom_client::CustomClientError), #[error("database error")] Database(#[from] sqlx::Error), #[error("fmt error")] Fmt(#[from] std::fmt::Error), #[error("image error")] Image(#[from] image::ImageError), #[error("received invalid options for command")] InvalidCommandOptions, #[error("invalid bg state")] InvalidBgState(#[from] InvalidBgState), #[error("invalid help state")] InvalidHelpState(#[from] InvalidHelpState), #[error("io error")] Io(#[from] tokio::io::Error), #[error("error while preparing beatmap file")] MapFile(#[from] MapFileError), #[error("failed to validate message")] MessageValidation(#[from] MessageValidationError), #[error("missing env variable `{0}`")] MissingEnvVariable(&'static str), #[error("interaction contained neighter member nor user")] MissingInteractionAuthor, #[error("osu error")] Osu(#[from] rosu_v2::error::OsuError), #[error("failed to parse env variable `{name}={value}`; expected {expected}")] ParsingEnvVariable { name: &'static str, value: String, expected: &'static str, }, #[error("error while calculating pp")] Pp(#[from] PpError), #[error("failed to send reaction after {0} retries")] ReactionRatelimit(usize), #[error("error while communicating with redis")] Redis(#[from] bb8_redis::redis::RedisError), #[error("serde json error")] Json(#[from] serde_json::Error), #[error("shard command error")] ShardCommand(#[from] twilight_gateway::shard::CommandError), #[error("twilight failed to deserialize response")] TwilightDeserialize(#[from] twilight_http::response::DeserializeBodyError), #[error("error while making discord request")] TwilightHttp(#[from] twilight_http::Error), #[error("unknown message component: {component:#?}")] UnknownMessageComponent { component: Box<MessageComponentInteraction>, }, #[error("unexpected autocomplete for slash command `{0}`")] UnknownSlashAutocomplete(String), #[error("unknown slash command `{name}`: {command:#?}")] UnknownSlashCommand { name: String, command: Box<ApplicationCommand>, }, } #[derive(Debug, thiserror::Error)] #[error("failed to create graph")] pub enum GraphError { #[error("client error")] Client(#[from] crate::custom_client::CustomClientError), #[error("failed to calculate curve")] Curve(#[from] enterpolation::linear::LinearError), #[error("image error")] Image(#[from] image::ImageError), #[error("no non-zero strain point")] InvalidStrainPoints, #[error("plotter error: {0}")] Plotter(String), } impl<E: std::error::Error + Send + Sync> From<DrawingAreaErrorKind<E>> for GraphError { fn from(err: DrawingAreaErrorKind<E>) -> Self { Self::Plotter(err.to_string()) } } #[derive(Debug, thiserror::Error)] pub enum InvalidBgState { #[error("missing embed")] MissingEmbed, } #[derive(Debug, thiserror::Error)] pub enum InvalidHelpState { #[error("unknown command")] UnknownCommand, #[error("missing embed")] MissingEmbed, #[error("missing embed title")] MissingTitle, }
#![deny(missing_docs)] //! Custom derive for GetCorresponding. See `relational_types` for the documentation. #![recursion_limit = "128"] extern crate proc_macro; use quote::*; use proc_macro::TokenStream; use std::collections::{HashMap, HashSet}; /// Generation of the `GetCorresponding` trait implementation. #[proc_macro_derive(GetCorresponding, attributes(get_corresponding))] pub fn get_corresponding(input: TokenStream) -> TokenStream { let s = input.to_string(); let ast = syn::parse_derive_input(&s).unwrap(); let gen = impl_get_corresponding(&ast); gen.parse().unwrap() } fn impl_get_corresponding(ast: &syn::DeriveInput) -> quote::Tokens { if let syn::Body::Struct(syn::VariantData::Struct(ref fields)) = ast.body { let name = &ast.ident; let edges: Vec<_> = fields.iter().filter_map(to_edge).collect(); let next = floyd_warshall(&edges); let edge_to_impl = make_edge_to_get_corresponding(name, &edges); let edges_impls = next.iter().map(|(&(from, to), &node)| { if from == to { quote! { impl GetCorresponding<#to> for IdxSet<#from> { fn get_corresponding(&self, _: &#name) -> IdxSet<#to> { self.clone() } } } } else if to == node { edge_to_impl[&(from, to)].clone() } else { quote! { impl GetCorresponding<#to> for IdxSet<#from> { fn get_corresponding(&self, pt_objects: &#name) -> IdxSet<#to> { let tmp: IdxSet<#node> = self.get_corresponding(pt_objects); tmp.get_corresponding(pt_objects) } } } } }); quote! { /// A trait that returns a set of objects corresponding to /// a given type. pub trait GetCorresponding<T: Sized> { /// For the given self, returns the set of /// corresponding `T` indices. fn get_corresponding(&self, model: &#name) -> IdxSet<T>; } impl #name { /// Returns the set of `U` indices corresponding to the `from` set. pub fn get_corresponding<T, U>(&self, from: &IdxSet<T>) -> IdxSet<U> where IdxSet<T>: GetCorresponding<U> { from.get_corresponding(self) } /// Returns the set of `U` indices corresponding to the `from` index. pub fn get_corresponding_from_idx<T, U>(&self, from: Idx<T>) -> IdxSet<U> where IdxSet<T>: GetCorresponding<U> { self.get_corresponding(&Some(from).into_iter().collect()) } } #(#edges_impls)* } } else { quote!() } } fn to_edge(field: &syn::Field) -> Option<Edge> { use syn::MetaItem::*; use syn::NestedMetaItem::MetaItem; use syn::PathParameters::AngleBracketed; let ident = field.ident.as_ref()?.as_ref(); let mut split = ident.split("_to_"); let _from_collection = split.next()?; let _to_collection = split.next()?; if split.next().is_some() { return None; } let segment = if let syn::Ty::Path(_, ref path) = field.ty { path.segments.last() } else { None }?; let (from_ty, to_ty) = if let AngleBracketed(ref data) = segment.parameters { match (data.types.get(0), data.types.get(1), data.types.get(2)) { (Some(from_ty), Some(to_ty), None) => Some((from_ty, to_ty)), _ => None, } } else { None }?; let weight = field .attrs .iter() .flat_map(|attr| match attr.value { List(ref i, ref v) if i == "get_corresponding" => v.as_slice(), _ => &[], }) .map(|mi| match *mi { MetaItem(NameValue(ref i, syn::Lit::Str(ref l, _))) => { assert_eq!(i, "weight", "{} is not a valid attribute", i); l.parse::<f64>() .expect("`weight` attribute must be convertible to f64") } _ => panic!("Only `key = \"value\"` attributes supported."), }) .last() .unwrap_or(1.); Edge { ident: ident.into(), from: from_ty.clone(), to: to_ty.clone(), weight, } .into() } fn make_edge_to_get_corresponding<'a>( name: &syn::Ident, edges: &'a [Edge], ) -> HashMap<(&'a syn::Ty, &'a syn::Ty), quote::Tokens> { let mut res = HashMap::default(); for e in edges { let ident: quote::Ident = e.ident.as_str().into(); let from = &e.from; let to = &e.to; res.insert( (from, to), quote! { impl GetCorresponding<#to> for IdxSet<#from> { fn get_corresponding(&self, pt_objects: &#name) -> IdxSet<#to> { pt_objects.#ident.get_corresponding_forward(self) } } }, ); res.insert( (to, from), quote! { impl GetCorresponding<#from> for IdxSet<#to> { fn get_corresponding(&self, pt_objects: &#name) -> IdxSet<#from> { pt_objects.#ident.get_corresponding_backward(self) } } }, ); } res } fn floyd_warshall(edges: &[Edge]) -> HashMap<(&Node, &Node), &Node> { use std::f64::INFINITY; let mut v = HashSet::<&Node>::default(); let mut dist = HashMap::<(&Node, &Node), f64>::default(); let mut next = HashMap::default(); for e in edges { let from = &e.from; let to = &e.to; v.insert(from); v.insert(to); dist.insert((from, to), e.weight); dist.insert((to, from), e.weight); next.insert((from, to), to); next.insert((to, from), from); } for &k in &v { for &i in &v { let dist_ik = match dist.get(&(i, k)) { Some(d) => *d, None => continue, }; for &j in &v { let dist_kj = match dist.get(&(k, j)) { Some(d) => *d, None => continue, }; let dist_ij = dist.entry((i, j)).or_insert(INFINITY); if *dist_ij > dist_ik + dist_kj { *dist_ij = dist_ik + dist_kj; let next_ik = next[&(i, k)]; next.insert((i, j), next_ik); } } } } next } struct Edge { ident: String, from: Node, to: Node, weight: f64, } type Node = syn::Ty;
pub mod bmx055; pub mod madgwick; pub mod potentio; pub mod serial;
use actix_web::{get, web, HttpResponse, Responder}; use drogue_cloud_service_api::version::DrogueVersion; use drogue_cloud_service_common::endpoints::EndpointSourceType; use serde_json::json; #[get("/info")] pub async fn get_info(endpoint_source: web::Data<EndpointSourceType>) -> impl Responder { match endpoint_source.eval_endpoints().await { Ok(endpoints) => HttpResponse::Ok().json(endpoints), Err(err) => HttpResponse::InternalServerError().json(json!( {"error": err.to_string()})), } } #[get("/drogue-endpoints")] pub async fn get_public_endpoints( endpoint_source: web::Data<EndpointSourceType>, ) -> impl Responder { match endpoint_source.eval_endpoints().await { Ok(endpoints) => HttpResponse::Ok().json(endpoints.publicize()), Err(err) => HttpResponse::InternalServerError().json(json!( {"error": err.to_string()})), } } #[get("/drogue-version")] pub async fn get_drogue_version() -> impl Responder { HttpResponse::Ok().json(DrogueVersion::new()) }
extern crate parenchyma; #[cfg(test)] mod backend_spec { mod native { use std::rc::Rc; use parenchyma::backend::Backend; use parenchyma::frameworks::Native; #[test] fn it_can_create_default_backend() { let backend: Result<Backend, _> = Backend::new::<Native>(); assert!(backend.is_ok()); } #[test] fn it_can_use_ibackend_trait_object() { let backend: Rc<Backend> = Rc::new(Backend::new::<Native>().unwrap()); use_ibackend(backend); } fn use_ibackend(backend: Rc<Backend>) { let backend: Rc<Backend> = backend.clone(); } } // #[cfg(feature = "cuda")] // mod cuda { // use co::*; // #[test] // fn it_can_create_default_backend() { // assert!(Backend::new::<Cuda>().is_ok()); // } // } // mod opencl { // //use parenchyma::{Backend, Framework, FrameworkCtor, OpenCL}; // use parenchyma::backend::Backend; // use parenchyma::frameworks::OpenCL; // use parenchyma::prelude::*; // #[test] // fn it_can_create_default_backend() { // let backend: Result<Backend, _> = Backend::new::<OpenCL>(); // assert!(backend.is_ok()); // } // #[test] // fn it_can_manually_create_backend() { // let framework = OpenCL::new().unwrap(); // let hardware = framework.hardware().to_vec(); // let backend: Backend = Backend::with(framework, hardware).unwrap(); // println!("{:?}", backend); // } // } }
use crate::{ gui::{BuildContext, Ui, UiMessage, UiNode}, load_image, send_sync_message, Message, }; use rg3d::{ core::{color::Color, pool::Handle, scope_profile}, gui::{ brush::Brush, button::ButtonBuilder, grid::{Column, GridBuilder, Row}, image::ImageBuilder, list_view::ListViewBuilder, message::{ButtonMessage, ListViewMessage, MessageDirection, UiMessageData}, scroll_viewer::ScrollViewerBuilder, stack_panel::StackPanelBuilder, text::TextBuilder, widget::WidgetBuilder, window::{WindowBuilder, WindowTitle}, Orientation, Thickness, }, }; use std::{fmt::Debug, sync::mpsc::Sender}; pub trait Command<'a> { type Context; fn name(&mut self, context: &Self::Context) -> String; fn execute(&mut self, context: &mut Self::Context); fn revert(&mut self, context: &mut Self::Context); fn finalize(&mut self, _: &mut Self::Context) {} } pub struct CommandStack<C> { commands: Vec<C>, top: Option<usize>, debug: bool, } impl<C> CommandStack<C> { pub fn new(debug: bool) -> Self { Self { commands: Default::default(), top: None, debug, } } pub fn do_command<'a, Ctx>(&mut self, mut command: C, mut context: Ctx) where C: Command<'a, Context = Ctx> + Debug, { if self.commands.is_empty() { self.top = Some(0); } else { // Advance top match self.top.as_mut() { None => self.top = Some(0), Some(top) => *top += 1, } // Drop everything after top. let top = self.top.unwrap_or(0); if top < self.commands.len() { for mut dropped_command in self.commands.drain(top..) { if self.debug { println!("Finalizing command {:?}", dropped_command); } dropped_command.finalize(&mut context); } } } if self.debug { println!("Executing command {:?}", command); } command.execute(&mut context); self.commands.push(command); } pub fn undo<'a, Ctx>(&mut self, mut context: Ctx) where C: Command<'a, Context = Ctx> + Debug, { if !self.commands.is_empty() { if let Some(top) = self.top.as_mut() { if let Some(command) = self.commands.get_mut(*top) { if self.debug { println!("Undo command {:?}", command); } command.revert(&mut context) } if *top == 0 { self.top = None; } else { *top -= 1; } } } } pub fn redo<'a, Ctx>(&mut self, mut context: Ctx) where C: Command<'a, Context = Ctx> + Debug, { if !self.commands.is_empty() { let command = match self.top.as_mut() { None => { self.top = Some(0); self.commands.first_mut() } Some(top) => { let last = self.commands.len() - 1; if *top < last { *top += 1; self.commands.get_mut(*top) } else { None } } }; if let Some(command) = command { if self.debug { println!("Redo command {:?}", command); } command.execute(&mut context) } } } pub fn clear<'a, Ctx>(&mut self, mut context: Ctx) where C: Command<'a, Context = Ctx> + Debug, { for mut dropped_command in self.commands.drain(..) { if self.debug { println!("Finalizing command {:?}", dropped_command); } dropped_command.finalize(&mut context); } } } pub struct CommandStackViewer { pub window: Handle<UiNode>, list: Handle<UiNode>, sender: Sender<Message>, undo: Handle<UiNode>, redo: Handle<UiNode>, clear: Handle<UiNode>, } impl CommandStackViewer { pub fn new(ctx: &mut BuildContext, sender: Sender<Message>) -> Self { let list; let undo; let redo; let clear; let window = WindowBuilder::new(WidgetBuilder::new()) .with_title(WindowTitle::Text("Command Stack".to_owned())) .with_content( GridBuilder::new( WidgetBuilder::new() .with_child( StackPanelBuilder::new( WidgetBuilder::new() .with_child({ undo = ButtonBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)), ) .with_content( ImageBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .with_height(28.0) .with_width(28.0), ) .with_opt_texture(load_image(include_bytes!( "../resources/embed/undo.png" ))) .build(ctx), ) .build(ctx); undo }) .with_child({ redo = ButtonBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)), ) .with_content( ImageBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .with_height(28.0) .with_width(28.0), ) .with_opt_texture(load_image(include_bytes!( "../resources/embed/redo.png" ))) .build(ctx), ) .build(ctx); redo }) .with_child({ clear = ButtonBuilder::new(WidgetBuilder::new()) .with_content( ImageBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .with_height(28.0) .with_width(28.0), ) .with_opt_texture(load_image(include_bytes!( "../resources/embed/clear.png" ))) .build(ctx), ) .build(ctx); clear }), ) .with_orientation(Orientation::Horizontal) .build(ctx), ) .with_child( ScrollViewerBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .on_row(1), ) .with_content({ list = ListViewBuilder::new(WidgetBuilder::new()).build(ctx); list }) .build(ctx), ), ) .add_column(Column::stretch()) .add_row(Row::strict(30.0)) .add_row(Row::stretch()) .build(ctx), ) .build(ctx); Self { window, list, sender, undo, redo, clear, } } pub fn handle_ui_message(&self, message: &UiMessage) { scope_profile!(); if let UiMessageData::Button(ButtonMessage::Click) = message.data() { if message.destination() == self.undo { self.sender.send(Message::UndoSceneCommand).unwrap(); } else if message.destination() == self.redo { self.sender.send(Message::RedoSceneCommand).unwrap(); } else if message.destination() == self.clear { self.sender.send(Message::ClearSceneCommandStack).unwrap(); } } } pub fn sync_to_model<'a, C, Ctx>( &mut self, command_stack: &mut CommandStack<C>, ctx: &Ctx, ui: &mut Ui, ) where C: Command<'a, Context = Ctx> + Debug, { scope_profile!(); let top = command_stack.top; let items = command_stack .commands .iter_mut() .enumerate() .rev() // First command in list is last on stack. .map(|(i, cmd)| { let brush = if let Some(top) = top { if (0..=top).contains(&i) { Brush::Solid(Color::opaque(255, 255, 255)) } else { Brush::Solid(Color::opaque(100, 100, 100)) } } else { Brush::Solid(Color::opaque(100, 100, 100)) }; TextBuilder::new(WidgetBuilder::new().with_foreground(brush)) .with_text(cmd.name(ctx)) .build(&mut ui.build_ctx()) }) .collect(); send_sync_message( ui, ListViewMessage::items(self.list, MessageDirection::ToWidget, items), ); } }
use std::error::Error; use std::fmt; use tokio::io; #[derive(Debug)] pub enum CacheError { IOError { source: io::Error }, DeserializationError { source: serde_json::Error }, } impl Error for CacheError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { CacheError::IOError { ref source } => Some(source), CacheError::DeserializationError { ref source } => Some(source), } } } impl fmt::Display for CacheError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CacheError::IOError { source } => source.fmt(f), CacheError::DeserializationError { source } => source.fmt(f), } } } impl From<io::Error> for CacheError { fn from(error: io::Error) -> Self { CacheError::IOError { source: error } } } impl From<serde_json::Error> for CacheError { fn from(error: serde_json::Error) -> Self { CacheError::DeserializationError { source: error } } }
#[doc = "Register `CMPCR` reader"] pub type R = crate::R<CMPCR_SPEC>; #[doc = "Field `CMP_PD` reader - Compensation cell power-down"] pub type CMP_PD_R = crate::BitReader; #[doc = "Field `READY` reader - READY"] pub type READY_R = crate::BitReader; impl R { #[doc = "Bit 0 - Compensation cell power-down"] #[inline(always)] pub fn cmp_pd(&self) -> CMP_PD_R { CMP_PD_R::new((self.bits & 1) != 0) } #[doc = "Bit 8 - READY"] #[inline(always)] pub fn ready(&self) -> READY_R { READY_R::new(((self.bits >> 8) & 1) != 0) } } #[doc = "Compensation cell control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmpcr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CMPCR_SPEC; impl crate::RegisterSpec for CMPCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cmpcr::R`](R) reader structure"] impl crate::Readable for CMPCR_SPEC {} #[doc = "`reset()` method sets CMPCR to value 0"] impl crate::Resettable for CMPCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[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::SUPPLYSTATUS { #[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 `BLEBUCKON`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BLEBUCKONR { #[doc = "Indicates the the LDO is supplying the BLE/Burst power domain value."] LDO, #[doc = "Indicates the the Buck is supplying the BLE/Burst power domain value."] BUCK, } impl BLEBUCKONR { #[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 { BLEBUCKONR::LDO => false, BLEBUCKONR::BUCK => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> BLEBUCKONR { match value { false => BLEBUCKONR::LDO, true => BLEBUCKONR::BUCK, } } #[doc = "Checks if the value of the field is `LDO`"] #[inline] pub fn is_ldo(&self) -> bool { *self == BLEBUCKONR::LDO } #[doc = "Checks if the value of the field is `BUCK`"] #[inline] pub fn is_buck(&self) -> bool { *self == BLEBUCKONR::BUCK } } #[doc = "Possible values of the field `SIMOBUCKON`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SIMOBUCKONR { #[doc = "Indicates the the SIMO Buck is OFF. value."] OFF, #[doc = "Indicates the the SIMO Buck is ON. value."] ON, } impl SIMOBUCKONR { #[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 { SIMOBUCKONR::OFF => false, SIMOBUCKONR::ON => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SIMOBUCKONR { match value { false => SIMOBUCKONR::OFF, true => SIMOBUCKONR::ON, } } #[doc = "Checks if the value of the field is `OFF`"] #[inline] pub fn is_off(&self) -> bool { *self == SIMOBUCKONR::OFF } #[doc = "Checks if the value of the field is `ON`"] #[inline] pub fn is_on(&self) -> bool { *self == SIMOBUCKONR::ON } } #[doc = "Values that can be written to the field `BLEBUCKON`"] pub enum BLEBUCKONW { #[doc = "Indicates the the LDO is supplying the BLE/Burst power domain value."] LDO, #[doc = "Indicates the the Buck is supplying the BLE/Burst power domain value."] BUCK, } impl BLEBUCKONW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { BLEBUCKONW::LDO => false, BLEBUCKONW::BUCK => true, } } } #[doc = r" Proxy"] pub struct _BLEBUCKONW<'a> { w: &'a mut W, } impl<'a> _BLEBUCKONW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: BLEBUCKONW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Indicates the the LDO is supplying the BLE/Burst power domain value."] #[inline] pub fn ldo(self) -> &'a mut W { self.variant(BLEBUCKONW::LDO) } #[doc = "Indicates the the Buck is supplying the BLE/Burst power domain value."] #[inline] pub fn buck(self) -> &'a mut W { self.variant(BLEBUCKONW::BUCK) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SIMOBUCKON`"] pub enum SIMOBUCKONW { #[doc = "Indicates the the SIMO Buck is OFF. value."] OFF, #[doc = "Indicates the the SIMO Buck is ON. value."] ON, } impl SIMOBUCKONW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SIMOBUCKONW::OFF => false, SIMOBUCKONW::ON => true, } } } #[doc = r" Proxy"] pub struct _SIMOBUCKONW<'a> { w: &'a mut W, } impl<'a> _SIMOBUCKONW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SIMOBUCKONW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Indicates the the SIMO Buck is OFF. value."] #[inline] pub fn off(self) -> &'a mut W { self.variant(SIMOBUCKONW::OFF) } #[doc = "Indicates the the SIMO Buck is ON. value."] #[inline] pub fn on(self) -> &'a mut W { self.variant(SIMOBUCKONW::ON) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 1 - Indicates whether the BLE (if supported) domain and burst (if supported) domain is supplied from the LDO or the Buck. Buck will be powered up only if there is an active request for BLEH domain or Burst mode and appropriate reature is allowed."] #[inline] pub fn blebuckon(&self) -> BLEBUCKONR { BLEBUCKONR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 0 - Indicates whether the Core/Mem low-voltage domains are supplied from the LDO or the Buck."] #[inline] pub fn simobuckon(&self) -> SIMOBUCKONR { SIMOBUCKONR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 1 - Indicates whether the BLE (if supported) domain and burst (if supported) domain is supplied from the LDO or the Buck. Buck will be powered up only if there is an active request for BLEH domain or Burst mode and appropriate reature is allowed."] #[inline] pub fn blebuckon(&mut self) -> _BLEBUCKONW { _BLEBUCKONW { w: self } } #[doc = "Bit 0 - Indicates whether the Core/Mem low-voltage domains are supplied from the LDO or the Buck."] #[inline] pub fn simobuckon(&mut self) -> _SIMOBUCKONW { _SIMOBUCKONW { w: self } } }
use std::vec; use std::unstable::atomics::{atomic_store, atomic_load, AtomicUint, fence, SeqCst, Acquire, Release, Relaxed}; use std::unstable::sync::{UnsafeArc, LittleLock}; use std::cast; struct Deque<T> { priv state: UnsafeArc<State<T>>, } impl<T: Send> Deque<T> { pub fn with_capacity(capacity: uint) -> Deque<T> { Deque{ state: UnsafeArc::new(State::with_capacity(capacity)) } } pub fn push(&mut self, value: T) { unsafe { (*self.state.get()).push(value) } } pub fn pop(&mut self) -> Option<T> { unsafe { (*self.state.get()).pop() } } pub fn steal(&mut self) -> Option<T> { unsafe { (*self.state.get()).steal() } } pub fn is_empty(&mut self) -> bool { unsafe { (*self.state.get()).is_empty() } } pub fn len(&mut self) -> uint { unsafe { (*self.state.get()).len() } } } impl<T: Send> Clone for Deque<T> { fn clone(&self) -> Deque<T> { Deque { state: self.state.clone() } } } struct State<T> { array: ~[*mut T], mask: uint, headIndex: AtomicUint, tailIndex: AtomicUint, lock: LittleLock, } impl<T: Send> State<T> { fn with_capacity(size: uint) -> State<T> { let mut state = State{ array: vec::with_capacity(size), mask: size-1, headIndex: AtomicUint::new(0), tailIndex: AtomicUint::new(0), lock: LittleLock::new() }; unsafe { vec::raw::set_len(&mut state.array, size); } state } fn push(&mut self, value: T) { let mut tail = self.tailIndex.load(Acquire); if tail < self.headIndex.load(Acquire) + self.mask { unsafe { atomic_store(&mut self.array[tail & self.mask], cast::transmute(value), Relaxed); } self.tailIndex.store(tail+1, Release); } else { unsafe { let value: *mut T = cast::transmute(value); self.lock.lock(|| { let head = self.headIndex.load(Acquire); let count = self.len(); if count >= self.mask { let arraySize = self.array.len(); let mask = self.mask; let mut newArray = vec::with_capacity(arraySize*2); vec::raw::set_len(&mut newArray, arraySize*2); for i in range(0, count) { newArray[i] = self.array[(i+head) & mask]; } self.array = newArray; self.headIndex.store(0, Release); self.tailIndex.store(count, Release); tail = count; self.mask = (mask * 2) | 1; } atomic_store(&mut self.array[tail & self.mask], value, Relaxed); self.tailIndex.store(tail+1, Release); }); } } } fn pop(&mut self) -> Option<T> { let mut tail = self.tailIndex.load(Acquire); if tail == 0 { return None } tail -= 1; self.tailIndex.store(tail, Release); fence(SeqCst); unsafe { if self.headIndex.load(Acquire) <= tail { Some(cast::transmute(atomic_load(&mut self.array[tail & self.mask], Relaxed))) } else { self.lock.lock(|| { if self.headIndex.load(Acquire) <= tail { Some(cast::transmute(atomic_load(&mut self.array[tail & self.mask], Relaxed))) } else { self.tailIndex.store(tail+1, Release); None } }) } } } fn steal(&mut self) -> Option<T> { unsafe { match self.lock.try_lock(|| { let head = self.headIndex.load(Acquire); self.headIndex.store(head+1, Release); fence(SeqCst); if head < self.tailIndex.load(Acquire) { Some(cast::transmute(atomic_load(&mut self.array[head & self.mask], Relaxed))) } else { self.headIndex.store(head, Release); None } }) { Some(T) => T, None => None } } } fn is_empty(&self) -> bool { self.headIndex.load(Acquire) >= self.tailIndex.load(Acquire) } fn len(&self) -> uint { self.tailIndex.load(Acquire) - self.headIndex.load(Acquire) } } #[cfg(test)] mod tests { use std::task; use std::comm; use std::unstable::sync::{UnsafeArc}; use std::unstable::atomics::{AtomicUint, Relaxed}; use super::Deque; #[test] fn test() { let mut q = Deque::with_capacity(10); q.push(1); assert_eq!(Some(1), q.pop()); assert_eq!(None, q.steal()); q.push(2); assert_eq!(Some(2), q.steal()); } #[test] fn test_grow() { let mut q = Deque::with_capacity(2); q.push(1); assert_eq!(Some(1), q.pop()); assert_eq!(None, q.steal()); q.push(2); assert_eq!(Some(2), q.steal()); q.push(3); q.push(4); assert_eq!(Some(4), q.pop()); assert_eq!(Some(3), q.pop()); assert_eq!(None, q.steal()); } #[test] fn test_steal() { let work_units = 1000u; let stealers = 8u; let q = Deque::with_capacity(100); let counter = UnsafeArc::new(AtomicUint::new(0)); let mut completion_ports = ~[]; let (port, chan) = comm::stream(); let (completion_port, completion_chan) = comm::stream(); completion_ports.push(completion_port); chan.send(q.clone()); { let counter = counter.clone(); do task::spawn_sched(task::SingleThreaded) { let mut q = port.recv(); for i in range(0, work_units) { q.push(i); } let mut count = 0u; loop { match q.pop() { Some(_) => unsafe { count += 1; (*counter.get()).fetch_add(1, Relaxed); // simulate work task::deschedule(); }, None => break, } } debug!("count: {}", count); completion_chan.send(0); } } for _ in range(0, stealers) { let (port, chan) = comm::stream(); let (completion_port, completion_chan) = comm::stream(); completion_ports.push(completion_port); chan.send(q.clone()); let counter = counter.clone(); do task::spawn_sched(task::SingleThreaded) { let mut count = 0u; let mut q = port.recv(); loop { match q.steal() { Some(_) => unsafe { count += 1; (*counter.get()).fetch_add(1, Relaxed); }, None => (), } // simulate work task::deschedule(); unsafe { if (*counter.get()).load(Relaxed) == work_units { break } } } debug!("count: {}", count); completion_chan.send(0); } } // wait for all tasks to finish work for completion_port in completion_ports.iter() { assert_eq!(0, completion_port.recv()); } unsafe { assert_eq!(work_units, (*counter.get()).load(Relaxed)); } } }
use crate::{ app::util::arg::formatter, repository::{Category, Repository}, util::{optfilter::OptFilter, repoobject::RepoObject}, }; use clap::{App, ArgMatches, Error, SubCommand}; use std::path::Path; pub(crate) const NAME: &str = "categories"; pub(crate) const ABOUT: &str = "Iterate all categories in a repository"; pub(crate) fn subcommand<'x, 'y>() -> App<'x, 'y> { SubCommand::with_name(NAME).about(ABOUT).arg(formatter::arg()) } pub(crate) fn run(repo: &str, command: &ArgMatches<'_>) -> Result<(), Error> { let r = Repository::new(Path::new(repo)); let citer = r.categories().expect("Error reading categories from repo"); let formatter = formatter::get(command); for it in citer.filter_oks(Category::is_legal).extract_errs(|e| panic!(e)) { println!("{}", it.render(&formatter)); } Ok(()) }
use piston_window::{ellipse, rectangle, Context, G2d}; use crate::colors; use crate::player::Player; use crate::shapes::{Circle, Rectangle, Shape}; pub enum SceneryType { Tree { base_width: f64, base_height: f64, top_radius: f64, }, } pub struct Scenery { pub type_: SceneryType, pub location: (f64, f64), } impl Scenery { pub fn collides(&self, player: &Player<'_>) -> bool { match self.type_ { SceneryType::Tree { base_width, base_height, top_radius, } => match player.shape { Shape::Circle { radius } => { let player_circle = Circle { x: player.location.0, y: player.location.1, radius, }; let top_circle = Circle { x: self.location.0 + (base_width / 2.0), y: self.location.1 - top_radius + 5.0, radius: top_radius, }; let base_rect = Rectangle { x: self.location.0, y: self.location.1, width: base_width, height: base_height, }; player_circle.collides_with_rectangle(base_rect) || player_circle.collides_with_circle(top_circle) } Shape::Rectangle { .. } => { // Temporary placeholder until we add a rectangle player false } }, } } pub fn render(&self, context: Context, graphics: &mut G2d) { match self.type_ { SceneryType::Tree { base_width, base_height, top_radius, } => { rectangle( colors::BLACK, [self.location.0, self.location.1, base_width, base_height], context.transform, graphics, ); let top_x = self.location.0 + (base_width / 2.0); let top_y = self.location.1 - top_radius + 5.0; ellipse( colors::BLUE, ellipse::circle(top_x, top_y, top_radius), context.transform, graphics, ); } } } }
// #![allow(unused_variables, unused_mut)] pub mod proto; pub mod server;
use std::collections::HashMap; use std::fmt; use indexmap::map::{IndexMap, IntoIter, Iter, IterMut}; use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, Serializer}; use super::{de::ValueDeserializer, ser::ValueSerializer, Error, Key, Value}; #[derive(Clone, Debug, PartialEq)] pub struct Table(IndexMap<String, Value>); impl Table { pub fn new() -> Self { Self::default() } pub fn get<'de, K, V>(&'de self, key: K) -> Result<V, Error> where K: Into<Key>, V: 'de + Deserialize<'de>, { let mut key = key.into(); match key.next() { Some(head) => match self.0.get(&head) { Some(val) => match key.peek() { Some(_) => val.get(key), None => Ok(V::deserialize(ValueDeserializer::new(val))?), }, None => Err(Error::custom(format!("missing value for key '{}'", head))), }, None => Err(Error::custom("empty key")), } } pub fn set<K, V>(&mut self, key: K, val: V) -> Result<&mut Table, Error> where K: Into<Key>, V: Serialize, { let mut key = key.into(); match key.next() { Some(head) => { let item = self.0.entry(head).or_insert_with(Value::entry); match key.peek() { Some(_) => { item.set(key, val)?; Ok(self) } None => { *item = val.serialize(ValueSerializer)?; Ok(self) } } } None => Err(Error::custom("empty key")), } } } impl Default for Table { fn default() -> Self { Self(IndexMap::new()) } } impl Serialize for Table { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(self.0.len()))?; for (key, value) in &self.0 { map.serialize_entry(&key, &value)?; } map.end() } } impl<'de> Deserialize<'de> for Table { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct TableVisitor; impl<'de> Visitor<'de> for TableVisitor { type Value = Table; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a valid table") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { Deserialize::deserialize(deserializer) } fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut map = IndexMap::new(); while let Some(key) = visitor.next_key()? { map.insert(key, visitor.next_value()?); } Ok(Table(map)) } } deserializer.deserialize_any(TableVisitor) } } impl IntoIterator for Table { type Item = (String, Value); type IntoIter = IntoIter<String, Value>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl<'a> IntoIterator for &'a Table { type Item = (&'a String, &'a Value); type IntoIter = Iter<'a, String, Value>; fn into_iter(self) -> Iter<'a, String, Value> { self.0.iter() } } impl<'a> IntoIterator for &'a mut Table { type Item = (&'a String, &'a mut Value); type IntoIter = IterMut<'a, String, Value>; fn into_iter(self) -> IterMut<'a, String, Value> { self.0.iter_mut() } } impl From<HashMap<String, Value>> for Table { fn from(from: HashMap<String, Value>) -> Self { let mut map = IndexMap::new(); for (key, val) in from { map.insert(key, val); } Self(map) } } impl From<IndexMap<String, Value>> for Table { fn from(from: IndexMap<String, Value>) -> Self { Self(from) } } #[cfg(test)] mod tests { use super::Table; #[test] fn test_table() { let mut table = Table::new(); assert!(table.set("username", "joe.bloggs").is_ok()); assert!(table.set("password", "hunter2").is_ok()); assert!(table.set("age", "42").is_ok()); assert_eq!( table.get::<_, String>("username"), Ok(String::from("joe.bloggs")) ); assert_eq!( table.get::<_, String>(String::from("password")), Ok(String::from("hunter2")) ); assert_eq!(table.get::<_, String>("age"), Ok(String::from("42"))); assert_eq!(table.get::<_, i32>("age"), Ok(42)); } }
use crate::{util::CowUtils, Context}; use chrono::FixedOffset; use hashbrown::HashMap; use serde::Deserialize; use smallstr::SmallString; use std::{borrow::Borrow, fmt, ops::Deref}; lazy_static! { static ref TIMEZONES: HashMap<&'static str, i32> = { const HOUR: i32 = 3600; const HALF_HOUR: i32 = 1800; let mut map = HashMap::with_capacity(250); // http://1min.in/content/international/time-zones map.insert("AF", 4 * HOUR + HALF_HOUR); map.insert("AL", 3 * HOUR); map.insert("DZ", HOUR); map.insert("AS", -11 * HOUR); map.insert("AD", 2 * HOUR); map.insert("AO", HOUR); map.insert("AI", -4 * HOUR); map.insert("AQ", 7 * HOUR); map.insert("AG", -4 * HOUR); map.insert("AR", -3 * HOUR); map.insert("AM", 4 * HOUR); map.insert("AW", -4 * HOUR); map.insert("AU", 10 * HOUR); map.insert("AT", 2 * HOUR); map.insert("AZ", 4 * HOUR); map.insert("BS", -4 * HOUR); map.insert("BH", 3 * HOUR); map.insert("BD", 6 * HOUR); map.insert("BB", -4 * HOUR); map.insert("BY", 3 * HOUR); map.insert("BE", 2 * HOUR); map.insert("BZ", -6 * HOUR); map.insert("BJ", HOUR); map.insert("BM", -3 * HOUR); map.insert("BT", 6 * HOUR); map.insert("BO", -4 * HOUR); map.insert("BQ", -4 * HOUR); map.insert("BA", 2 * HOUR); map.insert("BW", 2 * HOUR); // map.insert("BV", 0); map.insert("BR", -3 * HOUR); map.insert("IO", 6 * HOUR); map.insert("BN", 8 * HOUR); map.insert("BG", 3 * HOUR); map.insert("BF", 0); map.insert("BI", 2 * HOUR); map.insert("CV", -HOUR); map.insert("KH", 7 * HOUR); map.insert("CM", HOUR); map.insert("CA", -4 * HOUR); map.insert("KY", -5 * HOUR); map.insert("CF", HOUR); map.insert("TD", HOUR); map.insert("CL", -3 * HOUR); map.insert("CN", 8 * HOUR); map.insert("CX", 7 * HOUR); map.insert("CC", 6 * HOUR + HALF_HOUR); map.insert("CO", -5 * HOUR); map.insert("KM", 3 * HOUR); map.insert("CD", HOUR); map.insert("CG", HOUR); map.insert("CK", -10 * HOUR); map.insert("CR", -6 * HOUR); map.insert("HR", 2 * HOUR); map.insert("CU", -4 * HOUR); map.insert("CW", -4 * HOUR); map.insert("CY", 3 * HOUR); map.insert("CZ", 2 * HOUR); map.insert("CI", 0); map.insert("DK", 2 * HOUR); map.insert("DJ", 3 * HOUR); map.insert("DM", -4 * HOUR); map.insert("DO", -4 * HOUR); map.insert("EC", -5 * HOUR); map.insert("EG", 2 * HOUR); map.insert("SV", -6 * HOUR); map.insert("GQ", HOUR); map.insert("ER", 3 * HOUR); map.insert("EE", 3 * HOUR); map.insert("SZ", 2 * HOUR); map.insert("ET", 3 * HOUR); map.insert("FK", -3 * HOUR); map.insert("FO", HOUR); map.insert("FJ", 12 * HOUR); map.insert("FI", 3 * HOUR); map.insert("FR", 2 * HOUR); map.insert("GF", -3 * HOUR); map.insert("PF", -9 * HOUR); map.insert("TF", 5 * HOUR); map.insert("GA", HOUR); map.insert("GM", 0); map.insert("GE", 4 * HOUR); map.insert("DE", 2 * HOUR); map.insert("GH", 0); map.insert("GI", 2 * HOUR); map.insert("GR", 3 * HOUR); map.insert("GL", -2 * HOUR); map.insert("GD", -4 * HOUR); map.insert("GP", -4 * HOUR); map.insert("GU", 10 * HOUR); map.insert("GT", -6 * HOUR); map.insert("GG", HOUR); map.insert("GN", 0); map.insert("GW", 0); map.insert("GY", -4 * HOUR); map.insert("HT", -4 * HOUR); // map.insert("HM", HOUR); map.insert("VA", 2 * HOUR); map.insert("HN", -6 * HOUR); map.insert("HK", 8 * HOUR); map.insert("HU", 2 * HOUR); map.insert("IS", 0); map.insert("IN", 5 * HOUR + HALF_HOUR); map.insert("ID", 7 * HOUR); map.insert("IR", 4 * HOUR + HALF_HOUR); map.insert("IQ", 3 * HOUR); map.insert("IE", HOUR); map.insert("IM", HOUR); map.insert("IL", 3 * HOUR); map.insert("IT", 2 * HOUR); map.insert("JM", -5 * HOUR); map.insert("JP", 9 * HOUR); map.insert("JE", HOUR); map.insert("JO", 3 * HOUR); map.insert("KZ", 5 * HOUR); map.insert("KE", 3 * HOUR); map.insert("KI", 13 * HOUR); map.insert("KP", 8 * HOUR + HALF_HOUR); map.insert("KR", 9 * HOUR); map.insert("KW", 3 * HOUR); map.insert("KG", 6 * HOUR); map.insert("LA", 7 * HOUR); map.insert("LV", 3 * HOUR); map.insert("LB", 3 * HOUR); map.insert("LS", 2 * HOUR); map.insert("LR", 0); map.insert("LY", 2 * HOUR); map.insert("LI", 2 * HOUR); map.insert("LT", 3 * HOUR); map.insert("LU", 2 * HOUR); map.insert("MO", 8 * HOUR); map.insert("MG", 3 * HOUR); map.insert("MW", 2 * HOUR); map.insert("MY", 8 * HOUR); map.insert("MV", 5 * HOUR); map.insert("ML", 0); map.insert("MT", 2 * HOUR); map.insert("MH", 12 * HOUR); map.insert("MQ", -4 * HOUR); map.insert("MR", 0); map.insert("MU", 4 * HOUR); map.insert("YT", 3 * HOUR); map.insert("MX", -6 * HOUR); map.insert("FM", 11 * HOUR); map.insert("MD", 3 * HOUR); map.insert("MC", 2 * HOUR); map.insert("MN", 8 * HOUR); map.insert("ME", 2 * HOUR); map.insert("MS", -4 * HOUR); map.insert("MA", HOUR); map.insert("MZ", 2 * HOUR); map.insert("MM", 6 * HOUR + HALF_HOUR); map.insert("NA", 2 * HOUR); map.insert("NR", 12 * HOUR); map.insert("NP", 5 * HOUR + 2700); map.insert("NL", 2 * HOUR); map.insert("NC", 11 * HOUR); map.insert("NZ", 12 * HOUR); map.insert("NI", -6 * HOUR); map.insert("NE", HOUR); map.insert("NG", HOUR); map.insert("NU", -11 * HOUR); map.insert("NF", 11 * HOUR); map.insert("MP", 10 * HOUR); map.insert("NO", 2 * HOUR); map.insert("OM", 4 * HOUR); map.insert("PK", 5 * HOUR); map.insert("PW", 9 * HOUR); map.insert("PS", 3 * HOUR); map.insert("PA", -5 * HOUR); map.insert("PG", 10 * HOUR); map.insert("PY", -4 * HOUR); map.insert("PE", -5 * HOUR); map.insert("PH", 8 * HOUR); map.insert("PN", -8 * HOUR); map.insert("PL", 2 * HOUR); map.insert("PT", HOUR); map.insert("PR", -4 * HOUR); map.insert("QA", 3 * HOUR); map.insert("MK", 2 * HOUR); map.insert("RO", 3 * HOUR); map.insert("RU", 6 * HOUR); map.insert("RW", 2 * HOUR); map.insert("RE", 4 * HOUR); map.insert("BL", -4 * HOUR); map.insert("SH", 0); map.insert("KN", -4 * HOUR); map.insert("LC", -4 * HOUR); map.insert("MF", -4 * HOUR); map.insert("PM", -2 * HOUR); map.insert("PM", -2 * HOUR); map.insert("VC", -4 * HOUR); map.insert("WS", 13 * HOUR); map.insert("SM", 2 * HOUR); map.insert("ST", HOUR); map.insert("SA", 3 * HOUR); map.insert("SN", 0); map.insert("RS", 2 * HOUR); map.insert("SC", 4 * HOUR); map.insert("SL", 0); map.insert("SG", 8 * HOUR); map.insert("SX", -4 * HOUR); map.insert("SK", 2 * HOUR); map.insert("SI", 2 * HOUR); map.insert("SB", 11 * HOUR); map.insert("SO", 3 * HOUR); map.insert("ZA", 2 * HOUR); map.insert("GS", -2 * HOUR); map.insert("SS", 3 * HOUR); map.insert("ES", HOUR); map.insert("LK", 5 * HOUR + HALF_HOUR); map.insert("SD", 2 * HOUR); map.insert("SR", -3 * HOUR); map.insert("SJ", 2 * HOUR); map.insert("SE", 2 * HOUR); map.insert("CH", 2 * HOUR); map.insert("SY", 3 * HOUR); map.insert("TW", 8 * HOUR); map.insert("TJ", 5 * HOUR); map.insert("TZ", 3 * HOUR); map.insert("TH", 7 * HOUR); map.insert("TL", 9 * HOUR); map.insert("TG", 0); map.insert("TK", 13 * HOUR); map.insert("TO", 13 * HOUR); map.insert("TT", -4 * HOUR); map.insert("TN", HOUR); map.insert("TR", 3 * HOUR); map.insert("TM", 5 * HOUR); map.insert("TC", -4 * HOUR); map.insert("TV", 12 * HOUR); map.insert("UG", 3 * HOUR); map.insert("UA", 3 * HOUR); map.insert("AE", 4 * HOUR); map.insert("GB", HOUR); map.insert("UM", 12 * HOUR); map.insert("US", -5 * HOUR); map.insert("UY", -3 * HOUR); map.insert("UZ", 5 * HOUR); map.insert("VU", 11 * HOUR); map.insert("VE", -4 * HOUR); map.insert("VN", 7 * HOUR); map.insert("VG", -4 * HOUR); map.insert("VI", -4 * HOUR); map.insert("WF", 12 * HOUR); map.insert("EH", HOUR); map.insert("YE", 3 * HOUR); map.insert("ZM", 2 * HOUR); map.insert("ZW", 2 * HOUR); map }; static ref COUNTRIES: HashMap<&'static str, SmallString<[u8; 2]>> = { let mut map = HashMap::with_capacity(300); map.insert("afghanistan", "AF".into()); map.insert("albania", "AL".into()); map.insert("algeria", "DZ".into()); map.insert("american samoa", "AS".into()); map.insert("andorra", "AD".into()); map.insert("angola", "AO".into()); map.insert("anguilla", "AI".into()); map.insert("antarctica", "AQ".into()); map.insert("antigua", "AG".into()); map.insert("barbuda", "AG".into()); map.insert("argentina", "AR".into()); map.insert("armenia", "AM".into()); map.insert("aruba", "AW".into()); map.insert("australia", "AU".into()); map.insert("austria", "AT".into()); map.insert("azerbaijan", "AZ".into()); map.insert("bahamas", "BS".into()); map.insert("bahrain", "BH".into()); map.insert("bangladesh", "BD".into()); map.insert("barbados", "BB".into()); map.insert("belarus", "BY".into()); map.insert("belgium", "BE".into()); map.insert("belize", "BZ".into()); map.insert("benin", "BJ".into()); map.insert("bermuda", "BM".into()); map.insert("bhutan", "BT".into()); map.insert("bolivia", "BO".into()); map.insert("bonaire", "BQ".into()); map.insert("sint eustatius", "BQ".into()); map.insert("saba", "BQ".into()); map.insert("bosnia and herzegovina", "BA".into()); map.insert("botswana", "BW".into()); map.insert("bouvet island", "BV".into()); map.insert("brazil", "BR".into()); map.insert("british indian ocean territory", "IO".into()); map.insert("brunei darussalam", "BN".into()); map.insert("bulgaria", "BG".into()); map.insert("burkina faso", "BF".into()); map.insert("burundi", "BI".into()); map.insert("cabo verde", "CV".into()); map.insert("cambodia", "KH".into()); map.insert("cameroon", "CM".into()); map.insert("canada", "CA".into()); map.insert("cayman islands", "KY".into()); map.insert("central african republic", "CF".into()); map.insert("chad", "TD".into()); map.insert("chile", "CL".into()); map.insert("china", "CN".into()); map.insert("christmas island", "CX".into()); map.insert("cocos islands", "CC".into()); map.insert("colombia", "CO".into()); map.insert("comoros", "KM".into()); map.insert("democratic republic of congo", "CD".into()); map.insert("democratic republic of the congo", "CD".into()); map.insert("congo", "CG".into()); map.insert("cook islands", "CK".into()); map.insert("costa rica", "CR".into()); map.insert("croatia", "HR".into()); map.insert("cuba", "CU".into()); map.insert("curaçao", "CW".into()); map.insert("cyprus", "CY".into()); map.insert("czechia", "CZ".into()); map.insert("côte d'ivoire", "CI".into()); map.insert("denmark", "DK".into()); map.insert("djibouti", "DJ".into()); map.insert("dominica", "DM".into()); map.insert("dominican republic", "DO".into()); map.insert("ecuador", "EC".into()); map.insert("egypt", "EG".into()); map.insert("el salvador", "SV".into()); map.insert("equatorial guinea", "GQ".into()); map.insert("eritrea", "ER".into()); map.insert("estonia", "EE".into()); map.insert("eswatini", "SZ".into()); map.insert("ethiopia", "ET".into()); map.insert("falkland islands", "FK".into()); map.insert("malvinas", "FK".into()); map.insert("faroe islands", "FO".into()); map.insert("fiji", "FJ".into()); map.insert("finland", "FI".into()); map.insert("france", "FR".into()); map.insert("french guiana", "GF".into()); map.insert("french polynesia", "PF".into()); map.insert("french southern territories", "TF".into()); map.insert("gabon", "GA".into()); map.insert("gambia", "GM".into()); map.insert("georgia", "GE".into()); map.insert("germany", "DE".into()); map.insert("ghana", "GH".into()); map.insert("gibraltar", "GI".into()); map.insert("greece", "GR".into()); map.insert("greenland", "GL".into()); map.insert("grenada", "GD".into()); map.insert("guadeloupe", "GP".into()); map.insert("guam", "GU".into()); map.insert("guatemala", "GT".into()); map.insert("guernsey", "GG".into()); map.insert("guinea", "GN".into()); map.insert("guinea-bissau", "GW".into()); map.insert("guyana", "GY".into()); map.insert("haiti", "HT".into()); map.insert("heard island", "HM".into()); map.insert("mcdonald islands", "HM".into()); map.insert("holy see", "VA".into()); map.insert("honduras", "HN".into()); map.insert("hong Kong", "HK".into()); map.insert("hungary", "HU".into()); map.insert("iceland", "IS".into()); map.insert("india", "IN".into()); map.insert("indonesia", "ID".into()); map.insert("iran", "IR".into()); map.insert("iraq", "IQ".into()); map.insert("ireland", "IE".into()); map.insert("isle of man", "IM".into()); map.insert("israel", "IL".into()); map.insert("italy", "IT".into()); map.insert("jamaica", "JM".into()); map.insert("japan", "JP".into()); map.insert("jersey", "JE".into()); map.insert("jordan", "JO".into()); map.insert("kazakhstan", "KZ".into()); map.insert("kenya", "KE".into()); map.insert("kiribati", "KI".into()); map.insert("north korea", "KP".into()); map.insert("south korea", "KR".into()); map.insert("kuwait", "KW".into()); map.insert("kyrgyzstan", "KG".into()); map.insert("lao people's democratic republic", "LA".into()); map.insert("latvia", "LV".into()); map.insert("lebanon", "LB".into()); map.insert("lesotho", "LS".into()); map.insert("liberia", "LR".into()); map.insert("libya", "LY".into()); map.insert("liechtenstein", "LI".into()); map.insert("lithuania", "LT".into()); map.insert("luxembourg", "LU".into()); map.insert("macao", "MO".into()); map.insert("madagascar", "MG".into()); map.insert("malawi", "MW".into()); map.insert("malaysia", "MY".into()); map.insert("maldives", "MV".into()); map.insert("mali", "ML".into()); map.insert("malta", "MT".into()); map.insert("marshall islands", "MH".into()); map.insert("martinique", "MQ".into()); map.insert("mauritania", "MR".into()); map.insert("mauritius", "MU".into()); map.insert("mayotte", "YT".into()); map.insert("mexico", "MX".into()); map.insert("micronesia", "FM".into()); map.insert("moldova", "MD".into()); map.insert("monaco", "MC".into()); map.insert("mongolia", "MN".into()); map.insert("montenegro", "ME".into()); map.insert("montserrat", "MS".into()); map.insert("morocco", "MA".into()); map.insert("mozambique", "MZ".into()); map.insert("myanmar", "MM".into()); map.insert("namibia", "NA".into()); map.insert("nauru", "NR".into()); map.insert("nepal", "NP".into()); map.insert("the netherlands", "NL".into()); map.insert("netherlands", "NL".into()); map.insert("new caledonia", "NC".into()); map.insert("new zealand", "NZ".into()); map.insert("nicaragua", "NI".into()); map.insert("niger", "NE".into()); map.insert("nigeria", "NG".into()); map.insert("niue", "NU".into()); map.insert("norfolk island", "NF".into()); map.insert("northern mariana islands", "MP".into()); map.insert("norway", "NO".into()); map.insert("oman", "OM".into()); map.insert("pakistan", "PK".into()); map.insert("palau", "PW".into()); map.insert("palestine", "PS".into()); map.insert("panama", "PA".into()); map.insert("papua new guinea", "PG".into()); map.insert("paraguay", "PY".into()); map.insert("peru", "PE".into()); map.insert("philippines", "PH".into()); map.insert("pitcairn", "PN".into()); map.insert("poland", "PL".into()); map.insert("portugal", "PT".into()); map.insert("puerto rico", "PR".into()); map.insert("qatar", "QA".into()); map.insert("north macedonia", "MK".into()); map.insert("romania", "RO".into()); map.insert("russia", "RU".into()); map.insert("russian federation", "RU".into()); map.insert("rwanda", "RW".into()); map.insert("réunion", "RE".into()); map.insert("reunion", "RE".into()); map.insert("saint barthélemy", "BL".into()); map.insert("saint helena", "SH".into()); map.insert("saint kitts and nevis", "KN".into()); map.insert("saint lucia", "LC".into()); map.insert("saint martin", "MF".into()); map.insert("saint pierre", "PM".into()); map.insert("miquelon", "PM".into()); map.insert("saint vincent", "VC".into()); map.insert("grenadines", "VC".into()); map.insert("samoa", "WS".into()); map.insert("san marino", "SM".into()); map.insert("sao tome and principe", "ST".into()); map.insert("saudi arabia", "SA".into()); map.insert("senegal", "SN".into()); map.insert("serbia", "RS".into()); map.insert("seychelles", "SC".into()); map.insert("sierra leone", "SL".into()); map.insert("singapore", "SG".into()); map.insert("sint maarten", "SX".into()); map.insert("slovakia", "SK".into()); map.insert("slovenia", "SI".into()); map.insert("solomon islands", "SB".into()); map.insert("somalia", "SO".into()); map.insert("south africa", "ZA".into()); map.insert("south georgia", "GS".into()); map.insert("south sandwich islands", "GS".into()); map.insert("south sudan", "SS".into()); map.insert("spain", "ES".into()); map.insert("sri lanka", "LK".into()); map.insert("sudan", "SD".into()); map.insert("suriname", "SR".into()); map.insert("svalbard", "SJ".into()); map.insert("jan mayen", "SJ".into()); map.insert("sweden", "SE".into()); map.insert("switzerland", "CH".into()); map.insert("syrian arab republic", "SY".into()); map.insert("taiwan", "TW".into()); map.insert("tajikistan", "TJ".into()); map.insert("tanzania", "TZ".into()); map.insert("thailand", "TH".into()); map.insert("timor-leste", "TL".into()); map.insert("togo", "TG".into()); map.insert("tokelau", "TK".into()); map.insert("tonga", "TO".into()); map.insert("trinidad and tobago", "TT".into()); map.insert("tunisia", "TN".into()); map.insert("turkey", "TR".into()); map.insert("turkmenistan", "TM".into()); map.insert("turks and caicos islands", "TC".into()); map.insert("tuvalu", "TV".into()); map.insert("uganda", "UG".into()); map.insert("ukraine", "UA".into()); map.insert("united arab emirates", "AE".into()); map.insert("united kingdom", "GB".into()); map.insert("uk", "GB".into()); map.insert("great britain", "GB".into()); map.insert("united states minor outlying islands", "UM".into()); map.insert("united states of america", "US".into()); map.insert("usa", "US".into()); map.insert("united states", "US".into()); map.insert("uruguay", "UY".into()); map.insert("uzbekistan", "UZ".into()); map.insert("vanuatu", "VU".into()); map.insert("venezuela ", "VE".into()); map.insert("viet nam", "VN".into()); map.insert("virgin islands (british)", "VG".into()); map.insert("virgin islands (u.s.)", "VI".into()); map.insert("wallis and futuna", "WF".into()); map.insert("western sahara", "EH".into()); map.insert("yemen", "YE".into()); map.insert("zambia", "ZM".into()); map.insert("zimbabwe", "ZW".into()); map }; } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash)] pub struct CountryCode(rosu_v2::prelude::CountryCode); impl CountryCode { pub fn from_name(name: &str) -> Option<Self> { COUNTRIES .get(name.cow_to_ascii_lowercase().as_ref()) .cloned() .map(Self) } pub fn snipe_supported(&self, ctx: &Context) -> bool { ctx.contains_country(self.0.as_str()) } pub fn timezone(&self) -> FixedOffset { let offset = match TIMEZONES.get(self.0.as_str()) { Some(offset) => *offset, None => { warn!("missing timezone for country code {self}"); 0 } }; FixedOffset::east(offset) } } impl Deref for CountryCode { type Target = SmallString<[u8; 2]>; fn deref(&self) -> &Self::Target { &self.0 } } impl From<rosu_v2::prelude::CountryCode> for CountryCode { fn from(country_code: rosu_v2::prelude::CountryCode) -> Self { Self(country_code) } } impl From<String> for CountryCode { fn from(code: String) -> Self { Self(code.into()) } } impl From<&str> for CountryCode { fn from(code: &str) -> Self { Self(code.into()) } } impl Borrow<str> for CountryCode { fn borrow(&self) -> &str { self.0.as_str() } } impl fmt::Display for CountryCode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }
use graphql_client::{GraphQLQuery, Response as GQLResponse}; mod shared; use seed::{prelude::*, *}; use serde::{Deserialize, Serialize}; // Allows sort_by use itertools::Itertools; use rasciigraph::{plot, Config}; // Global types and Constant values type Id = String; type Name = String; type Author = String; type Points = String; // TODO: Change these urls for production const API_URL: &str = "http://c2.local:8000"; const WS_URL: &str = "ws://c2.local:8000"; // ------ ------ // GraphQL // ------ ------ macro_rules! generate_query { ($query:ident) => { // // graphql_client basics // #[derive(GraphQLQuery)] #[graphql( schema_path = "graphql/schema.graphql", query_path = "graphql/queries.graphql", response_derives = "Debug" )] struct $query; }; } generate_query!(QBooks); generate_query!(MCreateBook); generate_query!(MUpdateBook); generate_query!(MDeleteBook); async fn send_graphql_request<V, T>(variables: &V) -> fetch::Result<T> where V: Serialize, T: for<'de> Deserialize<'de> + 'static, { Request::new(API_URL) .method(Method::Post) .json(variables)? .fetch() .await? .check_status()? .json() .await } // ------ ------ // Init // ------ ------ fn init(_: Url, orders: &mut impl Orders<Msg>) -> Model { // // GraphQL Query fetch data // orders.perform_cmd(async { Msg::BooksFetched(send_graphql_request(&QBooks::build_query(q_books::Variables)).await) }); // // Init Model default values // Model { // books: Option::Some(Vec::new()), messages: Vec::new(), input_text_name: String::new(), input_text_author: String::new(), input_text_points: std::default::Default::default(), web_socket: create_websocket(orders), web_socket_reconnector: None, selected_name: std::default::Default::default(), selected_author: std::default::Default::default(), selected_points: std::default::Default::default(), selected_id: std::default::Default::default(), seconds: 0, // // Generate 10 vec values = 0.0 // graph: vec![0.0; 100], problems: vec![], timer_handle: Some(orders.stream_with_handle(streams::interval(1000, || Msg::OnTick))), } } // // websocket client connect to server // fn create_websocket(orders: &impl Orders<Msg>) -> WebSocket { WebSocket::builder(WS_URL, orders) .on_open(|| Msg::WebSocketOpened) .on_message(Msg::MessageReceived) .on_close(Msg::WebSocketClosed) .on_error(|| Msg::WebSocketFailed) .build_and_open() .unwrap() } // ------ ------ // Model // ------ ------ struct Model { messages: Vec<Message>, input_text_name: String, input_text_author: String, input_text_points: String, selected_name: Option<Name>, selected_author: Option<Author>, selected_points: Option<Points>, selected_id: Option<Id>, web_socket: WebSocket, web_socket_reconnector: Option<StreamHandle>, // books: Option<Vec<q_books::QBooksBooks>>, seconds: i64, graph: Vec<f64>, problems: Vec<Problem>, timer_handle: Option<StreamHandle>, } // Parse GraphQL Subscription Message #[derive(Serialize, Deserialize, Debug)] pub struct Message { id: String, name: String, author: String, points: u8, problems: Vec<Problem>, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Problem { letter: String, } // Message from the server to the client. #[derive(Serialize, Deserialize, Debug)] pub struct ServerMessage { id: String, payload: MessagePayload, r#type: String, } #[derive(Serialize, Deserialize, Debug)] pub struct MessagePayload { data: PayloadData, } #[derive(Serialize, Deserialize, Debug)] pub struct PayloadData { books: DataBook, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct DataBook{ mutation_type: String, id: String, name: String, author: String, points: u8, } // ------ ------ // Update // ------ ------ enum Msg { BooksFetched(fetch::Result<GQLResponse<q_books::ResponseData>>), BookDeleted(fetch::Result<GQLResponse<q_books::ResponseData>>), BookDeletedClick(Id), BookUpdated(fetch::Result<GQLResponse<q_books::ResponseData>>), BookUpdatedClick(Id, Name, Author, Points), BookCreated(fetch::Result<GQLResponse<q_books::ResponseData>>), BookCreatedClick(Name, Author, Points), WebSocketOpened, MessageReceived(WebSocketMessage), WebSocketClosed(CloseEvent), WebSocketFailed, ReconnectWebSocket(usize), InputTextNameChanged(String), InputTextAuthorChanged(String), InputTextPointsChanged(String), OnTick, } fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { match msg { // // Interval // Msg::OnTick => { if model.seconds != 600000 { model.seconds += 1000; if model.graph.len() < 100 { model.graph.push(1.0) } else { // Remove the first duplicate value model.graph.remove(0); model.graph.push(1.0); } } } // // GraphQL functions // Msg::BooksFetched(Ok(GQLResponse { data: Some(data), .. })) => { let vec_books_length = data.books.len(); for book_index in 0..vec_books_length { model.messages.push( Message { id: data.books[book_index].id.to_string(), name: data.books[book_index].name.to_string(), author: data.books[book_index].author.to_string(), points: data.books[book_index].points.to_string().parse().unwrap(), problems: vec![ Problem{ letter:"A".to_string() }, Problem{ letter:"B".to_string() }, ], } ); // if model.problems.iter().any(|i| i.letter != "A") { model.problems.push( Problem{ letter:"A".to_string() }, ); // } } } Msg::BookCreated(Ok(GQLResponse { data: Some(_), .. })) => { log!("Created Book"); } // // Trigger query on click // Msg::BookCreatedClick(name, author, points) => { model.selected_name = Some(name.clone()); model.selected_author = Some(author.clone()); model.selected_points = Some(points.clone()); orders.perform_cmd(async { Msg::BookCreated( send_graphql_request(&MCreateBook::build_query(m_create_book::Variables { name, author, points, })) .await, ) }); } Msg::BookCreated(error) => log!(error), Msg::BookUpdated(Ok(GQLResponse { data: Some(_), .. })) => { log!("Deleted Book"); } Msg::BookUpdatedClick(id, name, author, points) => { model.selected_id = Some(id.clone()); if let Some(index) = model.messages.iter().position(|message| message.id.to_string() == id) { model.messages[index] = Message { id: id.clone(), name: name.clone(), author: author.clone(), points: points.clone().parse().unwrap(), problems: vec![ Problem{ letter:"A".to_string() }, Problem{ letter:"B".to_string() }, ], } } orders.perform_cmd(async { Msg::BookUpdated( send_graphql_request(&MUpdateBook::build_query(m_update_book::Variables { id, name, author, points, })) .await, ) }); } Msg::BookUpdated(error) => log!(error), Msg::BookDeleted(Ok(GQLResponse { data: Some(_), .. })) => { log!("Updated Book"); } Msg::BookDeletedClick(id) => { model.selected_id = Some(id.clone()); if let Some(index) = model.messages.iter().position(|message| message.id.to_string() == id) { model.messages.remove(index); } orders.perform_cmd(async { Msg::BookDeleted( send_graphql_request(&MDeleteBook::build_query(m_delete_book::Variables { id })) .await, ) }); } Msg::BookDeleted(error) => log!(error), Msg::BooksFetched(error) => log!(error), // // Websocket functions // Msg::WebSocketOpened => { model.web_socket_reconnector = None; { model.web_socket .send_json(&shared::ClientMessageGQLInit { r#type: "connection_init".to_string(), payload: shared::PayloadEmp {}, }) .unwrap(); } // // Start GraphQL Subscription Query // { model.web_socket .send_json(&shared::ClientMessageGQLPay { // Set ID of this subscription id: "some_id".to_string(), r#type: "start".to_string(), payload: { shared::Payload { query: "subscription { books { mutationType, id, name, author, points, } }".to_string(), } }, }) .unwrap(); } log!("WebSocket connection is open now"); } Msg::MessageReceived(message) => { log!("Client received a message"); let json_message = message.json::<serde_json::Value>().unwrap(); let book = &json_message["payload"]["data"]["books"]; if json_message["type"] == "connection_ack" { log!("CONNECTED"); } else if json_message["type"] == "data" { log!("MESSAGE",json_message); let mutation_type = book["mutationType"].to_string().replace("\"", ""); let id = book["id"].to_string().replace("\"", ""); let name = book["name"].to_string().replace("\"", ""); let author = book["author"].to_string().replace("\"", ""); let points = book["points"].to_string().replace("\"", "").parse().unwrap(); let problems = vec![ Problem{ letter:"A".to_string() }, Problem{ letter:"B".to_string() }, ]; match mutation_type.as_str() { "CREATED" => { model.messages .push(Message { id, name, author, points, problems }); } "UPDATED" => { if let Some(index) = model.messages.iter().position(|message| message.id.to_string() == id) { model.messages[index] = Message { id: id.clone(), name: name.clone(), author: author.clone(), points: points.clone(), problems: problems.clone(), } } } "DELETED" => { if let Some(index) = model.messages.iter().position(|message| message.id.to_string() == id) { model.messages.remove(index); } } _ => { } } } } Msg::WebSocketClosed(close_event) => { log!("================================"); log!("WebSocket connection was closed:"); log!("Clean:", close_event.was_clean()); log!("Code:", close_event.code()); log!("Reason:", close_event.reason()); log!("================================"); // Chrome doesn't invoke `on_error` when the connection is lost. if !close_event.was_clean() && model.web_socket_reconnector.is_none() { model.web_socket_reconnector = Some( orders.stream_with_handle(streams::backoff(None, Msg::ReconnectWebSocket)), ); } } Msg::WebSocketFailed => { log!("WebSocket failed"); if model.web_socket_reconnector.is_none() { model.web_socket_reconnector = Some(orders.stream_with_handle(streams::backoff(None, Msg::ReconnectWebSocket))) } } Msg::ReconnectWebSocket(retries) => { log!("Reconnect attempt:", retries); model.web_socket = create_websocket(orders); } // // Handles input change state // Msg::InputTextNameChanged(input_text) => { model.input_text_name = input_text; } Msg::InputTextAuthorChanged(input_text) => { model.input_text_author = input_text; } Msg::InputTextPointsChanged(input_text) => { model.input_text_points = input_text; } } } // ------ ------ // View // ------ ------ fn view(model: &Model) -> Node<Msg> { let mut clock = shared::Clock::new(); div![C!["overflow-auto"], style! { St::BackgroundColor => "#282a36", St::Height => vh(100), }, // // HEADER // nav![C!["navbar navbar-expand-lg navbar-dark bg-dark"], a![C!["navbar-brand"], "LOGO", style!{ St::Color => "#50fa7b", } ], button![C!["navbar-toggler"], attrs! { At::Type => "button", }, span![C!["navbar-toggler-icon"]] ], div![C!["collapse navbar-collapse"], ul![C!["navbar-nav mr-auto"], li![C!["nav-item active"], a![C!["nav-link"], "Home"] ] ], form![C!["form-inline my-2 my-lg-0"], button![C!["btn btn-secondary mr-sm-2"], "Sign Up", attrs! { At::Type => "button", }, style! { St::BackgroundColor => "#9580ff" } ], button![C!["btn btn-secondary mr-sm-2"], "Log in", attrs! { At::Type => "button" }, style! { St::BackgroundColor => "#50fa7b" } ], ] ], ], // // Create Book // div![C!["container"], h3![C!["description"], "Create Book", style!{ St::Color => "#50fa7b" }, ], form![ div![C!["form-group"], label!["name"], style![ St::Color => "#9580ff", ], input![C!["form-control"], id!("text_input_name"), attrs! { At::Type => "text", At::Value => model.input_text_name, At::Placeholder => "name", }, input_ev(Ev::Input, Msg::InputTextNameChanged), ], ], div![C!["form-group"], label!["author"], style![ St::Color => "#9580ff", ], input![C!["form-control"], id!("text_input_author"), attrs! { At::Type => "text", At::Value => model.input_text_author, At::Placeholder => "author", }, input_ev(Ev::Input, Msg::InputTextAuthorChanged), ], ], div![C!["form-group"], label!["points"], style![ St::Color => "#9580ff", ], input![C!["form-control"], id!("text_input_points"), attrs! { At::Type => "number", At::Value => model.input_text_points, At::Placeholder => "points", }, input_ev(Ev::Input, Msg::InputTextPointsChanged), ], ], ], div![C!["container"], div![C!["row"], div![C!["col-sm"], // Button Click to trigger CREATE function button![C!["btn"], "Create Book", ev(Ev::Click, { let name = model.input_text_name.to_owned(); let author = model.input_text_author.to_owned(); let points = model.input_text_points.to_owned(); move |_| Msg::BookCreatedClick(name.to_string(), author.to_string(), points.to_string()) }), style! { St::BackgroundColor => "#50fa7b", } ], ], // // # of websocket messages // div![C!["col-sm"], p![format!("messages: {}", model.messages.len()), style![ St::Color => "#FFFFFF", ], ], ], // // Interval update // div![C!["col-sm"], p![C!["progress"], div![C!["progress-bar progress-bar-striped progress-bar-animated"], style![ St::Width => format!("{}%", model.seconds) ], format!("{}%", model.seconds) ] ], ] ], ], div![ // The class required by GitHub styles. See `index.html`. C!["markdown-body"], style![ St::Color => "#9580ff", ], md!( plot( model.graph.clone(), Config::default().with_offset(10).with_height(10) ).as_str() ), ], // // Scoring // div![ table![C!["table table-striped table-bordered table-dark"], // // Table headers // thead![ tr![ th![ C!["text-center"], attrs! { At::Scope => "col", }, "#" ], th![ C!["text-center"], attrs! { At::Scope => "col", }, "ID" ], th![ C!["text-center"], attrs! { At::Scope => "col", }, "Name" ], th![ C!["text-center"], attrs! { At::Scope => "col", }, "Author" ], th![ C!["text-center"], attrs! { At::Scope => "col", }, "Points" ], model.problems.iter().map(| problem | { th![ C!["text-center"], attrs! { At::Scope => "col", }, a![&problem.letter],br![],span!["100"] ] } ), th![ C!["text-center"], attrs! { At::Scope => "col", }, "Actions" ], // th![ C!["text-center"], attrs! { At::Scope => "col", }, a!["A"],br![],span!["100"] ], // th![ C!["text-center"], attrs! { At::Scope => "col", }, a!["B"],br![],span!["200"] ], // th![ C!["text-center"], attrs! { At::Scope => "col", }, a!["C"],br![],span!["300"] ], // th![ C!["text-center"], attrs! { At::Scope => "col", }, a!["D"],br![],span!["400"] ], // th![ C!["text-center"], attrs! { At::Scope => "col", }, a!["E"],br![],span!["500"] ], ] ], tbody![ // // Sort rows in table in decending order by 'points' key/value // Label new position // // GOTCHA 1: using enumerate() after sorted_by well create // sorted index // // GOTCHA 2: enumerate() creates a tuple (index, &thing) // index = 0, &thing = 1 // // Position/Index = some.0 // Key/Value = some.1.key // model.messages.iter().sorted_by(|a, b| Ord::cmp(&b.points, &a.points)).enumerate().map(| message | { clock.set_time_ms(model.seconds); tr![ td![ C!["text-center"], attrs! { At::Scope => "col", }, format!("{}", message.0+1 ) ], td![ C!["text-center"], attrs! { At::Scope => "col", }, format!("{}", message.1.id) ], td![ C!["text-center"], attrs! { At::Scope => "col", }, format!("{}", message.1.name) ], td![ C!["text-center"], attrs! { At::Scope => "col", }, format!("{}", message.1.author) ], td![ C!["text-center"], attrs! { At::Scope => "col", }, format!("{}", message.1.points) ], td![ C!["text-center"], attrs! { At::Scope => "col", }, a![format!("{}", "Score")],br![],span![format!("{}", clock.get_time()) ]], td![ C!["text-center"], attrs! { At::Scope => "col", }, a![format!("{}", "Score")],br![],span![format!("{}", clock.get_time()) ]], td![ C!["text-center"], attrs! { At::Scope => "col", }, a![format!("{}", "Score")],br![],span![format!("{}", clock.get_time()) ]], td![ C!["text-center"], attrs! { At::Scope => "col", }, a![format!("{}", "Score")],br![],span![format!("{}", clock.get_time()) ]], td![ C!["text-center"], attrs! { At::Scope => "col", }, a![format!("{}", "Score")],br![],span![format!("{}", clock.get_time()) ]], td![ C!["text-center"], attrs! { At::Scope => "col", }, button![C!["btn"], format!("Update"), attrs!{ At::Value => &message.1.id }, { let id = message.1.id.clone(); let name = "test".to_string(); let author = "test".to_string(); let points = "100".to_string(); ev(Ev::Click, { move |_| Msg::BookUpdatedClick(id, name, author, points) }) }, style! { St::BackgroundColor => "#50fa7b", } ], button![C!["btn"], format!("Delete"), attrs!{ At::Value => &message.1.id }, { let id = message.1.id.clone(); ev(Ev::Click, { move |_| Msg::BookDeletedClick(id) }) }, style! { St::BackgroundColor => "#50fa7b", } ], ], style![ St::Color => "#FFFFFF", ], ] }, ), ] ], style! { St::MarginTop => px(15), } ], ], ] } // ------ ------ // Start // ------ ------ #[wasm_bindgen(start)] pub fn start() { App::start("app", init, update, view); }
use anyhow::Error; use anyhow::Result; #[derive(PartialEq, Eq, Debug)] pub struct Stack { stack: [u16; 16], stack_ptr: usize, } impl Stack { pub fn new() -> Self { Self { stack: [0; 16], stack_ptr: 0, } } pub fn pop(&mut self) -> Result<u16> { if self.stack_ptr == 0 { Err(Error::msg("The stack has underflowed.")) } else { self.stack_ptr -= 1; Ok(self.stack[self.stack_ptr]) } } pub fn push(&mut self, byte: u16) -> Result<()> { if self.stack_ptr >= 16 { Err(Error::msg("The stack has overflowed.")) } else { self.stack[self.stack_ptr] = byte; self.stack_ptr += 1; Ok(()) } } }
use crate::client::API_VERSION_PARAM; use crate::Error; use crate::KeyClient; use azure_core::TokenCredential; use chrono::serde::{ts_seconds, ts_seconds_option}; use chrono::{DateTime, Utc}; use const_format::formatcp; use getset::Getters; use reqwest::Url; use serde::Deserialize; use serde_json::{Map, Value}; const DEFAULT_MAX_RESULTS: usize = 25; const API_VERSION_MAX_RESULTS_PARAM: &str = formatcp!("{}&maxresults={}", API_VERSION_PARAM, DEFAULT_MAX_RESULTS); #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultSecretBaseIdentifierAttributedRaw { enabled: bool, #[serde(with = "ts_seconds")] created: DateTime<Utc>, #[serde(with = "ts_seconds")] updated: DateTime<Utc>, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultSecretBaseIdentifierRaw { id: String, attributes: KeyVaultSecretBaseIdentifierAttributedRaw, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultGetSecretsResponse { value: Vec<KeyVaultSecretBaseIdentifierRaw>, #[serde(rename = "nextLink")] next_link: Option<String>, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultGetSecretResponse { value: String, id: String, attributes: KeyVaultGetSecretResponseAttributes, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultGetSecretResponseAttributes { enabled: bool, #[serde(default)] #[serde(with = "ts_seconds_option")] exp: Option<DateTime<Utc>>, #[serde(with = "ts_seconds")] created: DateTime<Utc>, #[serde(with = "ts_seconds")] updated: DateTime<Utc>, #[serde(rename = "recoveryLevel")] recovery_level: String, } #[derive(Deserialize, Debug)] pub(crate) struct KeyVaultSecretBackupResponseRaw { value: String, } #[derive(Debug, Getters)] #[getset(get = "pub")] pub struct KeyVaultSecretBackupBlob { value: String, } #[derive(Debug, Getters)] #[getset(get = "pub")] pub struct KeyVaultSecretBaseIdentifier { id: String, name: String, enabled: bool, time_created: DateTime<Utc>, time_updated: DateTime<Utc>, } #[derive(Debug, Getters)] #[getset(get = "pub")] pub struct KeyVaultSecret { id: String, value: String, enabled: bool, expires_on: Option<DateTime<Utc>>, time_created: DateTime<Utc>, time_updated: DateTime<Utc>, } impl<'a, T: TokenCredential> KeyClient<'a, T> { /// Gets a secret from the Key Vault. /// Note that the latest version is fetched. For a specific version, use `get_version_with_version`. /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// let secret = client.get_secret(&"SECRET_NAME").await.unwrap(); /// dbg!(&secret); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn get_secret(&mut self, secret_name: &str) -> Result<KeyVaultSecret, Error> { Ok(self.get_secret_with_version(secret_name, "").await?) } /// Gets a secret from the Key Vault with a specific version. /// If you need the latest version, use `get_secret`. /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// let secret = client.get_secret_with_version(&"SECRET_NAME", &"SECRET_VERSION").await.unwrap(); /// dbg!(&secret); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn get_secret_with_version( &mut self, secret_name: &str, secret_version_name: &str, ) -> Result<KeyVaultSecret, Error> { let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}/{}", secret_name, secret_version_name)); uri.set_query(Some(API_VERSION_PARAM)); let response_body = self.get_authed(uri.to_string()).await?; let response = serde_json::from_str::<KeyVaultGetSecretResponse>(&response_body).map_err(|error| { Error::BackupSecretParseError { error, secret_name: secret_name.to_string(), response_body, } })?; Ok(KeyVaultSecret { expires_on: response.attributes.exp, enabled: response.attributes.enabled, value: response.value, time_created: response.attributes.created, time_updated: response.attributes.updated, id: response.id, }) } /// Lists all the secrets in the Key Vault. /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// let secrets = client.list_secrets().await.unwrap(); /// dbg!(&secrets); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn list_secrets(&mut self) -> Result<Vec<KeyVaultSecretBaseIdentifier>, Error> { let mut secrets = Vec::<KeyVaultSecretBaseIdentifier>::new(); let mut uri = self.vault_url.clone(); uri.set_path("secrets"); uri.set_query(Some(API_VERSION_MAX_RESULTS_PARAM)); loop { let resp_body = self.get_authed(uri.to_string()).await?; let response = serde_json::from_str::<KeyVaultGetSecretsResponse>(&resp_body).unwrap(); secrets.extend( response .value .into_iter() .map(|s| KeyVaultSecretBaseIdentifier { id: s.id.to_owned(), name: s.id.split('/').last().unwrap().to_owned(), enabled: s.attributes.enabled, time_created: s.attributes.created, time_updated: s.attributes.updated, }) .collect::<Vec<KeyVaultSecretBaseIdentifier>>(), ); match response.next_link { None => break, Some(u) => uri = Url::parse(&u).unwrap(), } } Ok(secrets) } /// Gets all the versions for a secret in the Key Vault. // /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// let secret_versions = client.get_secret_versions(&"SECRET_NAME").await.unwrap(); /// dbg!(&secret_versions); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn get_secret_versions( &mut self, secret_name: &str, ) -> Result<Vec<KeyVaultSecretBaseIdentifier>, Error> { let mut secret_versions = Vec::<KeyVaultSecretBaseIdentifier>::new(); let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}/versions", secret_name)); uri.set_query(Some(API_VERSION_MAX_RESULTS_PARAM)); loop { let resp_body = self.get_authed(uri.to_string()).await?; let response = serde_json::from_str::<KeyVaultGetSecretsResponse>(&resp_body).unwrap(); secret_versions.extend( response .value .into_iter() .map(|s| KeyVaultSecretBaseIdentifier { id: s.id.to_owned(), name: s.id.split('/').last().unwrap().to_owned(), enabled: s.attributes.enabled, time_created: s.attributes.created, time_updated: s.attributes.updated, }) .collect::<Vec<KeyVaultSecretBaseIdentifier>>(), ); match response.next_link { None => break, Some(u) => uri = Url::parse(&u).unwrap(), } } // Return the secret versions sorted by the time modified in descending order. secret_versions.sort_by(|a, b| { if a.time_updated > b.time_updated { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater } }); Ok(secret_versions) } /// Sets the value of a secret in the Key Vault. /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.set_secret(&"SECRET_NAME", &"NEW_VALUE").await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn set_secret( &mut self, secret_name: &str, new_secret_value: &str, ) -> Result<(), Error> { let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}", secret_name)); uri.set_query(Some(API_VERSION_PARAM)); let mut request_body = Map::new(); request_body.insert( "value".to_owned(), Value::String(new_secret_value.to_owned()), ); self.put_authed(uri.to_string(), Value::Object(request_body).to_string()) .await?; Ok(()) } /// Updates whether a secret version is enabled or not. /// /// # Arguments /// /// * `secret_name` - Name of the secret /// * `secret_version` - Version of the secret. Use an empty string for the latest version /// * `enabled` - New `enabled` value of the secret /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.update_secret_enabled(&"SECRET_NAME", &"", true).await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn update_secret_enabled( &mut self, secret_name: &str, secret_version: &str, enabled: bool, ) -> Result<(), Error> { let mut attributes = Map::new(); attributes.insert("enabled".to_owned(), Value::Bool(enabled)); self.update_secret(secret_name, secret_version, attributes) .await?; Ok(()) } /// Updates the [`RecoveryLevel`](RecoveryLevel) of a secret version. /// /// # Arguments /// /// * `secret_name` - Name of the secret /// * `secret_version` - Version of the secret. Use an empty string for the latest version /// * `recovery_level` - New `RecoveryLevel`(RecoveryLevel) value of the secret /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.update_secret_recovery_level(&"SECRET_NAME", &"", "Purgeable".into()).await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn update_secret_recovery_level( &mut self, secret_name: &str, secret_version: &str, recovery_level: String, ) -> Result<(), Error> { let mut attributes = Map::new(); attributes.insert("enabled".to_owned(), Value::String(recovery_level)); self.update_secret(secret_name, secret_version, attributes) .await?; Ok(()) } /// Updates the expiration time of a secret version. /// /// # Arguments /// /// * `secret_name` - Name of the secret /// * `secret_version` - Version of the secret. Use an empty string for the latest version /// * `expiration_time - New expiration time of the secret /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// use chrono::{Utc, Duration}; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.update_secret_expiration_time(&"SECRET_NAME", &"", Utc::now() + Duration::days(14)).await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn update_secret_expiration_time( &mut self, secret_name: &str, secret_version: &str, expiration_time: DateTime<Utc>, ) -> Result<(), Error> { let mut attributes = Map::new(); attributes.insert( "exp".to_owned(), Value::Number(serde_json::Number::from(expiration_time.timestamp())), ); self.update_secret(secret_name, secret_version, attributes) .await?; Ok(()) } async fn update_secret( &mut self, secret_name: &str, secret_version: &str, attributes: Map<String, Value>, ) -> Result<(), Error> { let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}/{}", secret_name, secret_version)); uri.set_query(Some(API_VERSION_PARAM)); let mut request_body = Map::new(); request_body.insert("attributes".to_owned(), Value::Object(attributes)); self.patch_authed(uri.to_string(), Value::Object(request_body).to_string()) .await?; Ok(()) } /// Restores a backed up secret and all its versions. /// This operation requires the secrets/restore permission. /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.restore_secret(&"KUF6dXJlS2V5VmF1bHRTZWNyZXRCYWNrdXBWMS5taW").await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn restore_secret(&mut self, backup_blob: &str) -> Result<(), Error> { let mut uri = self.vault_url.clone(); uri.set_path("secrets/restore"); uri.set_query(Some(API_VERSION_PARAM)); let mut request_body = Map::new(); request_body.insert("value".to_owned(), Value::String(backup_blob.to_owned())); self.post_authed( uri.to_string(), Some(Value::Object(request_body).to_string()), ) .await?; Ok(()) } /// Restores a backed up secret and all its versions. /// This operation requires the secrets/restore permission. /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.backup_secret(&"SECRET_NAME").await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn backup_secret( &mut self, secret_name: &str, ) -> Result<KeyVaultSecretBackupBlob, Error> { let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}/backup", secret_name)); uri.set_query(Some(API_VERSION_PARAM)); let response_body = self.post_authed(uri.to_string(), None).await?; let backup_blob = serde_json::from_str::<KeyVaultSecretBackupResponseRaw>(&response_body) .map_err(|error| Error::BackupSecretParseError { error, secret_name: secret_name.to_string(), response_body, })?; Ok(KeyVaultSecretBackupBlob { value: backup_blob.value, }) } /// Deletes a secret in the Key Vault. /// /// # Arguments /// /// * `secret_name` - Name of the secret /// /// # Example /// /// ```no_run /// use azure_security_keyvault::KeyClient; /// use azure_identity::token_credentials::DefaultAzureCredential; /// use tokio::runtime::Runtime; /// /// async fn example() { /// let creds = DefaultAzureCredential::default(); /// let mut client = KeyClient::new( /// &"KEYVAULT_URL", /// &creds, /// ).unwrap(); /// client.delete_secret(&"SECRET_NAME").await.unwrap(); /// } /// /// Runtime::new().unwrap().block_on(example()); /// ``` pub async fn delete_secret(&mut self, secret_name: &str) -> Result<(), Error> { let mut uri = self.vault_url.clone(); uri.set_path(&format!("secrets/{}", secret_name)); uri.set_query(Some(API_VERSION_PARAM)); self.delete_authed(uri.to_string()).await?; Ok(()) } } #[cfg(test)] #[allow(unused_must_use)] mod tests { use super::*; use chrono::{Duration, Utc}; use mockito::{mock, Matcher}; use serde_json::json; use crate::client::API_VERSION; use crate::mock_key_client; use crate::tests::MockCredential; fn diff(first: DateTime<Utc>, second: DateTime<Utc>) -> Duration { if first > second { first - second } else { second - first } } #[tokio::test] async fn get_secret() { let time_created = Utc::now() - Duration::days(7); let time_updated = Utc::now(); let _m = mock("GET", "/secrets/test-secret/") .match_query(Matcher::UrlEncoded("api-version".into(), API_VERSION.into())) .with_header("content-type", "application/json") .with_body( json!({ "value": "secret-value", "id": "https://test-keyvault.vault.azure.net/secrets/test-secret/4387e9f3d6e14c459867679a90fd0f79", "attributes": { "enabled": true, "created": time_created.timestamp(), "updated": time_updated.timestamp(), "recoveryLevel": "Recoverable+Purgeable" } }) .to_string(), ) .with_status(200) .create(); let creds = MockCredential; dbg!(mockito::server_url()); let mut client = mock_key_client!(&"test-keyvault", &creds,); let secret: KeyVaultSecret = client.get_secret("test-secret").await.unwrap(); assert_eq!("secret-value", secret.value()); assert_eq!( "https://test-keyvault.vault.azure.net/secrets/test-secret/4387e9f3d6e14c459867679a90fd0f79", secret.id() ); assert_eq!(true, *secret.enabled()); assert!(diff(time_created, *secret.time_created()) < Duration::seconds(1)); assert!(diff(time_updated, *secret.time_updated()) < Duration::seconds(1)); } #[tokio::test] async fn get_secret_versions() { let time_created_1 = Utc::now() - Duration::days(7); let time_updated_1 = Utc::now(); let time_created_2 = Utc::now() - Duration::days(9); let time_updated_2 = Utc::now() - Duration::days(2); let _m1 = mock("GET", "/secrets/test-secret/versions") .match_query(Matcher::AllOf(vec![ Matcher::UrlEncoded("api-version".into(), API_VERSION.into()), Matcher::UrlEncoded("maxresults".into(), DEFAULT_MAX_RESULTS.to_string()), ])) .with_header("content-type", "application/json") .with_body( json!({ "value": [{ "id": "https://test-keyvault.vault.azure.net/secrets/test-secret/VERSION_1", "attributes": { "enabled": true, "created": time_created_1.timestamp(), "updated": time_updated_1.timestamp(), } }], "nextLink": format!("{}/secrets/text-secret/versions?api-version={}&maxresults=1&$skiptoken=SKIP_TOKEN_MOCK", mockito::server_url(), API_VERSION) }) .to_string(), ) .with_status(200) .create(); let _m2 = mock("GET", "/secrets/text-secret/versions") .match_query(Matcher::AllOf(vec![ Matcher::UrlEncoded("api-version".into(), API_VERSION.into()), Matcher::UrlEncoded("maxresults".into(), "1".into()), Matcher::UrlEncoded("$skiptoken".into(), "SKIP_TOKEN_MOCK".into()), ])) .with_header("content-type", "application/json") .with_body( json!({ "value": [{ "id": "https://test-keyvault.vault.azure.net/secrets/test-secret/VERSION_2", "attributes": { "enabled": true, "created": time_created_2.timestamp(), "updated": time_updated_2.timestamp(), } }], "nextLink": null }) .to_string(), ) .with_status(200) .create(); let creds = MockCredential; let mut client = mock_key_client!(&"test-keyvault", &creds,); let secret_versions = client.get_secret_versions("test-secret").await.unwrap(); let secret_1 = &secret_versions[0]; assert_eq!( "https://test-keyvault.vault.azure.net/secrets/test-secret/VERSION_1", secret_1.id() ); assert!(diff(time_created_1, *secret_1.time_created()) < Duration::seconds(1)); assert!(diff(time_updated_1, *secret_1.time_updated()) < Duration::seconds(1)); let secret_2 = &secret_versions[1]; assert_eq!( "https://test-keyvault.vault.azure.net/secrets/test-secret/VERSION_2", secret_2.id() ); assert!(diff(time_created_2, *secret_2.time_created()) < Duration::seconds(1)); assert!(diff(time_updated_2, *secret_2.time_updated()) < Duration::seconds(1)); } }
// https://video-api.wsj.com/api-video/find_all_videos.asp #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename_all = "camelCase")] pub struct WSJRoot { pub items: Vec<WSJVideos>, } impl crate::HasRecs for WSJRoot { fn to_recs(&self) -> Vec<Vec<String>> { self.items.iter().map(|x| x.to_rec()).collect() } } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename_all = "camelCase")] pub struct WSJVideos { pub id: String, pub unix_creation_date: i64, pub name: String, pub description: String, pub duration: String, #[serde(rename = "thumbnailURL")] pub thumbnail_url: Option<String>, #[serde(rename = "videoURL")] pub video_url: Option<String>, #[serde(rename = "emailURL")] pub email_url: Option<String>, #[serde(rename = "doctypeID")] pub doctype_id: Option<String>, pub column: Option<String>, } impl WSJVideos { pub fn to_rec(&self) -> Vec<String> { return vec![ self.id.to_string(), self.unix_creation_date.to_string(), self.name.to_string(), self.description.to_string(), self.duration.to_string(), self.column.clone().unwrap_or("".to_string()), self.doctype_id.clone().unwrap_or("".to_string()), self.email_url.clone().unwrap_or("".to_string()), self.thumbnail_url.clone().unwrap_or("".to_string()), ]; } }
#[doc = "Register `DOUTR12` reader"] pub type R = crate::R<DOUTR12_SPEC>; #[doc = "Register `DOUTR12` writer"] pub type W = crate::W<DOUTR12_SPEC>; #[doc = "Field `DOUT12` reader - Output data sent to MDIO Master during read frames"] pub type DOUT12_R = crate::FieldReader<u16>; #[doc = "Field `DOUT12` writer - Output data sent to MDIO Master during read frames"] pub type DOUT12_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; impl R { #[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"] #[inline(always)] pub fn dout12(&self) -> DOUT12_R { DOUT12_R::new((self.bits & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"] #[inline(always)] #[must_use] pub fn dout12(&mut self) -> DOUT12_W<DOUTR12_SPEC, 0> { DOUT12_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 = "MDIOS output data register 12\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`doutr12::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 [`doutr12::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DOUTR12_SPEC; impl crate::RegisterSpec for DOUTR12_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`doutr12::R`](R) reader structure"] impl crate::Readable for DOUTR12_SPEC {} #[doc = "`write(|w| ..)` method takes [`doutr12::W`](W) writer structure"] impl crate::Writable for DOUTR12_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DOUTR12 to value 0"] impl crate::Resettable for DOUTR12_SPEC { const RESET_VALUE: Self::Ux = 0; }
// // Parser // #[macro_use] extern crate nom; pub mod parser; // // Main // extern crate flate2; use std::fs::File; use std::io::prelude::*; use std::path::Path; use std::error::Error; use std::fs::DirBuilder; use std::fs::OpenOptions; use flate2::read::ZlibDecoder; const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION"); fn main() { // Obtain program arguments let mut args = std::env::args_os(); // Check if we have none if args.len() <= 1 { println!(" PFSExtractor v{} - extracts contents of Dell firmware update files in PFS format Usage: pfsextractor pfs_file.bin", VERSION.unwrap_or("1.0.2")); std::process::exit(1); } // The only expected argument is a path to input file let arg = args.nth(1).expect("Failed to obtain file path"); let path = Path::new(&arg); println!("Obtained file path: {:?}", path); // Open input file let mut file = match File::open(&path) { Err(e) => {println!("Can't open {:?}: {}", path, e.description()); std::process::exit(2);} Ok(f) => f }; // Read the whole file as binary data let mut data = Vec::new(); match file.read_to_end(&mut data) { Err(e) => {println!("Can't read {:?}: {}", path, e.description()); std::process::exit(3);} Ok(_) => {println!("Bytes read: 0x{:X}", &data.len());} } // Create directory for extracted components let mut new_arg = arg.clone(); new_arg.push(".extracted"); let dir = Path::new(&new_arg); match DirBuilder::new().create(&dir) { Err(e) => {println!("Can't create {:?}: {}", dir, e.description()); std::process::exit(4);} Ok(_) => {println!("Directory created: {:?}", &dir);} } // Set that created directory as current match std::env::set_current_dir(&dir) { Err(e) => {println!("Can't change current directory: {}", e.description()); std::process::exit(5);} Ok(_) => {println!("Current directory changed")} } // Call extraction function pfs_extract(&data, ""); } fn write_file(data: &[u8], filename: &str) -> () { let mut file = OpenOptions::new().write(true) .create_new(true) .open(filename) .expect(&format!("Can't create file {:?}", filename)); file.write(data).expect("Can't write data into file"); } fn pfs_extract(data: &[u8], prefix: &str) -> () { match parser::pfs_file(data) { Ok((unp, mut file)) => { if unp.len() > 0 { println!("Unparsed size: {:X}", unp.len()); } // Parse information section to obtain proper section names { // Information section is the last one let (info_section, other_sections) = (&mut file.sections).split_last_mut().unwrap(); if info_section.data_size != 0 { match parser::pfs_info(info_section.data.unwrap()) { Ok((unp, info)) => { if unp.len() > 0 { println!("Unparsed size: {:X}", unp.len()); } // Set section names info_section.name = String::from("Section Info"); let mut i = 0; for section in info { if i < other_sections.len() { other_sections[i].name = section.name; i += 1; } else { break; } } if i == other_sections.len() - 1 { other_sections[i].name = String::from("Model Properties"); } } _ => { println!("PFS info section parse error, falling back to generic names"); } } } } let mut i = 0; for section in file.sections { println!(""); i += 1; // Print infomation println!("GUID: {:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}", section.guid.data1, section.guid.data2, section.guid.data3, section.guid.data4[0], section.guid.data4[1], section.guid.data4[2], section.guid.data4[3], section.guid.data4[4], section.guid.data4[5], section.guid.data4[6], section.guid.data4[7]); println!("Header version: {:X}", section.header_version); println!("Data size: {:X}", section.data_size); println!("Data signature size: {:X}", section.data_sig_size); println!("Metadata size: {:X}", section.meta_size); println!("Metadata signature size: {:X}", section.meta_sig_size); // Print version let mut version = String::new(); for j in 0..section.version_type.len() { match section.version_type[j] { 0x41 => version.push_str(&format!("{:X}.", section.version[j])), 0x4E => version.push_str(&format!("{}.", section.version[j])), 0x20 | 0x00 => break, t => { println!("Unknown version type found: {:X}", t); version.clear(); break; } } } if version.len() > 0 { println!("Version: {}", version); } else { version.push_str("0."); } // Save components into files if section.data_size == 0 { continue; } let section_data = section.data.unwrap(); let section_name = if section.name.is_empty() { format!("section_{}", i) } else { format!("{}_{}", i, str::replace(&section.name, " ", "_")) }; write_file(section_data, &format!("{}{}_{}data", prefix, section_name, version)); if section.data_sig_size > 0 { write_file(section.data_sig.unwrap(), &format!("{}{}_{}data.sig", prefix, section_name, version)); } if section.meta_size > 0 { write_file(section.meta.unwrap(), &format!("{}{}_{}meta", prefix, section_name, version)); } if section.meta_sig_size > 0 { write_file(section.meta_sig.unwrap(), &format!("{}{}_{}meta.sig", prefix, section_name, version)); } // Check data to determine if and how it can be parsed further // Try parsing as PFS compressed section match parser::pfs_compressed_section(section_data) { Ok((rest, comp)) => { // This is a PFS compressed section println!("PFS section type: zlib-compressed"); if rest.len() > 0 { println!("Unparsed size: {:X}", rest.len()); } // Decompress section data from Zlib-compressed data let mut zlib_decoder = ZlibDecoder::new(comp.data); let mut decompressed = Vec::new(); zlib_decoder.read_to_end(&mut decompressed).expect("Zlib decompression failed"); // Write decompressed data to a file write_file(&decompressed, &format!("{}{}_{}decompressed", prefix, section_name, version)); // Extract decompressed data as PFS file pfs_extract(&decompressed, &format!("{}{}_{}_", prefix, section_name, version)); // Continue iteration over sections continue; } _ => () } // Try parsing as PFS subsection match parser::pfs_file(section_data) { Ok((rest, sub)) => { // This is a PFS subsection println!("PFS section type: subsection"); if rest.len() > 0 { println!("Unparsed size: {:X}", rest.len()); } // Obtain chunks let mut chunks = Vec::new(); for chunk in sub.sections { if section.data_size == 0 { continue; } match parser::pfs_chunk(chunk.data.unwrap()) { Ok((_, ch)) => { chunks.push(ch); } _ => { chunks.clear(); break; } } } // Construct and write payload if chunks.len() > 0 { // Sort the obtained chunks chunks.sort(); // Combine sorted chunks into vector let mut payload = Vec::new(); chunks.iter().for_each(|&x| payload.extend_from_slice(x.data)); // Write payload to file write_file(&payload, &format!("{}{}_{}data.payload", prefix, section_name, version)); } // Continue iteration over sections continue; } _ => () } } } _ => { println!("PFS file parse error, this file can't be parsed"); } } }
use std::time::Duration; use crate::pbteddy; use crate::service::rpc; use etcd_rs::KeyRange; use futures::StreamExt; use prost::Message; use redis::Value as RV; use redis::{aio::MultiplexedConnection, AsyncCommands}; pub struct Client { nc: nats::Connection, rpc: rpc::Client, redis: redis::Client, } impl Client { pub fn new(nc: nats::Connection, rpc: rpc::Client, redis: redis::Client) -> Self { Client { nc, rpc, redis } } pub async fn start(&self) { let sub = self.nc.subscribe("messages").unwrap(); let rpc = self.rpc.clone(); let redis = self.redis.clone(); tokio::spawn(async move { loop { match sub.next() { Some(msg) => { let mut con = redis.get_async_connection().await.unwrap(); let msg = pbteddy::Message::decode(msg.data.as_ref()).unwrap(); match con .hget::<&str, i64, RV>("online", msg.header.as_ref().unwrap().id) .await { Ok(v) => match v { RV::Bulk(value) => { if let Some(mut client) = rpc.teddys.get_mut("key") { if let Some(status) = client .send_message(pbteddy::SendMessageReq { message: Some(msg), }) .await .err() { println!("{:?}", status); } }; } _ => {} }, Err(_) => {} } } None => { break; } } } }); } }
use std::fs::File; use std::io; use std::io::{BufRead, BufReader}; fn read_input() -> Result<Vec<String>, io::Error> { let filename = "input"; let file = File::open(filename)?; let reader = BufReader::new(file); let input: Vec<String> = reader.lines().collect::<Result<_, _>>().unwrap(); Ok(input) } fn toboggan(forest: &Vec<String>, vx: usize, vy: usize) -> u64 { let mut x = 0; let mut y = 0; let mut tree_count = 0; while y < forest.len() { if forest[y].chars().nth(x).unwrap() == '#' { tree_count += 1; } x = (x + vx) % forest[0].len(); y += vy; } return tree_count } fn part1() -> u64{ let input = read_input(); if let Err(e) = &input { eprintln!("Error occured: {}", e); std::process::exit(1); } let forest = input.unwrap(); let tree_count = toboggan(&forest, 3, 1); return tree_count; } fn part2() ->u64{ let input = read_input(); if let Err(e) = &input { eprintln!("Error occured: {}", e); std::process::exit(1); } let forest = input.unwrap(); let tree_results: Vec<u64> = vec![ toboggan(&forest, 1, 1), toboggan(&forest, 3, 1), toboggan(&forest, 5, 1), toboggan(&forest, 7, 1), toboggan(&forest, 1, 2), ]; let tree_count: u64 = tree_results.iter().fold(1, |acc, x| acc * x); return tree_count; } fn main() { let part1_result = part1(); println!("The first answer is: {}", part1_result); let part2_result = part2(); println!("The second answer is: {}", part2_result); }
use dynamixel_driver::DynamixelDriver; use looprate::{ Rate, RateTimer }; use std::time::Instant; use clap::Clap; #[derive(Clap)] #[clap()] struct Args { #[clap( about = "Serial port to use" )] port: String, } fn main() -> Result<(), Box<dyn std::error::Error>> { let args: Args = Args::parse(); let start = Instant::now(); let mut rate = Rate::from_frequency(200.0); let mut loop_rate_counter = RateTimer::new(); let mut driver = DynamixelDriver::new(&args.port).unwrap(); loop { rate.wait(); driver.write_position_degrees(2, (start.elapsed().as_secs_f32()).sin() * 90.0 + 150.0)?; loop_rate_counter.tick(); } }
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use crate::{power, u64_key, BytesKey, OptionalEpoch, HAMT_BIT_WIDTH}; use address::Address; use cid::Cid; use clock::ChainEpoch; use encoding::{BytesDe, BytesSer}; use ipld_amt::{Amt, Error as AmtError}; use ipld_blockstore::BlockStore; use ipld_hamt::{Error as HamtError, Hamt}; use num_bigint::bigint_ser::{BigIntDe, BigIntSer}; use num_bigint::biguint_ser::{BigUintDe, BigUintSer}; use num_bigint::BigInt; use rleplus::bitvec::prelude::{BitVec, Lsb0}; use rleplus::{BitVecDe, BitVecSer}; use runtime::Runtime; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use vm::{DealID, RegisteredProof, SectorInfo, SectorNumber, SectorSize, TokenAmount}; /// Miner actor state pub struct State { /// Map, HAMT<SectorNumber, SectorPreCommitOnChainInfo> pub pre_committed_sectors: Cid, /// Sectors this miner has committed /// Array, AMT<SectorOnChainInfo> pub sectors: Cid, /// BitField of faults pub fault_set: BitVec<Lsb0, u8>, /// Sectors in proving set /// Array, AMT<SectorOnChainInfo> pub proving_set: Cid, /// Contains static info about this miner // TODO revisit as will likely change to Cid in future pub info: MinerInfo, /// The height at which this miner was slashed at. /// Array, AMT<SectorOnChainInfo> pub post_state: PoStState, } impl State { pub fn new( empty_arr: Cid, empty_map: Cid, owner: Address, worker: Address, peer_id: Vec<u8>, sector_size: SectorSize, ) -> Self { Self { pre_committed_sectors: empty_map, sectors: empty_arr.clone(), fault_set: BitVec::default(), proving_set: empty_arr, info: MinerInfo { owner, worker, pending_worker_key: None, peer_id, sector_size, }, post_state: PoStState { proving_period_start: OptionalEpoch(None), num_consecutive_failures: 0, }, } } pub fn sector_count<BS: BlockStore>(&self, store: &BS) -> Result<u64, AmtError> { let arr = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; Ok(arr.count()) } pub fn get_max_allowed_faults<BS: BlockStore>(&self, store: &BS) -> Result<u64, AmtError> { let sector_count = self.sector_count(store)?; Ok(2 * sector_count) } pub fn put_precommitted_sector<BS: BlockStore>( &mut self, store: &BS, info: SectorPreCommitOnChainInfo, ) -> Result<(), HamtError> { let mut precommitted = Hamt::load_with_bit_width(&self.pre_committed_sectors, store, HAMT_BIT_WIDTH)?; precommitted.set(u64_key(info.info.sector_number), info)?; self.pre_committed_sectors = precommitted.flush()?; Ok(()) } pub fn get_precommitted_sector<BS: BlockStore>( &self, store: &BS, sector_num: SectorNumber, ) -> Result<Option<SectorPreCommitOnChainInfo>, HamtError> { let precommitted = Hamt::<BytesKey, _>::load_with_bit_width( &self.pre_committed_sectors, store, HAMT_BIT_WIDTH, )?; precommitted.get(&u64_key(sector_num)) } pub fn delete_precommitted_sector<BS: BlockStore>( &mut self, store: &BS, sector_num: SectorNumber, ) -> Result<(), HamtError> { let mut precommitted = Hamt::<BytesKey, _>::load_with_bit_width( &self.pre_committed_sectors, store, HAMT_BIT_WIDTH, )?; precommitted.delete(&u64_key(sector_num))?; self.pre_committed_sectors = precommitted.flush()?; Ok(()) } pub fn has_sector_number<BS: BlockStore>( &self, store: &BS, sector_num: SectorNumber, ) -> Result<bool, AmtError> { let sectors = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; match sectors.get(sector_num)? { Some(_) => Ok(true), None => Ok(false), } } pub fn put_sector<BS: BlockStore>( &mut self, store: &BS, sector: SectorOnChainInfo, ) -> Result<(), AmtError> { let mut sectors = Amt::load(&self.sectors, store)?; sectors.set(sector.info.sector_number, sector)?; self.sectors = sectors.flush()?; Ok(()) } pub fn get_sector<BS: BlockStore>( &self, store: &BS, sector_num: SectorNumber, ) -> Result<Option<SectorOnChainInfo>, AmtError> { let sectors = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; sectors.get(sector_num) } pub fn delete_sector<BS: BlockStore>( &mut self, store: &BS, sector_num: SectorNumber, ) -> Result<(), AmtError> { let mut sectors = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; sectors.delete(sector_num)?; self.sectors = sectors.flush()?; Ok(()) } pub fn for_each_sector<BS: BlockStore, F>(&self, store: &BS, mut f: F) -> Result<(), String> where F: FnMut(&SectorOnChainInfo) -> Result<(), String>, { let sectors = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; sectors.for_each(|_, v| f(&v)) } pub fn get_storage_weight_desc_for_sector<BS: BlockStore>( &self, store: &BS, sector_num: SectorNumber, ) -> Result<power::SectorStorageWeightDesc, String> { let sector_info = self .get_sector(store, sector_num)? .ok_or(format!("no such sector {}", sector_num))?; Ok(as_storage_weight_desc(self.info.sector_size, sector_info)) } pub fn in_challenge_window<BS, RT>(&self, epoch: ChainEpoch) -> bool where BS: BlockStore, RT: Runtime<BS>, { // TODO revisit TODO in spec impl match *self.post_state.proving_period_start { Some(e) => epoch > e, None => true, } } pub fn compute_proving_set<BS: BlockStore>( &self, store: &BS, ) -> Result<Vec<SectorInfo>, String> { let proving_set = Amt::<SectorOnChainInfo, _>::load(&self.sectors, store)?; let max_allowed_faults = self.get_max_allowed_faults(store)?; if self.fault_set.count_ones() > max_allowed_faults as usize { return Err("Bitfield larger than maximum allowed".to_owned()); } let mut sector_infos: Vec<SectorInfo> = Vec::new(); proving_set.for_each(|i, v: &SectorOnChainInfo| { if *v.declared_fault_epoch != None || *v.declared_fault_duration != None { return Err("sector fault epoch or duration invalid".to_owned()); } let fault = match self.fault_set.get(i as usize) { Some(true) => true, _ => false, }; if !fault { sector_infos.push(SectorInfo { sealed_cid: v.info.sealed_cid.clone(), sector_number: v.info.sector_number, proof: v.info.registered_proof, }); } Ok(()) })?; Ok(sector_infos) } } impl Serialize for State { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.pre_committed_sectors, &self.sectors, BitVecSer(&self.fault_set), &self.proving_set, &self.info, &self.post_state, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for State { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (pre_committed_sectors, sectors, BitVecDe(fault_set), proving_set, info, post_state) = Deserialize::deserialize(deserializer)?; Ok(Self { pre_committed_sectors, sectors, fault_set, proving_set, info, post_state, }) } } /// Static information about miner #[derive(Debug, PartialEq)] pub struct MinerInfo { /// Account that owns this miner /// - Income and returned collateral are paid to this address /// - This address is also allowed to change the worker address for the miner pub owner: Address, /// Worker account for this miner /// This will be the key that is used to sign blocks created by this miner, and /// sign messages sent on behalf of this miner to commit sectors, submit PoSts, and /// other day to day miner activities pub worker: Address, /// Optional worker key to update at an epoch pub pending_worker_key: Option<WorkerKeyChange>, /// Libp2p identity that should be used when connecting to this miner pub peer_id: Vec<u8>, /// Amount of space in each sector committed to the network by this miner pub sector_size: SectorSize, } impl Serialize for MinerInfo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.owner, &self.worker, &self.pending_worker_key, BytesSer(&self.peer_id), &self.sector_size, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for MinerInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (owner, worker, pending_worker_key, BytesDe(peer_id), sector_size) = Deserialize::deserialize(deserializer)?; Ok(Self { owner, worker, pending_worker_key, peer_id, sector_size, }) } } pub struct PoStState { /// Epoch that starts the current proving period pub proving_period_start: OptionalEpoch, /// Number of surprised post challenges that have been failed since last successful PoSt. /// Indicates that the claimed storage power may not actually be proven. Recovery can proceed by /// submitting a correct response to a subsequent PoSt challenge, up until /// the limit of number of consecutive failures. pub num_consecutive_failures: i64, } impl PoStState { pub fn has_failed_post(&self) -> bool { self.num_consecutive_failures > 0 } pub fn is_ok(&self) -> bool { !self.has_failed_post() } } impl Serialize for PoStState { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { (&self.proving_period_start, &self.num_consecutive_failures).serialize(serializer) } } impl<'de> Deserialize<'de> for PoStState { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (proving_period_start, num_consecutive_failures) = Deserialize::deserialize(deserializer)?; Ok(Self { proving_period_start, num_consecutive_failures, }) } } #[derive(Debug, PartialEq)] pub struct WorkerKeyChange { /// Must be an ID address pub new_worker: Address, pub effective_at: ChainEpoch, } impl Serialize for WorkerKeyChange { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { (&self.new_worker, &self.effective_at).serialize(serializer) } } impl<'de> Deserialize<'de> for WorkerKeyChange { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (new_worker, effective_at) = Deserialize::deserialize(deserializer)?; Ok(Self { new_worker, effective_at, }) } } #[derive(Debug, PartialEq, Clone)] pub struct SectorPreCommitInfo { pub registered_proof: RegisteredProof, pub sector_number: SectorNumber, pub sealed_cid: Cid, pub seal_rand_epoch: ChainEpoch, pub deal_ids: Vec<DealID>, pub expiration: ChainEpoch, } impl Serialize for SectorPreCommitInfo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.registered_proof, &self.sector_number, &self.sealed_cid, &self.seal_rand_epoch, &self.deal_ids, &self.expiration, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for SectorPreCommitInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (registered_proof, sector_number, sealed_cid, seal_rand_epoch, deal_ids, expiration) = Deserialize::deserialize(deserializer)?; Ok(Self { registered_proof, sector_number, sealed_cid, seal_rand_epoch, deal_ids, expiration, }) } } #[derive(Debug, PartialEq, Clone)] pub struct SectorPreCommitOnChainInfo { pub info: SectorPreCommitInfo, pub pre_commit_deposit: TokenAmount, pub pre_commit_epoch: ChainEpoch, } impl Serialize for SectorPreCommitOnChainInfo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.info, BigUintSer(&self.pre_commit_deposit), &self.pre_commit_epoch, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for SectorPreCommitOnChainInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let (info, BigUintDe(pre_commit_deposit), pre_commit_epoch) = Deserialize::deserialize(deserializer)?; Ok(Self { info, pre_commit_deposit, pre_commit_epoch, }) } } #[derive(Debug, PartialEq, Clone)] pub struct SectorOnChainInfo { pub info: SectorPreCommitInfo, /// Epoch at which SectorProveCommit is accepted pub activation_epoch: ChainEpoch, /// Integral of active deals over sector lifetime, 0 if CommittedCapacity sector pub deal_weight: BigInt, /// Fixed pledge collateral requirement determined at activation pub pledge_requirement: TokenAmount, /// Can be undefined pub declared_fault_epoch: OptionalEpoch, pub declared_fault_duration: OptionalEpoch, } impl Serialize for SectorOnChainInfo { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { ( &self.info, &self.activation_epoch, BigIntSer(&self.deal_weight), BigUintSer(&self.pledge_requirement), &self.declared_fault_epoch, &self.declared_fault_duration, ) .serialize(serializer) } } impl<'de> Deserialize<'de> for SectorOnChainInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let ( info, activation_epoch, BigIntDe(deal_weight), BigUintDe(pledge_requirement), declared_fault_epoch, declared_fault_duration, ) = Deserialize::deserialize(deserializer)?; Ok(Self { info, activation_epoch, deal_weight, pledge_requirement, declared_fault_epoch, declared_fault_duration, }) } } fn as_storage_weight_desc( sector_size: SectorSize, sector_info: SectorOnChainInfo, ) -> power::SectorStorageWeightDesc { power::SectorStorageWeightDesc { sector_size, deal_weight: sector_info.deal_weight, duration: sector_info.info.expiration - sector_info.activation_epoch, } } #[cfg(test)] mod tests { use super::*; use encoding::{from_slice, to_vec}; use libp2p::PeerId; #[test] fn miner_info_serialize() { let info = MinerInfo { owner: Address::new_id(2), worker: Address::new_id(3), pending_worker_key: None, peer_id: PeerId::random().into_bytes(), sector_size: SectorSize::_2KiB, }; let bz = to_vec(&info).unwrap(); assert_eq!(from_slice::<MinerInfo>(&bz).unwrap(), info); } }
fn main() { // セミコロンが文の区切りになる let a = 10 ; let b = 20 ; println!("a is {}, b is {}", a, b ); // これも3つの文 let a = 10 ; let b = 20 ; println!("a is {}, b is {}", a, b ); // 文の中に改行が入っても良い let a = 10 ; let b = 20 ; println!("a is {}, b is {}", a, b ); // 式は値を返す let a = 10 + 20 ; println!("a is {}", a ); // ブロックの場合も、値を返すので式にできる let a = { 10 + 20 } ; println!("a is {}", a ); // ブロック内にセミコロンを入れると文になるので、コンパイルエラー // a は値を持たない let a = { 10 + 20 ; } ; println!("a is {:?}", a ); // 関数は式になる let a = add( 10, 20 ) ; println!("a is {}", a ); // if 文は bool 値を持つ式を条件に付けられる let a = 10 ; if a > 0 { println!("a is {}", a ); } // 関数もbool値を返せば if文に渡せる if plus( a ) { println!("plus(a) is {}", a ); } } fn add( x: i32, y: i32 ) -> i32 { x + y } fn plus( x: i32 ) -> bool { x > 0 }
use super::*; pick! { if #[cfg(target_feature="avx2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct i16x16 { avx2: m256i } } else if #[cfg(target_feature="sse2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct i16x16 { pub(crate) sse0: m128i, pub(crate) sse1: m128i } } else if #[cfg(target_feature="simd128")] { use core::arch::wasm32::*; #[derive(Clone, Copy)] #[repr(C, align(32))] pub struct i16x16 { simd0: v128, simd1: v128 } impl Default for i16x16 { fn default() -> Self { Self::splat(0) } } impl PartialEq for i16x16 { fn eq(&self, other: &Self) -> bool { !v128_any_true(v128_or(v128_xor(self.simd0, other.simd0), v128_xor(self.simd1, other.simd1))) } } impl Eq for i16x16 { } } else { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct i16x16 { arr: [i16;16] } } } int_uint_consts!(i16, 16, i16x16, i16x16, i16a16, const_i16_as_i16x16, 256); unsafe impl Zeroable for i16x16 {} unsafe impl Pod for i16x16 {} impl Add for i16x16 { type Output = Self; #[inline] #[must_use] fn add(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: add_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: add_i16_m128i(self.sse0, rhs.sse0), sse1: add_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_add(self.simd0, rhs.simd0), simd1: i16x8_add(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].wrapping_add(rhs.arr[0]), self.arr[1].wrapping_add(rhs.arr[1]), self.arr[2].wrapping_add(rhs.arr[2]), self.arr[3].wrapping_add(rhs.arr[3]), self.arr[4].wrapping_add(rhs.arr[4]), self.arr[5].wrapping_add(rhs.arr[5]), self.arr[6].wrapping_add(rhs.arr[6]), self.arr[7].wrapping_add(rhs.arr[7]), self.arr[8].wrapping_add(rhs.arr[8]), self.arr[9].wrapping_add(rhs.arr[9]), self.arr[10].wrapping_add(rhs.arr[10]), self.arr[11].wrapping_add(rhs.arr[11]), self.arr[12].wrapping_add(rhs.arr[12]), self.arr[13].wrapping_add(rhs.arr[13]), self.arr[14].wrapping_add(rhs.arr[14]), self.arr[15].wrapping_add(rhs.arr[15]), ]} } } } } impl Sub for i16x16 { type Output = Self; #[inline] #[must_use] fn sub(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: sub_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: sub_i16_m128i(self.sse0, rhs.sse0), sse1: sub_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_sub(self.simd0, rhs.simd0), simd1: i16x8_sub(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].wrapping_sub(rhs.arr[0]), self.arr[1].wrapping_sub(rhs.arr[1]), self.arr[2].wrapping_sub(rhs.arr[2]), self.arr[3].wrapping_sub(rhs.arr[3]), self.arr[4].wrapping_sub(rhs.arr[4]), self.arr[5].wrapping_sub(rhs.arr[5]), self.arr[6].wrapping_sub(rhs.arr[6]), self.arr[7].wrapping_sub(rhs.arr[7]), self.arr[8].wrapping_sub(rhs.arr[8]), self.arr[9].wrapping_sub(rhs.arr[9]), self.arr[10].wrapping_sub(rhs.arr[10]), self.arr[11].wrapping_sub(rhs.arr[11]), self.arr[12].wrapping_sub(rhs.arr[12]), self.arr[13].wrapping_sub(rhs.arr[13]), self.arr[14].wrapping_sub(rhs.arr[14]), self.arr[15].wrapping_sub(rhs.arr[15]), ]} } } } } impl Mul for i16x16 { type Output = Self; #[inline] #[must_use] fn mul(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: mul_i16_keep_low_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: mul_i16_keep_low_m128i(self.sse0, rhs.sse0), sse1: mul_i16_keep_low_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_mul(self.simd0, rhs.simd0), simd1: i16x8_mul(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].wrapping_mul(rhs.arr[0]), self.arr[1].wrapping_mul(rhs.arr[1]), self.arr[2].wrapping_mul(rhs.arr[2]), self.arr[3].wrapping_mul(rhs.arr[3]), self.arr[4].wrapping_mul(rhs.arr[4]), self.arr[5].wrapping_mul(rhs.arr[5]), self.arr[6].wrapping_mul(rhs.arr[6]), self.arr[7].wrapping_mul(rhs.arr[7]), self.arr[8].wrapping_mul(rhs.arr[8]), self.arr[9].wrapping_mul(rhs.arr[9]), self.arr[10].wrapping_mul(rhs.arr[10]), self.arr[11].wrapping_mul(rhs.arr[11]), self.arr[12].wrapping_mul(rhs.arr[12]), self.arr[13].wrapping_mul(rhs.arr[13]), self.arr[14].wrapping_mul(rhs.arr[14]), self.arr[15].wrapping_mul(rhs.arr[15]), ]} } } } } impl Add<i16> for i16x16 { type Output = Self; #[inline] #[must_use] fn add(self, rhs: i16) -> Self::Output { self.add(Self::splat(rhs)) } } impl Sub<i16> for i16x16 { type Output = Self; #[inline] #[must_use] fn sub(self, rhs: i16) -> Self::Output { self.sub(Self::splat(rhs)) } } impl Mul<i16> for i16x16 { type Output = Self; #[inline] #[must_use] fn mul(self, rhs: i16) -> Self::Output { self.mul(Self::splat(rhs)) } } impl Add<i16x16> for i16 { type Output = i16x16; #[inline] #[must_use] fn add(self, rhs: i16x16) -> Self::Output { i16x16::splat(self).add(rhs) } } impl Sub<i16x16> for i16 { type Output = i16x16; #[inline] #[must_use] fn sub(self, rhs: i16x16) -> Self::Output { i16x16::splat(self).sub(rhs) } } impl Mul<i16x16> for i16 { type Output = i16x16; #[inline] #[must_use] fn mul(self, rhs: i16x16) -> Self::Output { i16x16::splat(self).mul(rhs) } } impl BitAnd for i16x16 { type Output = Self; #[inline] #[must_use] fn bitand(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitand_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: bitand_m128i(self.sse0, rhs.sse0), sse1: bitand_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: v128_and(self.simd0, rhs.simd0), simd1: v128_and(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].bitand(rhs.arr[0]), self.arr[1].bitand(rhs.arr[1]), self.arr[2].bitand(rhs.arr[2]), self.arr[3].bitand(rhs.arr[3]), self.arr[4].bitand(rhs.arr[4]), self.arr[5].bitand(rhs.arr[5]), self.arr[6].bitand(rhs.arr[6]), self.arr[7].bitand(rhs.arr[7]), self.arr[8].bitand(rhs.arr[8]), self.arr[9].bitand(rhs.arr[9]), self.arr[10].bitand(rhs.arr[10]), self.arr[11].bitand(rhs.arr[11]), self.arr[12].bitand(rhs.arr[12]), self.arr[13].bitand(rhs.arr[13]), self.arr[14].bitand(rhs.arr[14]), self.arr[15].bitand(rhs.arr[15]), ]} } } } } impl BitOr for i16x16 { type Output = Self; #[inline] #[must_use] fn bitor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: bitor_m128i(self.sse0, rhs.sse0), sse1: bitor_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: v128_or(self.simd0, rhs.simd0), simd1: v128_or(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].bitor(rhs.arr[0]), self.arr[1].bitor(rhs.arr[1]), self.arr[2].bitor(rhs.arr[2]), self.arr[3].bitor(rhs.arr[3]), self.arr[4].bitor(rhs.arr[4]), self.arr[5].bitor(rhs.arr[5]), self.arr[6].bitor(rhs.arr[6]), self.arr[7].bitor(rhs.arr[7]), self.arr[8].bitor(rhs.arr[8]), self.arr[9].bitor(rhs.arr[9]), self.arr[10].bitor(rhs.arr[10]), self.arr[11].bitor(rhs.arr[11]), self.arr[12].bitor(rhs.arr[12]), self.arr[13].bitor(rhs.arr[13]), self.arr[14].bitor(rhs.arr[14]), self.arr[15].bitor(rhs.arr[15]), ]} } } } } impl BitXor for i16x16 { type Output = Self; #[inline] #[must_use] fn bitxor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitxor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: bitxor_m128i(self.sse0, rhs.sse0), sse1: bitxor_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: v128_xor(self.simd0, rhs.simd0), simd1: v128_xor(self.simd1, rhs.simd1) } } else { Self { arr: [ self.arr[0].bitxor(rhs.arr[0]), self.arr[1].bitxor(rhs.arr[1]), self.arr[2].bitxor(rhs.arr[2]), self.arr[3].bitxor(rhs.arr[3]), self.arr[4].bitxor(rhs.arr[4]), self.arr[5].bitxor(rhs.arr[5]), self.arr[6].bitxor(rhs.arr[6]), self.arr[7].bitxor(rhs.arr[7]), self.arr[8].bitxor(rhs.arr[8]), self.arr[9].bitxor(rhs.arr[9]), self.arr[10].bitxor(rhs.arr[10]), self.arr[11].bitxor(rhs.arr[11]), self.arr[12].bitxor(rhs.arr[12]), self.arr[13].bitxor(rhs.arr[13]), self.arr[14].bitxor(rhs.arr[14]), self.arr[15].bitxor(rhs.arr[15]), ]} } } } } macro_rules! impl_shl_t_for_i16x16 { ($($shift_type:ty),+ $(,)?) => { $(impl Shl<$shift_type> for i16x16 { type Output = Self; /// Shifts all lanes by the value given. #[inline] #[must_use] fn shl(self, rhs: $shift_type) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { let shift = cast([rhs as u64, 0]); Self { avx2: shl_all_u16_m256i(self.avx2, shift) } } else if #[cfg(target_feature="sse2")] { let shift = cast([rhs as u64, 0]); Self { sse0: shl_all_u16_m128i(self.sse0, shift), sse1: shl_all_u16_m128i(self.sse1, shift) } } else if #[cfg(target_feature="simd128")] { let u = rhs as u32; Self { simd0: i16x8_shl(self.simd0, u), simd1: i16x8_shl(self.simd1, u) } } else { let u = rhs as u64; Self { arr: [ self.arr[0] << u, self.arr[1] << u, self.arr[2] << u, self.arr[3] << u, self.arr[4] << u, self.arr[5] << u, self.arr[6] << u, self.arr[7] << u, self.arr[8] << u, self.arr[9] << u, self.arr[10] << u, self.arr[11] << u, self.arr[12] << u, self.arr[13] << u, self.arr[14] << u, self.arr[15] << u, ]} } } } })+ }; } impl_shl_t_for_i16x16!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); macro_rules! impl_shr_t_for_i16x16 { ($($shift_type:ty),+ $(,)?) => { $(impl Shr<$shift_type> for i16x16 { type Output = Self; /// Shifts all lanes by the value given. #[inline] #[must_use] fn shr(self, rhs: $shift_type) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { let shift = cast([rhs as u64, 0]); Self { avx2: shr_all_i16_m256i(self.avx2, shift) } } else if #[cfg(target_feature="sse2")] { let shift = cast([rhs as u64, 0]); Self { sse0: shr_all_i16_m128i(self.sse0, shift), sse1: shr_all_i16_m128i(self.sse1, shift) } } else if #[cfg(target_feature="simd128")] { let u = rhs as u32; Self { simd0: i16x8_shr(self.simd0, u), simd1: i16x8_shr(self.simd1, u) } } else { let u = rhs as u64; Self { arr: [ self.arr[0] >> u, self.arr[1] >> u, self.arr[2] >> u, self.arr[3] >> u, self.arr[4] >> u, self.arr[5] >> u, self.arr[6] >> u, self.arr[7] >> u, self.arr[8] >> u, self.arr[9] >> u, self.arr[10] >> u, self.arr[11] >> u, self.arr[12] >> u, self.arr[13] >> u, self.arr[14] >> u, self.arr[15] >> u, ]} } } } })+ }; } impl_shr_t_for_i16x16!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); impl CmpEq for i16x16 { type Output = Self; #[inline] #[must_use] fn cmp_eq(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_eq_mask_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: cmp_eq_mask_i16_m128i(self.sse0, rhs.sse0), sse1: cmp_eq_mask_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_eq(self.simd0, rhs.simd0), simd1: i16x8_eq(self.simd1, rhs.simd1) } } else { Self { arr: [ if self.arr[0] == rhs.arr[0] { -1 } else { 0 }, if self.arr[1] == rhs.arr[1] { -1 } else { 0 }, if self.arr[2] == rhs.arr[2] { -1 } else { 0 }, if self.arr[3] == rhs.arr[3] { -1 } else { 0 }, if self.arr[4] == rhs.arr[4] { -1 } else { 0 }, if self.arr[5] == rhs.arr[5] { -1 } else { 0 }, if self.arr[6] == rhs.arr[6] { -1 } else { 0 }, if self.arr[7] == rhs.arr[7] { -1 } else { 0 }, if self.arr[8] == rhs.arr[8] { -1 } else { 0 }, if self.arr[9] == rhs.arr[9] { -1 } else { 0 }, if self.arr[10] == rhs.arr[10] { -1 } else { 0 }, if self.arr[11] == rhs.arr[11] { -1 } else { 0 }, if self.arr[12] == rhs.arr[12] { -1 } else { 0 }, if self.arr[13] == rhs.arr[13] { -1 } else { 0 }, if self.arr[14] == rhs.arr[14] { -1 } else { 0 }, if self.arr[15] == rhs.arr[15] { -1 } else { 0 }, ]} } } } } impl CmpGt for i16x16 { type Output = Self; #[inline] #[must_use] fn cmp_gt(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_gt_mask_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: cmp_gt_mask_i16_m128i(self.sse0, rhs.sse0), sse1: cmp_gt_mask_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_gt(self.simd0, rhs.simd0), simd1: i16x8_gt(self.simd1, rhs.simd1) } } else { Self { arr: [ if self.arr[0] > rhs.arr[0] { -1 } else { 0 }, if self.arr[1] > rhs.arr[1] { -1 } else { 0 }, if self.arr[2] > rhs.arr[2] { -1 } else { 0 }, if self.arr[3] > rhs.arr[3] { -1 } else { 0 }, if self.arr[4] > rhs.arr[4] { -1 } else { 0 }, if self.arr[5] > rhs.arr[5] { -1 } else { 0 }, if self.arr[6] > rhs.arr[6] { -1 } else { 0 }, if self.arr[7] > rhs.arr[7] { -1 } else { 0 }, if self.arr[8] > rhs.arr[8] { -1 } else { 0 }, if self.arr[9] > rhs.arr[9] { -1 } else { 0 }, if self.arr[10] > rhs.arr[10] { -1 } else { 0 }, if self.arr[11] > rhs.arr[11] { -1 } else { 0 }, if self.arr[12] > rhs.arr[12] { -1 } else { 0 }, if self.arr[13] > rhs.arr[13] { -1 } else { 0 }, if self.arr[14] > rhs.arr[14] { -1 } else { 0 }, if self.arr[15] > rhs.arr[15] { -1 } else { 0 }, ]} } } } } impl CmpLt for i16x16 { type Output = Self; #[inline] #[must_use] fn cmp_lt(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: !cmp_gt_mask_i16_m256i(self.avx2, rhs.avx2) ^ cmp_eq_mask_i16_m256i(self.avx2,rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: cmp_lt_mask_i16_m128i(self.sse0, rhs.sse0), sse1: cmp_lt_mask_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_lt(self.simd0, rhs.simd0), simd1: i16x8_lt(self.simd1, rhs.simd1) } } else { Self { arr: [ if self.arr[0] < rhs.arr[0] { -1 } else { 0 }, if self.arr[1] < rhs.arr[1] { -1 } else { 0 }, if self.arr[2] < rhs.arr[2] { -1 } else { 0 }, if self.arr[3] < rhs.arr[3] { -1 } else { 0 }, if self.arr[4] < rhs.arr[4] { -1 } else { 0 }, if self.arr[5] < rhs.arr[5] { -1 } else { 0 }, if self.arr[6] < rhs.arr[6] { -1 } else { 0 }, if self.arr[7] < rhs.arr[7] { -1 } else { 0 }, if self.arr[8] < rhs.arr[8] { -1 } else { 0 }, if self.arr[9] < rhs.arr[9] { -1 } else { 0 }, if self.arr[10] < rhs.arr[10] { -1 } else { 0 }, if self.arr[11] < rhs.arr[11] { -1 } else { 0 }, if self.arr[12] < rhs.arr[12] { -1 } else { 0 }, if self.arr[13] < rhs.arr[13] { -1 } else { 0 }, if self.arr[14] < rhs.arr[14] { -1 } else { 0 }, if self.arr[15] < rhs.arr[15] { -1 } else { 0 }, ]} } } } } impl i16x16 { #[inline] #[must_use] pub fn blend(self, t: Self, f: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: blend_varying_i8_m256i(f.avx2, t.avx2, self.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: blend_varying_i8_m128i(f.sse0, t.sse0, self.sse0), sse1: blend_varying_i8_m128i(f.sse1, t.sse1, self.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: v128_bitselect(t.simd0, f.simd0, self.simd0), simd1: v128_bitselect(t.simd1, f.simd1, self.simd1) } } else { generic_bit_blend(self, t, f) } } } #[inline] #[must_use] pub fn abs(self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: abs_i16_m256i(self.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: abs_i16_m128i(self.sse0), sse1: abs_i16_m128i(self.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_abs(self.simd0), simd1: i16x8_abs(self.simd1) } } else { let arr: [i16; 16] = cast(self); cast([ arr[0].wrapping_abs(), arr[1].wrapping_abs(), arr[2].wrapping_abs(), arr[3].wrapping_abs(), arr[4].wrapping_abs(), arr[5].wrapping_abs(), arr[6].wrapping_abs(), arr[7].wrapping_abs(), arr[8].wrapping_abs(), arr[9].wrapping_abs(), arr[10].wrapping_abs(), arr[11].wrapping_abs(), arr[12].wrapping_abs(), arr[13].wrapping_abs(), arr[14].wrapping_abs(), arr[15].wrapping_abs(), ]) } } } #[inline] #[must_use] pub fn max(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: max_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse2")] { Self { sse0: max_i16_m128i(self.sse0, rhs.sse0), sse1: max_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_max(self.simd0, rhs.simd0), simd1: i16x8_max(self.simd1, rhs.simd1) } } else { self.cmp_lt(rhs).blend(rhs, self) } } } #[inline] #[must_use] pub fn min(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: min_i16_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: min_i16_m128i(self.sse0, rhs.sse0), sse1: min_i16_m128i(self.sse1, rhs.sse1) } } else if #[cfg(target_feature="simd128")] { Self { simd0: i16x8_min(self.simd0, rhs.simd0), simd1: i16x8_min(self.simd1, rhs.simd1) } } else { self.cmp_lt(rhs).blend(self, rhs) } } } pub fn to_array(self) -> [i16; 16] { cast(self) } }
#[allow(unused_variables)] use std:env; fn main(){ y :}
use std::ops::Neg; use sdl2::{pixels::Color, rect::Rect, mouse::SystemCursor, render::{Canvas, Texture}, video}; use sdl2::gfx::primitives::DrawRenderer; use crate::{TextBuffer, Scroller, Window, PaneManager, Cursor, color::STANDARD_TEXT_COLOR}; #[derive(Debug, Clone)] pub struct EditorBounds { pub editor_left_margin: usize, pub line_number_gutter_width: usize, pub letter_height: usize, pub letter_width: usize, } impl EditorBounds{ pub fn line_number_digits(&self, text_buffer: &TextBuffer) -> usize { digit_count(text_buffer.line_count()) } pub fn line_number_padding(&self, text_buffer: &TextBuffer) -> usize { self.line_number_digits(text_buffer) * self.letter_width as usize + self.line_number_gutter_width + self.editor_left_margin + self.letter_width as usize } } pub fn digit_count(x: usize) -> usize { let mut count = 0; let mut x = x; while x > 0 { x /= 10; count += 1; } count } pub struct Renderer<'a> { pub canvas: Canvas<video::Window>, pub texture: Texture<'a>, pub target: Rect, pub bounds: EditorBounds, pub system_cursor: sdl2::mouse::Cursor, } impl<'a> Renderer<'a> { pub fn draw_triangle(&mut self, x: i16, y: i16, color: Color) -> Result<(), String> { self.canvas.filled_trigon(x, y, x, y+10, x+5, y+5, color) } pub fn set_draw_color(&mut self, color: Color) { self.canvas.set_draw_color(color); } pub fn clear(&mut self) { self.canvas.clear(); } pub fn set_color_mod(&mut self, color: Color) { let (r, g, b, _) = color.rgba(); self.texture.set_color_mod(r, g, b); } pub fn set_initial_rendering_location(&mut self, scroller: &Scroller) { // TODO: // Abstract out where we start drawing // so we could change pane look easily self.target = Rect::new( self.bounds.editor_left_margin as i32, (scroller.line_fraction_y(&self.bounds) as i32).neg() + self.bounds.letter_height as i32 * 2, self.bounds.letter_width as u32, self.bounds.letter_height as u32 ); } pub fn copy(&mut self, source: &Rect) -> Result<(), String> { self.canvas.copy(&self.texture, *source, self.target) } pub fn fill_rect(&mut self, rect: &Rect) -> Result<(), String> { self.canvas.fill_rect(*rect) } pub fn draw_rect(&mut self, rect: &Rect) -> Result<(), String> { self.canvas.draw_rect(*rect) } pub fn move_right(&mut self, padding: i32) { self.target.set_x(self.target.x() + padding); } pub fn move_left(&mut self, padding: i32) { self.target.set_x(self.target.x().saturating_sub(padding)); } pub fn move_down(&mut self, padding: i32) { self.target.set_y(self.target.y() + padding); } pub fn move_right_one_char(&mut self) { self.move_right(self.bounds.letter_width as i32); } pub fn move_down_one_line(&mut self) { self.move_down(self.bounds.letter_height as i32); } pub fn set_x(&mut self, x: i32) { self.target.set_x(x); } pub fn set_y(&mut self, x: i32) { self.target.set_y(x); } pub fn char_position_in_atlas(&self, c: char) -> Rect { Rect::new(self.bounds.letter_width as i32 * (c as i32 - 33), 0, self.bounds.letter_width as u32, self.bounds.letter_height as u32) } pub fn draw_string(&mut self, text: &str) -> Result<(), String> { for char in text.chars() { self.move_right_one_char(); self.copy(&self.char_position_in_atlas(char))? } Ok(()) } pub fn draw_fps(&mut self, fps: usize, window: &Window) -> Result<(), String> { // Do something better with this target self.target = Rect::new(window.width - (self.bounds.letter_width * 10) as i32, 0, self.bounds.letter_width as u32, self.bounds.letter_height as u32); self.set_color_mod(STANDARD_TEXT_COLOR); self.draw_string(&format!("fps: {}", fps)) } pub fn draw_column_line(&mut self, pane_manager: &mut PaneManager) -> Result<(), String> { self.target = Rect::new(pane_manager.window.width - (self.bounds.letter_width * 22) as i32, pane_manager.window.height-self.bounds.letter_height as i32, self.bounds.letter_width as u32, self.bounds.letter_height as u32); if let Some(pane) = pane_manager.get_active_pane().and_then(|pane| pane.get_text_pane()) { if let Some(Cursor(cursor_line, cursor_column)) = pane.cursor_context.cursor { self.draw_string( &format!("Line {}, Column {}", cursor_line, cursor_column))?; } } Ok(()) } pub fn present(&mut self) { self.canvas.present(); } pub fn set_cursor_pointer(&mut self) { self.system_cursor = sdl2::mouse::Cursor::from_system(SystemCursor::Hand).unwrap(); self.system_cursor.set(); } pub fn set_cursor_ibeam(&mut self) { self.system_cursor = sdl2::mouse::Cursor::from_system(SystemCursor::IBeam).unwrap(); self.system_cursor.set(); } }
use proc_macro::{self, *}; use lustre_lib::{object::{Object, RefObject}, reader::{Reader, tokenizer::Tokenizer}}; use std::io::prelude::*; use std::io::Cursor; fn ref_object_to_parsable(refobj: &RefObject) -> String { if let Some(obj) = refobj.as_ref() { format!("Arc::new(Some({}))", object_to_parsable(obj)) } else { "Arc::new(None)".to_string() } } fn object_to_parsable(obj: &Object) -> String { match obj { Object::Cons(car,cdr) => { format!("Object::Cons({},{})", ref_object_to_parsable(car), ref_object_to_parsable(cdr)) }, Object::Integer(value) => format!("Object::Integer({})", value ), Object::IString(value) => format!("Object::IString(String::from(\"{}\"))", value ), Object::Lambda(_,_) => unimplemented!(), Object::Operator(_,_) => unimplemented!(), Object::Symbol(value) => format!("Object::Symbol(String::from(\"{}\"))", value ), }.to_string() } #[proc_macro] pub fn lustre(sexp: TokenStream) -> TokenStream { let cursor = Cursor::new(sexp.to_string()); let tokenizer = Tokenizer::new(cursor.bytes()); let mut reader = Reader::new(tokenizer); ref_object_to_parsable(&reader.read().unwrap()).parse().unwrap() }
// (c) Dean McNamee <dean@gmail.com>, 2012. // (c) Rust port by Katkov Oleksandr <alexx.katkoff@gmail.com>, 2016. // // https://github.com/deanm/css-color-parser-js // https://github.com/7thSigil/css-color-parser-rs // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. use crate::color::color::Color; #[test] fn rgb() { let c = " rgb(255, 128, 12)".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 255, g: 128, b: 12, a: 1.0, }); } #[test] fn rgba() { let c = " rgba (255, 128, 12, 0.5)".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 255, g: 128, b: 12, a: 0.5, }); } #[test] fn abc() { let c = "#fff".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 255, g: 255, b: 255, a: 1.0, }); } #[test] fn abc123() { let c = "#ff0011".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 255, g: 0, b: 17, a: 1.0, }); } #[test] fn named_color() { let c = "slateblue".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 106, g: 90, b: 205, a: 1.0, }); } #[test] #[should_panic] #[allow(unused_variables)] fn invalid_color1() { let c = "blah".parse::<Color>().unwrap(); } #[test] #[should_panic] #[allow(unused_variables)] fn invalid_color2() { let c = "ffffff".parse::<Color>().unwrap(); } #[test] fn hsla() { let c = "hsla(900, 15%, 90%, 0.5)".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 226, g: 233, b: 233, a: 0.5, }); } #[test] #[should_panic] #[allow(unused_variables)] fn hsla_invalid() { let c = "hsla(900, 15%, 90%)".parse::<Color>().unwrap(); } #[test] fn hsl() { let c = "hsl(900, 15%, 90%)".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 226, g: 233, b: 233, a: 1.0, }); } #[test] fn hsl_non_spec_compliant() { let c = "hsl(900, 0.15, 90%)".parse::<Color>().unwrap(); assert_eq!(c, Color { r: 226, g: 233, b: 233, a: 1.0, }); } // This test is disabled by default due to practicality concerns // Passes but takes quite a long time to do so ~16+ million combinations // Use cargo test -- --ignored it you want to use it anyway #[test] #[ignore] fn rgb_range_test() { for r in 0..255 { for g in 0..255 { for b in 0..255 { let c = format!("rgb({}, {}, {})", r, g, b).parse::<Color>().unwrap(); assert_eq!(c, Color { r: r, g: g, b: b, a: 1.0 }); } } } } // This test is disabled by defualt due to practicality concerns // Passes but takes quite a long time to do so ~160 million combinations // Use cargo test -- --ignored it you want to use it anyway #[test] #[ignore] fn rgba_range_test() { for r in 0..255 { for g in 0..255 { for b in 0..255 { let mut a = 0.0; while a <= 1.0 { let c = format!("rgba({}, {}, {}, {})", r, g, b, a).parse::<Color>().unwrap(); assert_eq!(c, Color { r: r, g: g, b: b, a: a }); a+=0.1; } } } } }
// This example just prints "Hello Tock World" to the terminal. // Run `tockloader listen`, or use any serial program of your choice // (e.g. `screen`, `minicom`) to view the message. #![no_std] #![feature(asm)] use libtock::println; use libtock::result::TockResult; libtock_core::stack_size! {0x400} #[libtock::main] async fn main() -> TockResult<()> { let drivers = libtock::retrieve_drivers()?; drivers.console.create_console(); let start: u32; let end: u32; unsafe{ asm!("RDCYCLE {}", out(reg) start); } for i in 1..10 { println!("Hello World {}", i); } unsafe{ asm!("RDCYCLE {}", out(reg) end); } println!("Hello Demo Took {} cycles", end - start); Ok(()) }
extern crate bit_vec; pub mod genetic; pub mod algorithm; pub mod distributions; pub mod abstractions; mod samplefitness; pub type Chromosome = bit_vec::BitVec; pub use genetic::Genetic; pub use genetic::gen_custom::GeneticCustom; pub use crate::algorithm::algorithm::AlgorithmParams; pub use crate::algorithm::algorithm::genetic_algorithm; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
#[macro_use] extern crate log; mod worker; use kube::Client; use chrono::Local; use std::{io::Write, sync::Arc}; use tokio::signal::unix::{signal, SignalKind}; #[tokio::main] async fn main() -> anyhow::Result<()> { std::env::set_var("RUST_LOG", "info,kube=debug"); env_logger::Builder::from_env(env_logger::Env::default()) .format(|buf, record| { let level = { buf.default_styled_level(record.level()) }; writeln!( buf, "[{} {} {}:{}] {}", Local::now().format("%Y-%m-%d %H:%M:%S"), level, record.module_path().unwrap_or("<unnamed>"), record.line().unwrap_or(0), &record.args() ) }) .init(); let client = Client::try_default().await?; let worker = Arc::new(worker::SyncWorker::new( client, "default", "docker-registry", )); let watch_ns = worker.clone(); let watch_cfg = worker.clone(); tokio::spawn(async move { if let Err(e) = watch_ns.watch_ns().await { panic!("sync worker watch ns err: {}", e); } }); tokio::spawn(async move { if let Err(e) = watch_cfg.watch_cfg_secret().await { panic!("sync worker watch config secret err: {}", e); } }); signal(SignalKind::terminate())?.recv().await; info!("recv SIGTERM, graceful shutdown..."); Ok(()) }
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn test_open_browser(url: String) { web_sys::console::log_1(&format!("checking in {}", &url).into()); webbrowser::open(&url).expect("failed to open browser"); web_sys::console::log_1(&"yolo".into()); }
/// An enum to represent all characters in the OldNorthArabian block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum OldNorthArabian { /// \u{10a80}: '𐪀' LetterHeh, /// \u{10a81}: '𐪁' LetterLam, /// \u{10a82}: '𐪂' LetterHah, /// \u{10a83}: '𐪃' LetterMeem, /// \u{10a84}: '𐪄' LetterQaf, /// \u{10a85}: '𐪅' LetterWaw, /// \u{10a86}: '𐪆' LetterEsDash2, /// \u{10a87}: '𐪇' LetterReh, /// \u{10a88}: '𐪈' LetterBeh, /// \u{10a89}: '𐪉' LetterTeh, /// \u{10a8a}: '𐪊' LetterEsDash1, /// \u{10a8b}: '𐪋' LetterKaf, /// \u{10a8c}: '𐪌' LetterNoon, /// \u{10a8d}: '𐪍' LetterKhah, /// \u{10a8e}: '𐪎' LetterSad, /// \u{10a8f}: '𐪏' LetterEsDash3, /// \u{10a90}: '𐪐' LetterFeh, /// \u{10a91}: '𐪑' LetterAlef, /// \u{10a92}: '𐪒' LetterAin, /// \u{10a93}: '𐪓' LetterDad, /// \u{10a94}: '𐪔' LetterGeem, /// \u{10a95}: '𐪕' LetterDal, /// \u{10a96}: '𐪖' LetterGhain, /// \u{10a97}: '𐪗' LetterTah, /// \u{10a98}: '𐪘' LetterZain, /// \u{10a99}: '𐪙' LetterThal, /// \u{10a9a}: '𐪚' LetterYeh, /// \u{10a9b}: '𐪛' LetterTheh, /// \u{10a9c}: '𐪜' LetterZah, /// \u{10a9d}: '𐪝' NumberOne, /// \u{10a9e}: '𐪞' NumberTen, } impl Into<char> for OldNorthArabian { fn into(self) -> char { match self { OldNorthArabian::LetterHeh => '𐪀', OldNorthArabian::LetterLam => '𐪁', OldNorthArabian::LetterHah => '𐪂', OldNorthArabian::LetterMeem => '𐪃', OldNorthArabian::LetterQaf => '𐪄', OldNorthArabian::LetterWaw => '𐪅', OldNorthArabian::LetterEsDash2 => '𐪆', OldNorthArabian::LetterReh => '𐪇', OldNorthArabian::LetterBeh => '𐪈', OldNorthArabian::LetterTeh => '𐪉', OldNorthArabian::LetterEsDash1 => '𐪊', OldNorthArabian::LetterKaf => '𐪋', OldNorthArabian::LetterNoon => '𐪌', OldNorthArabian::LetterKhah => '𐪍', OldNorthArabian::LetterSad => '𐪎', OldNorthArabian::LetterEsDash3 => '𐪏', OldNorthArabian::LetterFeh => '𐪐', OldNorthArabian::LetterAlef => '𐪑', OldNorthArabian::LetterAin => '𐪒', OldNorthArabian::LetterDad => '𐪓', OldNorthArabian::LetterGeem => '𐪔', OldNorthArabian::LetterDal => '𐪕', OldNorthArabian::LetterGhain => '𐪖', OldNorthArabian::LetterTah => '𐪗', OldNorthArabian::LetterZain => '𐪘', OldNorthArabian::LetterThal => '𐪙', OldNorthArabian::LetterYeh => '𐪚', OldNorthArabian::LetterTheh => '𐪛', OldNorthArabian::LetterZah => '𐪜', OldNorthArabian::NumberOne => '𐪝', OldNorthArabian::NumberTen => '𐪞', } } } impl std::convert::TryFrom<char> for OldNorthArabian { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '𐪀' => Ok(OldNorthArabian::LetterHeh), '𐪁' => Ok(OldNorthArabian::LetterLam), '𐪂' => Ok(OldNorthArabian::LetterHah), '𐪃' => Ok(OldNorthArabian::LetterMeem), '𐪄' => Ok(OldNorthArabian::LetterQaf), '𐪅' => Ok(OldNorthArabian::LetterWaw), '𐪆' => Ok(OldNorthArabian::LetterEsDash2), '𐪇' => Ok(OldNorthArabian::LetterReh), '𐪈' => Ok(OldNorthArabian::LetterBeh), '𐪉' => Ok(OldNorthArabian::LetterTeh), '𐪊' => Ok(OldNorthArabian::LetterEsDash1), '𐪋' => Ok(OldNorthArabian::LetterKaf), '𐪌' => Ok(OldNorthArabian::LetterNoon), '𐪍' => Ok(OldNorthArabian::LetterKhah), '𐪎' => Ok(OldNorthArabian::LetterSad), '𐪏' => Ok(OldNorthArabian::LetterEsDash3), '𐪐' => Ok(OldNorthArabian::LetterFeh), '𐪑' => Ok(OldNorthArabian::LetterAlef), '𐪒' => Ok(OldNorthArabian::LetterAin), '𐪓' => Ok(OldNorthArabian::LetterDad), '𐪔' => Ok(OldNorthArabian::LetterGeem), '𐪕' => Ok(OldNorthArabian::LetterDal), '𐪖' => Ok(OldNorthArabian::LetterGhain), '𐪗' => Ok(OldNorthArabian::LetterTah), '𐪘' => Ok(OldNorthArabian::LetterZain), '𐪙' => Ok(OldNorthArabian::LetterThal), '𐪚' => Ok(OldNorthArabian::LetterYeh), '𐪛' => Ok(OldNorthArabian::LetterTheh), '𐪜' => Ok(OldNorthArabian::LetterZah), '𐪝' => Ok(OldNorthArabian::NumberOne), '𐪞' => Ok(OldNorthArabian::NumberTen), _ => Err(()), } } } impl Into<u32> for OldNorthArabian { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for OldNorthArabian { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for OldNorthArabian { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl OldNorthArabian { /// The character with the lowest index in this unicode block pub fn new() -> Self { OldNorthArabian::LetterHeh } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("OldNorthArabian{:#?}", self); string_morph::to_sentence_case(&s) } }
use std::thread::spawn; use std::process::Command; use std::num::Wrapping; use std::cmp::max; use libc::{c_uchar,c_int, c_ulong}; use std::ffi::CString; use std::ptr::{ null, null_mut, }; use x11::xlib; use config; use config::KeyCmd; unsafe extern fn error_handler(_: *mut xlib::Display, _: *mut xlib::XErrorEvent) -> c_int { return 0; } pub struct WindowSystem { display: *mut xlib::Display, root: xlib::Window, x: i32, y: i32, w: u32, h: u32, button_id: u32, borderinfo: config::BorderInfo, focuswin: xlib::Window, } impl WindowSystem { pub fn new() -> WindowSystem { use x11::xlib::*; let borderinfo = config::BorderInfo::new( config::FOCUS_BORDERS, config::UNFOCUSED_BORDERS ); unsafe { // Open display let display = xlib::XOpenDisplay(null()); if display == null_mut() { panic!("Exiting: Cannot find display"); } // Create window let screen = xlib::XDefaultScreenOfDisplay(display); let root = xlib::XRootWindowOfScreen(screen); xlib::XSetErrorHandler(Some(error_handler)); let ws = WindowSystem { display: display, root: root, x: 0, y: 0, w: 0, h: 0, button_id: 0, borderinfo: borderinfo, focuswin: root, }; let mut wa = XSetWindowAttributes { background_pixmap: 0, background_pixel: 0, border_pixmap: 0, border_pixel: 0, bit_gravity: 0, win_gravity: 0, backing_store: 0, backing_planes: 0, backing_pixel: 0, save_under: 0, do_not_propagate_mask: 0, override_redirect: 0, colormap: 0, cursor: 0, event_mask: SubstructureRedirectMask| SubstructureNotifyMask| StructureNotifyMask| ButtonPressMask| ButtonReleaseMask| PropertyChangeMask, }; // Set up window events XChangeWindowAttributes( ws.display, ws.root, CWEventMask|CWCursor, &mut wa ); XSelectInput( ws.display, ws.root, wa.event_mask ); xlib::XSync( ws.display, 0 ); xlib::XUngrabButton(ws.display, 0, 0x8000, ws.root); let name = (*CString::new(&b"ALWM"[..]).unwrap()).as_ptr(); let wmcheck = ws.get_atom("_NET_SUPPORTING_WM_CHECK"); let wmname = ws.get_atom("_NET_WM_NAME"); let utf8 = ws.get_atom("UTF8_STRING"); let xa_window = ws.get_atom("xlib::XA_WINDOW"); let mut root_cpy = ws.root; let root_ptr : *mut Window = &mut root_cpy; xlib::XChangeProperty(ws.display, ws.root, wmcheck, xa_window, 32, 0, root_ptr as *mut c_uchar, 1); xlib::XChangeProperty(ws.display, ws.root, wmname, utf8, 8, 0, name as *mut c_uchar, 5); ws } } pub fn grab_keys(&self) { unsafe { // Grab keys // Exit key behavior let kc_exit = xlib::XKeysymToKeycode( self.display, KeyCmd::get_keysym( config::EXIT_KEY ) ); xlib::XGrabKey( self.display, kc_exit as i32, KeyCmd::get_modifier( config::EXIT_KEY ), self.root as c_ulong, 1, xlib::GrabModeAsync, xlib::GrabModeAsync ); let kc_term = xlib::XKeysymToKeycode( self.display, KeyCmd::get_keysym( config::TERM_KEY ) ); xlib::XGrabKey( self.display, kc_term as i32, KeyCmd::get_modifier( config::TERM_KEY ), self.root as c_ulong, 1, xlib::GrabModeAsync, xlib::GrabModeAsync ); let kc_run = xlib::XKeysymToKeycode( self.display, KeyCmd::get_keysym( config::RUN_KEY ) ); xlib::XGrabKey( self.display, kc_run as i32, KeyCmd::get_modifier( config::RUN_KEY ), self.root as c_ulong, 1, xlib::GrabModeAsync, xlib::GrabModeAsync ); } } pub fn grab_buttons(&self) { unsafe { // Grab mouse xlib::XGrabButton( self.display, config::MOUSE_MOVE.button, config::MOUSE_MOVE.modifier, self.root, 1, xlib::ButtonPressMask as u32, xlib::GrabModeAsync, xlib::GrabModeAsync, 0, 0 ); xlib::XGrabButton( self.display, config::MOUSE_RESIZE.button, config::MOUSE_RESIZE.modifier, self.root, 1, xlib::ButtonPressMask as u32, xlib::GrabModeAsync, xlib::GrabModeAsync, 0, 0 ); xlib::XGrabButton( self.display, config::MOUSE_RAISE.button, config::MOUSE_RAISE.modifier, self.root, 1, xlib::ButtonPressMask as u32, xlib::GrabModeAsync, xlib::GrabModeAsync, 0, 0 ); } } fn get_atom(&self, s: &str) -> u64 { unsafe { match CString::new(s) { Ok(b) => xlib::XInternAtom(self.display, b.as_ptr(), 0) as u64, _ => panic!("Invalid atom! {}", s) } } } pub fn on_update( &mut self ) -> bool { let mut ev = xlib::XEvent { pad : [0; 24] }; unsafe { xlib::XNextEvent( self.display, &mut ev ); } let event_type = ev.get_type(); match event_type { xlib::MotionNotify => { unsafe { while xlib::XCheckTypedEvent( self.display, xlib::MotionNotify, &mut ev ) == 1 {}; } let event = xlib::XMotionEvent::from(ev); self.on_motion( &event ); }, xlib::ButtonPress => { let event = xlib::XButtonEvent::from(ev); self.on_button_press( &event ); }, xlib::ButtonRelease => { let event = xlib::XButtonEvent::from(ev); self.on_button_release( &event ); }, // xlib::ClientMessage => { // let event = xlib::XClientMessageEvent::from(ev); // self.on_client_message( &event ); // }, xlib::ConfigureNotify => { let event = xlib::XConfigureEvent::from(ev); unsafe { xlib::XClearWindow( self.display, self.root ); } if event.window != self.root { if event.window == self.focuswin { self.draw_borders( true, event.window ); } else { self.draw_borders( false, event.window ); } } } xlib::DestroyNotify => { }, xlib::EnterNotify => { let event = xlib::XEnterWindowEvent::from(ev); self.on_enter_notify( &event ); } xlib::MapRequest => { let mut event = xlib::XMapRequestEvent::from(ev); self.on_map_request( &mut event ); }, // xlib::CreateNotify => { // } xlib::KeyPress => { let event = xlib::XKeyEvent::from(ev); if self.on_keypress( &event ) { return true; } }, _ => {}, } false } pub fn flush(&self) { unsafe { xlib::XFlush(self.display); } } fn focus( &mut self, window: xlib::Window, time: c_ulong ) { if self.focuswin != window { unsafe{ xlib::XSetInputFocus( self.display, window, xlib::RevertToParent, time ); if !config::SLOPPYFOCUS { xlib::XRaiseWindow( self.display, window ); } } } self.draw_borders( true, window ); self.focuswin = window; } fn draw_borders( &mut self, isfocused: bool, window: xlib::Window ) { if self.root as u64 == window as u64 { return; } let mut borders = config::UNFOCUSED_BORDERS; let mut count = config::NUM_UNFOCUSED_BORDERS; let mut size = self.borderinfo.get_unfocus_size(); if isfocused { borders = config::FOCUS_BORDERS; count = config::NUM_FOCUSED_BORDERS; size = self.borderinfo.get_focus_size(); } unsafe { // let mut wc = xlib::XWindowChanges { // x: 0, // y: 0, // width: 0, // height: 0, // border_width: size * 2, // sibling: 0, // stack_mode: 0, // }; // // xlib::XConfigureWindow( self.display, window, xlib::CWBorderWidth as u32, &mut wc ); let mut gcv = xlib::XGCValues { function: 0, plane_mask: 0, foreground: 0, background: 0, line_width: 0, line_style: 0, cap_style: 0, join_style: 0, fill_style: 0, fill_rule: 0, arc_mode: 0, tile: 0, stipple: 0, ts_x_origin: 0, ts_y_origin: 0, font: 0, subwindow_mode: 0, graphics_exposures: 0, clip_x_origin: 0, clip_y_origin: 0, clip_mask: 0, dash_offset: 0, dashes: 0, }; let mut wa = self.get_empty_wa(); xlib::XGetWindowAttributes( self.display, window, &mut wa ); let cmap = xlib::XDefaultColormap( self.display, 0 ); let pixmap = xlib::XCreatePixmap( self.display, self.root, (wa.x - size) as u32, (wa.y - size) as u32, wa.depth as u32 ); for i in 0 .. count { let new_x = wa.x - size; let new_y = wa.y - size; let new_w = wa.width + ( 2 * size ); let new_h = wa.height + ( 2 * size ); let mut color = xlib::XColor { pixel: 0, red: 0, green: 0, blue: 0, flags: 0, pad: 0, }; let gc = xlib::XCreateGC( self.display, pixmap, 0, &mut gcv ); let color_string = CString::new( borders[i].color).unwrap().into_raw(); xlib::XParseColor( self.display, cmap, color_string, &mut color); xlib::XAllocColor( self.display, cmap, &mut color ); let _ = CString::from_raw(color_string); xlib::XSetForeground( self.display, gc, color.pixel ); xlib::XFillRectangle( self.display, pixmap, gc, new_x, new_y, new_w as u32, new_h as u32 ); xlib::XSync( self.display, 0 ); xlib::XFreeGC( self.display, gc ); size = size - borders[i].size; } let mut s_wa = xlib::XSetWindowAttributes { background_pixmap: 0, background_pixel: 0, border_pixmap: pixmap, border_pixel: 0, bit_gravity: 0, win_gravity: 0, backing_store: 0, backing_planes: 0, backing_pixel: 0, save_under: 0, event_mask: 0, do_not_propagate_mask: 0, override_redirect: 0, colormap: 0, cursor: 0, }; xlib::XChangeWindowAttributes( self.display, window, xlib::CWBorderPixmap, &mut s_wa ); xlib::XSync( self.display, 0 ); xlib::XFreePixmap( self.display, pixmap ); xlib::XFreeColormap( self.display, cmap ); self.flush(); } } fn on_enter_notify( &mut self, event: &xlib::XEnterWindowEvent ) { if config::SLOPPYFOCUS { self.focus( event.window, event.time ); } } fn on_map_request( &mut self, event: &mut xlib::XMapRequestEvent ) { unsafe { let mut wa = self.get_empty_wa(); if xlib::XGetWindowAttributes( self.display, event.window, &mut wa ) == 0 { return; } if wa.override_redirect == 1 { return; } let mut wc = xlib::XWindowChanges { x: wa.x, y: wa.y, width: wa.width, height: wa.height, border_width: 0, sibling: 0, stack_mode: 0, }; xlib::XConfigureWindow( self.display, event.window, xlib::CWBorderWidth as u32, &mut wc ); xlib::XSetWindowBorder( self.display, event.window, wc.border_width as u64 ); xlib::XMoveResizeWindow( self.display, event.window, wc.x, wc.y, wc.width as u32, wc.height as u32 ); xlib::XSelectInput( self.display, event.window, xlib::EnterWindowMask| xlib::FocusChangeMask| xlib::PropertyChangeMask| xlib::StructureNotifyMask ); self.draw_borders( false, event.window ); xlib::XMapWindow( self.display, event.window ); } } fn on_keypress( &mut self, event: &xlib::XKeyEvent ) -> bool { use config::*; let mut open_term = false; let mut open_run = false; unsafe { let key = xlib::XKeysymToString( xlib::XKeycodeToKeysym( self.display, event.keycode as u8, 0 ) ); let key = CString::from_raw(key); let key_info = KeyCmd::new( key.to_str().unwrap(), event.state ); // Handle key events match key_info { EXIT_KEY => { return true; }, TERM_KEY => { open_term = true; }, RUN_KEY => { open_run = true; }, _ => {}, } } if open_run { spawn(move || { Command::new( RUN ).spawn().unwrap_or_else( |e| { panic!("Invalid run command {}", e)}); }); } if open_term { spawn(move || { Command::new( TERMINAL ).spawn().unwrap_or_else( |e| { panic!("Inavlid terminal command {}", e)}); }); } false } fn on_resize_move( &mut self, event: &xlib::XButtonEvent ) { if event.button == 1 { self.x = event.x_root; self.y = event.y_root; } if event.button == 3 { self.w = event.x_root as u32; self.h = event.y_root as u32; } self.button_id = event.button; unsafe { xlib::XGrabPointer( self.display, event.subwindow, 1, (xlib::PointerMotionMask|xlib::ButtonReleaseMask) as u32, xlib::GrabModeAsync, xlib::GrabModeAsync, 0, 0, event.time); } } fn on_button_press( &mut self, event: &xlib::XButtonEvent ) { let button_info = config::MouseCmd::new( event.button, event.state ); match button_info { config::MOUSE_RESIZE => { if event.subwindow != 0 { self.focus( event.subwindow, event.time ); self.on_resize_move( &event ); } }, config::MOUSE_MOVE => { if event.subwindow != 0 { self.focus( event.subwindow, event.time ); self.on_resize_move( &event ); } }, config::MOUSE_RAISE => { if event.subwindow != 0 { self.focus( event.subwindow, event.time ); } }, _ => {}, } } fn on_button_release( &mut self, event: &xlib::XButtonEvent ) { unsafe { xlib::XUngrabPointer( self.display, event.time ); } } fn on_motion( &mut self, event: &xlib::XMotionEvent ) { if self.button_id == 1 { self.on_move( &event ); } if self.button_id == 3 { self.on_resize( &event ); } self.flush(); } fn on_resize( &mut self, event: &xlib::XMotionEvent ) { unsafe { let mut wa = self.get_empty_wa(); if xlib::XGetWindowAttributes( self.display, event.window, &mut wa ) == 0 { return; } let xdiff = Wrapping::<u32>( event.x_root as u32 ) - Wrapping::<u32>( self.w ); let ydiff = Wrapping::<u32>( event.y_root as u32 ) - Wrapping::<u32>( self.h ); self.w = event.x_root as u32; self.h = event.y_root as u32; let new_w = Wrapping::<u32>(wa.width as u32) + xdiff; let new_h = Wrapping::<u32>(wa.height as u32) + ydiff; let new_w = max(1, new_w.0); let new_h = max(1, new_h.0); xlib::XResizeWindow( self.display, event.window, new_w, new_h ); } } fn on_move( &mut self, event: &xlib::XMotionEvent ) { unsafe { let mut wa = self.get_empty_wa(); if xlib::XGetWindowAttributes( self.display, event.window, &mut wa ) == 0 { return; } let xdiff = event.x_root - self.x; let ydiff = event.y_root - self.y; self.x = event.x_root; self.y = event.y_root; let new_x = wa.x + xdiff; let new_y = wa.y + ydiff; xlib::XMoveWindow( self.display, event.window, new_x, new_y ); } } unsafe fn get_empty_wa ( &self ) -> xlib::XWindowAttributes { let screen = xlib::XDefaultScreenOfDisplay( self.display ); let visual = xlib::XDefaultVisual( self.display, xlib::XDefaultScreen( self.display ) ); xlib::XWindowAttributes { x: 0, y: 0, width: 0, height: 0, border_width: 0, depth: 0, visual: visual, root: 0, class: 0, bit_gravity: 0, win_gravity: 0, backing_store: 0, backing_planes: 0, backing_pixel: 0, save_under: 0, colormap: 0, map_installed: 0, map_state: 0, all_event_masks: 0, your_event_mask: 0, do_not_propagate_mask: 0, override_redirect: 0, screen: screen, } } }
#[doc = "Reader of register DDFT_CTRL"] pub type R = crate::R<u32, super::DDFT_CTRL>; #[doc = "Writer for register DDFT_CTRL"] pub type W = crate::W<u32, super::DDFT_CTRL>; #[doc = "Register DDFT_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::DDFT_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DDFT_IN0_SEL`"] pub type DDFT_IN0_SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DDFT_IN0_SEL`"] pub struct DDFT_IN0_SEL_W<'a> { w: &'a mut W, } impl<'a> DDFT_IN0_SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `DDFT_IN1_SEL`"] pub type DDFT_IN1_SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DDFT_IN1_SEL`"] pub struct DDFT_IN1_SEL_W<'a> { w: &'a mut W, } impl<'a> DDFT_IN1_SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `DDFT_OUT0_SEL`"] pub type DDFT_OUT0_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DDFT_OUT0_SEL`"] pub struct DDFT_OUT0_SEL_W<'a> { w: &'a mut W, } impl<'a> DDFT_OUT0_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 & !(0x07 << 16)) | (((value as u32) & 0x07) << 16); self.w } } #[doc = "Reader of field `DDFT_OUT1_SEL`"] pub type DDFT_OUT1_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DDFT_OUT1_SEL`"] pub struct DDFT_OUT1_SEL_W<'a> { w: &'a mut W, } impl<'a> DDFT_OUT1_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 & !(0x07 << 20)) | (((value as u32) & 0x07) << 20); self.w } } impl R { #[doc = "Bit 0 - Specifies signal that is connected to 'ddft_in\\[0\\]' (digital DfT input signal 0): '0': not used '1': used as 'i2c_scl_in' in I2C mode, as 'spi_clk_in' in SPI mode"] #[inline(always)] pub fn ddft_in0_sel(&self) -> DDFT_IN0_SEL_R { DDFT_IN0_SEL_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 4 - Specifies signal that is connected to 'ddft_in\\[1\\]' (digital DfT input signal 0): '0': not used '1': used as 'i2c_sda_in' in I2C mode, as 'spi_mosi_in' in SPI mode"] #[inline(always)] pub fn ddft_in1_sel(&self) -> DDFT_IN1_SEL_R { DDFT_IN1_SEL_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bits 16:18 - Specifies signal that is connected to 'ddft_out\\[0\\]' (digital DfT output signal 0): In I2C mode (CTRL.MODE=0), '0': Constant '0'. '1': 'ec_busy_pp'. '2': 'rst_i2c_start_stop_n'. '3': 'rst_i2c_start_stop_n'. '4': 'i2c_scl_in_qual'. '5': 'i2c_sda_out_prel'. '6'-'7': Undefined. in SPI mode (CTRL.MODE=1), '0': Constant '0'. '1': 'rst_spi_n' '2': 'rst_spi_stop_n' '3'-'7': Undefined."] #[inline(always)] pub fn ddft_out0_sel(&self) -> DDFT_OUT0_SEL_R { DDFT_OUT0_SEL_R::new(((self.bits >> 16) & 0x07) as u8) } #[doc = "Bits 20:22 - Specifies signal that is connected to 'ddft_out\\[1\\]' (digital DfT output signal 1): In I2C mode (CTRL.MODE=0), '0': Constant '0'. '1': 'clk_ff_sram'. '2': 'rst_i2c_n'. '3': 'rst_i2c_stop_n'. '4': 'i2c_sda_in_qual'. '5': 'i2c_sda_out'. '6': 'event_i2c_ec_wake_up_ddft' from I2CS_IC '7': Undefined. In SPI mode (CTRL.MODE=1), '0': Constant '0'. '1': 'spi_start_detect' '2': 'spi_stop_detect' '3'-'7': Undefined."] #[inline(always)] pub fn ddft_out1_sel(&self) -> DDFT_OUT1_SEL_R { DDFT_OUT1_SEL_R::new(((self.bits >> 20) & 0x07) as u8) } } impl W { #[doc = "Bit 0 - Specifies signal that is connected to 'ddft_in\\[0\\]' (digital DfT input signal 0): '0': not used '1': used as 'i2c_scl_in' in I2C mode, as 'spi_clk_in' in SPI mode"] #[inline(always)] pub fn ddft_in0_sel(&mut self) -> DDFT_IN0_SEL_W { DDFT_IN0_SEL_W { w: self } } #[doc = "Bit 4 - Specifies signal that is connected to 'ddft_in\\[1\\]' (digital DfT input signal 0): '0': not used '1': used as 'i2c_sda_in' in I2C mode, as 'spi_mosi_in' in SPI mode"] #[inline(always)] pub fn ddft_in1_sel(&mut self) -> DDFT_IN1_SEL_W { DDFT_IN1_SEL_W { w: self } } #[doc = "Bits 16:18 - Specifies signal that is connected to 'ddft_out\\[0\\]' (digital DfT output signal 0): In I2C mode (CTRL.MODE=0), '0': Constant '0'. '1': 'ec_busy_pp'. '2': 'rst_i2c_start_stop_n'. '3': 'rst_i2c_start_stop_n'. '4': 'i2c_scl_in_qual'. '5': 'i2c_sda_out_prel'. '6'-'7': Undefined. in SPI mode (CTRL.MODE=1), '0': Constant '0'. '1': 'rst_spi_n' '2': 'rst_spi_stop_n' '3'-'7': Undefined."] #[inline(always)] pub fn ddft_out0_sel(&mut self) -> DDFT_OUT0_SEL_W { DDFT_OUT0_SEL_W { w: self } } #[doc = "Bits 20:22 - Specifies signal that is connected to 'ddft_out\\[1\\]' (digital DfT output signal 1): In I2C mode (CTRL.MODE=0), '0': Constant '0'. '1': 'clk_ff_sram'. '2': 'rst_i2c_n'. '3': 'rst_i2c_stop_n'. '4': 'i2c_sda_in_qual'. '5': 'i2c_sda_out'. '6': 'event_i2c_ec_wake_up_ddft' from I2CS_IC '7': Undefined. In SPI mode (CTRL.MODE=1), '0': Constant '0'. '1': 'spi_start_detect' '2': 'spi_stop_detect' '3'-'7': Undefined."] #[inline(always)] pub fn ddft_out1_sel(&mut self) -> DDFT_OUT1_SEL_W { DDFT_OUT1_SEL_W { w: self } } }
#![allow(clippy::use_self)] // Gives a false positive on the Logos proc-macro #![allow(clippy::non_ascii_literal)] use logos::Logos; pub type Lexer<'a> = logos::Lexer<'a, TokenKind>; #[derive(Debug, Copy, Clone, PartialEq, Eq, Logos)] #[rustfmt::skip] #[logos(subpattern DecDigit = r"[0-9]")] #[logos(subpattern DecDigit_ = r"[0-9_]")] #[logos(subpattern BinDigit = r"[0-1]")] #[logos(subpattern BinDigit_ = r"[0-1_]")] #[logos(subpattern HexDigit = r"[0-9a-fA-F]")] #[logos(subpattern HexDigit_ = r"[0-9a-fA-F_]")] pub enum TokenKind { #[error] Error, #[regex(r"\s+")] Whitespace, #[regex(r"//[^\n]*")] LineComment, #[token(r"/*", block_comment)] BlockComment, #[token("break")] KwBreak, #[token("continue")] KwContinue, #[token("else")] KwElse, #[token("enum")] KwEnum, #[token("false")] KwFalse, #[token("fn")] KwFn, #[token("if")] KwIf, #[token("let")] KwLet, #[token("loop")] KwLoop, #[token("match")] KwMatch, #[token("mut")] KwMut, #[token("return")] KwReturn, #[token("struct")] KwStruct, #[token("true")] KwTrue, #[regex(r"(\p{XID_Start}|_)\p{XID_Continue}*")] Ident, #[regex(r"(?&DecDigit)(?&DecDigit_)*")] DecInt, #[regex(r"(0b|0B)(?&BinDigit)(?&BinDigit_)*")] BinInt, #[regex(r"(0x|0X)(?&HexDigit)(?&HexDigit_)*")] HexInt, #[regex(r"(?&DecDigit)(?&DecDigit_)*\.(?&DecDigit)(?&DecDigit_)*")] Float, #[regex(r"'[^']'")] SimpleChar, #[regex(r"'\\.'")] EscapedChar, #[regex(r"'\\(u|U)\{(?&HexDigit)(?&HexDigit_)*\}'")] UnicodeChar, #[regex(r#""([^"]|\\")*""#)] String, #[token("(")] LParen, #[token(")")] RParen, #[token("{")] LCurly, #[token("}")] RCurly, #[token(".")] Dot, #[token(",")] Comma, #[token(";")] Semicolon, #[token(":")] Colon, #[token("::")] ColonColon, #[token("->")] ThinArrow, #[token("=>")] FatArrow, #[token("_")] Underscore, #[token("+")] Plus, #[token("-")] Minus, #[token("*")] Star, #[token("/")] Slash, #[token("%")] Percent, #[token("!")] Bang, #[token("&&")] AndAnd, #[token("||")] OrOr, #[token("=")] Eq, #[token("==")] EqEq, #[token("!=")] BangEq, #[token("<")] Less, #[token("<=")] LessEq, #[token(">")] Greater, #[token(">=")] GreaterEq, } fn block_comment(lexer: &mut Lexer) { const OPEN: &str = "/*"; const CLOSE: &str = "*/"; let mut level = 1; while level > 0 && !lexer.remainder().is_empty() { let src = lexer.remainder(); if src.starts_with(OPEN) { level += 1; lexer.bump(OPEN.len()); } else if src.starts_with(CLOSE) { level -= 1; lexer.bump(CLOSE.len()); } else { lexer.bump(src.chars().next().unwrap().len_utf8()) } } } impl TokenKind { pub const fn is_trivia(self) -> bool { matches!( self, Self::Whitespace | Self::LineComment | Self::BlockComment ) } } #[cfg(test)] mod tests { use insta::*; fn test_lex(src: &str) { let got = crate::lex(src).collect::<Vec<_>>(); let mut settings = insta::Settings::new(); settings.set_snapshot_path("../snapshots"); settings.set_prepend_module_to_snapshot(false); settings.bind(|| assert_debug_snapshot!(got)); } macro_rules! test_lex { ($name:ident, $src:expr) => { #[test] fn $name() { test_lex($src); } }; } test_lex!(empty_file, ""); test_lex!( trivia, "// line comment /* block comment */ " ); test_lex!( keywords, r"break continue else enum false fn if let loop match mut return struct true" ); test_lex!(idents, "abc_DEF_123"); test_lex!(unicode_idents, "セイウチ"); test_lex!(dec_int, "123_456_7890"); test_lex!(bin_int, "0b101"); test_lex!(hex_int, "0x1234_56789_abc_def"); test_lex!(float, "123.456"); test_lex!(simple_char, "'a'"); test_lex!(escaped_char, r"'\n'"); test_lex!(unicode_char, r"'\u{0a}'"); test_lex!(simple_string, r#""hello world""#); test_lex!(escaped_string, r#""he said \"hello world\"""#); test_lex!(symbols, "() {} . , ; : :: -> => _"); test_lex!(operators, "+ - * / ! = == != < <= > >= || &&"); }
use specs::*; use types::*; use SystemInfo; use std::time::Duration; use component::channel::*; use component::event::*; use consts::timer::RESPAWN_TIME; use systems::missile::MissileHit; pub struct SetRespawnTimer { reader: Option<OnPlayerKilledReader>, } #[derive(SystemData)] pub struct SetRespawnTimerData<'a> { pub channel: Read<'a, OnPlayerKilled>, pub future: ReadExpect<'a, FutureDispatcher>, } impl<'a> System<'a> for SetRespawnTimer { type SystemData = SetRespawnTimerData<'a>; fn setup(&mut self, res: &mut Resources) { Self::SystemData::setup(res); self.reader = Some(res.fetch_mut::<OnPlayerKilled>().register_reader()); } fn run(&mut self, data: Self::SystemData) { for evt in data.channel.read(self.reader.as_mut().unwrap()) { let player = evt.player; data.future .run_delayed(Duration::from_secs(2), move |instant| { Some(TimerEvent { ty: *RESPAWN_TIME, instant, data: Some(Box::new(player)), }) }); } } } impl SystemInfo for SetRespawnTimer { type Dependencies = MissileHit; fn name() -> &'static str { concat!(module_path!(), "::", line!()) } fn new() -> Self { Self { reader: None } } }
pub mod housing_parameters; pub use housing_parameters::HousingParameters;
use malvolio::prelude::*; use crate::prelude::*; #[test] fn diffing_regression_2021_06_06() { let mut before = H1::new("") .raw_attribute("¡", "") .wrap() .into_element(vec![0]); let expected_after = H1::new("").wrap().into_element(vec![0]); let diff_before = before.clone(); let cs = diff_before.diff(Some(&expected_after)); dbg!(&cs); cs.apply(&mut before); assert_eq!(before, expected_after); }
use intrusive_collections::{intrusive_adapter, LinkedList, LinkedListLink}; const NUM_PLAYERS: usize = 455; const NUM_MARBLES: usize = 71223; struct Marble { value: usize, link: LinkedListLink, } impl Marble { fn new(value: usize) -> Box<Self> { Box::new(Marble { value, link: LinkedListLink::new(), }) } } intrusive_adapter!(MarbleAdapter = Box<Marble>: Marble { link: LinkedListLink }); macro_rules! cw { ($cursor:expr) => { let cursor = &mut $cursor; cursor.move_next(); if cursor.is_null() { cursor.move_next(); } }; } macro_rules! ccw { ($cursor:expr) => { let cursor = &mut $cursor; cursor.move_prev(); if cursor.is_null() { cursor.move_prev(); } }; } struct Game { num_players: usize, num_marbles: usize, } impl Game { fn new(num_players: usize, num_marbles: usize) -> Self { Game { num_players, num_marbles, } } fn high_score(&self) -> usize { let mut scores = vec![0; self.num_players]; let mut circle = LinkedList::new(MarbleAdapter::new()); circle.push_front(Marble::new(0)); let mut curr_player = 0; let mut curr_marble = circle.front_mut(); for marble in 1..=self.num_marbles { if marble % 23 == 0 { let player_score = &mut scores[curr_player]; *player_score += marble; for _ in 0..7 { ccw!(curr_marble); } let removed = curr_marble.remove().unwrap(); *player_score += removed.value; } else { cw!(curr_marble); curr_marble.insert_after(Marble::new(marble)); cw!(curr_marble); } curr_player = (curr_player + 1) % self.num_players; } *scores.iter().max().unwrap() } } fn part1() { let game = Game::new(NUM_PLAYERS, NUM_MARBLES); println!("{}", game.high_score()); } fn part2() { let game = Game::new(NUM_PLAYERS, NUM_MARBLES * 100); println!("{}", game.high_score()); } fn main() { part1(); part2(); }
use chrono::{NaiveDateTime}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Comment { pub id: String, pub user_id: u16, pub username: String, pub avatar_url: String, pub topic_id: String, pub content: String, pub agree_count: u16, pub disagree_count: u16, pub status: u8, pub create_time: NaiveDateTime, pub update_time: NaiveDateTime }
use auto_impl::auto_impl; #[auto_impl(Fn)] trait Greeter { fn greet<const N: usize>(&self, id: usize); } fn main() {}
//判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 // //示例 1: // //输入: 121 //输出: true //示例 2: // //输入: -121 //输出: false //解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 //示例 3: // //输入: 10 //输出: false //解释: 从右向左读, 为 01 。因此它不是一个回文数。 //进阶: // //你能不将整数转为字符串来解决这个问题吗? fn pow(a: u32, b: i32) -> u32 { if b == 0 { return 1; } let mut res = 1; for _i in 0..b { res *= a; } res } fn abs_i32(i: i32) -> u32 { if i < 0 { return (-(i+1) as u32) + 1; } i as u32 } fn reverse(num: i32) -> i32 { let mut res: u32 = 0; let mut abs_num: u32 = abs_i32(num); let n_neg: bool = num.ge(&0); let threshold:u32 = pow(2, 31)-(n_neg as u32); let mut all_num: Vec<u32> = vec![]; let mut level = -1; while abs_num.ne(&0) { let cur_num = abs_num % 10; abs_num = abs_num / 10; all_num.push(cur_num); level += 1; } for i in 0..all_num.len() { if level >= 9 && all_num[i] > 2 { return 0; } res += all_num[i] * pow(10, level); if res > threshold { return 0; } level -= 1; } if !n_neg { return (res as i32)*-1; } res as i32 } fn is_palindrome(num: i32) -> bool { if num < 0 { return false; } if num == reverse(num) { return true; } false } fn main() { assert_eq!(true, is_palindrome(0)); assert_eq!(true, is_palindrome(121)); assert_eq!(true, is_palindrome(2147447412)); assert_eq!(false, is_palindrome(2147447413)); assert_eq!(false, is_palindrome(-121)); println!("finish"); }
//! Unit test macro collections. //! //! Contains macros for asserting approximate equivalence for floating-point numbers, and for //! comparing whether or not two floating-point vectors (or any iterable) are approximately //! equivalent. #![warn(missing_docs)] #[macro_export] macro_rules! assert_fp_eq { ($lhs:expr, $rhs:expr, $eps:expr) => {{ assert!((($lhs - $rhs) as f64).abs() < $eps); }}; ($lhs:expr, $rhs:expr) => {{ const DEFAULT_EPS: f64 = 1.0e-6; assert_fp_eq!($lhs, $rhs, DEFAULT_EPS); }}; } #[macro_export] macro_rules! assert_fpvec_eq { ($lhs:expr, $rhs:expr, $eps:expr) => {{ use std::f64; assert!(($lhs.iter().zip($rhs.iter())).fold(f64::NEG_INFINITY, |acc, (l, r)| { acc.max((l.clone() as f64 - r.clone() as f64).abs()) }) < $eps); }}; ($lhs:expr, $rhs:expr) => {{ const DEFAULT_EPS: f64 = 1.0e-6; assert_fpvec_eq!($lhs, $rhs, DEFAULT_EPS); }}; } #[macro_export] macro_rules! assert_fpvec_neq { ($lhs:expr, $rhs:expr, $eps:expr) => {{ use std::f64; assert!(($lhs.iter().zip($rhs.iter())).fold(f64::NEG_INFINITY, |acc, (l, r)| { acc.max((l.clone() as f64 - r.clone() as f64).abs()) }) > $eps); }}; ($lhs:expr, $rhs:expr) => {{ const DEFAULT_EPS: f64 = 1.0e-6; assert_fpvec_neq!($lhs, $rhs, DEFAULT_EPS); }}; } #[cfg(test)] mod tests { #[test] fn test_assert_fp_eq() { assert_fp_eq!(5.1000001, 5.1000002); assert_fp_eq!(5.1000001, 5.1000002, 1e-4); } #[test] #[should_panic(expected = "assertion failed")] fn test_assert_fp_eq_fail() { assert_fp_eq!(5.1000001, 5.1000002, 1.0e-8); } #[test] fn test_assert_fpvec_eq() { assert_fpvec_eq!([5.1000001, 6.2000002], [5.1000002, 6.2000005]); assert_fpvec_eq!([5.1000001, 6.2000002], [5.1000002, 6.2000005], 1e-4); } #[test] #[should_panic(expected = "assertion failed")] fn test_assert_fpvec_eq_fail() { assert_fpvec_eq!([5.100000001, 6.200000002], [5.1000002, 6.2000005], 1e-8); } #[test] fn test_assert_fpvec_neq() { assert_fpvec_neq!([5.100001, 6.200002], [5.1000002, 6.2000005]); assert_fpvec_neq!([5.100000001, 6.200000002], [5.1000002, 6.2000005], 1e-8); } #[test] #[should_panic(expected = "assertion failed")] fn test_assert_fpvec_neq_fail() { assert_fpvec_neq!([5.1000001, 6.2000002], [5.1000002, 6.2000005]); } }
#[doc = "Register `BMCR` reader"] pub type R = crate::R<BMCR_SPEC>; #[doc = "Register `BMCR` writer"] pub type W = crate::W<BMCR_SPEC>; #[doc = "Field `BME` reader - Burst Mode enable"] pub type BME_R = crate::BitReader; #[doc = "Field `BME` writer - Burst Mode enable"] pub type BME_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BMOM` reader - Burst Mode operating mode"] pub type BMOM_R = crate::BitReader; #[doc = "Field `BMOM` writer - Burst Mode operating mode"] pub type BMOM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BMCLK` reader - Burst Mode Clock source"] pub type BMCLK_R = crate::FieldReader; #[doc = "Field `BMCLK` writer - Burst Mode Clock source"] pub type BMCLK_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `BMPRSC` reader - Burst Mode Prescaler"] pub type BMPRSC_R = crate::FieldReader; #[doc = "Field `BMPRSC` writer - Burst Mode Prescaler"] pub type BMPRSC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `BMPREN` reader - Burst Mode Preload Enable"] pub type BMPREN_R = crate::BitReader; #[doc = "Field `BMPREN` writer - Burst Mode Preload Enable"] pub type BMPREN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MTBM` reader - Master Timer Burst Mode"] pub type MTBM_R = crate::BitReader; #[doc = "Field `MTBM` writer - Master Timer Burst Mode"] pub type MTBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TABM` reader - Timer A Burst Mode"] pub type TABM_R = crate::BitReader; #[doc = "Field `TABM` writer - Timer A Burst Mode"] pub type TABM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TBBM` reader - Timer B Burst Mode"] pub type TBBM_R = crate::BitReader; #[doc = "Field `TBBM` writer - Timer B Burst Mode"] pub type TBBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCBM` reader - Timer C Burst Mode"] pub type TCBM_R = crate::BitReader; #[doc = "Field `TCBM` writer - Timer C Burst Mode"] pub type TCBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TDBM` reader - Timer D Burst Mode"] pub type TDBM_R = crate::BitReader; #[doc = "Field `TDBM` writer - Timer D Burst Mode"] pub type TDBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TEBM` reader - Timer E Burst Mode"] pub type TEBM_R = crate::BitReader; #[doc = "Field `TEBM` writer - Timer E Burst Mode"] pub type TEBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BMSTAT` reader - Burst Mode Status"] pub type BMSTAT_R = crate::BitReader; #[doc = "Field `BMSTAT` writer - Burst Mode Status"] pub type BMSTAT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] pub fn bme(&self) -> BME_R { BME_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] pub fn bmom(&self) -> BMOM_R { BMOM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] pub fn bmclk(&self) -> BMCLK_R { BMCLK_R::new(((self.bits >> 2) & 0x0f) as u8) } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] pub fn bmprsc(&self) -> BMPRSC_R { BMPRSC_R::new(((self.bits >> 6) & 0x0f) as u8) } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] pub fn bmpren(&self) -> BMPREN_R { BMPREN_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] pub fn mtbm(&self) -> MTBM_R { MTBM_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] pub fn tabm(&self) -> TABM_R { TABM_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] pub fn tbbm(&self) -> TBBM_R { TBBM_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] pub fn tcbm(&self) -> TCBM_R { TCBM_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] pub fn tdbm(&self) -> TDBM_R { TDBM_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] pub fn tebm(&self) -> TEBM_R { TEBM_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] pub fn bmstat(&self) -> BMSTAT_R { BMSTAT_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] #[must_use] pub fn bme(&mut self) -> BME_W<BMCR_SPEC, 0> { BME_W::new(self) } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] #[must_use] pub fn bmom(&mut self) -> BMOM_W<BMCR_SPEC, 1> { BMOM_W::new(self) } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] #[must_use] pub fn bmclk(&mut self) -> BMCLK_W<BMCR_SPEC, 2> { BMCLK_W::new(self) } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] #[must_use] pub fn bmprsc(&mut self) -> BMPRSC_W<BMCR_SPEC, 6> { BMPRSC_W::new(self) } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] #[must_use] pub fn bmpren(&mut self) -> BMPREN_W<BMCR_SPEC, 10> { BMPREN_W::new(self) } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] #[must_use] pub fn mtbm(&mut self) -> MTBM_W<BMCR_SPEC, 16> { MTBM_W::new(self) } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] #[must_use] pub fn tabm(&mut self) -> TABM_W<BMCR_SPEC, 17> { TABM_W::new(self) } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] #[must_use] pub fn tbbm(&mut self) -> TBBM_W<BMCR_SPEC, 18> { TBBM_W::new(self) } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] #[must_use] pub fn tcbm(&mut self) -> TCBM_W<BMCR_SPEC, 19> { TCBM_W::new(self) } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] #[must_use] pub fn tdbm(&mut self) -> TDBM_W<BMCR_SPEC, 20> { TDBM_W::new(self) } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] #[must_use] pub fn tebm(&mut self) -> TEBM_W<BMCR_SPEC, 21> { TEBM_W::new(self) } #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] #[must_use] pub fn bmstat(&mut self) -> BMSTAT_W<BMCR_SPEC, 31> { BMSTAT_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 = "Burst Mode Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bmcr::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 [`bmcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct BMCR_SPEC; impl crate::RegisterSpec for BMCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`bmcr::R`](R) reader structure"] impl crate::Readable for BMCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`bmcr::W`](W) writer structure"] impl crate::Writable for BMCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets BMCR to value 0"] impl crate::Resettable for BMCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub const __AUDIT_ARCH_CONVENTION_MASK: u32 = 0x3000_0000; pub const __AUDIT_ARCH_CONVENTION_MIPS64_N32: u32 = 0x2000_0000; pub const __AUDIT_ARCH_64BIT: u32 = 0x0800_0000; pub const __AUDIT_ARCH_LE: u32 = 0x4000_0000; pub const AUDIT_ARCH_AARCH64: u32 = 0xC000_00B7; pub const AUDIT_ARCH_ALPHA: u32 = 0xC000_9026; pub const AUDIT_ARCH_ARM: u32 = 0x4000_0028; pub const AUDIT_ARCH_ARMEB: u32 = 0x28; pub const AUDIT_ARCH_CRIS: u32 = 0x4000_004C; pub const AUDIT_ARCH_FRV: u32 = 0x5441; pub const AUDIT_ARCH_I386: u32 = 0x4000_0003; pub const AUDIT_ARCH_IA64: u32 = 0xC000_0032; pub const AUDIT_ARCH_M32R: u32 = 0x58; pub const AUDIT_ARCH_M68K: u32 = 0x04; pub const AUDIT_ARCH_MICROBLAZE: u32 = 0xBD; pub const AUDIT_ARCH_MIPS: u32 = 0x08; pub const AUDIT_ARCH_MIPSEL: u32 = 0x4000_0008; pub const AUDIT_ARCH_MIPS64: u32 = 0x8000_0008; pub const AUDIT_ARCH_MIPS64N32: u32 = 0xA000_0008; pub const AUDIT_ARCH_MIPSEL64: u32 = 0xC000_0008; pub const AUDIT_ARCH_MIPSEL64N32: u32 = 0xE000_0008; pub const AUDIT_ARCH_OPENRISC: u32 = 92; pub const AUDIT_ARCH_PARISC: u32 = 15; pub const AUDIT_ARCH_PARISC64: u32 = 0x8000_000F; pub const AUDIT_ARCH_PPC: u32 = 20; pub const AUDIT_ARCH_PPC64: u32 = 0x8000_0015; pub const AUDIT_ARCH_PPC64LE: u32 = 0xC000_0015; pub const AUDIT_ARCH_S390: u32 = 22; pub const AUDIT_ARCH_S390X: u32 = 0x8000_0016; pub const AUDIT_ARCH_SH: u32 = 42; pub const AUDIT_ARCH_SHEL: u32 = 0x4000_002A; pub const AUDIT_ARCH_SH64: u32 = 0x8000_002A; pub const AUDIT_ARCH_SHEL64: u32 = 0xC000_002A; pub const AUDIT_ARCH_SPARC: u32 = 2; pub const AUDIT_ARCH_SPARC64: u32 = 0x8000_002B; pub const AUDIT_ARCH_TILEGX: u32 = 0xC000_00BF; pub const AUDIT_ARCH_TILEGX32: u32 = 0x4000_00BF; pub const AUDIT_ARCH_TILEPRO: u32 = 0x4000_00BC; pub const AUDIT_ARCH_X86_64: u32 = 0xC000_003E;
use anyhow::Result; use rusoto_credential::{AwsCredentials, ChainProvider, ProvideAwsCredentials}; use tokio; async fn find_credentials() -> Result<AwsCredentials> { let provider = ChainProvider::new(); let credentials = provider.credentials().await?; Ok(credentials) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let credentials = find_credentials().await?; println!("Found AWS credentials: {:?}", credentials); Ok(()) }
use super::*; use super::*; use crate::gui::*; use physics::*; use physics::*; #[derive(Default, Clone)] pub struct ControllingSystem; impl<'a> System<'a> for ControllingSystem { type SystemData = (WriteExpect<'a, Touches>, Write<'a, AppState>); fn run(&mut self, data: Self::SystemData) { let (touches, mut app_state) = data; #[cfg(any(target_os = "android"))] { let controlling = touches.iter().filter(|x| x.is_some()).count() > 1; if let AppState::Play(ref mut play_state) = *app_state { match play_state { PlayState::Action => { if !controlling { *play_state = PlayState::Upgrade; } } PlayState::Upgrade => { if controlling { *play_state = PlayState::Action } } } } } } }
#![ allow( unused_imports ) ] pub(crate) mod e_handler ; pub(crate) mod color ; pub(crate) mod user_list ; mod import { pub(crate) use { chat_format :: { ServerMsg, ClientMsg } , async_runtime :: { * } , web_sys :: { *, console::log_1 as dbg } , ws_stream_wasm :: { * } , futures_codec :: { * } , futures_cbor_codec :: { Codec, Error as CodecError } , futures :: { prelude::*, stream::SplitStream, select, ready } , futures :: { channel::{ mpsc::{ unbounded, UnboundedReceiver, UnboundedSender } } } , log :: { * } , web_sys :: { * } , wasm_bindgen :: { prelude::*, JsCast } , gloo_events :: { * } , std :: { rc::Rc, convert::TryInto, cell::RefCell, io } , std :: { task::*, pin::Pin, collections::HashMap, panic } , regex :: { Regex } , js_sys :: { Date, Math } , pin_utils :: { pin_mut } , wasm_bindgen_futures :: { futures_0_3::spawn_local } , }; } use crate::{ import::*, e_handler::*, color::*, user_list::* }; const HELP: &str = "Available commands: /nick NEWNAME # change nick (must be between 1 and 15 word characters) /help # Print available commands"; // Called when the wasm module is instantiated // #[ wasm_bindgen( start ) ] // pub fn main() -> Result<(), JsValue> { panic::set_hook(Box::new(console_error_panic_hook::hook)); // Let's only log output when in debug mode // #[ cfg( debug_assertions ) ] // wasm_logger::init( wasm_logger::Config::new(Level::Debug).message_on_new_line() ); let program = async { let cform = get_id( "connect_form" ); let tarea = get_id( "chat_input" ); let chat = get_id( "chat_form" ); let cnick: HtmlInputElement = get_id( "connect_nick" ).unchecked_into(); cnick.set_value( random_name() ); let enter_evts = EHandler::new( &tarea, "keypress", false ); let csubmit_evts = EHandler::new( &cform, "submit" , false ); let creset_evts = EHandler::new( &cform, "reset" , false ); let reset_evts = EHandler::new( &chat , "reset" , false ); let (tx, rx) = unbounded(); spawn_local( on_disconnect( reset_evts, rx ) ); spawn_local( on_key ( enter_evts ) ); spawn_local( on_cresets ( creset_evts ) ); on_connect( csubmit_evts, tx ).await; info!( "main function ends" ); }; spawn_local( program ); Ok(()) } fn append_line( chat: &Element, time: f64, nick: &str, line: &str, color: &Color, color_all: bool ) { let p: HtmlElement = document().create_element( "p" ).expect_throw( "create p" ).unchecked_into(); let n: HtmlElement = document().create_element( "span" ).expect_throw( "create span" ).unchecked_into(); let m: HtmlElement = document().create_element( "span" ).expect_throw( "create span" ).unchecked_into(); let t: HtmlElement = document().create_element( "span" ).expect_throw( "create span" ).unchecked_into(); n.style().set_property( "color", &color.to_css() ).expect_throw( "set color" ); if color_all { m.style().set_property( "color", &color.to_css() ).expect_throw( "set color" ); } // Js needs milliseconds, where the server sends seconds // let time = Date::new( &( time * 1000 as f64 ).into() ); n.set_inner_text( &format!( "{}: ", nick ) ); m.set_inner_text( line ); t.set_inner_text( &format!( "{:02}:{:02}:{:02} - ", time.get_hours(), time.get_minutes(), time.get_seconds() ) ); n.set_class_name( "nick" ); m.set_class_name( "message_text" ); t.set_class_name( "time" ); p.append_child( &t ).expect( "Coundn't append child" ); p.append_child( &n ).expect( "Coundn't append child" ); p.append_child( &m ).expect( "Coundn't append child" ); // order is important here, we need to measure the scroll before adding the item // let max_scroll = chat.scroll_height() - chat.client_height(); chat.append_child( &p ).expect( "Coundn't append child" ); // Check whether we are scolled to the bottom. If so, we autoscroll new messages // into vies. If the user has scrolled up, we don't. // // We keep a margin of up to 2 pixels, because sometimes the two numbers don't align exactly. // if ( chat.scroll_top() - max_scroll ).abs() < 3 { p.scroll_into_view(); } } async fn on_msg( mut stream: impl Stream<Item=Result<ServerMsg, CodecError>> + Unpin ) { let chat = get_id( "chat" ); let mut u_list = UserList::new(); let mut colors: HashMap<usize, Color> = HashMap::new(); // for the server messages // colors.insert( 0, Color::random().light() ); while let Some( msg ) = stream.next().await { // TODO: handle io errors // let msg = match msg { Ok( msg ) => msg, _ => continue, }; debug!( "received message" ); match msg { ServerMsg::ChatMsg{ time, nick, sid, txt } => { let color = colors.entry( sid ).or_insert( Color::random().light() ); append_line( &chat, time as f64, &nick, &txt, color, false ); } ServerMsg::ServerMsg{ time, txt } => { append_line( &chat, time as f64, "Server", &txt, colors.get( &0 ).unwrap(), true ); } ServerMsg::Welcome{ time, users, txt } => { users.into_iter().for_each( |(s,n)| u_list.insert(s,n) ); let udiv = get_id( "users" ); u_list.render( udiv.unchecked_ref() ); append_line( &chat, time as f64, "Server", &txt, colors.get( &0 ).unwrap(), true ); // Client Welcome message // append_line( &chat, time as f64, "ws_stream_wasm Client", HELP, colors.get( &0 ).unwrap(), true ); } ServerMsg::NickChanged{ time, old, new, sid } => { append_line( &chat, time as f64, "Server", &format!( "{} has changed names => {}.", &old, &new ), colors.get( &0 ).unwrap(), true ); u_list.insert( sid, new ); } ServerMsg::NickUnchanged{ time, .. } => { append_line( &chat, time as f64, "Server", "Error: You specified your old nick instead of your new one, it's unchanged.", colors.get( &0 ).unwrap(), true ); } ServerMsg::NickInUse{ time, nick, .. } => { append_line( &chat, time as f64, "Server", &format!( "Error: The nick is already in use: '{}'.", &nick ), colors.get( &0 ).unwrap(), true ); } ServerMsg::NickInvalid{ time, nick, .. } => { append_line( &chat, time as f64, "Server", &format!( "Error: The nick you specify must be between 1 and 15 word characters, was invalid: '{}'.", &nick ), colors.get( &0 ).unwrap(), true ); } ServerMsg::UserJoined{ time, nick, sid } => { append_line( &chat, time as f64, "Server", &format!( "We welcome a new user, {}!", &nick ), colors.get( &0 ).unwrap(), true ); u_list.insert( sid, nick ); } ServerMsg::UserLeft{ time, nick, sid } => { u_list.remove( sid ); append_line( &chat, time as f64, "Server", &format!( "Sadly, {} has left us.", &nick ), colors.get( &0 ).unwrap(), true ); } _ => {} } } // The stream has closed, so we are disconnected // show_connect_form(); debug!( "leaving on_msg" ); } async fn on_submit ( mut submits: impl Stream< Item=Event > + Unpin , mut out : impl Sink < ClientMsg, Error=CodecError > + Unpin , ) { let chat = get_id( "chat" ); let nickre = Regex::new( r"^/nick (\w{1,15})" ).unwrap(); // Note that we always add a newline below, so we have to match it. // let helpre = Regex::new(r"^/help\n$").unwrap(); let textarea = get_id( "chat_input" ); let textarea: &HtmlTextAreaElement = textarea.unchecked_ref(); while let Some( evt ) = submits.next().await { debug!( "on_submit" ); evt.prevent_default(); let text = textarea.value().trim().to_string() + "\n"; textarea.set_value( "" ); let _ = textarea.focus(); if text == "\n" { continue; } let msg; // if this is a /nick somename message // if let Some( cap ) = nickre.captures( &text ) { debug!( "handle set nick: {:#?}", &text ); msg = ClientMsg::SetNick( cap[1].to_string() ); } // if this is a /help message // else if helpre.is_match( &text ) { debug!( "handle /help: {:#?}", &text ); append_line( &chat, Date::now(), "ws_stream_wasm Client", HELP, &Color::random().light(), true ); return; } else { debug!( "handle send: {:#?}", &text ); msg = ClientMsg::ChatMsg( text ); } match out.send( msg ).await { Ok(()) => {} Err(e) => { match e { // We lost the connection to the server // CodecError::Io(err) => match err.kind() { io::ErrorKind::NotConnected => { error!( "The connection to the server was lost" ); // Show login screen... // show_connect_form(); } _ => error!( "{}", &err ), }, _ => error!( "{}", &e ), } } }; }; } // When the user presses the Enter key in the textarea we submit, rather than adding a new line // for newline, the user can use shift+Enter. // // We use the click effect on the Send button, because form.submit() wont let our on_submit handler run. // async fn on_key ( mut keys: impl Stream< Item=Event > + Unpin , ) { let send: HtmlElement = get_id( "chat_submit" ).unchecked_into(); while let Some( evt ) = keys.next().await { let evt: KeyboardEvent = evt.unchecked_into(); if evt.code() == "Enter" && !evt.shift_key() { send.click(); evt.prevent_default(); } }; } async fn on_connect( mut evts: impl Stream< Item=Event > + Unpin, mut disconnect: UnboundedSender<WsMeta> ) { while let Some(evt) = evts.next().await { info!( "Connect button clicked" ); evt.prevent_default(); // validate form // let (nick, url) = match validate_connect_form() { Ok(ok) => ok, Err( _ ) => { // report error to the user // continue loop // unreachable!() } }; let (ws, wsio) = match WsMeta::connect( url, None ).await { Ok(conn) => conn, Err(e) => { // report error to the user // error!( "{}", e ); continue; } }; let framed = Framed::new( wsio, Codec::new() ); let (mut out, mut msgs) = framed.split(); let form = get_id( "chat_form" ); let on_send = EHandler::new( &form, "submit", false ); // hide the connect form // let cform: HtmlElement = get_id( "connect_form" ).unchecked_into(); // Ask the server to join // match out.send( ClientMsg::Join( nick ) ).await { Ok(()) => {} Err(e) => { error!( "{}", e ); } }; // Error handling // let cerror: HtmlElement = get_id( "connect_error" ).unchecked_into(); if let Some(response) = msgs.next().await { match response { Ok( ServerMsg::JoinSuccess ) => { info!( "got joinsuccess" ); cform.style().set_property( "display", "none" ).expect_throw( "set cform display none" ); disconnect.send( ws ).await.expect_throw( "send ws to disconnect" ); let msg = on_msg ( msgs ).fuse(); let sub = on_submit( on_send , out ).fuse(); pin_mut!( msg ); pin_mut!( sub ); // on_msg will end when the stream get's closed by disconnect. This way we will // stop on_submit as well. // select! { _ = msg => {} _ = sub => {} } } // Show an error message on the connect form and let the user try again // Ok( ServerMsg::NickInUse{ .. } ) => { cerror.set_inner_text( "The nick name is already in use. Please choose another." ); cerror.style().set_property( "display", "block" ).expect_throw( "set display block on cerror" ); continue; } Ok( ServerMsg::NickInvalid{ .. } ) => { cerror.set_inner_text( "The nick name is invalid. It must be between 1 and 15 word characters." ); cerror.style().set_property( "display", "block" ).expect_throw( "set display block on cerror" ); continue; } // cbor decoding error // Err(e) => { error!( "{}", e ); } _ => { } } } } error!( "on_connect ends" ); } fn validate_connect_form() -> Result< (String, String), () > { let nick_field: HtmlInputElement = get_id( "connect_nick" ).unchecked_into(); let url_field : HtmlInputElement = get_id( "connect_url" ).unchecked_into(); let nick = nick_field.value(); let url = url_field .value(); Ok((nick, url)) } async fn on_cresets( mut evts: impl Stream< Item=Event > + Unpin ) { while let Some( evt ) = evts.next().await { evt.prevent_default(); let cnick: HtmlInputElement = get_id( "connect_nick" ).unchecked_into(); let curl : HtmlInputElement = get_id( "connect_url" ).unchecked_into(); cnick.set_value( random_name() ); curl .set_value( "ws://127.0.0.1:3412/chat" ); } } async fn on_disconnect( mut evts: impl Stream< Item=Event > + Unpin, mut wss: UnboundedReceiver<WsMeta> ) { let ws1: Rc<RefCell<Option<WsMeta>>> = Rc::new(RefCell::new( None )); let ws2 = ws1.clone(); let wss_in = async move { while let Some( ws ) = wss.next().await { *ws2.borrow_mut() = Some(ws); } }; spawn_local( wss_in ); while evts.next().await.is_some() { debug!( "on_disconnect" ); if let Some( ws_stream ) = ws1.borrow_mut().take() { ws_stream.close().await.expect_throw( "close ws" ); debug!( "connection closed by disconnect" ); show_connect_form(); } } } fn show_connect_form() { // show the connect form // let cform: HtmlElement = get_id( "connect_form" ).unchecked_into(); cform.style().set_property( "display", "flex" ).expect_throw( "set cform display none" ); get_id( "users" ).set_inner_html( "" ); get_id( "chat" ).set_inner_html( "" ); } pub fn document() -> Document { let window = web_sys::window().expect_throw( "no global `window` exists"); window.document().expect_throw( "should have a document on window" ) } // Return a random name // pub fn random_name() -> &'static str { // I wanted to use the crate scottish_names to generate a random username, but // it uses the rand crate which doesn't support wasm for now, so we're just using // a small sample. // let list = vec! [ "Aleeza" , "Aoun" , "Arya" , "Azaan" , "Ebony" , "Emke" , "Elena" , "Hafsa" , "Hailie" , "Inaaya" , "Iqra" , "Kobi" , "Noor" , "Nora" , "Nuala" , "Orin" , "Pippa" , "Rhuaridh" , "Salah" , "Susheela" , "Teya" ]; // pick one // list[ Math::floor( Math::random() * list.len() as f64 ) as usize ] } fn get_id( id: &str ) -> Element { document().get_element_by_id( id ).expect_throw( &format!( "find {}", id ) ) }
impl Solution { pub fn get_maximum_generated(n: i32) -> i32 { if n == 0{ return 0; } let mut res = vec![0;n as usize + 1]; res[1] = 1; for i in 2..=n as usize{ res[i] = res[i / 2] + (i & 1) * res[i / 2 + 1]; } res[0..=n as usize].iter().max().unwrap().to_owned() as i32 } }