text
stringlengths
8
4.13M
use day07::{part_1, part_2}; fn main() { let result1 = part_1(); println!("The highest signal that can be sent to thrusters is {}", result1); let result2 = part_2(); println!("The highest signal that can be sent to thrusters with is {}", result2) }
use std::{ error::Error, io::Read, sync::{Arc, Mutex}, }; use crate::database::Database; use crate::models::Post; use iron::{headers::ContentType, status, AfterMiddleware, Handler, IronResult, Request, Response}; use router::Router; use serde_json; use uuid::Uuid; macro_rules! handle_json { ($payload: expr) => { match $payload { Ok(payload) => payload, Err(err) => { return Ok(Response::with(( status::InternalServerError, err.description(), ))) } } }; ($payload: expr, $status: expr) => { match $payload { Ok(value) => value, Err(err) => return Ok(Response::with(($status, err.description()))), } }; } macro_rules! lock { ($mutex: expr) => { $mutex.lock().unwrap() }; } macro_rules! get_http_param { ($r:expr, $e:expr) => { match $r.extensions.get::<Router>() { Some(router) => match router.find($e) { Some(v) => v, None => return Ok(Response::with(status::BadRequest)), }, None => return Ok(Response::with(status::InternalServerError)), } }; } pub struct Handlers { pub find: Find, pub create: Create, pub find_by_id: FindById, } impl Handlers { pub fn new(db: Database) -> Handlers { let database = Arc::new(Mutex::new(db)); Handlers { find: Find::new(database.clone()), create: Create::new(database.clone()), find_by_id: FindById::new(database.clone()), } } } pub struct Find { database: Arc<Mutex<Database>>, } impl Find { fn new(database: Arc<Mutex<Database>>) -> Find { Find { database } } } impl Handler for Find { fn handle(&self, _req: &mut Request) -> IronResult<Response> { let db = lock!(self.database); let payload = handle_json!(serde_json::to_string(db.get_posts())); Ok(Response::with((status::Ok, payload))) } } pub struct Create { database: Arc<Mutex<Database>>, } impl Create { fn new(database: Arc<Mutex<Database>>) -> Create { Create { database } } } impl Handler for Create { fn handle(&self, req: &mut Request) -> IronResult<Response> { let mut payload = String::new(); handle_json!(req.body.read_to_string(&mut payload)); let post = handle_json!(serde_json::from_str(&payload), status::BadRequest); let mut db = lock!(self.database); db.add_post(post); Ok(Response::with((status::Created, payload))) } } pub struct FindById { database: Arc<Mutex<Database>>, } impl FindById { fn new(database: Arc<Mutex<Database>>) -> FindById { FindById { database } } fn find_post(&self, post_id: &Uuid) -> Option<Post> { let db = lock!(self.database); db.get_posts() .iter() .find(|p| p.post_id() == post_id) .map(|p| p.clone()) } } impl Handler for FindById { fn handle(&self, req: &mut Request) -> IronResult<Response> { let post_id = get_http_param!(req, "post_id"); let post_id = handle_json!(Uuid::parse_str(post_id), status::BadRequest); if let Some(post) = self.find_post(&post_id) { let payload = handle_json!(serde_json::to_string(&post), status::InternalServerError); Ok(Response::with((status::Ok, payload))) } else { Ok(Response::with((status::NotFound, "{}"))) } } } pub struct JsonAfterMiddleware; impl AfterMiddleware for JsonAfterMiddleware { fn after(&self, _: &mut Request, mut res: Response) -> IronResult<Response> { res.headers.set(ContentType::json()); Ok(res) } }
use std::collections::VecDeque; use std::collections::HashMap; #[derive(Debug)] pub struct FunctionCall { pub name: String, pub args_exprs: Vec<AstExpressionNode>, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum PointerType { // just a regular pointer, nothing special about it Raw, // Is freed when it goes out of scope, and can be "moved" Owned, } #[derive(Debug, Clone, PartialEq)] pub enum VarType { Int, Char, Pointer(PointerType, Box<VarType>), Struct(String), } #[derive(Debug, Clone, PartialEq)] pub struct FunctionType { pub return_type: VarType, pub arg_types: Vec<VarType>, pub is_var_args: bool, } #[derive(Debug, PartialEq, Clone, Copy)] pub enum BinaryOp { Plus, Minus, Multiply, Divide, CompareEqual, CompareGreater, CompareLess, CompareGreaterOrEqual, CompareLessOrEqual, CompareNotEqual, } #[derive(Debug)] pub enum Expression { Value(i32), SizeOf(VarType), Variable(String), StringValue(String), BinaryOp(BinaryOp, Box<AstExpressionNode>, Box<AstExpressionNode>), Call(FunctionCall), Reference(Box<AstExpressionNode>), // FIXME: Should eventually be an expression, not string // For now we'll say this is ok though. Dereference(Box<AstExpressionNode>), FieldAccess(Box<AstExpressionNode>, String), } // Part of AST. The "typ" field is set when we go to the type checker/annotator #[derive(Debug)] pub struct AstExpressionNode { pub expr: Expression, // Before type checking, it's None. // If it passes the type checker, it's guaranteed to be Some. pub typ: Option<VarType>, } impl AstExpressionNode { pub fn new(ex: Expression) -> AstExpressionNode { AstExpressionNode { expr: ex, typ: None } } } #[derive(Debug)] pub enum Statement { Return(AstExpressionNode), Print(AstExpressionNode), If(AstExpressionNode, Block, Option<Block>), While(AstExpressionNode, Block), Let(String, VarType, Option<AstExpressionNode>), Assign(AstExpressionNode, AstExpressionNode), Call(FunctionCall), } #[derive(Debug)] pub struct Block { pub statements: VecDeque<Statement>, } #[derive(Debug)] pub struct Function { pub name: String, pub statements: Block, pub args: Vec<String>, pub fn_type: FunctionType, } #[derive(Debug, Clone)] pub struct StructDefinition { pub name: String, pub fields: HashMap<String, VarType>, } #[derive(Debug)] pub struct Program { pub functions: Vec<Function>, pub structs: Vec<StructDefinition>, }
extern crate image; extern crate rand; use std::f32; use Circle; use Point; use ResultRaster; use RasterUtils; use std::fs::File; use std::path::Path; static LEN: usize = 66_049; // struct for a raster: this raster's pixels contain elevation data pub struct Raster{ pub pixels: Vec<Option<f32>>, // height array pub width: u32, // width of raster pub x0: f32, // related to extent? maybe corner in mercator pub y1: f32, // see above pub max_height: Option<f32>, pub min_height: Option<f32> } // add methods to raster impl Raster { pub fn new(source_raster: Vec<Option<f32>>, width: u32, x0: f32, y1: f32) -> Raster{ let mut r = Raster{ pixels: source_raster, width: width, x0: x0, y1: y1, max_height: None, min_height: None }; r.set_min_max(); r } // convert raster's pixel to image buffer pub fn to_img(&self) -> image::ImageBuffer<image::Luma<u8>, Vec<u8>> { let mut imgbuf = image::ImageBuffer::new(self.width, self.pixels.len() as u32/self.width); for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { let height = self.value_at(&Point::Point{x:x as i32,y:y as i32}); *pixel = match height { Some(h) => image::Luma([self.f32_to_u8(h)]), None => image::Luma([0]) }; } imgbuf } pub fn to_no_data(&self) -> image::ImageBuffer<image::Luma<u8>, Vec<u8>> { let mut imgbuf = image::ImageBuffer::new(self.width, self.pixels.len() as u32/self.width); let mut no_data_num = 0; for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { *pixel = match self.value_at(&Point::Point{x:x as i32,y:y as i32}) { Some(_) => image::Luma([255]), None => { no_data_num+=1; image::Luma([0]) } }; } println!("{} pixels without data.",no_data_num); imgbuf } // set the min and max vals on a raster pub fn set_min_max(& mut self){ self.max_height = Some(self.max()); self.min_height = Some(self.min()); } // find max pixel in raster, returns value pub fn max(&self) -> f32 { RasterUtils::max_in_raster_opt(&self.pixels) } // find min pixel in raster, returns value pub fn min(&self) -> f32 { RasterUtils::min_in_raster_opt(&self.pixels) } // fit to 0-255 - go from f32 height to u8 for greyscale image pub fn f32_to_u8(&self, height: f32) -> u8 { let max = self.max_height.unwrap(); let min = self.min_height.unwrap(); RasterUtils::f32_to_u8(min,max,height) } // save raster's pixels as png. this uses to_img to first get an image buf pub fn save_png(&self, file_path: &str){ let ref mut fout = File::create(&Path::new(file_path)).unwrap(); let _ = image::ImageLuma8(self.to_img()).save(fout, image::PNG); } // save raster's pixels as png. this uses to_img to first get an image buf pub fn save_png_no_data(&self, file_path: &str){ let ref mut fout = File::create(&Path::new(file_path)).unwrap(); let _ = image::ImageLuma8(self.to_no_data()).save(fout, image::PNG); } // distance formula pub fn get_dist(&self, p1: &Point::Point, p2: &Point::Point) -> f32 { (((p2.x-p1.x).pow(2) + (p2.y-p1.y).pow(2)) as f32).sqrt() } // slope formula pub fn get_slope(&self, p1: &Point::Point, p2: &Point::Point) -> Option<f32> { // let h1 = match self.value_at(p1) { // Some(h) => Some(h), // None => self.get_height_recur(p1) // }; // let h2 = match self.value_at(p2) { // Some(h) => Some(h), // None => self.get_height_recur(p2) // }; // let h1 = self.value_at(p1); // let h2 = self.value_at(p2); let h1 = RasterUtils::bilinear_interp_mid_point(&self.pixels, p1, self.width); let h2 = RasterUtils::bilinear_interp_mid_point(&self.pixels, p2, self.width); if h1.is_some() && h2.is_some() { Some(h2.unwrap()-h1.unwrap() as f32/self.get_dist(p1,p2)) } else { None } } fn get_pix_dist(&self, idx_1: usize, idx_2: usize) -> f32 { (idx_1 as isize % self.width as isize - idx_2 as isize % self.width as isize).abs() as f32 } // check 8 pixels around for height pub fn get_height_recur(&self,p: &Point::Point) -> Option<f32> { let mut heights: [Option<f32>;8] = [None;8]; heights[0] = self.value_at(&Point::Point{x:p.x+1,y:p.y}); heights[1] = self.value_at(&Point::Point{x:p.x-1,y:p.y}); heights[2] = self.value_at(&Point::Point{x:p.x,y:p.y+1}); heights[3] = self.value_at(&Point::Point{x:p.x,y:p.y-1}); heights[4] = self.value_at(&Point::Point{x:p.x+1,y:p.y+1}); heights[5] = self.value_at(&Point::Point{x:p.x-1,y:p.y-1}); heights[6] = self.value_at(&Point::Point{x:p.x-1,y:p.y+1}); heights[7] = self.value_at(&Point::Point{x:p.x+1,y:p.y-1}); let mut num_heights = 0; let heights_sum: f32 = heights.iter().fold(0.0, |acc, &pix_height| { match pix_height { Some(h) => { num_heights += 1; acc + h }, None => acc } }); if heights_sum != 0.0 { Some(heights_sum/num_heights as f32) } else { None } } // return pixel value @ x,y pub fn value_at(&self, point: &Point::Point) -> Option<f32> { let idx: i32 = (self.width as i32 * point.y as i32) + point.x as i32; if idx >= 0 && idx < 66_049 { self.pixels[idx as usize] } else { None } } // generate a test raster pub fn rand_raster() -> Raster{ Raster::new(Raster::rand_raster_source(), 256 as u32, rand::random::<f32>(), rand::random::<f32>()) } // do the generation here: currently the raster is flat. pub fn rand_raster_source() -> Vec<Option<f32>>{ // let mut last_height: f32 = 0.0; // let mut arr: [Option<f32>; 66_049] = [Some(5.5); 66_049]; // for i in 0..arr.len() { // let pos_or_neg: f32 = if rand::random::<f32>() > 0.5 { 1.0 } else { -1.0 }; // let curr_height = last_height + rand::random::<f32>() * pos_or_neg; // arr[i] = curr_height; // last_height = curr_height; // } // arr vec![Some(5.5); 66_049] } // perform viewshed pub fn do_viewshed(&self, origin: &Point::Point, radius: u32) -> ResultRaster::ResultRaster { let circle = RasterUtils::draw_circle(origin, radius); self.check_raster(circle, origin) } // check a raster pub fn check_raster(&self, circle: Circle::Circle, origin: &Point::Point) -> ResultRaster::ResultRaster { let mut result_vec = vec![None; LEN]; for point in &circle.edge { let line = RasterUtils::draw_line(origin,&point); let line_result = self.check_line(&line); let iter = line.iter().zip(line_result.iter()); for (point, result) in iter { if let Some(idx) = RasterUtils::point_to_idx(point, self.pixels.len(), self.width) { result_vec[idx] = Some(*result) } } } ResultRaster::ResultRaster::new(result_vec, self.width, self.x0, self.y1, circle) } // check a line of points for visibility from the first point pub fn check_line(&self, line: &Vec<Point::Point>) -> Vec<bool> { let origin = &line[0]; let mut highest_slope: f32 = f32::NEG_INFINITY; let mut last_was_true: bool = true; // take line of points, map to line of slopes line.iter() .map(|p: &Point::Point| { if p == origin { Some(f32::NEG_INFINITY) } else { self.get_slope(origin, p) } }) .collect::<Vec<Option<f32>>>() // take line of slopes, map to line of bools .iter() .map(|curr_slope: &Option<f32>|{ match *curr_slope { Some(x) => { if x == f32::NEG_INFINITY { true } else { if x >= highest_slope { highest_slope = x; last_was_true = true; true } else { last_was_true = false; false } } }, None => last_was_true } }) .collect::<Vec<bool>>() } // pub fn interp_raster(&mut self) { // } // pub fn wmercator_to_raster(&self,wmercator_point: Point) -> Point { // } // pub fn raster_to_wmercator(&self, raster_point: &Point) -> Point { // } //return an array that has slope value for each pixel pub fn to_slope_raster(&self) -> Vec<Option<f32>> { self.pixels.iter() .enumerate() .map(|enumerate_val|{ RasterUtils::get_max_slope_idx(&self.pixels, self.width, enumerate_val.0) }) .collect::<Vec<Option<f32>>>() } pub fn print_slope_png(&self, file_name: &str) { let slope_raster = self.to_slope_raster(); let max_slope = RasterUtils::max_in_raster_opt(&slope_raster); let min_slope = RasterUtils::min_in_raster_opt(&slope_raster); let mut buf: [u8; 66_049] = [0; 66_049]; for (idx, &slope) in slope_raster.iter().enumerate() { buf[idx] = match slope { Some(slope) => { RasterUtils::f32_to_u8(min_slope, max_slope, slope) }, None => { RasterUtils::f32_to_u8(min_slope, max_slope, 0.0) } } } image::save_buffer(&Path::new(file_name), &buf, self.width, self.pixels.len() as u32/self.width, image::Gray(8)).unwrap(); } }
pub struct MissingArmoredPublicKey; pub struct ArmoredPublicKeyExists; pub struct MissingAttachment; pub struct AttachmentExists; pub struct MissingAttachmentId; pub struct AttachmentIdExists; pub struct MissingBody; pub struct BodyExists; pub struct MissingBranch; pub struct BranchExists; pub struct MissingCloneAddr; pub struct CloneAddrExists; pub struct MissingCollaborator; pub struct CollaboratorExists; pub struct MissingColor; pub struct ColorExists; pub struct MissingConfig; pub struct ConfigExists; pub struct MissingContent; pub struct ContentExists; pub struct MissingDo; pub struct DoExists; pub struct MissingDueDate; pub struct DueDateExists; pub struct MissingEmail; pub struct EmailExists; pub struct MissingFilepath; pub struct FilepathExists; pub struct MissingId; pub struct IdExists; pub struct MissingIndex; pub struct IndexExists; pub struct MissingKey; pub struct KeyExists; pub struct MissingName; pub struct NameExists; pub struct MissingNewBranchName; pub struct NewBranchNameExists; pub struct MissingNewOwner; pub struct NewOwnerExists; pub struct MissingOrg; pub struct OrgExists; pub struct MissingOwner; pub struct OwnerExists; pub struct MissingPassword; pub struct PasswordExists; pub struct MissingQ; pub struct QExists; pub struct MissingRef; pub struct RefExists; pub struct MissingRepo; pub struct RepoExists; pub struct MissingRepoName; pub struct RepoNameExists; pub struct MissingSha; pub struct ShaExists; pub struct MissingTag; pub struct TagExists; pub struct MissingTagName; pub struct TagNameExists; pub struct MissingTime; pub struct TimeExists; pub struct MissingTitle; pub struct TitleExists; pub struct MissingType; pub struct TypeExists; pub struct MissingUid; pub struct UidExists; pub struct MissingUser; pub struct UserExists; pub struct MissingUsername; pub struct UsernameExists;
//! Translation of //! <http://www.cs.brandeis.edu/~storer/LunarLander/LunarLander/LunarLanderListing.jpg> //! by Jim Storer from FOCAL to Rust. use lunar::lander::Lander; use lunar::stdio::StdIO; use std::env; fn main() { let mut io = StdIO::default(); let args = env::args().collect::<Vec<String>>(); if args.len() > 1 { // If --echo is present, then write all input back to standard output. // (This is useful for testing with files as redirected input.) if args[1] == "--echo" { io.echo_input = true; } } io.greeting(); let mut lander = Lander::default(); loop { lander.play_game(&mut io); if !io.play_again() { break; } } io.farewell(); }
// Implementation based off of http://blog.libtorrent.org/2011/11/writing-a-fast-piece-picker/ use torrent::{Peer, Bitfield}; use std::ops::IndexMut; use control::cio; #[derive(Clone, Debug)] pub struct Picker { /// Current order of pieces pieces: Vec<u32>, /// Indices into pieces which indicate priority bounds priorities: Vec<usize>, /// Index mapping a piece to a position in the pieces field piece_idx: Vec<PieceInfo>, } #[derive(Clone, Debug, PartialEq)] enum PieceStatus { Incomplete, Complete, } #[derive(Clone, Debug)] struct PieceInfo { idx: usize, availability: usize, status: PieceStatus, } const PIECE_COMPLETE_INC: usize = 100; impl Picker { pub fn new(pieces: &Bitfield) -> Picker { let mut piece_idx = Vec::new(); for i in 0..pieces.len() { piece_idx.push(PieceInfo { idx: i as usize, availability: 0, status: PieceStatus::Incomplete, }); } let mut p = Picker { pieces: (0..pieces.len() as u32).collect(), piece_idx, priorities: vec![pieces.len() as usize], }; // Start every piece at an availability of 1. // This way when we decrement availability for an initial // pick we never underflow, and can keep track of which pieces // are unpicked(odd) and picked(even). // We additionally mark pieces as properly completed for i in 0..pieces.len() { p.piece_available(i as u32); if pieces.has_bit(i) { p.completed(i as u32); } } p } pub fn add_peer<T: cio::CIO>(&mut self, peer: &Peer<T>) { for idx in peer.pieces().iter() { self.piece_available(idx as u32); } } pub fn remove_peer<T: cio::CIO>(&mut self, peer: &Peer<T>) { for idx in peer.pieces().iter() { self.piece_unavailable(idx as u32); } } pub fn piece_available(&mut self, piece: u32) { self.inc_avail(piece); self.inc_avail(piece); } pub fn inc_avail(&mut self, piece: u32) { let (idx, avail) = { let piece = self.piece_idx.index_mut(piece as usize); self.priorities[piece.availability] -= 1; piece.availability += 1; if self.priorities.len() == piece.availability { self.priorities.push(self.pieces.len()); } (piece.idx, piece.availability - 1) }; let swap_idx = self.priorities[avail]; self.swap_piece(idx, swap_idx); } pub fn piece_unavailable(&mut self, piece: u32) { self.dec_avail(piece); self.dec_avail(piece); } pub fn dec_avail(&mut self, piece: u32) { let (idx, avail) = { let piece = self.piece_idx.index_mut(piece as usize); piece.availability -= 1; self.priorities[piece.availability] += 1; (piece.idx, piece.availability) }; let swap_idx = self.priorities[avail - 1]; self.swap_piece(idx, swap_idx); } pub fn pick<T: cio::CIO>(&mut self, peer: &Peer<T>) -> Option<u32> { // Find the first matching piece which is not complete, // and that the peer also has self.pieces.iter() .cloned() .filter(|p| self.piece_idx[*p as usize].status == PieceStatus::Incomplete) .find(|p| peer.pieces().has_bit(*p as u64)) .map(|p| { if (self.piece_idx[p as usize].availability % 2) == 0 { self.dec_avail(p); } p }) /* or bidx in 0..self.c.scale { let block = *pidx as u64 * self.c.scale + bidx; if !self.c.blocks.has_bit(block) { self.c.blocks.set_bit(block); let mut hs = HashSet::with_capacity(1); hs.insert(peer.id()); self.c.waiting_peers.insert(block, hs); self.c.waiting.insert(block); if self.c.endgame_cnt == 1 { // println!("Entering endgame!"); } self.c.endgame_cnt = self.c.endgame_cnt.saturating_sub(1); return Some(picker::Block { index: *pidx as u32, offset: bidx as u32 * 16384, }); } } */ } pub fn incomplete(&mut self, piece: u32) { self.piece_idx[piece as usize].status = PieceStatus::Incomplete; for _ in 0..PIECE_COMPLETE_INC { self.piece_unavailable(piece); } } pub fn completed(&mut self, piece: u32) { self.piece_idx[piece as usize].status = PieceStatus::Complete; // As hacky as this is, it's a good way to ensure that // we never waste time picking already selected pieces for _ in 0..PIECE_COMPLETE_INC { self.piece_available(piece); } //let idx: u64 = oidx as u64 * self.c.scale; //let offset: u64 = offset as u64 / 16384; //let block = idx + offset; //self.c.waiting.remove(&block); //let peers = self.c.waiting_peers.remove(&block).unwrap_or_else(|| { // HashSet::with_capacity(0) //}); //for i in 0..self.c.scale { // if (idx + i < self.c.blocks.len() && !self.c.blocks.has_bit(idx + i)) || // self.c.waiting.contains(&(idx + i)) // { // return (false, peers); // } //} // TODO: Make this less hacky somehow // let pri_idx = self.piece_idx[oidx as usize].availability; // let pinfo_idx = self.piece_idx[oidx as usize].idx; // for pri in self.priorities.iter_mut() { // if *pri > pri_idx as usize { // *pri -= 1; // } // } // for pinfo in self.piece_idx.iter_mut() { // if pinfo.idx > pinfo_idx { // pinfo.idx -= 1; // } // } // self.pieces.remove(pinfo_idx); } fn swap_piece(&mut self, a: usize, b: usize) { self.piece_idx[self.pieces[a] as usize].idx = b; self.piece_idx[self.pieces[b] as usize].idx = a; self.pieces.swap(a, b); } } #[cfg(test)] mod tests { use super::Picker; use torrent::{Peer, Bitfield}; #[test] fn test_available() { let b = Bitfield::new(3); let mut picker = Picker::new(&b); let mut peers = vec![ Peer::test_from_pieces(0, b.clone()), Peer::test_from_pieces(0, b.clone()), Peer::test_from_pieces(0, b.clone()), ]; assert_eq!(picker.pick(&peers[0]), None); peers[0].pieces_mut().set_bit(0); peers[1].pieces_mut().set_bit(0); peers[1].pieces_mut().set_bit(2); peers[2].pieces_mut().set_bit(1); for peer in peers.iter() { picker.add_peer(peer); } assert_eq!(picker.pick(&peers[1]), Some(2)); picker.completed(2); assert_eq!(picker.pick(&peers[1]), Some(0)); picker.completed(0); assert_eq!(picker.pick(&peers[1]), None); assert_eq!(picker.pick(&peers[0]), None); assert_eq!(picker.pick(&peers[2]), Some(1)); picker.completed(1); } #[test] fn test_unavailable() { let b = Bitfield::new(3); let mut picker = Picker::new(&b); let mut peers = vec![ Peer::test_from_pieces(0, b.clone()), Peer::test_from_pieces(0, b.clone()), Peer::test_from_pieces(0, b.clone()), ]; assert_eq!(picker.pick(&peers[0]), None); peers[0].pieces_mut().set_bit(0); peers[0].pieces_mut().set_bit(1); peers[1].pieces_mut().set_bit(1); peers[1].pieces_mut().set_bit(2); peers[2].pieces_mut().set_bit(0); peers[2].pieces_mut().set_bit(1); for peer in peers.iter() { picker.add_peer(peer); } picker.remove_peer(&peers[0]); assert_eq!(picker.pick(&peers[1]), Some(2)); picker.completed(2); assert_eq!(picker.pick(&peers[2]), Some(0)); picker.completed(0); assert_eq!(picker.pick(&peers[2]), Some(1)); picker.completed(1); assert_eq!(picker.pick(&peers[1]), None); picker.incomplete(1); assert_eq!(picker.pick(&peers[1]), Some(1)); } }
//! This module contains a different functions which are used by the [`Grid`]. //! //! You should use it if you want to comply with how [`Grid`]. //! //! [`Grid`]: crate::grid::iterable::Grid /// Returns string width and count lines of a string. It's a combination of [`string_width_multiline`] and [`count_lines`]. #[cfg(feature = "std")] pub fn string_dimension(text: &str) -> (usize, usize) { #[cfg(not(feature = "color"))] { let (lines, acc, max) = text.chars().fold((1, 0, 0), |(lines, acc, max), c| { if c == '\n' { (lines + 1, 0, acc.max(max)) } else { let w = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); (lines, acc + w, max) } }); (lines, acc.max(max)) } #[cfg(feature = "color")] { get_lines(text) .map(|line| string_width(&line)) .fold((0, 0), |(i, acc), width| (i + 1, acc.max(width))) } } /// Returns a string width. pub fn string_width(text: &str) -> usize { #[cfg(not(feature = "color"))] { unicode_width::UnicodeWidthStr::width(text) } #[cfg(feature = "color")] { // we need to strip ansi because of terminal links // and they're can't be stripped by ansi_str. ansitok::parse_ansi(text) .filter(|e| e.kind() == ansitok::ElementKind::Text) .map(|e| &text[e.start()..e.end()]) .map(unicode_width::UnicodeWidthStr::width) .sum() } } /// Returns a max string width of a line. pub fn string_width_multiline(text: &str) -> usize { #[cfg(not(feature = "color"))] { text.lines() .map(unicode_width::UnicodeWidthStr::width) .max() .unwrap_or(0) } #[cfg(feature = "color")] { text.lines().map(string_width).max().unwrap_or(0) } } /// Calculates a number of lines. pub fn count_lines(s: &str) -> usize { if s.is_empty() { return 1; } bytecount::count(s.as_bytes(), b'\n') + 1 } /// Returns a list of tabs (`\t`) in a string.. pub fn count_tabs(s: &str) -> usize { bytecount::count(s.as_bytes(), b'\t') } /// Splits the string by lines. #[cfg(feature = "std")] pub fn get_lines(text: &str) -> Lines<'_> { #[cfg(not(feature = "color"))] { // we call `split()` but not `lines()` in order to match colored implementation // specifically how we treat a trailing '\n' character. Lines { inner: text.split('\n'), } } #[cfg(feature = "color")] { Lines { inner: ansi_str::AnsiStr::ansi_split(text, "\n"), } } } /// Iterator over lines. /// /// In comparison to `std::str::Lines`, it treats trailing '\n' as a new line. #[allow(missing_debug_implementations)] #[cfg(feature = "std")] pub struct Lines<'a> { #[cfg(not(feature = "color"))] inner: std::str::Split<'a, char>, #[cfg(feature = "color")] inner: ansi_str::AnsiSplit<'a>, } #[cfg(feature = "std")] impl<'a> Iterator for Lines<'a> { type Item = std::borrow::Cow<'a, str>; fn next(&mut self) -> Option<Self::Item> { #[cfg(not(feature = "color"))] { self.inner.next().map(std::borrow::Cow::Borrowed) } #[cfg(feature = "color")] { self.inner.next() } } } #[cfg(feature = "std")] /// Replaces tabs in a string with a given width of spaces. pub fn replace_tab(text: &str, n: usize) -> std::borrow::Cow<'_, str> { if !text.contains('\t') { return std::borrow::Cow::Borrowed(text); } // it's a general case which probably must be faster? let replaced = if n == 4 { text.replace('\t', " ") } else { let mut text = text.to_owned(); replace_tab_range(&mut text, n); text }; std::borrow::Cow::Owned(replaced) } #[cfg(feature = "std")] fn replace_tab_range(cell: &mut String, n: usize) -> &str { let mut skip = 0; while let &Some(pos) = &cell[skip..].find('\t') { let pos = skip + pos; let is_escaped = pos > 0 && cell.get(pos - 1..pos) == Some("\\"); if is_escaped { skip = pos + 1; } else if n == 0 { cell.remove(pos); skip = pos; } else { // I'am not sure which version is faster a loop of 'replace' // or allacation of a string for replacement; cell.replace_range(pos..=pos, &" ".repeat(n)); skip = pos + 1; } if cell.is_empty() || skip >= cell.len() { break; } } cell } #[cfg(test)] mod tests { use super::*; #[test] fn string_width_emojie_test() { // ...emojis such as “joy”, which normally take up two columns when printed in a terminal // https://github.com/mgeisler/textwrap/pull/276 assert_eq!(string_width("🎩"), 2); assert_eq!(string_width("Rust 💕"), 7); assert_eq!(string_width_multiline("Go 👍\nC 😎"), 5); } #[cfg(feature = "color")] #[test] fn colored_string_width_test() { use owo_colors::OwoColorize; assert_eq!(string_width(&"hello world".red().to_string()), 11); assert_eq!( string_width_multiline(&"hello\nworld".blue().to_string()), 5 ); assert_eq!(string_width("\u{1b}[34m0\u{1b}[0m"), 1); assert_eq!(string_width(&"0".red().to_string()), 1); } #[test] fn count_lines_test() { assert_eq!( count_lines("\u{1b}[37mnow is the time for all good men\n\u{1b}[0m"), 2 ); assert_eq!(count_lines("now is the time for all good men\n"), 2); } #[cfg(feature = "color")] #[test] fn string_width_multinline_for_link() { assert_eq!( string_width_multiline( "\u{1b}]8;;file:///home/nushell/asd.zip\u{1b}\\asd.zip\u{1b}]8;;\u{1b}\\" ), 7 ); } #[cfg(feature = "color")] #[test] fn string_width_for_link() { assert_eq!( string_width("\u{1b}]8;;file:///home/nushell/asd.zip\u{1b}\\asd.zip\u{1b}]8;;\u{1b}\\"), 7 ); } #[cfg(feature = "std")] #[test] fn string_dimension_test() { assert_eq!( string_dimension("\u{1b}[37mnow is the time for all good men\n\u{1b}[0m"), { #[cfg(feature = "color")] { (2, 32) } #[cfg(not(feature = "color"))] { (2, 36) } } ); assert_eq!( string_dimension("now is the time for all good men\n"), (2, 32) ); assert_eq!(string_dimension("asd"), (1, 3)); assert_eq!(string_dimension(""), (1, 0)); } #[cfg(feature = "std")] #[test] fn replace_tab_test() { assert_eq!(replace_tab("123\t\tabc\t", 3), "123 abc "); assert_eq!(replace_tab("\t", 0), ""); assert_eq!(replace_tab("\t", 3), " "); assert_eq!(replace_tab("123\tabc", 3), "123 abc"); assert_eq!(replace_tab("123\tabc\tzxc", 0), "123abczxc"); assert_eq!(replace_tab("\\t", 0), "\\t"); assert_eq!(replace_tab("\\t", 4), "\\t"); assert_eq!(replace_tab("123\\tabc", 0), "123\\tabc"); assert_eq!(replace_tab("123\\tabc", 4), "123\\tabc"); } }
use std::ffi::OsStr; use std::fs::File; use std::io::{BufRead, BufReader}; use std::net::SocketAddr; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use log::debug; use log::error; use log::warn; use crate::base::check_access; use crate::base::{FileKind, Timestamp, UserContext}; use crate::client::NodeClient; use crate::ErrorCode; use fuser::consts::FOPEN_DIRECT_IO; use fuser::{ Filesystem, KernelConfig, ReplyAttr, ReplyBmap, ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyLock, ReplyOpen, ReplyStatfs, ReplyWrite, ReplyXattr, Request, TimeOrNow, }; use libc::ENOSYS; use std::collections::HashMap; use std::os::raw::c_int; use std::sync::Mutex; use std::time::{Duration, SystemTime, UNIX_EPOCH}; const FMODE_EXEC: i32 = 0x20; struct FileHandleAttributes { read: bool, write: bool, } pub struct FleetFUSE { client: NodeClient, next_file_handle: AtomicU64, direct_io: bool, file_handles: Mutex<HashMap<u64, FileHandleAttributes>>, } impl FleetFUSE { pub fn new(server_ip_port: SocketAddr, direct_io: bool) -> FleetFUSE { FleetFUSE { client: NodeClient::new(server_ip_port), next_file_handle: AtomicU64::new(1), direct_io, file_handles: Mutex::new(HashMap::new()), } } fn allocate_file_handle(&self, read: bool, write: bool) -> u64 { let handle = self.next_file_handle.fetch_add(1, Ordering::SeqCst); let mut handles = self .file_handles .lock() .expect("file_handles lock is poisoned"); handles.insert(handle, FileHandleAttributes { read, write }); handle } fn deallocate_file_handle(&self, handle: u64) { let mut handles = self .file_handles .lock() .expect("file_handles lock is poisoned"); handles.remove(&handle); } fn check_read(&self, handle: u64) -> bool { let handles = self .file_handles .lock() .expect("file_handles lock is poisoned"); if let Some(value) = handles.get(&handle).map(|x| x.read) { value } else { error!("Undefined file handle: {}", handle); false } } fn check_write(&self, handle: u64) -> bool { let handles = self .file_handles .lock() .expect("file_handles lock is poisoned"); if let Some(value) = handles.get(&handle).map(|x| x.write) { value } else { error!("Undefined file handle: {}", handle); false } } } fn into_fuse_error(error: ErrorCode) -> c_int { match error { ErrorCode::DoesNotExist => libc::ENOENT, ErrorCode::InodeDoesNotExist => libc::EBADFD, ErrorCode::Uncategorized => libc::EIO, ErrorCode::Corrupted => libc::EIO, ErrorCode::RaftFailure => libc::EIO, ErrorCode::BadResponse => libc::EIO, ErrorCode::BadRequest => libc::EIO, ErrorCode::FileTooLarge => libc::EFBIG, ErrorCode::AccessDenied => libc::EACCES, ErrorCode::OperationNotPermitted => libc::EPERM, ErrorCode::NameTooLong => libc::ENAMETOOLONG, ErrorCode::NotEmpty => libc::ENOTEMPTY, ErrorCode::MissingXattrKey => libc::ENODATA, ErrorCode::AlreadyExists => libc::EEXIST, ErrorCode::InvalidXattrNamespace => libc::ENOTSUP, } } // t_mode type is u16 on MacOS, but u32 on Linux #[allow(clippy::unnecessary_cast)] fn as_file_kind(mut mode: u32) -> FileKind { mode &= libc::S_IFMT as u32; if mode == libc::S_IFREG as u32 { FileKind::File } else if mode == libc::S_IFLNK as u32 { FileKind::Symlink } else if mode == libc::S_IFDIR as u32 { FileKind::Directory } else { unimplemented!("{}", mode); } } impl Filesystem for FleetFUSE { fn init(&mut self, _req: &Request, _config: &mut KernelConfig) -> Result<(), c_int> { Ok(()) } fn lookup(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) { let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; // TODO: avoid this double lookup match self .client .lookup(parent, name, UserContext::new(req.uid(), req.gid())) { Ok(inode) => match self.client.getattr(inode) { Ok(attr) => reply.entry(&Duration::new(0, 0), &attr, 0), Err(error_code) => reply.error(into_fuse_error(error_code)), }, Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn forget(&mut self, _req: &Request, _ino: u64, _nlookup: u64) {} fn getattr(&mut self, _req: &Request, inode: u64, reply: ReplyAttr) { debug!("getattr() called with {:?}", inode); match self.client.getattr(inode) { Ok(attr) => reply.attr(&Duration::new(0, 0), &attr), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn setattr( &mut self, req: &Request, inode: u64, mode: Option<u32>, uid: Option<u32>, gid: Option<u32>, size: Option<u64>, atime: Option<TimeOrNow>, mtime: Option<TimeOrNow>, _ctime: Option<SystemTime>, fh: Option<u64>, _crtime: Option<SystemTime>, _chgtime: Option<SystemTime>, _bkuptime: Option<SystemTime>, _flags: Option<u32>, reply: ReplyAttr, ) { if let Some(mode) = mode { debug!("chmod() called with {:?}, {:o}", inode, mode); if let Err(error_code) = self.client .chmod(inode, mode, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); return; } } if uid.is_some() || gid.is_some() { debug!("chown() called with {:?} {:?} {:?}", inode, uid, gid); if let Some(gid) = gid { // Non-root users can only change gid to a group they're in if req.uid() != 0 && !get_groups(req.pid()).contains(&gid) { reply.error(libc::EPERM); return; } } if let Err(error_code) = self.client .chown(inode, uid, gid, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); return; } } if let Some(size) = size { debug!("truncate() called with {:?}", inode); if let Some(handle) = fh { // If the file handle is available, check access locally. // This is important as it preserves the semantic that a file handle opened // with W_OK will never fail to truncate, even if the file has been subsequently // chmod'ed if self.check_write(handle) { if let Err(error_code) = self.client.truncate(inode, size, UserContext::new(0, 0)) { reply.error(into_fuse_error(error_code)); return; } } else { reply.error(libc::EACCES); return; } } else if let Err(error_code) = self.client .truncate(inode, size, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); return; } } if atime.is_some() || mtime.is_some() { debug!( "utimens() called with {:?}, {:?}, {:?}", inode, atime, mtime ); let atimestamp = atime.map(|time_or_now| match time_or_now { TimeOrNow::SpecificTime(x) => { let (seconds, nanos) = match x.duration_since(UNIX_EPOCH) { Ok(x) => (x.as_secs() as i64, x.subsec_nanos() as i32), // We get an error if the timestamp if before the epoch Err(error) => ( -(error.duration().as_secs() as i64), error.duration().subsec_nanos() as i32, ), }; Timestamp::new(seconds, nanos) } TimeOrNow::Now => Timestamp::new(0, libc::UTIME_NOW as i32), }); let mtimestamp = mtime.map(|time_or_now| match time_or_now { TimeOrNow::SpecificTime(x) => { let (seconds, nanos) = match x.duration_since(UNIX_EPOCH) { Ok(x) => (x.as_secs() as i64, x.subsec_nanos() as i32), // We get an error if the timestamp if before the epoch Err(error) => ( -(error.duration().as_secs() as i64), error.duration().subsec_nanos() as i32, ), }; Timestamp::new(seconds, nanos) } TimeOrNow::Now => Timestamp::new(0, libc::UTIME_NOW as i32), }); if let Err(error_code) = self.client.utimens( inode, atimestamp, mtimestamp, UserContext::new(req.uid(), req.gid()), ) { reply.error(into_fuse_error(error_code)); return; } } match self.client.getattr(inode) { Ok(attr) => reply.attr(&Duration::new(0, 0), &attr), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn readlink(&mut self, _req: &Request, inode: u64, reply: ReplyData) { debug!("readlink() called on {:?}", inode); match self.client.readlink(inode) { Ok(data) => reply.data(&data), Err(error_code) => reply.error(into_fuse_error(error_code)), } } // t_mode type is u16 on MacOS, but u32 on Linux #[allow(clippy::unnecessary_cast)] fn mknod( &mut self, req: &Request, parent: u64, name: &OsStr, mode: u32, _umask: u32, _rdev: u32, reply: ReplyEntry, ) { let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; let file_type = mode & libc::S_IFMT as u32; if file_type != libc::S_IFREG as u32 && file_type != libc::S_IFLNK as u32 && file_type != libc::S_IFDIR as u32 { // TODO warn!("mknod() implementation is incomplete. Only supports regular files, symlinks, and directories. Got {:o}", mode); reply.error(libc::ENOSYS); } else { match self.client.create( parent, name, req.uid(), req.gid(), mode as u16, as_file_kind(mode), ) { Ok(attr) => reply.entry(&Duration::new(0, 0), &attr, 0), Err(error_code) => reply.error(into_fuse_error(error_code)), } } } fn mkdir( &mut self, req: &Request, parent: u64, name: &OsStr, mode: u32, _umask: u32, reply: ReplyEntry, ) { debug!("mkdir() called with {:?} {:?} {:o}", parent, name, mode); let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; match self .client .mkdir(parent, name, req.uid(), req.gid(), mode as u16) { Ok(attr) => reply.entry(&Duration::new(0, 0), &attr, 0), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn unlink(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) { debug!("unlink() called with {:?} {:?}", parent, name); let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; if let Err(error_code) = self.client .unlink(parent, name, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn rmdir(&mut self, req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) { debug!("rmdir() called with {:?} {:?}", parent, name); let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; if let Err(error_code) = self.client .rmdir(parent, name, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn symlink( &mut self, req: &Request, parent: u64, name: &OsStr, link: &Path, reply: ReplyEntry, ) { debug!("symlink() called with {:?} {:?} {:?}", parent, name, link); let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; let link = if let Some(value) = link.to_str() { value } else { error!("Link is not UTF-8"); reply.error(libc::EINVAL); return; }; match self .client .create(parent, name, req.uid(), req.gid(), 0o755, FileKind::Symlink) { Ok(attrs) => { if let Err(error_code) = self.client .truncate(attrs.ino, 0, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); return; } if let Err(error_code) = self.client .write(attrs.ino, &Vec::from(link.to_string()), 0) { reply.error(into_fuse_error(error_code)); return; } reply.entry(&Duration::new(0, 0), &attrs, 0); } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn rename( &mut self, req: &Request, parent: u64, name: &OsStr, new_parent: u64, new_name: &OsStr, _flags: u32, reply: ReplyEmpty, ) { let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; let new_name = if let Some(value) = new_name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; if let Err(error_code) = self.client.rename( parent, name, new_parent, new_name, UserContext::new(req.uid(), req.gid()), ) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn link( &mut self, req: &Request, inode: u64, new_parent: u64, new_name: &OsStr, reply: ReplyEntry, ) { debug!( "link() called for {}, {}, {:?}", inode, new_parent, new_name ); let new_name = if let Some(value) = new_name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; match self.client.hardlink( inode, new_parent, new_name, UserContext::new(req.uid(), req.gid()), ) { Ok(attr) => reply.entry(&Duration::new(0, 0), &attr, 0), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn open(&mut self, req: &Request, inode: u64, flags: i32, reply: ReplyOpen) { debug!("open() called for {:?}", inode); let (access_mask, read, write) = match flags & libc::O_ACCMODE { libc::O_RDONLY => { // Behavior is undefined, but most filesystems return EACCES if flags & libc::O_TRUNC != 0 { reply.error(libc::EACCES); return; } if flags & FMODE_EXEC != 0 { // Open is from internal exec syscall (libc::X_OK, true, false) } else { (libc::R_OK, true, false) } } libc::O_WRONLY => (libc::W_OK, false, true), libc::O_RDWR => (libc::R_OK | libc::W_OK, true, true), // Exactly one access mode flag must be specified _ => { reply.error(libc::EINVAL); return; } }; match self.client.getattr(inode) { Ok(attr) => { if check_access( attr.uid, attr.gid, attr.perm, req.uid(), req.gid(), access_mask, ) { let flags = if self.direct_io { FOPEN_DIRECT_IO } else { 0 }; reply.opened(self.allocate_file_handle(read, write), flags); } else { reply.error(libc::EACCES); } } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn read( &mut self, _req: &Request, inode: u64, fh: u64, offset: i64, size: u32, _flags: i32, _lock_owner: Option<u64>, reply: ReplyData, ) { debug!("read() called on {:?}", inode); assert!(offset >= 0); if !self.check_read(fh) { reply.error(libc::EACCES); return; } self.client .read(inode, offset as u64, size, move |result| match result { Ok(data) => reply.data(data), Err(error_code) => reply.error(into_fuse_error(error_code)), }); } fn write( &mut self, _req: &Request, inode: u64, fh: u64, offset: i64, data: &[u8], _write_flags: u32, _flags: i32, _lock_owner: Option<u64>, reply: ReplyWrite, ) { debug!("write() called with {:?}", inode); assert!(offset >= 0); if !self.check_write(fh) { reply.error(libc::EACCES); return; } match self.client.write(inode, data, offset as u64) { Ok(written) => reply.written(written), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn flush(&mut self, _req: &Request, inode: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) { debug!("flush() called on {:?}", inode); reply.error(ENOSYS); } fn release( &mut self, _req: &Request, inode: u64, fh: u64, _flags: i32, _lock_owner: Option<u64>, _flush: bool, reply: ReplyEmpty, ) { debug!("release() called on {:?} {}", inode, fh); self.deallocate_file_handle(fh); reply.ok(); } fn fsync(&mut self, _req: &Request, inode: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) { debug!("fsync() called with {:?}", inode); if let Err(error_code) = self.client.fsync(inode) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn opendir(&mut self, req: &Request, inode: u64, flags: i32, reply: ReplyOpen) { debug!("opendir() called on {:?}", inode); let (access_mask, read, write) = match flags & libc::O_ACCMODE { libc::O_RDONLY => { // Behavior is undefined, but most filesystems return EACCES if flags & libc::O_TRUNC != 0 { reply.error(libc::EACCES); return; } (libc::R_OK, true, false) } libc::O_WRONLY => (libc::W_OK, false, true), libc::O_RDWR => (libc::R_OK | libc::W_OK, true, true), // Exactly one access mode flag must be specified _ => { reply.error(libc::EINVAL); return; } }; match self.client.getattr(inode) { Ok(attr) => { if check_access( attr.uid, attr.gid, attr.perm, req.uid(), req.gid(), access_mask, ) { let flags = if self.direct_io { FOPEN_DIRECT_IO } else { 0 }; reply.opened(self.allocate_file_handle(read, write), flags); } else { reply.error(libc::EACCES); } } Err(error_code) => reply.error(into_fuse_error(error_code)), } } // TODO: send offset to server and do pagination fn readdir( &mut self, _req: &Request, inode: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory, ) { debug!("readdir() called with {:?}", inode); assert!(offset >= 0); match self.client.readdir(inode) { Ok(entries) => { for (index, entry) in entries.iter().skip(offset as usize).enumerate() { let (inode, name, file_type) = entry; let buffer_full: bool = reply.add(*inode, offset + index as i64 + 1, *file_type, name); if buffer_full { break; } } reply.ok(); } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn releasedir(&mut self, _req: &Request, inode: u64, fh: u64, _flags: i32, reply: ReplyEmpty) { debug!("releasedir() called on {:?} {}", inode, fh); self.deallocate_file_handle(fh); reply.ok(); } fn fsyncdir( &mut self, _req: &Request, inode: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty, ) { debug!("fsyncdir() called with {:?}", inode); if let Err(error_code) = self.client.fsync(inode) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn statfs(&mut self, _req: &Request, _ino: u64, reply: ReplyStatfs) { debug!("statfs()"); match self.client.statfs() { Ok(info) => reply.statfs( 10, 10, 10, 1, 10, info.block_size, info.max_name_length, 4096, ), Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn setxattr( &mut self, req: &Request, inode: u64, name: &OsStr, value: &[u8], _flags: i32, _position: u32, reply: ReplyEmpty, ) { debug!("setxattr() called with {:?} {:?} {:?}", inode, name, value); let name = if let Some(value) = name.to_str() { value } else { error!("Key is not UTF-8"); reply.error(libc::EINVAL); return; }; if let Err(error_code) = self.client .setxattr(inode, name, value, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn getxattr(&mut self, req: &Request, inode: u64, name: &OsStr, size: u32, reply: ReplyXattr) { debug!("getxattr() called with {:?} {:?}", inode, name); let name = if let Some(value) = name.to_str() { value } else { error!("Key is not UTF-8"); reply.error(libc::EINVAL); return; }; match self .client .getxattr(inode, name, UserContext::new(req.uid(), req.gid())) { Ok(data) => { if size == 0 { reply.size(data.len() as u32); } else if data.len() <= size as usize { reply.data(&data); } else { reply.error(libc::ERANGE); } } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn listxattr(&mut self, _req: &Request, inode: u64, size: u32, reply: ReplyXattr) { debug!("listxattr() called with {:?}", inode); match self.client.listxattr(inode).map(|xattrs| { let mut bytes = vec![]; // Convert to concatenated null-terminated strings for attr in xattrs { bytes.extend(attr.as_bytes()); bytes.push(0); } bytes }) { Ok(data) => { if size == 0 { reply.size(data.len() as u32); } else if data.len() <= size as usize { reply.data(&data); } else { reply.error(libc::ERANGE); } } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn removexattr(&mut self, req: &Request, inode: u64, name: &OsStr, reply: ReplyEmpty) { debug!("removexattr() called with {:?} {:?}", inode, name); let name = if let Some(value) = name.to_str() { value } else { error!("Key is not UTF-8"); reply.error(libc::EINVAL); return; }; if let Err(error_code) = self.client .removexattr(inode, name, UserContext::new(req.uid(), req.gid())) { reply.error(into_fuse_error(error_code)); } else { reply.ok(); } } fn access(&mut self, req: &Request, inode: u64, mask: i32, reply: ReplyEmpty) { debug!("access() called with {:?} {:?}", inode, mask); match self.client.getattr(inode) { Ok(attr) => { if check_access(attr.uid, attr.gid, attr.perm, req.uid(), req.gid(), mask) { reply.ok(); } else { reply.error(libc::EACCES); } } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn create( &mut self, req: &Request, parent: u64, name: &OsStr, mode: u32, _umask: u32, flags: i32, reply: ReplyCreate, ) { debug!("create() called with {:?} {:?}", parent, name); let name = if let Some(value) = name.to_str() { value } else { error!("Path component is not UTF-8"); reply.error(libc::EINVAL); return; }; let (read, write) = match flags & libc::O_ACCMODE { libc::O_RDONLY => (true, false), libc::O_WRONLY => (false, true), libc::O_RDWR => (true, true), // Exactly one access mode flag must be specified _ => { reply.error(libc::EINVAL); return; } }; match self.client.create( parent, name, req.uid(), req.gid(), mode as u16, as_file_kind(mode), ) { Ok(attr) => { let flags = if self.direct_io { FOPEN_DIRECT_IO } else { 0 }; // TODO: implement flags reply.created( &Duration::new(0, 0), &attr, 0, self.allocate_file_handle(read, write), flags, ) } Err(error_code) => reply.error(into_fuse_error(error_code)), } } fn getlk( &mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: i32, _pid: u32, reply: ReplyLock, ) { reply.error(ENOSYS); } fn setlk( &mut self, _req: &Request, _ino: u64, _fh: u64, _lock_owner: u64, _start: u64, _end: u64, _typ: i32, _pid: u32, _sleep: bool, reply: ReplyEmpty, ) { reply.error(ENOSYS); } fn bmap(&mut self, _req: &Request, _ino: u64, _blocksize: u32, _idx: u64, reply: ReplyBmap) { reply.error(ENOSYS); } } fn get_groups(pid: u32) -> Vec<u32> { let path = format!("/proc/{pid}/task/{pid}/status"); let file = File::open(path).unwrap(); for line in BufReader::new(file).lines() { let line = line.unwrap(); if line.starts_with("Groups:") { return line["Groups: ".len()..] .split(' ') .filter(|x| !x.trim().is_empty()) .map(|x| x.parse::<u32>().unwrap()) .collect(); } } vec![] }
use anyhow::Result; use criterion::{black_box, criterion_group, criterion_main, Criterion, ParameterizedBenchmark}; use filecoin_hashers::{ poseidon::PoseidonDomain, poseidon::PoseidonHasher, sha256::Sha256Hasher, Domain, }; use rand::{thread_rng, Rng}; use storage_proofs_core::merkle::{create_base_merkle_tree, BinaryMerkleTree}; fn merkle_benchmark_sha256(c: &mut Criterion) { let params = if cfg!(feature = "big-sector-sizes-bench") { vec![128, 1024, 1_048_576] } else { vec![128, 1024] }; c.bench( "merkletree-binary", ParameterizedBenchmark::new( "sha256", move |b, n_nodes| { let mut rng = thread_rng(); let data: Vec<u8> = (0..32 * *n_nodes).map(|_| rng.gen()).collect(); b.iter(|| { black_box( create_base_merkle_tree::<BinaryMerkleTree<Sha256Hasher>>( None, *n_nodes, &data, ) .unwrap(), ) }) }, params, ), ); } fn merkle_benchmark_poseidon(c: &mut Criterion) { let params = if cfg!(feature = "big-sector-sizes-bench") { vec![64, 128, 1024, 1_048_576] } else { vec![64, 128, 1024] }; c.bench( "merkletree-binary", ParameterizedBenchmark::new( "poseidon", move |b, n_nodes| { let mut rng = thread_rng(); let mut data: Vec<u8> = Vec::with_capacity(32 * *n_nodes); (0..*n_nodes) .into_iter() .try_for_each(|_| -> Result<()> { let node = PoseidonDomain::random(&mut rng); Ok(data.extend(node.into_bytes())) }) .expect("failed to generate data"); b.iter(|| { black_box( create_base_merkle_tree::<BinaryMerkleTree<PoseidonHasher>>( None, *n_nodes, &data, ) .unwrap(), ) }) }, params, ), ); } criterion_group!(benches, merkle_benchmark_sha256, merkle_benchmark_poseidon); criterion_main!(benches);
use std::{borrow::Cow, marker::PhantomData, ops::Range}; use async_trait::async_trait; use custodian_password::{ ClientConfig, ClientFile, ClientRegistration, RegistrationFinalization, RegistrationRequest, RegistrationResponse, }; use serde::{Deserialize, Serialize}; use crate::{ document::{Document, Header, KeyId}, schema::{ self, view, Key, Map, MappedDocument, MappedValue, NamedReference, Schema, SchemaName, }, transaction::{self, Command, Operation, OperationResult, Transaction}, Error, PASSWORD_CONFIG, }; /// Defines all interactions with a [`schema::Schema`], regardless of whether it is local or remote. #[async_trait] pub trait Connection: Send + Sync { /// Accesses a collection for the connected [`schema::Schema`]. fn collection<'a, C: schema::Collection + 'static>(&'a self) -> Collection<'a, Self, C> where Self: Sized, { Collection::new(self) } /// Inserts a newly created document into the connected [`schema::Schema`] for the [`Collection`] `C`. async fn insert<C: schema::Collection>( &self, contents: Vec<u8>, encryption_key: Option<KeyId>, ) -> Result<Header, Error> { let mut tx = Transaction::default(); tx.push(Operation { collection: C::collection_name()?, command: Command::Insert { contents: Cow::from(contents), encryption_key, }, }); let results = self.apply_transaction(tx).await?; if let OperationResult::DocumentUpdated { header, .. } = &results[0] { Ok(header.clone()) } else { unreachable!( "apply_transaction on a single insert should yield a single DocumentUpdated entry" ) } } /// Updates an existing document in the connected [`schema::Schema`] for the /// [`Collection`] `C`. Upon success, `doc.revision` will be updated with /// the new revision. async fn update<C: schema::Collection>(&self, doc: &mut Document<'_>) -> Result<(), Error> { let mut tx = Transaction::default(); tx.push(Operation { collection: C::collection_name()?, command: Command::Update { header: Cow::Owned(doc.header.as_ref().clone()), contents: Cow::Owned(doc.contents.to_vec()), }, }); let results = self.apply_transaction(tx).await?; if let OperationResult::DocumentUpdated { header, .. } = &results[0] { doc.header = Cow::Owned(header.clone()); Ok(()) } else { unreachable!( "apply_transaction on a single update should yield a single DocumentUpdated entry" ) } } /// Retrieves a stored document from [`Collection`] `C` identified by `id`. async fn get<C: schema::Collection>(&self, id: u64) -> Result<Option<Document<'static>>, Error>; /// Retrieves all documents matching `ids`. Documents that are not found /// are not returned, but no error will be generated. async fn get_multiple<C: schema::Collection>( &self, ids: &[u64], ) -> Result<Vec<Document<'static>>, Error>; /// Removes a `Document` from the database. async fn delete<C: schema::Collection>(&self, doc: &Document<'_>) -> Result<(), Error> { let mut tx = Transaction::default(); tx.push(Operation { collection: C::collection_name()?, command: Command::Delete { header: Cow::Owned(doc.header.as_ref().clone()), }, }); let results = self.apply_transaction(tx).await?; if let OperationResult::DocumentDeleted { .. } = &results[0] { Ok(()) } else { unreachable!( "apply_transaction on a single update should yield a single DocumentUpdated entry" ) } } /// Initializes [`View`] for [`schema::View`] `V`. #[must_use] fn view<V: schema::View>(&'_ self) -> View<'_, Self, V> where Self: Sized, { View::new(self) } /// Queries for view entries matching [`View`]. #[must_use] async fn query<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<Map<V::Key, V::Value>>, Error> where Self: Sized; /// Queries for view entries matching [`View`]. #[must_use] async fn query_with_docs<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedDocument<V::Key, V::Value>>, Error> where Self: Sized; /// Reduces the view entries matching [`View`]. #[must_use] async fn reduce<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<V::Value, Error> where Self: Sized; /// Reduces the view entries matching [`View`], reducing the values by each /// unique key. #[must_use] async fn reduce_grouped<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedValue<V::Key, V::Value>>, Error> where Self: Sized; /// Applies a [`Transaction`] to the [`schema::Schema`]. If any operation in the /// [`Transaction`] fails, none of the operations will be applied to the /// [`schema::Schema`]. async fn apply_transaction( &self, transaction: Transaction<'static>, ) -> Result<Vec<OperationResult>, Error>; /// Lists executed [`Transaction`]s from this [`schema::Schema`]. By default, a maximum of /// 1000 entries will be returned, but that limit can be overridden by /// setting `result_limit`. A hard limit of 100,000 results will be /// returned. To begin listing after another known `transaction_id`, pass /// `transaction_id + 1` into `starting_id`. async fn list_executed_transactions( &self, starting_id: Option<u64>, result_limit: Option<usize>, ) -> Result<Vec<transaction::Executed<'static>>, Error>; /// Fetches the last transaction id that has been committed, if any. async fn last_transaction_id(&self) -> Result<Option<u64>, Error>; } /// Interacts with a collection over a `Connection`. pub struct Collection<'a, Cn, Cl> { connection: &'a Cn, _phantom: PhantomData<Cl>, // allows for extension traits to be written for collections of specific types } impl<'a, Cn, Cl> Collection<'a, Cn, Cl> where Cn: Connection, Cl: schema::Collection, { /// Creates a new instance using `connection`. pub fn new(connection: &'a Cn) -> Self { Self { connection, _phantom: PhantomData::default(), } } /// Adds a new `Document<Cl>` with the contents `item`. pub async fn push<S: Serialize + Sync>(&self, item: &S) -> Result<Header, crate::Error> { let contents = serde_cbor::to_vec(item)?; Ok(self.connection.insert::<Cl>(contents, None).await?) } /// Adds a new `Document<Cl>` with the contents `item`. Encrypts the /// document using `encryption_key`. pub async fn push_encrypted<S: Serialize + Sync>( &self, item: &S, encryption_key: KeyId, ) -> Result<Header, crate::Error> { let contents = serde_cbor::to_vec(item)?; Ok(self .connection .insert::<Cl>(contents, Some(encryption_key)) .await?) } /// Retrieves a `Document<Cl>` with `id` from the connection. pub async fn get(&self, id: u64) -> Result<Option<Document<'static>>, Error> { self.connection.get::<Cl>(id).await } } /// Parameters to query a `schema::View`. pub struct View<'a, Cn, V: schema::View> { connection: &'a Cn, /// Key filtering criteria. pub key: Option<QueryKey<V::Key>>, /// The view's data access policy. The default value is [`AccessPolicy::UpdateBefore`]. pub access_policy: AccessPolicy, } impl<'a, Cn, V> View<'a, Cn, V> where V: schema::View, Cn: Connection, { fn new(connection: &'a Cn) -> Self { Self { connection, key: None, access_policy: AccessPolicy::UpdateBefore, } } /// Filters for entries in the view with `key`. #[must_use] pub fn with_key(mut self, key: V::Key) -> Self { self.key = Some(QueryKey::Matches(key)); self } /// Filters for entries in the view with `keys`. #[must_use] pub fn with_keys(mut self, keys: Vec<V::Key>) -> Self { self.key = Some(QueryKey::Multiple(keys)); self } /// Filters for entries in the view with the range `keys`. #[must_use] pub fn with_key_range(mut self, range: Range<V::Key>) -> Self { self.key = Some(QueryKey::Range(range)); self } /// Sets the access policy for queries. pub fn with_access_policy(mut self, policy: AccessPolicy) -> Self { self.access_policy = policy; self } /// Executes the query and retrieves the results. pub async fn query(self) -> Result<Vec<Map<V::Key, V::Value>>, Error> { self.connection .query::<V>(self.key, self.access_policy) .await } /// Executes the query and retrieves the results with the associated `Document`s. pub async fn query_with_docs(self) -> Result<Vec<MappedDocument<V::Key, V::Value>>, Error> { self.connection .query_with_docs::<V>(self.key, self.access_policy) .await } /// Executes a reduce over the results of the query pub async fn reduce(self) -> Result<V::Value, Error> { self.connection .reduce::<V>(self.key, self.access_policy) .await } /// Executes a reduce over the results of the query pub async fn reduce_grouped(self) -> Result<Vec<MappedValue<V::Key, V::Value>>, Error> { self.connection .reduce_grouped::<V>(self.key, self.access_policy) .await } } /// Filters a [`View`] by key. #[derive(Clone, Serialize, Deserialize, Debug)] pub enum QueryKey<K> { /// Matches all entries with the key provided. Matches(K), /// Matches all entires with keys in the range provided. Range(Range<K>), /// Matches all entries that have keys that are included in the set provided. Multiple(Vec<K>), } #[allow(clippy::use_self)] // clippy is wrong, Self is different because of generic parameters impl<K: Key> QueryKey<K> { /// Converts this key to a serialized format using the [`Key`] trait. pub fn serialized(&self) -> Result<QueryKey<Vec<u8>>, Error> { match self { Self::Matches(key) => key .as_big_endian_bytes() .map_err(|err| Error::Database(view::Error::KeySerialization(err).to_string())) .map(|v| QueryKey::Matches(v.to_vec())), Self::Range(range) => { let start = range .start .as_big_endian_bytes() .map_err(|err| Error::Database(view::Error::KeySerialization(err).to_string()))? .to_vec(); let end = range .end .as_big_endian_bytes() .map_err(|err| Error::Database(view::Error::KeySerialization(err).to_string()))? .to_vec(); Ok(QueryKey::Range(start..end)) } Self::Multiple(keys) => { let keys = keys .iter() .map(|key| { key.as_big_endian_bytes() .map(|key| key.to_vec()) .map_err(|err| { Error::Database(view::Error::KeySerialization(err).to_string()) }) }) .collect::<Result<Vec<_>, Error>>()?; Ok(QueryKey::Multiple(keys)) } } } } #[allow(clippy::use_self)] // clippy is wrong, Self is different because of generic parameters impl QueryKey<Vec<u8>> { /// Deserializes the bytes into `K` via the [`Key`] trait. pub fn deserialized<K: Key>(&self) -> Result<QueryKey<K>, Error> { match self { Self::Matches(key) => K::from_big_endian_bytes(key) .map_err(|err| Error::Database(view::Error::KeySerialization(err).to_string())) .map(QueryKey::Matches), Self::Range(range) => { let start = K::from_big_endian_bytes(&range.start).map_err(|err| { Error::Database(view::Error::KeySerialization(err).to_string()) })?; let end = K::from_big_endian_bytes(&range.end).map_err(|err| { Error::Database(view::Error::KeySerialization(err).to_string()) })?; Ok(QueryKey::Range(start..end)) } Self::Multiple(keys) => { let keys = keys .iter() .map(|key| { K::from_big_endian_bytes(key).map_err(|err| { Error::Database(view::Error::KeySerialization(err).to_string()) }) }) .collect::<Result<Vec<_>, Error>>()?; Ok(QueryKey::Multiple(keys)) } } } } /// Changes how the view's outdated data will be treated. #[derive(Clone, Serialize, Deserialize, Debug)] pub enum AccessPolicy { /// Update any changed documents before returning a response. UpdateBefore, /// Return the results, which may be out-of-date, and start an update job in /// the background. This pattern is useful when you want to ensure you /// provide consistent response times while ensuring the database is /// updating in the background. UpdateAfter, /// Returns the restuls, which may be out-of-date, and do not start any /// background jobs. This mode is useful if you're using a view as a cache /// and have a background process that is responsible for controlling when /// data is refreshed and updated. While the default `UpdateBefore` /// shouldn't have much overhead, this option removes all overhead related /// to view updating from the query. NoUpdate, } /// Functions for interacting with a multi-database `BonsaiDb` instance. #[async_trait] pub trait ServerConnection: Send + Sync { /// Creates a database named `name` with the `Schema` provided. /// /// ## Errors /// /// * [`Error::InvalidDatabaseName`]: `name` must begin with an alphanumeric /// character (`[a-zA-Z0-9]`), and all remaining characters must be /// alphanumeric, a period (`.`), or a hyphen (`-`). /// * [`Error::DatabaseNameAlreadyTaken]: `name` was already used for a /// previous database name. Database names are case insensitive. async fn create_database<DB: Schema>(&self, name: &str) -> Result<(), crate::Error> { self.create_database_with_schema(name, DB::schema_name()?) .await } /// Creates a database named `name` using the [`SchemaName`] `schema`. /// /// ## Errors /// /// * [`Error::InvalidDatabaseName`]: `name` must begin with an alphanumeric /// character (`[a-zA-Z0-9]`), and all remaining characters must be /// alphanumeric, a period (`.`), or a hyphen (`-`). /// * [`Error::DatabaseNameAlreadyTaken]: `name` was already used for a /// previous database name. Database names are case insensitive. async fn create_database_with_schema( &self, name: &str, schema: SchemaName, ) -> Result<(), crate::Error>; /// Deletes a database named `name`. /// /// ## Errors /// /// * [`Error::DatabaseNotFound`]: database `name` does not exist. /// * [`Error::Io)`]: an error occurred while deleting files. async fn delete_database(&self, name: &str) -> Result<(), crate::Error>; /// Lists the databases on this server. async fn list_databases(&self) -> Result<Vec<Database>, crate::Error>; /// Lists the [`SchemaName`]s on this server. async fn list_available_schemas(&self) -> Result<Vec<SchemaName>, crate::Error>; /// Creates a user. async fn create_user(&self, username: &str) -> Result<u64, crate::Error>; /// Sets a user's password using `custodian-password` to register a password using `OPAQUE-PAKE`. async fn set_user_password<'user, U: Into<NamedReference<'user>> + Send + Sync>( &self, user: U, password_request: RegistrationRequest, ) -> Result<RegistrationResponse, crate::Error>; /// Finishes setting a user's password by finishing the `OPAQUE-PAKE` /// registration. async fn finish_set_user_password<'user, U: Into<NamedReference<'user>> + Send + Sync>( &self, user: U, password_finalization: RegistrationFinalization, ) -> Result<(), crate::Error>; /// Sets a user's password with the provided string. The password provided /// will never leave the machine that is calling this function. Internally /// uses `set_user_password` and `finish_set_user_password` in conjunction /// with `custodian-password`. async fn set_user_password_str<'user, U: Into<NamedReference<'user>> + Send + Sync>( &self, user: U, password: &str, ) -> Result<ClientFile, crate::Error> { let user = user.into(); let (registration, request) = ClientRegistration::register(&ClientConfig::new(PASSWORD_CONFIG, None)?, password)?; let response = self.set_user_password(user.clone(), request).await?; let (file, finalization, _export_key) = registration.finish(response)?; self.finish_set_user_password(user, finalization).await?; Ok(file) } /// Adds a user to a permission group. async fn add_permission_group_to_user< 'user, 'group, U: Into<NamedReference<'user>> + Send + Sync, G: Into<NamedReference<'group>> + Send + Sync, >( &self, user: U, permission_group: G, ) -> Result<(), crate::Error>; /// Removes a user from a permission group. async fn remove_permission_group_from_user< 'user, 'group, U: Into<NamedReference<'user>> + Send + Sync, G: Into<NamedReference<'group>> + Send + Sync, >( &self, user: U, permission_group: G, ) -> Result<(), crate::Error>; /// Adds a user to a permission group. async fn add_role_to_user< 'user, 'role, U: Into<NamedReference<'user>> + Send + Sync, R: Into<NamedReference<'role>> + Send + Sync, >( &self, user: U, role: R, ) -> Result<(), crate::Error>; /// Removes a user from a permission group. async fn remove_role_from_user< 'user, 'role, U: Into<NamedReference<'user>> + Send + Sync, R: Into<NamedReference<'role>> + Send + Sync, >( &self, user: U, role: R, ) -> Result<(), crate::Error>; } /// A database on a server. #[derive(Clone, PartialEq, Deserialize, Serialize, Debug)] pub struct Database { /// The name of the database. pub name: String, /// The schema defining the database. pub schema: SchemaName, }
#![allow(nonstandard_style)] // Generated from crates/unflow-parser/src/grammar/Design.g4 by ANTLR 4.8 use antlr_rust::tree::{ParseTreeVisitor}; use super::designparser::*; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link DesignParser}. */ pub trait DesignVisitor<'input>: ParseTreeVisitor<'input,DesignParserContextType>{ /** * Visit a parse tree produced by {@link DesignParser#start}. * @param ctx the parse tree */ fn visit_start(&mut self, ctx: &StartContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#declarations}. * @param ctx the parse tree */ fn visit_declarations(&mut self, ctx: &DeclarationsContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#config_decl}. * @param ctx the parse tree */ fn visit_config_decl(&mut self, ctx: &Config_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#config_key}. * @param ctx the parse tree */ fn visit_config_key(&mut self, ctx: &Config_keyContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#config_value}. * @param ctx the parse tree */ fn visit_config_value(&mut self, ctx: &Config_valueContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#unit}. * @param ctx the parse tree */ fn visit_unit(&mut self, ctx: &UnitContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#flow_decl}. * @param ctx the parse tree */ fn visit_flow_decl(&mut self, ctx: &Flow_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#interaction_decl}. * @param ctx the parse tree */ fn visit_interaction_decl(&mut self, ctx: &Interaction_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#see_decl}. * @param ctx the parse tree */ fn visit_see_decl(&mut self, ctx: &See_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#do_decl}. * @param ctx the parse tree */ fn visit_do_decl(&mut self, ctx: &Do_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#react_decl}. * @param ctx the parse tree */ fn visit_react_decl(&mut self, ctx: &React_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#animate_decl}. * @param ctx the parse tree */ fn visit_animate_decl(&mut self, ctx: &Animate_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#react_action}. * @param ctx the parse tree */ fn visit_react_action(&mut self, ctx: &React_actionContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#goto_action}. * @param ctx the parse tree */ fn visit_goto_action(&mut self, ctx: &Goto_actionContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#show_action}. * @param ctx the parse tree */ fn visit_show_action(&mut self, ctx: &Show_actionContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#action_name}. * @param ctx the parse tree */ fn visit_action_name(&mut self, ctx: &Action_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#component_name}. * @param ctx the parse tree */ fn visit_component_name(&mut self, ctx: &Component_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#scene_name}. * @param ctx the parse tree */ fn visit_scene_name(&mut self, ctx: &Scene_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#animate_name}. * @param ctx the parse tree */ fn visit_animate_name(&mut self, ctx: &Animate_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#page_decl}. * @param ctx the parse tree */ fn visit_page_decl(&mut self, ctx: &Page_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#component_decl}. * @param ctx the parse tree */ fn visit_component_decl(&mut self, ctx: &Component_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_body_name} * labeled alternative in {@link DesignParser#component_body_decl}. * @param ctx the parse tree */ fn visit_component_body_name(&mut self, ctx: &Component_body_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_body_config} * labeled alternative in {@link DesignParser#component_body_decl}. * @param ctx the parse tree */ fn visit_component_body_config(&mut self, ctx: &Component_body_configContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#layout_decl}. * @param ctx the parse tree */ fn visit_layout_decl(&mut self, ctx: &Layout_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code empty_line} * labeled alternative in {@link DesignParser#flex_child}. * @param ctx the parse tree */ fn visit_empty_line(&mut self, ctx: &Empty_lineContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code flex_component_use} * labeled alternative in {@link DesignParser#flex_child}. * @param ctx the parse tree */ fn visit_flex_component_use(&mut self, ctx: &Flex_component_useContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_use_decimal} * labeled alternative in {@link DesignParser#component_use_decl}. * @param ctx the parse tree */ fn visit_component_use_decimal(&mut self, ctx: &Component_use_decimalContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_use_position} * labeled alternative in {@link DesignParser#component_use_decl}. * @param ctx the parse tree */ fn visit_component_use_position(&mut self, ctx: &Component_use_positionContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_use_name_value} * labeled alternative in {@link DesignParser#component_use_decl}. * @param ctx the parse tree */ fn visit_component_use_name_value(&mut self, ctx: &Component_use_name_valueContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code component_use_string} * labeled alternative in {@link DesignParser#component_use_decl}. * @param ctx the parse tree */ fn visit_component_use_string(&mut self, ctx: &Component_use_stringContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#component_parameter}. * @param ctx the parse tree */ fn visit_component_parameter(&mut self, ctx: &Component_parameterContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#style_decl}. * @param ctx the parse tree */ fn visit_style_decl(&mut self, ctx: &Style_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#style_name}. * @param ctx the parse tree */ fn visit_style_name(&mut self, ctx: &Style_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#style_body}. * @param ctx the parse tree */ fn visit_style_body(&mut self, ctx: &Style_bodyContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#library_name}. * @param ctx the parse tree */ fn visit_library_name(&mut self, ctx: &Library_nameContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#library_decl}. * @param ctx the parse tree */ fn visit_library_decl(&mut self, ctx: &Library_declContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code library_config} * labeled alternative in {@link DesignParser#library_exp}. * @param ctx the parse tree */ fn visit_library_config(&mut self, ctx: &Library_configContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by the {@code library_object} * labeled alternative in {@link DesignParser#library_exp}. * @param ctx the parse tree */ fn visit_library_object(&mut self, ctx: &Library_objectContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#key_value}. * @param ctx the parse tree */ fn visit_key_value(&mut self, ctx: &Key_valueContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#preset_key}. * @param ctx the parse tree */ fn visit_preset_key(&mut self, ctx: &Preset_keyContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#preset_value}. * @param ctx the parse tree */ fn visit_preset_value(&mut self, ctx: &Preset_valueContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#preset_array}. * @param ctx the parse tree */ fn visit_preset_array(&mut self, ctx: &Preset_arrayContext<'input>) { self.visit_children(ctx) } /** * Visit a parse tree produced by {@link DesignParser#preset_call}. * @param ctx the parse tree */ fn visit_preset_call(&mut self, ctx: &Preset_callContext<'input>) { self.visit_children(ctx) } }
use anyhow::{Context, Result}; use chrono::prelude::*; use serde::{Deserialize, Serialize}; use std::{net::Ipv4Addr, str::FromStr}; use strum_macros::{Display, EnumIter}; use url::Url; /// Holds all application state /// /// Holds current connection information and settings for the current (only) user #[derive(Serialize, Deserialize, Debug, Default)] pub struct Config { /// Actual config info pub user: UserConfig, /// Current connection information pub connection_info: Option<ConnectionInfo>, /// Random extra info pub metadata: MetaData, } /// Holds all user settings. See the docs on each field to learn more. #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct UserConfig { pub(crate) username: String, pub(crate) password: String, pub(crate) tier: PlanTier, pub(crate) protocol: ConnectionProtocol, /// A recommended security setting that enables using Proton VPN's dns servers, or your own. In other words, don't use the dns servers from your operating system / internet service provider pub(crate) dns_leak_protection: bool, /// This setting is only referenced if the dns_leak_protection is enabled pub(crate) custom_dns: Vec<Ipv4Addr>, pub(crate) check_update_interval: u8, pub(crate) killswitch: u8, pub(crate) split_tunnel: bool, // Remove this field. It can't change. Its always the default (see impl Default) pub(crate) api_domain: Url, } impl UserConfig { /// Constructor: All other params assume default values. Use the setters in [super::settings] for mutation pub fn new(username: String, password: String) -> Self { Self { username, password, ..Default::default() } } } /// Creates unusable initial state. Must set the username and password fields (is initially None) impl Default for UserConfig { fn default() -> Self { Self { username: String::new(), password: String::new(), tier: PlanTier::Free, protocol: ConnectionProtocol::UDP, dns_leak_protection: true, custom_dns: Vec::with_capacity(3), check_update_interval: 3, killswitch: 0, split_tunnel: false, api_domain: Url::parse("https://api.protonvpn.ch") .context("Failed to parse protonvpn api url") .unwrap(), } } } #[derive( Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, EnumIter, Display, )] pub(crate) enum PlanTier { Free, Basic, Plus, Visionary, } impl From<u8> for PlanTier { fn from(u: u8) -> Self { use PlanTier::*; match u { 0 => Free, 1 => Basic, 2 => Plus, 3 => Visionary, _ => panic!("u8 was too big to convert to PlanTier"), } } } /// The connection protocol to use for vpn connections. The default is UDP #[derive(Debug, Serialize, Deserialize, PartialEq, Copy, Clone, EnumIter, Display)] pub enum ConnectionProtocol { /// Default variant, [User Datagram Protocol](https://www.cloudflare.com/learning/ddos/glossary/user-datagram-protocol-udp/) UDP, /// [Transmission Control Protocol](https://www.cloudflare.com/learning/ddos/glossary/tcp-ip/) TCP, } impl Default for ConnectionProtocol { fn default() -> Self { Self::UDP } } impl FromStr for ConnectionProtocol { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "udp" => Ok(Self::UDP), "tcp" => Ok(Self::TCP), _ => Err("String must be udp or tcp".into()), } } } /// Random extra info used by the application. #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct MetaData { pub(crate) resolvconf_hash: Option<String>, /// Time of the last call to the `/vpn/logicals` api endpoint. See [get_servers()](crate::utils::get_servers). /// /// If config could not be found, this defaults to 0 milliseconds, as a sort of Time::MIN pub(crate) last_api_pull: DateTime<Utc>, } impl Default for MetaData { fn default() -> Self { Self { resolvconf_hash: None, last_api_pull: Utc.timestamp_millis(0), } } } /// Information about the current vpn connection. #[derive(Serialize, Deserialize, Debug)] pub struct ConnectionInfo { pub(crate) server_id: String, pub(crate) protocol: ConnectionProtocol, pub(crate) dns_server: String, pub(crate) connected_time: String, }
// Copyright 2019, 2020 Wingchain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::marker::PhantomData; use std::sync::Arc; use fixed_hash::construct_fixed_hash; use hash_db::Hasher; use memory_db::PrefixedKey; use mut_static::MutStatic; use reference_trie::ReferenceNodeCodec; use trie_db::{DBValue, TrieLayout}; use crypto::hash::{Hash, HashImpl}; use crypto::HashLength; use lazy_static::lazy_static; use primitives::errors::CommonResult; use crate::errors; lazy_static! { pub static ref HASH_IMPL_20: MutStatic<Arc<HashImpl>> = MutStatic::new(); pub static ref HASH_IMPL_32: MutStatic<Arc<HashImpl>> = MutStatic::new(); pub static ref HASH_IMPL_64: MutStatic<Arc<HashImpl>> = MutStatic::new(); } pub struct TrieHasher20; pub struct TrieHasher32; pub struct TrieHasher64; /// should call load before using TrieHasher20/TrieHasher32/TrieHasher64 pub fn load_hasher(hash_impl: Arc<HashImpl>) -> CommonResult<()> { let length = hash_impl.length(); match length { HashLength::HashLength20 => { let name = hash_impl.name(); match HASH_IMPL_20.set(hash_impl) { Ok(_) => (), Err(mut_static::Error(mut_static::ErrorKind::StaticIsAlreadySet, _)) if HASH_IMPL_20 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name() == name => {} _ => { return Err(errors::ErrorKind::LoadHasherConflict( HASH_IMPL_32 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name(), name, ) .into()); } } } HashLength::HashLength32 => { let name = hash_impl.name(); match HASH_IMPL_32.set(hash_impl) { Ok(_) => (), Err(mut_static::Error(mut_static::ErrorKind::StaticIsAlreadySet, _)) if HASH_IMPL_32 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name() == name => {} _ => { return Err(errors::ErrorKind::LoadHasherConflict( HASH_IMPL_32 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name(), name, ) .into()); } } } HashLength::HashLength64 => { let name = hash_impl.name(); match HASH_IMPL_64.set(hash_impl) { Ok(_) => (), Err(mut_static::Error(mut_static::ErrorKind::StaticIsAlreadySet, _)) if HASH_IMPL_64 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name() == name => {} _ => { return Err(errors::ErrorKind::LoadHasherConflict( HASH_IMPL_32 .read() .map_err(|_| errors::ErrorKind::LoadHasherFail)? .name(), name, ) .into()); } } } } Ok(()) } pub type DefaultTrieDB<'a, H> = trie_db::TrieDB<'a, DefaultTrieLayout<H>>; pub type DefaultTrieDBMut<'a, H> = trie_db::TrieDBMut<'a, DefaultTrieLayout<H>>; pub type DefaultMemoryDB<H> = memory_db::MemoryDB<H, PrefixedKey<H>, DBValue>; pub struct DefaultTrieLayout<H>(PhantomData<H>); impl<H: Hasher> TrieLayout for DefaultTrieLayout<H> { const USE_EXTENSION: bool = true; type Hash = H; type Codec = ReferenceNodeCodec<H>; } impl Hasher for TrieHasher20 { type Out = [u8; 20]; type StdHasher = DummyStdHasher; const LENGTH: usize = 20; fn hash(x: &[u8]) -> Self::Out { let hasher = HASH_IMPL_20.read().expect("Should load_hasher first"); let mut out = [0u8; 20]; hasher.hash(&mut out, x); out } } impl Hasher for TrieHasher32 { type Out = [u8; 32]; type StdHasher = DummyStdHasher; const LENGTH: usize = 32; fn hash(x: &[u8]) -> Self::Out { let hasher = HASH_IMPL_32.read().expect("Should load_hasher first"); let mut out = [0u8; 32]; hasher.hash(&mut out, x); out } } construct_fixed_hash! { pub struct H512(64); } impl Hasher for TrieHasher64 { type Out = H512; type StdHasher = DummyStdHasher; const LENGTH: usize = 64; fn hash(x: &[u8]) -> Self::Out { let hasher = HASH_IMPL_64.read().expect("Should load_hasher first"); let mut out = [0u8; 64]; hasher.hash(&mut out, x); H512::from(out) } } #[derive(Default)] pub struct DummyStdHasher; impl std::hash::Hasher for DummyStdHasher { fn finish(&self) -> u64 { 0 } fn write(&mut self, _bytes: &[u8]) {} }
use std::fmt; use std::iter::FromIterator; use std::mem; use std::ops::{Deref, DerefMut}; use std::ptr; use std::slice; use unreachable::unreachable; use iter_exact::FromExactSizeIterator; use typehack::binary::*; use typehack::dim::*; #[derive(Clone)] #[repr(u8)] enum MaybeDropped<T> { Allocated(T), Dropped, } use self::MaybeDropped::*; impl<T> MaybeDropped<T> { unsafe fn unchecked_unwrap(self) -> T { match self { Allocated(obj) => obj, Dropped => unreachable(), } } fn take(&mut self) -> MaybeDropped<T> { mem::replace(self, Dropped) } fn as_ref(&self) -> MaybeDropped<&T> { match *self { Allocated(ref obj) => Allocated(obj), Dropped => Dropped, } } fn as_mut(&mut self) -> MaybeDropped<&mut T> { match *self { Allocated(ref mut obj) => Allocated(obj), Dropped => Dropped, } } fn is_allocated(&self) -> bool { match *self { Allocated(_) => true, Dropped => false, } } } #[macro_export] macro_rules! data { (@assign $data:ident $n:expr => $x:expr $(, $xs:expr)*) => ($data[$n] = $x; data!(@assign $data ($n + 1) => $($xs),*)); (@assign $data:ident $n:expr =>) => (); (@count $x:expr $(, $xs:expr)*) => (<data!(@count $($xs),*) as $crate::typehack::binary::Nat>::Succ); (@count) => ($crate::typehack::binary::O); ($($xs:expr),*) => ({ let mut data: $crate::typehack::data::Data<_, data!(@count $($xs),*)>; unsafe { data = $crate::typehack::data::Data::uninitialized( <data!(@count $($xs),*) as $crate::typehack::binary::Nat>::as_data()); data!(@assign data 0 => $($xs),*); } data }); } pub trait DependentClone<T>: Sized { fn dependent_clone(&self) -> Self where T: Clone; } impl<T> DependentClone<T> for Vec<T> { fn dependent_clone(&self) -> Self where T: Clone { self.clone() } } impl<E, T: DependentClone<E>> DependentClone<E> for Box<T> { fn dependent_clone(&self) -> Self where E: Clone { Box::new(self.as_ref().dependent_clone()) } } #[derive(Copy, Clone)] #[repr(C)] pub struct PopulatedNode<E, C> { e: E, l: C, r: C, } #[derive(Copy, Clone)] #[repr(C)] pub struct EmptyNode<C> { l: C, r: C, } impl<E, C: DependentClone<E>> DependentClone<E> for PopulatedNode<E, C> { fn dependent_clone(&self) -> Self where E: Clone { PopulatedNode { e: self.e.clone(), l: self.l.dependent_clone(), r: self.r.dependent_clone(), } } } impl<E, C: DependentClone<E>> DependentClone<E> for EmptyNode<C> { fn dependent_clone(&self) -> Self where E: Clone { EmptyNode { l: self.l.dependent_clone(), r: self.r.dependent_clone(), } } } pub trait Raw<E>: Nat { type Data: DependentClone<E> + Diceable<E, Self>; } impl<E> DependentClone<E> for () { fn dependent_clone(&self) -> Self { () } } #[cfg_attr(rustfmt, rustfmt_skip)] impl<T: Nat, E> Raw<E> for T { default type Data = (); } impl<E> Raw<E> for P { type Data = (); } impl<E, N: Nat> Raw<E> for O<N> { type Data = EmptyNode<<N as Raw<E>>::Data>; } impl<E, N: Nat> Raw<E> for I<N> { type Data = PopulatedNode<E, <N as Raw<E>>::Data>; } pub trait Diceable<E, D: Dim> { fn size(&self) -> D; unsafe fn uninitialized(D) -> Self; unsafe fn forget_internals(self); unsafe fn into_slice<'a>(&'a self) -> &'a [E]; unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E]; } impl<E, D: Dim> Diceable<E, D> for () { fn size(&self) -> D { D::from_usize(0) } unsafe fn uninitialized(_: D) -> () { () // It's a fscking unit. } unsafe fn forget_internals(self) {} // It's a fscking unit. unsafe fn into_slice<'a>(&'a self) -> &'a [E] { &[] } unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E] { &mut [] } } impl<E, D: Dim> Diceable<E, D> for Vec<E> { fn size(&self) -> D { D::from_usize(self.len()) } unsafe fn uninitialized(dim: D) -> Vec<E> { // We can create a Vec with uninitialized memory by asking for a given capacity, and // then manually setting its length. let mut vec = Vec::with_capacity(dim.reify()); vec.set_len(dim.reify()); vec } unsafe fn forget_internals(mut self) { // Similarly to creating an uninitialized Vec, we can cause the Vec to forget its // internals by setting its length to zero. The memory it holds will still be freed // correctly, but without running destructors on the elements inside, which is // exactly what we want. self.set_len(0); } unsafe fn into_slice<'a>(&'a self) -> &'a [E] { &self[..] } unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E] { &mut self[..] } } impl<E, D: Nat> Diceable<E, D> for EmptyNode<<D::ShrOnce as Raw<E>>::Data> { fn size(&self) -> D { D::as_data() } unsafe fn uninitialized(_: D) -> Self { mem::uninitialized() } unsafe fn forget_internals(self) { mem::forget(self); } unsafe fn into_slice<'a>(&'a self) -> &'a [E] { slice::from_raw_parts(mem::transmute::<&Self, *const E>(self), D::as_usize()) } unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E] { slice::from_raw_parts_mut(mem::transmute::<&mut Self, *mut E>(self), D::as_usize()) } } impl<E, D: Nat> Diceable<E, D> for PopulatedNode<E, <D::ShrOnce as Raw<E>>::Data> { fn size(&self) -> D { D::as_data() } unsafe fn uninitialized(_: D) -> Self { mem::uninitialized() } unsafe fn forget_internals(self) { mem::forget(self); } unsafe fn into_slice<'a>(&'a self) -> &'a [E] { slice::from_raw_parts(mem::transmute::<&Self, *const E>(self), D::as_usize()) } unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E] { slice::from_raw_parts_mut(mem::transmute::<&mut Self, *mut E>(self), D::as_usize()) } } impl<E, D: Nat, T> Diceable<E, D> for Box<T> { fn size(&self) -> D { D::as_data() } unsafe fn uninitialized(_: D) -> Self { Box::new(mem::uninitialized()) } unsafe fn forget_internals(self) { let unboxed = *self; mem::forget(unboxed) } unsafe fn into_slice<'a>(&'a self) -> &'a [E] { slice::from_raw_parts(mem::transmute::<&T, *const E>(self.as_ref()), D::as_usize()) } unsafe fn into_mut_slice<'a>(&'a mut self) -> &'a mut [E] { slice::from_raw_parts_mut(mem::transmute::<&mut T, *mut E>(self.as_mut()), D::as_usize()) } } pub trait Size<E>: Dim { type Reify: DependentClone<E> + Diceable<E, Self> + Sized; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<E, D: Dim> Size<E> for D { default type Reify = Vec<E>; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<E> Size<E> for Dyn { type Reify = Vec<E>; } impl<E, N: Nat> Size<E> for N where N: NatSub<B32> { type Reify = Box<<N as Raw<E>>::Data>; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<E, N: Nat> Size<E> for N { default type Reify = <N as Raw<E>>::Data; } #[derive(Copy)] #[repr(C)] pub struct Data<T, S: Size<T>> { data: S::Reify, } impl<T: Clone, S: Size<T>> Clone for Data<T, S> { fn clone(&self) -> Self { Data { data: self.data.dependent_clone() } } } impl<T, S: Size<T>> Deref for Data<T, S> { type Target = [T]; fn deref<'a>(&'a self) -> &'a [T] { unsafe { self.data.into_slice() } } } impl<T, S: Size<T>> DerefMut for Data<T, S> { fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { unsafe { self.data.into_mut_slice() } } } impl<T, S: Size<T>> Data<T, S> { pub fn from_elem(s: S, elem: &T) -> Data<T, S> where T: Clone { let mut data: Self; unsafe { data = Data { data: S::Reify::uninitialized(s) }; for loc in data.iter_mut() { ptr::write(loc, elem.clone()); } } data } pub fn from_slice(s: S, slice: &[T]) -> Data<T, S> where T: Clone { assert_eq!(slice.len(), s.reify()); let mut data: Self; unsafe { data = Data { data: S::Reify::uninitialized(s) }; for (i, loc) in data.iter_mut().enumerate() { ptr::write(loc, slice[i].clone()); } } data } pub fn from_fn<F: Fn(usize) -> T>(s: S, f: F) -> Data<T, S> { let mut data: Self; unsafe { data = Data { data: S::Reify::uninitialized(s) }; for (i, loc) in data.iter_mut().enumerate() { ptr::write(loc, f(i)); } } data } pub unsafe fn uninitialized(s: S) -> Data<T, S> { Data { data: S::Reify::uninitialized(s) } } pub fn size(&self) -> S { self.data.size() } pub fn len(&self) -> usize { self.data.size().reify() } pub fn extend(self, t: T) -> Data<T, S::Succ> { let mut data: Data<T, S::Succ>; let s = self.size().succ(); unsafe { data = Data::uninitialized(s); ptr::write(&mut data[self.len()], t); for (i, val) in self.into_iter().enumerate() { ptr::write(&mut data[i], val); } } data } pub fn contract(self, idx: usize) -> Data<T, S::Pred> { assert!(idx < self.len()); let mut data: Data<T, S::Pred>; let s = self.size().pred(); unsafe { data = Data::uninitialized(s); for i in 0..idx { ptr::write(&mut data[i], ptr::read(&self[i])); } for i in idx..s.reify() { ptr::write(&mut data[i], ptr::read(&self[i + 1])); } self.forget(); } data } pub unsafe fn forget(self) { self.data.forget_internals(); } } impl<T: PartialEq, N: Size<T>> PartialEq for Data<T, N> { fn eq(&self, rhs: &Self) -> bool { self.deref() == rhs.deref() } } impl<T: Eq, N: Size<T>> Eq for Data<T, N> {} impl<T: fmt::Debug, N: Size<T>> fmt::Debug for Data<T, N> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(fmt) } } impl<T, N: Size<T>> IntoIterator for Data<T, N> { type Item = T; type IntoIter = IntoIter<T, N>; fn into_iter(self) -> Self::IntoIter { IntoIter { data: Allocated(self), idx: 0, } } } pub struct IntoIter<T, N: Size<T>> { data: MaybeDropped<Data<T, N>>, idx: usize, } impl<T, N: Size<T>> Iterator for IntoIter<T, N> { type Item = T; fn next(&mut self) -> Option<T> { match self.data { Allocated(ref data) => unsafe { if self.idx < data.len() { let idx = self.idx; self.idx += 1; Some(ptr::read(&data[idx])) } else { None } }, Dropped => None, } } fn size_hint(&self) -> (usize, Option<usize>) { unsafe { let data = self.data.as_ref().unchecked_unwrap(); let remaining = data.len() - self.idx; (remaining, Some(remaining)) } } } impl<T, N: Size<T>> ExactSizeIterator for IntoIter<T, N> {} impl<T, N: Size<T>> Drop for IntoIter<T, N> { fn drop(&mut self) { unsafe { { let data = self.data.as_ref().unchecked_unwrap(); for i in self.idx..data.len() { mem::drop(ptr::read(&data[i])); } } self.data.take().unchecked_unwrap().forget() } } } impl<T> FromIterator<T> for Data<T, Dyn> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let vec: Vec<T> = iter.into_iter().collect(); Data { data: vec } } } impl<T, N: Dim> FromExactSizeIterator<T> for Data<T, N> { fn from_exact_size_iter<I: IntoIterator<Item = T>>(iter: I) -> Self where I::IntoIter: ExactSizeIterator { let iter = iter.into_iter(); let size = iter.len(); assert!(N::compatible(size)); let mut out: Data<T, N>; unsafe { out = Data::uninitialized(N::from_usize(size)); for (i, t) in iter.enumerate() { ptr::write(&mut out[i], t); } } out } } #[derive(Clone)] pub struct DataVec<T, N: Size<T>> { data: MaybeDropped<Data<T, N>>, len: usize, } impl<T, N: Dim> From<DataVec<T, N>> for Data<T, N> { fn from(mut dvec: DataVec<T, N>) -> Data<T, N> { // TODO: Assert sizes match. unsafe { dvec.data.take().unchecked_unwrap() } } } impl<T, N: Size<T>> Drop for DataVec<T, N> { fn drop(&mut self) { match self.data.take() { Allocated(data) => unsafe { for i in 0..self.len { mem::drop(ptr::read(&data[i])); } data.forget(); }, Dropped => {} } } } impl<T, N: Nat + Size<T>> DataVec<T, N> { pub fn new() -> DataVec<T, N> { DataVec { data: Allocated(unsafe { Data::uninitialized(N::as_data()) }), len: 0, } } } impl<T, N: Size<T>> DataVec<T, N> { pub fn with_capacity(len: N) -> DataVec<T, N> { DataVec { data: Allocated(unsafe { Data::uninitialized(len) }), len: 0, } } pub fn push(&mut self, elem: T) where T: ::std::fmt::Debug { unsafe { debug!("data is some? {:?}", self.data.is_allocated()); let data = self.data.as_mut().unchecked_unwrap(); assert!(self.len < data.len()); ptr::write(&mut data[self.len], elem); self.len += 1; } } pub fn pop(&mut self) -> T { unsafe { let data = self.data.as_mut().unchecked_unwrap(); assert!(self.len > 0); let elem = ptr::read(&data[self.len]); self.len -= 1; elem } } pub fn set(&mut self, idx: usize, elem: T) { unsafe { let data = self.data.as_mut().unchecked_unwrap(); assert!(idx <= self.len && idx < data.len()); if idx < self.len { data[idx] = elem; } else { ptr::write(&mut data[idx], elem); self.len += 1; } } } pub fn insert(&mut self, idx: usize, elem: T) { unsafe { let data = self.data.as_mut().unchecked_unwrap(); assert!(idx <= self.len && idx < data.len()); for i in idx..self.len { ptr::write(&mut data[i + 1], ptr::read(&data[i])); } ptr::write(&mut data[idx], elem); self.len = self.len + 1; } } pub fn sorted_insert(&mut self, elem: T) where T: Ord { match self.binary_search(&elem) { Ok(_) => {} Err(idx) => self.insert(idx, elem), } } pub fn len(&self) -> usize { self.len } pub fn size(&self) -> N { unsafe { self.data.as_ref().unchecked_unwrap().size() } } pub fn is_full(&self) -> bool { self.len >= unsafe { self.data.as_ref().unchecked_unwrap().len() } } } impl<T, N: Size<T>> FromExactSizeIterator<T> for DataVec<T, N> { fn from_exact_size_iter<I: IntoIterator<Item = T>>(iter: I) -> Self where I::IntoIter: ExactSizeIterator { let iter = iter.into_iter(); let size = iter.len(); assert!(size <= N::from_usize(size).reify()); unsafe { let mut data: Data<T, N>; data = Data::uninitialized(N::from_usize(size)); for (i, t) in iter.enumerate() { ptr::write(&mut data[i], t); } DataVec { data: Allocated(data), len: size, } } } } impl<T, N: Size<T>> Deref for DataVec<T, N> { type Target = [T]; fn deref(&self) -> &[T] { &(unsafe { self.data.as_ref().unchecked_unwrap() })[0..self.len] } } impl<T, N: Size<T>> DerefMut for DataVec<T, N> { fn deref_mut(&mut self) -> &mut [T] { &mut (unsafe { self.data.as_mut().unchecked_unwrap() })[0..self.len] } } #[cfg(test)] mod tests { use std::mem; use typehack::binary::*; use super::*; #[test] fn data_create_p1() { let _: Data<i32, B1> = Data::from_elem(B1::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B1>>(), mem::size_of::<[i32; 1]>()); } #[test] fn data_create_p2() { let _: Data<i32, B2> = Data::from_elem(B2::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B2>>(), mem::size_of::<[i32; 2]>()); } #[test] fn data_create_p4() { let _: Data<i32, B4> = Data::from_elem(B4::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B4>>(), mem::size_of::<[i32; 4]>()); } #[test] fn data_create_p8() { let _: Data<i32, B8> = Data::from_elem(B8::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B8>>(), mem::size_of::<[i32; 8]>()); } #[test] fn data_create_p16() { let _: Data<i32, B16> = Data::from_elem(B16::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B16>>(), mem::size_of::<[i32; 16]>()); } #[test] fn data_create_p32() { let _: Data<i32, B32> = Data::from_elem(B32::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B32>>(), mem::size_of::<Box<i32>>()); } #[test] fn data_create_p64() { let _: Data<i32, B64> = Data::from_elem(B64::as_data(), &0); assert_eq!(mem::size_of::<Data<i32, B64>>(), mem::size_of::<Box<i32>>()); } }
//! Extra parsing combinators for Nom. use nom::{error::ParseError, Err, IResult, InputIter, InputLength, InputTake, Parser}; #[cfg(test)] use nom::{bytes::complete::tag, combinator::eof, error::Error, number::complete::float}; #[cfg(test)] type TestResult<'a, X, S = &'a str> = IResult<&'a str, (S, X), Error<&'a str>>; /// Consume input until a parser succeeds, and return the skipped input and parse result. pub fn take_until_parse<I, O, E, G>(mut parser: G) -> impl FnMut(I) -> IResult<I, (I, O), E> where I: InputTake + InputLength + InputIter, G: Parser<I, O, E>, E: ParseError<I>, { move |i: I| { let mut iter = i.iter_indices(); let mut pos = 0; loop { let (back, front) = i.take_split(pos); match parser.parse(back) { Ok((tail, v)) => return Ok((tail, (front, v))), Err(Err::Error(x)) => { // skip forward! if let Some((np, _)) = iter.next() { pos = np; } else { return Err(Err::Error(x)); } } Err(e) => return Err(e), } } } } /// Match a pair of parsers, matching the second *first* and the first on the string skipped /// to reach it. pub fn pair_nongreedy<I, O1, O2, E, F, G>( mut first: F, mut second: G, ) -> impl FnMut(I) -> IResult<I, (O1, O2), E> where I: InputTake + InputLength + InputIter + Clone, F: Parser<I, O1, E>, G: Parser<I, O2, E>, E: ParseError<I>, { move |i: I| { let (rest, (skipped, o2)) = take_until_parse(|ii| second.parse(ii))(i)?; let (_s, o1) = first.parse(skipped)?; Ok((rest, (o1, o2))) } } #[test] fn test_tu_empty() { let text = ""; let res: TestResult<'_, _> = take_until_parse(eof)(text); let (_, (f, _)) = res.expect("parse error"); assert_eq!(f, ""); } #[test] fn test_tu_immediate() { let text = "foo"; let res: TestResult<'_, _> = take_until_parse(tag("foo"))(text); let (_, (f, v)) = res.expect("parse error"); assert_eq!(f, ""); assert_eq!(v, "foo"); } #[test] fn test_tu_skip() { let text = "foobie bletch"; let res: TestResult<'_, _> = take_until_parse(tag("bletch"))(text); let (_, (f, v)) = res.expect("parse error"); assert_eq!(f, "foobie "); assert_eq!(v, "bletch"); } #[test] fn test_tu_skip_leftovers() { let text = "foobie bletch scroll"; let res: TestResult<'_, _> = take_until_parse(tag("bletch"))(text); let (r, (f, v)) = res.expect("parse error"); assert_eq!(r, " scroll"); assert_eq!(f, "foobie "); assert_eq!(v, "bletch"); } #[test] fn test_tu_nothing() { let text = "hackem muche"; let res: TestResult<'_, _> = take_until_parse(tag("bletch"))(text); assert!(res.is_err()); } #[test] fn test_tu_unilarge() { let text = "hackεm muche"; let res: TestResult<'_, _> = take_until_parse(tag("muche"))(text); let (r, (f, v)) = res.expect("parse error"); assert_eq!(r, ""); assert_eq!(f, "hackεm "); assert_eq!(v, "muche"); } #[test] fn test_nongreedy_value() { let text = "47bob"; let res: TestResult<'_, _, f32> = pair_nongreedy(float, tag("bob"))(text); let (_r, (n, tag)) = res.expect("parse error"); assert_eq!(n, 47.0); assert_eq!(tag, "bob"); } #[test] fn test_nongreedy_early() { let text = "479"; let res: TestResult<'_, _, f32> = pair_nongreedy(float, tag("9"))(text); let (_r, (n, tag)) = res.expect("parse error"); assert_eq!(n, 47.0); assert_eq!(tag, "9"); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - OctoSPI IO Manager Control Register"] pub cr: CR, #[doc = "0x04 - OctoSPI IO Manager Port 1 configuration register"] pub p1cr: P1CR, #[doc = "0x08 - OctoSPI IO Manager Port 2 configuration register"] pub p2cr: P2CR, } #[doc = "CR (rw) register accessor: OctoSPI IO Manager Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "OctoSPI IO Manager Control Register"] pub mod cr; #[doc = "P1CR (rw) register accessor: OctoSPI IO Manager Port 1 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`p1cr::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 [`p1cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`p1cr`] module"] pub type P1CR = crate::Reg<p1cr::P1CR_SPEC>; #[doc = "OctoSPI IO Manager Port 1 configuration register"] pub mod p1cr; #[doc = "P2CR (rw) register accessor: OctoSPI IO Manager Port 2 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`p2cr::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 [`p2cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`p2cr`] module"] pub type P2CR = crate::Reg<p2cr::P2CR_SPEC>; #[doc = "OctoSPI IO Manager Port 2 configuration register"] pub mod p2cr;
use shape::Shape; use ::std::default; #[derive(Default, Copy, Clone)] pub struct BitBoard { bits: [u64; 7], } impl BitBoard { pub fn new() -> Self { BitBoard { bits: [0; 7] } } #[inline] pub fn index(&self, index: usize) -> bool { let array_index = index / 64; let shift = index % 64; ((self.bits[array_index] >> shift) & 1) == 1 } #[inline] pub fn index_xy(&self, x: usize, y: usize) -> bool { self.index(y * 20 + x) } #[inline] pub fn set(&mut self, index: usize) { let array_index = index / 64; let shift = index % 64; self.bits[array_index] |= 1 << shift; } #[inline] pub fn set_xy(&mut self, x: usize, y: usize) { self.set(y * 20 + x) } #[inline] pub fn shape_intersects(&self, shape: &Shape, index: usize) -> bool { for &(i, bits) in shape.intersection_bitfields(index) { if bits & unsafe { self.bits.get_unchecked(i as usize) } != 0 { return true; } } false } #[inline] pub fn place_shape(&mut self, shape: &Shape, index: usize) { for &(i, bits) in shape.intersection_bitfields(index) { unsafe { *self.bits.get_unchecked_mut(i as usize) |= bits }; } } }
#![allow(clippy::cognitive_complexity)] #![warn(absolute_paths_not_starting_with_crate)] #![warn(explicit_outlives_requirements)] #![warn(unreachable_pub)] #![warn(deprecated_in_future)] #![deny(unsafe_code)] #![deny(unused_extern_crates)] use std::collections::VecDeque; use std::fs::File; use std::io::{self, Write}; use std::path::Path; use std::process::Command; use cranelift_module::Backend; use cranelift_object::ObjectBackend; pub type Product = <ObjectBackend as Backend>::Product; use data::prelude::CompileError; pub use data::prelude::*; pub use lex::PreProcessor; pub use parse::Parser; #[macro_use] pub mod utils; pub mod arch; pub mod data; mod fold; pub mod intern; mod ir; mod lex; mod parse; #[derive(Debug)] pub enum Error { Source(VecDeque<CompileError>), Platform(String), IO(io::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::IO(err) } } impl From<CompileError> for Error { fn from(err: CompileError) -> Error { Error::Source(vec_deque![err]) } } impl From<VecDeque<CompileError>> for Error { fn from(errs: VecDeque<CompileError>) -> Self { Error::Source(errs) } } /// Compile and return the declarations and warnings. pub fn compile( buf: &str, filename: String, debug_lex: bool, debug_ast: bool, debug_ir: bool, ) -> (Result<Product, Error>, VecDeque<CompileWarning>) { let filename_ref = InternedStr::get_or_intern(&filename); let mut cpp = PreProcessor::new(filename, buf.chars(), debug_lex); let (first, mut errs) = cpp.first_token(); let eof = || Location { span: (buf.len() as u32..buf.len() as u32).into(), filename: filename_ref, }; let first = match first { Some(token) => token, None => { if errs.is_empty() { errs.push_back(eof().error(SemanticError::EmptyProgram)); } return (Err(Error::Source(errs)), cpp.warnings()); } }; let mut parser = Parser::new(first, &mut cpp, debug_ast); let (hir, parse_errors) = parser.collect_results(); errs.extend(parse_errors.into_iter()); if hir.is_empty() && errs.is_empty() { errs.push_back(eof().error(SemanticError::EmptyProgram)); } let mut warnings = parser.warnings(); warnings.extend(cpp.warnings()); if !errs.is_empty() { return (Err(Error::Source(errs)), warnings); } let (result, ir_warnings) = ir::compile(hir, debug_ir); warnings.extend(ir_warnings); (result.map_err(Error::from), warnings) } pub fn assemble(product: Product, output: &Path) -> Result<(), Error> { let bytes = product.emit().map_err(Error::Platform)?; File::create(output)? .write_all(&bytes) .map_err(io::Error::into) } pub fn link(obj_file: &Path, output: &Path) -> Result<(), io::Error> { use std::io::{Error, ErrorKind}; // link the .o file using host linker let status = Command::new("cc") .args(&[&obj_file, Path::new("-o"), output]) .status() .map_err(|err| { if err.kind() == ErrorKind::NotFound { Error::new( ErrorKind::NotFound, "could not find host cc (for linking). Is it on your PATH?", ) } else { err } })?; if !status.success() { Err(Error::new(ErrorKind::Other, "linking program failed")) } else { Ok(()) } } #[cfg(test)] mod tests { use super::*; fn compile(src: &str) -> Result<Product, Error> { super::compile(src, "<test-suite>".to_owned(), false, false, false).0 } fn compile_err(src: &str) -> VecDeque<CompileError> { match compile(src).err().unwrap() { Error::Source(errs) => errs, _ => unreachable!(), } } #[test] fn empty() { let mut lex_errs = compile_err("`"); assert!(lex_errs.pop_front().unwrap().data.is_lex_err()); assert!(lex_errs.is_empty()); let mut empty_errs = compile_err(""); let err = empty_errs.pop_front().unwrap().data; assert_eq!(err, SemanticError::EmptyProgram.into()); assert!(err.is_semantic_err()); assert!(empty_errs.is_empty()); let mut parse_err = compile_err("+++"); let err = parse_err.pop_front(); assert!(parse_err.is_empty()); assert!(err.unwrap().data.is_syntax_err()); } }
use crate::eval::prelude::*; impl Eval<&ast::Condition> for ConstCompiler<'_> { fn eval( &mut self, condition: &ast::Condition, used: Used, ) -> Result<Option<ConstValue>, crate::CompileError> { self.budget.take(condition)?; match condition { ast::Condition::Expr(expr) => self.eval(&**expr, used), _ => Ok(None), } } }
struct Radix { x: i32, radix: u32, } impl Radix { fn new(x: i32, radix: u32) -> Result<Self, &'static str> { if radix < 2 || radix > 36 { Err("Unnsupported radix") } else { Ok(Self { x, radix }) } } } use std::fmt; impl fmt::Display for Radix { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut x = self.x; // Good for binary formatting of `u128`s let mut result = ['\0'; 128]; let mut used = 0; let negative = x < 0; if negative { x *= -1; } let mut x = x as u32; loop { let m = x % self.radix; x /= self.radix; result[used] = std::char::from_digit(m, self.radix).unwrap(); used += 1; if x == 0 { break; } } if negative { write!(f, "-")?; } for c in result[..used].iter().rev() { write!(f, "{}", c)?; } Ok(()) } } pub fn to36String(n: i32) -> String { let radix = Radix { x: n, radix: 36 }; radix.to_string() }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use super::*; /// Generate boilerplate code for the `NodeKind` enum. macro_rules! gen_nodekind_enum { ($name:ident { $( $kind:ident $([ $parent:ident ])? $({ $( $field:ident : $type:ty $( [ $( $constraint:ident ),* ] )? ),* $(,)? })? ),* $(,)? }) => { // The kind of an AST node. // Matching against this enum allows traversal of the AST. // Each variant of the enum must only have fields of the following types: // * `NodePtr` // * `Option<NodePtr>` // * `NodeList` // * `StringLiteral` // * `NodeLabel` // * `bool` // * `f64` #[derive(Debug)] pub enum NodeKind { // Create each field in the enum. $( $kind $({ $($field : $type),* })? ),* } impl NodeKind { /// Visit the child fields of this kind. /// `node` is the node for which this is the kind. pub fn visit_children<'a, V: Visitor<'a>>(&'a self, visitor: &mut V, node: &'a Node) { match self { $( Self::$kind $({$($field),*})? => { $($( $field.visit(visitor, node); )*)? } ),* } } pub fn variant(&self) -> NodeVariant { match self { $( Self::$kind { .. } => NodeVariant::$kind ),* } } pub fn name(&self) -> &'static str { match self { $( Self::$kind { .. } => { stringify!($kind) } ),* } } } /// Just type information on the node without any of the children. /// Used for performing tasks based only on the type of the AST node /// without having to know more about it. /// Includes "abstract" nodes which cannot be truly constructed. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum NodeVariant { Expression, Statement, Declaration, Literal, Pattern, LVal, $($kind),* } impl NodeVariant { /// The `parent` of the variant in ESTree, used for validation. /// Return `None` if there is no parent. pub fn parent(&self) -> Option<NodeVariant> { match self { Self::Expression => None, Self::Statement => None, Self::Declaration => Some(Self::Statement), Self::Literal => Some(Self::Expression), Self::Pattern => Some(Self::LVal), Self::LVal => Some(Self::Expression), $( Self::$kind => { None$(.or(Some(Self::$parent)))? } ),* } } } }; } nodekind_defs! { gen_nodekind_enum }
//Reads and writes to the db use diesel::prelude::*; use uuid::Uuid; use crate::schema::{markets}; use crate::api::components::market::model::Market; use crate::database::DbConn; pub fn insert_new_market(market : Market, connection : DbConn) -> Market { let db_con = &*connection; diesel::insert_into(markets::table) .values(&market) .get_result(db_con) .expect("Error saving new Market") } pub fn get_all_markets(connection : DbConn) -> Vec<Market> { let db_con = &*connection; markets::table.load::<Market>(db_con).expect("Error reading from markets") } pub fn get_market_by_id(uuid : Uuid, connection : DbConn) -> Market { let db_con = &*connection; markets::table.find(uuid).first(db_con).expect("Could not find Market") } pub fn update_market(market : Market, connection : DbConn) -> Market { let db_con = &*connection; diesel::update(markets::table) .set(&market) .get_result(db_con) .expect("Could not update market") } pub fn delete_market(uuid : Uuid, connection : DbConn) -> usize { let db_con = &*connection; diesel::delete(markets::table.filter(markets::id.eq(uuid))) .execute(db_con) .expect("Could not delete market") }
use bevy::math::Vec3; use bvh::{Point3, aabb::{AABB, Bounded}}; use crate::constants::CHUNK_SIZE; impl Bounded for crate::chunks::Voxel { fn aabb(&self) -> AABB { let min = self.position; let max = self.position + Vec3::ONE; AABB::with_bounds(Point3::new(min.x, min.y, min.z), Point3::new(max.x, max.y, max.z)) } } impl Bounded for crate::chunks::VoxelChunk { fn aabb(&self) -> AABB { let min = self.position; let max = self.position + (CHUNK_SIZE as f32) * Vec3::ONE; AABB::with_bounds(Point3::new(min.x, min.y, min.z), Point3::new(max.x, max.y, max.z)) } }
use libp2p::core::ConnectedPoint; use libp2p::swarm::{PollParameters, NetworkBehaviour, NetworkBehaviourAction}; use libp2p::multiaddr::Multiaddr; use std::error::Error; use tokio::prelude::{AsyncRead, AsyncWrite, Async}; use libp2p::PeerId; use std::collections::{VecDeque, HashSet, HashMap}; use crate::message::{ClientRequest, PrePrepareSequence, PrePrepare, Prepare, Commit, ClientReply}; use crate::handler::{PbftHandlerIn, PbftHandler, PbftHandlerEvent}; use crate::state::State; use libp2p::identity::Keypair; use std::sync::{Arc, RwLock}; pub struct Pbft<TSubstream> { keypair: Keypair, addresses: HashMap<PeerId, HashSet<Multiaddr>>, connected_peers: HashSet<PeerId>, queued_events: VecDeque<NetworkBehaviourAction<PbftHandlerIn, PbftEvent>>, state: State, pre_prepare_sequence: PrePrepareSequence, client_replies: Arc<RwLock<VecDeque<ClientReply>>>, _marker: std::marker::PhantomData<TSubstream>, } impl<TSubstream> Pbft<TSubstream> { pub fn new( keypair: Keypair, client_replies: Arc<RwLock<VecDeque<ClientReply>>>, ) -> Self { Self { keypair, addresses: HashMap::new(), connected_peers: HashSet::new(), queued_events: VecDeque::with_capacity(100), // FIXME state: State::new(), pre_prepare_sequence: PrePrepareSequence::new(), client_replies, _marker: std::marker::PhantomData, } } pub fn has_peer(&self, peer_id: &PeerId) -> bool { self.connected_peers.iter().any(|connected_peer_id| { connected_peer_id.clone() == peer_id.clone() }) } pub fn add_peer(&mut self, peer_id: &PeerId, address: &Multiaddr) { println!("[Pbft::add_peer] {:?}, {:?}", peer_id, address); { let mut addresses = match self.addresses.get(peer_id) { Some(addresses) => addresses.clone(), None => HashSet::new(), }; addresses.insert(address.clone()); self.addresses.insert(peer_id.clone(), addresses.clone()); } self.queued_events.push_back(NetworkBehaviourAction::DialPeer { peer_id: peer_id.clone(), }); } pub fn add_client_request(&mut self, client_request: ClientRequest) { println!("[Pbft::add_client_request] client_request: {:?}", client_request); // In the pre-prepare phase, the primary assigns a sequence number, n, to the request self.pre_prepare_sequence.increment(); let pre_prepare = PrePrepare::from( self.state.current_view(), self.pre_prepare_sequence.value(), client_request, ); println!("[Pbft::add_client_request] [broadcasting the pre_prepare message] pre_prepare: {:?}", pre_prepare); println!("[Pbft::add_client_request] [broadcasting to the peers] connected_peers: {:?}", self.connected_peers); if self.connected_peers.is_empty() { panic!("[Pbft::add_client_request] !!! connected_peers is empty !!!"); } for peer_id in self.connected_peers.iter() { self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id: peer_id.clone(), event: PbftHandlerIn::PrePrepareRequest(pre_prepare.clone()) }); } self.process_pre_prepare(pre_prepare).unwrap(); // TODO: error handling } fn process_pre_prepare(&mut self, pre_prepare: PrePrepare) -> Result<(), String> { self.validate_pre_prepare(&pre_prepare)?; self.state.insert_pre_prepare(pre_prepare.clone()); // If backup replica accepts the message, it enters the prepare phase by multicasting a PREPARE message to // all other replicas and adds both messages to its log. let prepare = Prepare::from(&pre_prepare); self.state.insert_prepare(PeerId::from_public_key(self.keypair.public()), prepare.clone()); if self.connected_peers.is_empty() { panic!("[Pbft::process_pre_prepare] !!! Peers not found !!!"); } for peer_id in self.connected_peers.iter() { self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id: peer_id.clone(), event: PbftHandlerIn::PrepareRequest(prepare.clone()) }) } Ok(()) } fn validate_pre_prepare(&self, pre_prepare: &PrePrepare) -> Result<(), String> { // TODO: the signatures in the request and the pre-prepare message are correct // _d_ is the digest for _m_ pre_prepare.validate_digest()?; { // it is in view _v_ let current_view = self.state.current_view(); if pre_prepare.view() != current_view { return Err(format!("view number isn't matched. message: {}, state: {}", pre_prepare.view(), current_view)); } // it has not accepted a pre-prepare message for view _v_ and sequence number _n_ containing a different digest match self.state.get_pre_prepare(pre_prepare) { Some(stored_pre_prepare) => { if pre_prepare.digest() != stored_pre_prepare.digest() { return Err(format!("The pre-prepare key has already stored into logs and its digest dont match. message: {}, stored message: {}", pre_prepare, stored_pre_prepare)); } } None => {} } } // TODO: the sequence number in the pre-prepare message is between a low water mark, _h_, and a high water mark, _H_ Ok(()) } fn validate_prepare(&self, prepare: &Prepare) -> Result<(), String> { // The replicas verify whether the prepares match the pre-prepare by checking that they have the // same view, sequence number, and digest. if let Some(pre_prepare) = self.state.get_pre_prepare_by_key(prepare.view(), prepare.sequence_number()) { if pre_prepare.digest() == prepare.digest() { return Ok(()); } return Err(format!("the Prepare request doesn't match with the PrePrepare. prepare: {}, pre-prepare: {}", prepare, pre_prepare)) } Err(format!("No PrePrepare that matches with the Prepare. prepare: {}", prepare)) } fn prepared(&self, view: u64, sequence_number: u64) -> bool { // 2f prepares from different backups that match the pre-prepare. let len = self.state.prepare_len(view, sequence_number); println!("[Pbft::prepared] prepare_len: {}", len); len >= 1 // TODO } fn validate_commit(&self, commit: &Commit) -> Result<(), String> { // TODO: properly signed // the view number in the message is equal to the replica's current view if commit.view() != self.state.current_view() { return Err(format!("The view number in the message is NOT equal to the replica's current view. Commit.view: {}, current_view: {}", commit.view(), self.state.current_view())); } // TODO: the sequence number is between h and H Ok(()) } // `committed(m, v, n)` is true if and only if `prepared(m, v, n, i)` is true for all _i_ in // some set of `f + 1` non-faulty replicas. #[allow(dead_code)] fn committed(&self, view: u64, sequence_number: u64) -> bool { let len = self.state.commit_len(view); let prepared = self.prepared(view, sequence_number); println!("[Pbft::committed] commit_len: {}, prepared: {}", len, prepared); prepared && len >= 1 // TODO: f + 1 } // `committed-local(m, v, n, i)` is true if and only if `prepared(m, v, n, i)` is true and _i_ // has accepted `2f + 1` commits (possibly including its own) from different replicas that match // the pre-prepare for _m_. fn committed_local(&self, view: u64, sequence_number: u64) -> bool { let len = self.state.commit_len(view); let prepared = self.prepared(view, sequence_number); println!("[Pbft::committed_local] commit_len: {}, prepared: {}", len, prepared); prepared && len >= 1 // TODO: 2f + 1 } } #[derive(Debug)] pub struct PbftFailure; impl Error for PbftFailure { } impl std::fmt::Display for PbftFailure { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("pbft failure") } } #[derive(Debug)] pub struct PbftEvent; impl<TSubstream> NetworkBehaviour for Pbft<TSubstream> where TSubstream: AsyncRead + AsyncWrite { type ProtocolsHandler = PbftHandler<TSubstream>; type OutEvent = PbftEvent; fn new_handler(&mut self) -> Self::ProtocolsHandler { println!("Pbft::new_handler()"); PbftHandler::new() } fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> { println!("[Pbft::addresses_of_peer] peer_id: {:?}", peer_id); match self.addresses.get(peer_id) { Some(addresses) => { println!("[Pbft::addresses_of_peer] peer_id: {:?}, addresses: {:?}", peer_id, addresses); addresses.clone().into_iter().collect() }, None => { println!("[Pbft::addresses_of_peer] addresses not found. peer_id: {:?}", peer_id); Vec::new() } } } fn inject_connected(&mut self, peer_id: PeerId, connected_point: ConnectedPoint) { println!("[Pbft::inject_connected] peer_id: {:?}, connected_point: {:?}", peer_id, connected_point); // match connected_point { // ConnectedPoint::Dialer { address } => { // }, // ConnectedPoint::Listener { .. } => {} // }; self.connected_peers.insert(peer_id); println!("[Pbft::inject_connected] connected_peers: {:?}, addresses: {:?}", self.connected_peers, self.addresses); } fn inject_disconnected(&mut self, peer_id: &PeerId, connected_point: ConnectedPoint) { println!("[Pbft::inject_disconnected] {:?}, {:?}", peer_id, connected_point); // let address = match connected_point { // ConnectedPoint::Dialer { address } => address, // ConnectedPoint::Listener { local_addr: _, send_back_addr } => send_back_addr // }; self.connected_peers.remove(peer_id); println!("[Pbft::inject_disconnected] connected_peers: {:?}, addresses: {:?}", self.connected_peers, self.addresses); } fn inject_node_event(&mut self, peer_id: PeerId, handler_event: PbftHandlerEvent) { println!("[Pbft::inject_node_event] handler_event: {:?}", handler_event); match handler_event { PbftHandlerEvent::ProcessPrePrepareRequest { request, connection_id } => { println!("[Pbft::inject_node_event] [PbftHandlerEvent::PrePrepareRequest] request: {:?}", request); self.process_pre_prepare(request.clone()).unwrap(); // TODO: error handling self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id, event: PbftHandlerIn::PrePrepareResponse("OK".into(), connection_id), }); } PbftHandlerEvent::Response { response } => { let response_message = String::from_utf8(response).expect("Failed to parse response"); println!("[Pbft::inject_node_event] [PbftHandlerEvent::Response] response_message: {:?}", response_message); if response_message == "OK" { println!("[Pbft::inject_node_event] [PbftHandlerEvent::Response] the communications has done successfully") } else { // TODO: retry? eprintln!("[Pbft::inject_node_event] [PbftHandlerEvent::Response] response_message: {:?}", response_message); } } PbftHandlerEvent::ProcessPrepareRequest { request, connection_id } => { println!("[Pbft::inject_node_event] [PbftHandlerEvent::ProcessPrepareRequest] request: {:?}", request); self.validate_prepare(&request).unwrap(); self.state.insert_prepare(peer_id.clone(), request.clone()); self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id, event: PbftHandlerIn::PrepareResponse("OK".into(), connection_id) }); if self.prepared(request.view(), request.sequence_number()) { let commit: Commit = request.into(); for p in self.connected_peers.iter() { self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id: p.clone(), event: PbftHandlerIn::CommitRequest(commit.clone()) }) } } } PbftHandlerEvent::ProcessCommitRequest { request, connection_id } => { println!("[Pbft::inject_node_event] [PbftHandlerEvent::ProcessCommitRequest] request: {:?}", request); self.validate_commit(&request).unwrap(); self.queued_events.push_back(NetworkBehaviourAction::SendEvent { peer_id: peer_id.clone(), event: PbftHandlerIn::CommitResponse("OK".into(), connection_id) }); // Replicas accept commit messages and insert them in their log self.state.insert_commit(peer_id, request.clone()); // Each replica _i_ executes the operation requested by _m_ after `committed-local(m, v, n, i)` is true if self.committed_local(request.view(), request.sequence_number()) { let client_request = self.state.get_pre_prepare_by_key(request.view(), request.sequence_number()).unwrap().client_reqeust(); println!("[Pbft::inject_node_event] [PbftHandlerEvent::ProcessCommitRequest] client_message: {:?}", client_request); // Discard requests whose timestamp is lower than the timestamp in the last reply this node sent to the client to guarantee exactly-once semantics. if client_request.timestamp() <= self.state.last_timestamp() { eprintln!( "[Pbft::inject_node_event] [PbftHandlerEvent::ProcessCommitRequest] the request was discarded as its timestamp is lower than the last timestamp. last_timestamp: {:?}", self.state.last_timestamp() ); return; } println!("[Pbft::inject_node_event] [PbftHandlerEvent::ProcessCommitRequest] the operation has been executed: {:?}", client_request.operation()); // After executing the requested operation, replicas send a reply to the client. let reply = ClientReply::new( PeerId::from_public_key(self.keypair.public()), client_request, &request ); println!("[Pbft::inject_node_event] [PbftHandlerEvent::ProcessCommitRequest] reply: {:?}", reply); self.state.update_last_timestamp(reply.timestamp()); self.client_replies.write().unwrap().push_back(reply); } } } } fn poll(&mut self, _: &mut impl PollParameters) -> Async<NetworkBehaviourAction<PbftHandlerIn, PbftEvent>> { println!("[Pbft::poll]"); if let Some(event) = self.queued_events.pop_front() { println!("[Pbft::poll] event: {:?}", event); return Async::Ready(event); } Async::NotReady } }
// SPDX-FileCopyrightText: 2020 Alexander Dean-Kennedy <dstar@slackless.com> // SPDX-License-Identifier: CC0-1.0 use std::env; use genpdf::Alignment; use genpdf::Element as _; use genpdf::{elements, fonts, style}; const FONT_DIRS: &[&str] = &[ "/usr/share/fonts/liberation", "/usr/share/fonts/truetype/liberation", ]; const DEFAULT_FONT_NAME: &'static str = "LiberationSans"; const IMAGE_PATH_JPG: &'static str = "examples/images/test_image.jpg"; const IMAGE_PATH_BMP: &'static str = "examples/images/test_image.bmp"; const IMAGE_PATH_PNG: &'static str = "examples/images/test_image.png"; fn main() { let args: Vec<_> = env::args().skip(1).collect(); if args.len() != 1 { panic!("Missing argument: output file"); } let output_file = &args[0]; let font_dir = FONT_DIRS .iter() .filter(|path| std::path::Path::new(path).exists()) .next() .expect("Could not find font directory"); let default_font = fonts::from_files(font_dir, DEFAULT_FONT_NAME, Some(fonts::Builtin::Helvetica)) .expect("Failed to load the default font family"); let mut doc = genpdf::Document::new(default_font); doc.set_title("genpdf Demo Document"); doc.set_minimal_conformance(); doc.set_line_spacing(1.25); let mut decorator = genpdf::SimplePageDecorator::new(); decorator.set_margins(10); decorator.set_header(|page| { let mut layout = elements::LinearLayout::vertical(); if page > 1 { layout.push( elements::Paragraph::new(format!("Page {}", page)).aligned(Alignment::Center), ); layout.push(elements::Break::new(1)); } layout.styled(style::Style::new().with_font_size(10)) }); doc.set_page_decorator(decorator); doc.push( elements::Paragraph::new("genpdf Image Tests") .aligned(Alignment::Center) .styled(style::Style::new().bold().with_font_size(20)), ); doc.push(elements::Break::new(1.5)); doc.push(elements::Paragraph::new( "You may also: override the position, dpi, and/or default line-breaks, etc. See image here =>" )); doc.push( elements::Image::from_path(IMAGE_PATH_JPG) .expect("Unable to load alt image") .with_position(genpdf::Position::new(170, -10)) // far over to right and down .with_clockwise_rotation(90.0), ); // adding a break to avoid the image posted above with an "absolute image. doc.push(elements::Break::new(2)); // IMAGE FILE TYPE HANDLING: doc.push(elements::Paragraph::new( "Table with image format/scaling tests:", )); let mut img_table = elements::TableLayout::new(vec![2, 2, 2, 2]); img_table.set_cell_decorator(elements::FrameCellDecorator::new(true, true, false)); img_table .row() .element(elements::Text::new("Format").padded(1)) .element(elements::Text::new("1:1").padded(1)) .element(elements::Text::new("Half Size").padded(1)) .element(elements::Text::new("Double Size").padded(1)) .push() .expect("Invalid row"); for (ftype, path) in vec![ ("BMP", IMAGE_PATH_BMP), ("JPG", IMAGE_PATH_JPG), ("PNG", IMAGE_PATH_PNG), ] { let img = elements::Image::from_path(path).expect("invalid image"); let mut row = img_table .row() .element(elements::Paragraph::new(ftype).padded(1)); for scale in &[1.0, 0.5, 2.0] { row.push_element( img.clone() .with_scale(genpdf::Scale::new(*scale, *scale)) .framed(style::LineStyle::new()) .padded(1), ); } row.push().expect("Invalid row"); } doc.push(img_table); doc.push(elements::Break::new(2)); doc.push(elements::Paragraph::new( "Table with image rotation/offset calculation tests:", )); let mut rot_table = elements::TableLayout::new(vec![2, 2, 2, 2, 2, 2, 2]); rot_table.set_cell_decorator(elements::FrameCellDecorator::new(true, true, false)); let mut heading_row: Vec<Box<dyn genpdf::Element>> = vec![Box::new(elements::Text::new("Rot").padded(1))]; let mut pos_row: Vec<Box<dyn genpdf::Element>> = vec![Box::new(elements::Text::new("Positive").padded(1))]; let mut neg_row: Vec<Box<dyn genpdf::Element>> = vec![Box::new(elements::Text::new("Negative").padded(1))]; let img = elements::Image::from_path(IMAGE_PATH_JPG).expect("invalid image"); for rot in &[30, 45, 90, 120, 150, 180] { heading_row.push(Box::new(elements::Text::new(format!("{}°", rot)).padded(1))); let rot = f64::from(*rot); pos_row.push(Box::new( img.clone() .with_clockwise_rotation(rot) .framed(style::LineStyle::new()) .padded(1), )); neg_row.push(Box::new( img.clone() .with_clockwise_rotation(rot * -1.0) .framed(style::LineStyle::new()) .padded(1), )); } rot_table.push_row(heading_row).expect("Invalid row"); rot_table.push_row(pos_row).expect("Invalid row"); rot_table.push_row(neg_row).expect("Invalid row"); doc.push(rot_table); doc.render_to_file(output_file) .expect("Failed to write output file"); }
#![allow(dead_code)] use std::ffi::OsStr; use std::ffi::OsString; use std::io; use std::io::Write; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; use std::sync::RwLock; use hashbrown::HashSet; use rayon::prelude::*; use slog::{debug, o, Level, Logger}; use walkdir::WalkDir; use chainerror::prelude::v1::*; use regex::bytes::Regex; use crate::elfkit::ld_so_cache::LdsoCache; use crate::elfkit::ldd::Ldd; use crate::file::{canonicalize_dir, clone_path}; pub use crate::modules::modalias_list; use dynqueue::IntoDynQueue; mod acl; mod cstrviter; mod elfkit; mod file; mod modules; mod readstruct; pub type ResultSend<T> = std::result::Result<T, Box<dyn std::error::Error + 'static + Send>>; pub struct RunContext { pub hmac: bool, pub createdir: bool, pub optional: bool, pub silent: bool, pub all: bool, pub module: bool, pub modalias: bool, pub resolvelazy: bool, pub resolvedeps: bool, pub hostonly: bool, pub loglevel: Level, pub destrootdir: PathBuf, pub kerneldir: Option<OsString>, pub logdir: Option<OsString>, pub logger: Logger, pub mod_filter_path: Option<Regex>, pub mod_filter_nopath: Option<Regex>, pub mod_filter_symbol: Option<Regex>, pub mod_filter_nosymbol: Option<Regex>, pub mod_filter_noname: Option<Regex>, pub firmwaredirs: Vec<OsString>, pub pathdirs: Vec<OsString>, } impl Default for RunContext { fn default() -> Self { RunContext { hmac: false, createdir: false, optional: false, silent: false, all: false, module: false, modalias: false, resolvelazy: false, resolvedeps: false, hostonly: false, loglevel: Level::Critical, destrootdir: Default::default(), kerneldir: None, logdir: None, logger: slog::Logger::root(slog::Discard, o!()), mod_filter_path: None, mod_filter_nopath: None, mod_filter_symbol: None, mod_filter_nosymbol: None, mod_filter_noname: None, firmwaredirs: vec![], pathdirs: vec![], } } } pub fn ldd(files: &[OsString], report_error: bool, dest_path: &Path) -> Vec<OsString> { let sysroot = OsStr::new("/"); let cache = LdsoCache::read_ld_so_cache(sysroot).ok(); let standard_libdirs = vec![OsString::from("/lib64/dyninst"), OsString::from("/lib64")]; let visited = RwLock::new(HashSet::<OsString>::new()); let ldd = Ldd::new(cache.as_ref(), &standard_libdirs, dest_path); let mut _buf = Vec::<u8>::new(); //let lpaths = HashSet::new(); let dest = OsString::from(dest_path.as_os_str()); let filequeue = files .to_vec() .drain(..) .map(|path| { canonicalize_dir(PathBuf::from(path)) .unwrap() .as_os_str() .to_os_string() }) .map(|path| { visited.write().unwrap().insert(path.clone()); (path, HashSet::new()) }) .collect::<Vec<_>>() .into_dyn_queue(); filequeue .into_par_iter() .filter_map(|(handle, (path, lpaths))| { let mut dest = dest.clone(); dest.push(path.as_os_str()); let dest = PathBuf::from(dest); if !dest.exists() { ldd.recurse(handle, &path, &lpaths, &visited) .unwrap_or_else(|e| { if report_error { let stderr = io::stderr(); let mut stderr = stderr.lock(); let _ = stderr.write_all(path.as_bytes()); let _ = stderr.write_all(b": "); let _ = stderr.write_all(e.to_string().as_bytes()); let _ = stderr.write_all(b"\n"); } }); Some(path) } else { None } }) .collect::<Vec<_>>() } pub fn install_files_ldd( ctx: &mut RunContext, files: &[OsString], ) -> Result<(), Box<dyn std::error::Error + 'static + Send + Sync>> { debug!(ctx.logger, "Path = {:#?}", ctx.pathdirs); debug!(ctx.logger, "FirmwareDirs = {:#?}", ctx.firmwaredirs); debug!(ctx.logger, "KernelDir = {:#?}", ctx.kerneldir); let res = ldd(&files, true, &ctx.destrootdir); debug!(ctx.logger, "install {:#?}", res); install_files(ctx, &res) } pub fn install_files( ctx: &mut RunContext, files: &[OsString], ) -> Result<(), Box<dyn std::error::Error + 'static + Send + Sync>> { for i in files { clone_path(&PathBuf::from(i), &ctx.destrootdir)?; } Ok(()) } //noinspection RsUnresolvedReference,RsUnresolvedReference pub fn install_modules( ctx: &mut RunContext, module_args: &[OsString], ) -> Result<(), Box<dyn std::error::Error + 'static + Send + Sync>> { let visited = RwLock::new(HashSet::<OsString>::new()); let kmod_ctx = kmod::Context::new_with(ctx.kerneldir.as_deref(), None) .context("kmod::Context::new_with")?; let (module_iterators, errors): (Vec<_>, Vec<_>) = module_args .iter() .flat_map(|module| { if module.as_bytes().starts_with(b"/") { debug!(ctx.logger, "by file path"); let m = kmod_ctx .module_new_from_path(module.to_str().unwrap()) .unwrap(); return if let Some(name) = m.name() { vec![kmod_ctx.module_new_from_lookup(&OsString::from(name))] } else { vec![Err(kmod::ErrorKind::Errno(kmod::Errno(42)).into())] }; } else if module.as_bytes().starts_with(b"=") { let (_, b) = module.as_bytes().split_at(1); let driver_dir = OsString::from_vec(b.to_vec()); let mut dirname = PathBuf::from(kmod_ctx.dirname()); dirname.push("kernel"); if !driver_dir.is_empty() { dirname.push(driver_dir); } debug!(ctx.logger, "driver_dir {}", dirname.to_str().unwrap()); WalkDir::new(dirname) .into_iter() .filter_map(std::result::Result::<_, _>::ok) .filter(|e| e.path().is_file()) .map(|e| { kmod_ctx .module_new_from_path(e.path().to_str().unwrap()) .and_then(|m| { m.name() .ok_or_else(|| kmod::ErrorKind::Errno(kmod::Errno(42)).into()) .map(OsString::from) }) .and_then(|name| kmod_ctx.module_new_from_lookup(&name)) }) .collect::<Vec<_>>() } else { debug!(ctx.logger, "by name {}", module.to_str().unwrap()); if let Some(module) = PathBuf::from(module).file_stem() { debug!(ctx.logger, "file stem {}", module.to_str().unwrap()); if let Some(module) = PathBuf::from(module).file_stem() { debug!(ctx.logger, "file stem {}", module.to_str().unwrap()); vec![kmod_ctx.module_new_from_lookup(module)] } else { vec![kmod_ctx.module_new_from_lookup(module)] } } else { vec![kmod_ctx.module_new_from_lookup(module)] } } }) .partition(kmod::Result::is_ok); let errors: Vec<_> = errors.into_iter().map(kmod::Result::unwrap_err).collect(); if !errors.is_empty() { for e in errors { eprintln!("Module Error: {:?}", e); } return Err("Module errors".into()); } let modules: Vec<_> = module_iterators .into_iter() .map(kmod::Result::unwrap) .flat_map(|it| it.collect::<Vec<_>>()) .collect(); let install_errors: Vec<_> = modules .into_iter() .map(|m| install_module(ctx, &kmod_ctx, &m, &visited, true)) .filter(ChainResult::is_err) .map(ChainResult::unwrap_err) .collect(); if !install_errors.is_empty() { for e in install_errors { eprintln!("{:?}", e); } return Err("Module errors".into()); } let files = visited.write().unwrap().drain().collect::<Vec<_>>(); install_files(ctx, &files) } derive_str_context!(InstallModuleError); fn filter_module_name_path_symbols(ctx: &RunContext, module: &kmod::Module, path: &OsStr) -> bool { if let Some(name) = module.name() { if let Some(ref r) = ctx.mod_filter_noname { if r.is_match(name.as_bytes()) { return false; } } } if let Some(ref r) = ctx.mod_filter_nopath { if r.is_match(path.as_bytes()) { return false; } } if let Some(ref r) = ctx.mod_filter_path { if !r.is_match(path.as_bytes()) { return false; } } if ctx.mod_filter_nosymbol.is_none() && ctx.mod_filter_symbol.is_none() { return true; } let sit = match module.dependency_symbols() { Err(e) => { slog::warn!( ctx.logger, "Error getting dependency symbols for {:?}: {}", path, e ); return true; } Ok(sit) => sit, }; for symbol in sit { if let Some(ref r) = ctx.mod_filter_nosymbol { if r.is_match(symbol.as_bytes()) { return false; } } if let Some(ref r) = ctx.mod_filter_symbol { if r.is_match(symbol.as_bytes()) { return true; } } } false } fn install_module( ctx: &RunContext, kmod_ctx: &kmod::Context, module: &kmod::Module, visited: &RwLock<HashSet<OsString>>, filter: bool, ) -> ChainResult<(), InstallModuleError> { debug!( ctx.logger, "handling module <{:?}>", module.name().unwrap_or_default() ); let path = match module.path() { Some(p) => p, None => { // FIXME: Error or not? //use slog::warn; //warn!(ctx.logger, "No path for module `{}´", module.name()); return Ok(()); } }; if filter && !filter_module_name_path_symbols(ctx, module, &path) { debug!( ctx.logger, "No name or symbol or path match for '{:?}'", path ); return Ok(()); } if visited.write().unwrap().insert(path.into()) { for m in module.dependencies() { install_module(ctx, kmod_ctx, &m, visited, false)?; } if let Ok((pre, _post)) = module.soft_dependencies() { for pre_mod in pre { let name = pre_mod .name() .ok_or("pre_mod_error") .context(InstallModuleError(format!( "Failed to get name for {:?}", pre_mod )))?; let it = kmod_ctx .module_new_from_lookup(&OsString::from(&name)) .context(InstallModuleError(format!("Failed lookup for {:?}", name)))?; for m in it { debug!(ctx.logger, "pre <{:?}>", m.path()); install_module(ctx, kmod_ctx, &m, visited, false)?; } } } } else { debug!(ctx.logger, "cache hit <{:?}>", module.name()); } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::ffi::OsString; use slog::*; use slog_async::OverflowStrategy; use slog_term; use tempfile::TempDir; #[test] fn test_modules() { let tmpdir = TempDir::new_in("/var/tmp").unwrap().into_path(); let mut ctx: RunContext = RunContext { destrootdir: tmpdir, module: true, loglevel: Level::Info, ..Default::default() }; let decorator = slog_term::TermDecorator::new().build(); let drain = slog_term::FullFormat::new(decorator) .use_original_order() .build() .filter_level(ctx.loglevel) .fuse(); let drain = slog_async::Async::new(drain) .overflow_strategy(OverflowStrategy::Block) .build() .fuse(); ctx.logger = Logger::root(drain, o!()); if let Err(e) = install_modules(&mut ctx, &vec![OsString::from("=")]) { panic!("Error: {:?}", e); } } #[test] fn test_usr() { use std::fs::read_dir; let tmpdir = TempDir::new_in("/var/tmp").unwrap().into_path(); let files = read_dir("/usr/bin") .unwrap() .map(|e| OsString::from(e.unwrap().path().as_os_str())) .collect::<Vec<_>>(); let mut res = ldd(&files, false, &tmpdir); eprintln!("no. files = {}", res.len()); let hs: HashSet<OsString> = res.iter().cloned().collect(); eprintln!("no. unique files = {}", hs.len()); assert_eq!(hs.len(), res.len()); res.sort(); eprintln!("files = {:#?}", res); } }
// 16.16 Contiguous Sequence fn contiguous_sequence(array: &[i32]) -> (usize, usize) { // Returns inclusive bounds of subarray with maximal sum. // O(n) time, O(1) space. // We iterate through the array, keeping the maximal subarray and // maximal suffix as invariants. When a new element is better than // the whole suffix, the old suffix is abandoned. As every subarray // was a suffix at some point, we just keep the maximal encountered // suffix. if array.is_empty() { return (0, 0); } if array.len() == 1 { return (0, 0); } let mut left = 0; let mut right = 0; let mut subarray_sum = array[0]; let mut left_suffix = 0; let mut suffix_sum = array[0]; for index in 1..array.len() { if array[index] > array[index] + suffix_sum { left_suffix = index; suffix_sum = array[index]; } else { suffix_sum += array[index]; } if suffix_sum > subarray_sum { left = left_suffix; right = index; subarray_sum = suffix_sum; } } (left, right) } #[test] fn test() { assert!(contiguous_sequence(&[2, -8, 3, -2, 4, -10]) == (2, 4)); println!("Ex 16.17 ok!"); }
use crate::rtb_type; rtb_type! { ApiFramework, 500, VPAID1=1; VPAID2=2; MRAID1=3; ORMMA=4; MRAID2=5; MRAID3=6; OMID1=7; SIMID=8 }
use ckb_error::Error; use ckb_store::{ChainStore, StoreTransaction}; use ckb_types::{ core::{BlockView, TransactionMeta}, packed::Byte32, prelude::*, }; use im::hashmap as hamt; use im::hashmap::HashMap as HamtMap; pub fn attach_block_cell( txn: &StoreTransaction, block: &BlockView, cell_set: &mut HamtMap<Byte32, TransactionMeta>, ) -> Result<(), Error> { for tx in block.transactions() { for cell in tx.input_pts_iter() { if let hamt::Entry::Occupied(mut o) = cell_set.entry(cell.tx_hash().clone()) { o.get_mut().set_dead(cell.index().unpack()); if o.get().all_dead() { txn.delete_cell_set(&cell.tx_hash())?; o.remove_entry(); } else { txn.update_cell_set(&cell.tx_hash(), &o.get().pack())?; } } } let tx_hash = tx.hash(); let outputs_len = tx.outputs().len(); let meta = if tx.is_cellbase() { TransactionMeta::new_cellbase( block.number(), block.epoch().number(), block.hash(), outputs_len, false, ) } else { TransactionMeta::new( block.number(), block.epoch().number(), block.hash(), outputs_len, false, ) }; txn.update_cell_set(&tx_hash, &meta.pack())?; cell_set.insert(tx_hash.to_owned(), meta); } Ok(()) } pub fn detach_block_cell( txn: &StoreTransaction, block: &BlockView, cell_set: &mut HamtMap<Byte32, TransactionMeta>, ) -> Result<(), Error> { for tx in block.transactions().iter().rev() { txn.delete_cell_set(&tx.hash())?; cell_set.remove(&tx.hash()); for cell in tx.input_pts_iter() { let cell_tx_hash = cell.tx_hash(); let index: usize = cell.index().unpack(); if let Some(tx_meta) = cell_set.get_mut(&cell_tx_hash) { tx_meta.unset_dead(index); txn.update_cell_set(&cell_tx_hash, &tx_meta.pack())?; } else { // the tx is full dead, deleted from cellset, we need recover it when fork if let Some((tx, header)) = txn.get_transaction(&cell_tx_hash) .and_then(|(tx, block_hash)| { txn.get_block_header(&block_hash).map(|header| (tx, header)) }) { let mut meta = if tx.is_cellbase() { TransactionMeta::new_cellbase( header.number(), header.epoch().number(), header.hash(), tx.outputs().len(), true, // init with all dead ) } else { TransactionMeta::new( header.number(), header.epoch().number(), header.hash(), tx.outputs().len(), true, // init with all dead ) }; meta.unset_dead(index); // recover txn.update_cell_set(&cell_tx_hash, &meta.pack())?; cell_set.insert(cell_tx_hash, meta); } } } } Ok(()) }
use std::io::{self, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap; fn main() -> io::Result<()> { let f = File::open("input.txt")?; let f = BufReader::new(f); let mut lines = f.lines(); let first_wire = lines.next().unwrap()?; let second_wire = lines.next().unwrap()?; let mut map: HashMap<i32, HashMap<i32, u8>> = HashMap::new(); let mut shortest_distance = 0; let mut x = 0; let mut y = 0; for op in first_wire.split(",") { let direction = &op[0..1]; let mut distance: i32 = op[1..].parse().expect("must be a number"); while distance > 0 { match direction { "U" => y += 1, "D" => y -= 1, "R" => x += 1, "L" => x -= 1, _ => panic!("invalid direction: {}", direction), } let column = map.entry(x).or_insert(HashMap::new()); column.insert(y, 1); distance -= 1; } } x = 0; y = 0; for op in second_wire.split(",") { let direction = &op[0..1]; let mut distance: i32 = op[1..].parse().expect("must be a number"); while distance > 0 { match direction { "U" => y += 1, "D" => y -= 1, "R" => x += 1, "L" => x -= 1, _ => panic!("invalid direction: {}", direction), } let column = map.entry(x).or_insert(HashMap::new()); let result = column.entry(y).and_modify(|val| *val |= 2).or_insert(2); if *result == 3 { let from_start = x.abs() + y.abs(); if shortest_distance == 0 || from_start < shortest_distance { shortest_distance = from_start; } } distance -= 1; } } println!("{:?}", shortest_distance); Ok(()) }
use log::warn; use nix::libc; use nix::sys::mman; use nix::unistd; use std::ffi::c_void; use std::fs::File; use std::os::unix::io::AsRawFd; use std::path::Path; use std::ptr::null_mut; #[cfg(target_os = "linux")] type MincoreChar = u8; #[cfg(target_os = "macos")] type MincoreChar = i8; pub struct MappedFile { file: File, len: usize, mmap: *mut c_void, mincore_array: *mut MincoreChar, page_size: usize, pages: usize, } #[derive(Debug)] pub struct MincoreStat { page_size: usize, total_pages: usize, resident_pages: usize, } impl MincoreStat { pub fn page_size(&self) -> usize { self.page_size } pub fn total_pages(&self) -> usize { self.total_pages } pub fn resident_pages(&self) -> usize { self.resident_pages } } impl Drop for MappedFile { fn drop(&mut self) { unsafe { libc::free(self.mincore_array as *mut c_void); Self::_cleanup_mmap(self.mmap, self.len); } } } #[derive(Debug)] pub enum Error { IO(std::io::Error), NotPageAligned, AllocFailed, Nix(nix::Error), } pub type Result<T> = core::result::Result<T, Error>; impl MappedFile { pub fn open<P: AsRef<Path>>(path: P) -> Result<MappedFile> { let page_size = unistd::sysconf(unistd::SysconfVar::PAGE_SIZE) .ok() .flatten() .expect("Failed to get page size") as usize; let file = File::open(path).map_err(Error::IO)?; let file_meta = file.metadata().map_err(Error::IO)?; let file_len = file_meta.len() as usize; let mmap = unsafe { mman::mmap( null_mut(), file_len, mman::ProtFlags::PROT_READ, mman::MapFlags::MAP_SHARED, file.as_raw_fd(), 0, ) } .map_err(Error::Nix)?; if (mmap as i64 & (page_size - 1) as i64) != 0 { Self::_cleanup_mmap(mmap, file_len); return Err(Error::NotPageAligned); } let pages = (file_len + page_size + 1) / page_size; let mincore_array = unsafe { libc::malloc(pages) } as *mut MincoreChar; if mincore_array.is_null() { Self::_cleanup_mmap(mmap, file_len); return Err(Error::AllocFailed); } unsafe { if let Err(err) = nix::Error::result(libc::mincore(mmap, file_len, mincore_array)) { libc::free(mincore_array as *mut c_void); Self::_cleanup_mmap(mmap, file_len); return Err(Error::Nix(err)); } }; Ok(MappedFile { file, len: file_len, mmap, mincore_array, page_size, pages, }) } fn _cleanup_mmap(mmap: *mut c_void, len: usize) { unsafe { if let Err(err) = mman::munmap(mmap, len) { warn!("failed to unmap. error: {}", err.desc()); } } } pub fn resident_pages(&self) -> MincoreStat { let resident_pages = (0..self.pages) .filter(|&i| (unsafe { self.mincore_array.add(i).read() }) & 0x1 != 0) .count(); MincoreStat { page_size: self.page_size, total_pages: self.pages, resident_pages, } } pub fn touch(&mut self) { unsafe { for i in 0..self.pages { (self.mmap as *mut i8).add(i * self.page_size).read(); self.mincore_array.add(i).write(1); } } } #[cfg(target_os = "macos")] pub fn evict(&mut self) -> Result<()> { unsafe { nix::sys::mman::msync(self.mmap, self.len, nix::sys::mman::MsFlags::MS_INVALIDATE) } .map_err(Error::Nix) } #[cfg(target_os = "linux")] pub fn evict(&mut self) -> Result<()> { match nix::fcntl::posix_fadvise( self.file.as_raw_fd(), 0, self.len as i64, nix::fcntl::PosixFadviseAdvice::POSIX_FADV_DONTNEED, ) { Ok(ret) if ret == 0 => Ok(()), Ok(ret) => Err(Error::Nix(nix::Error::from_i32(ret))), Err(err) => Err(Error::Nix(err)), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_file_not_exist() { let mmap = MappedFile::open("/__foo_bar_invalid__"); assert!(mmap.is_err()); } #[test] fn test_resident_pages() { let mmap = MappedFile::open("/etc/hosts").unwrap(); assert!(mmap.resident_pages().resident_pages <= mmap.resident_pages().total_pages); } #[test] fn test_touch() { let mut mmap = MappedFile::open("/etc/hosts").unwrap(); mmap.touch(); } #[test] fn test_evict() { let mut mmap = MappedFile::open("/etc/hosts").unwrap(); mmap.evict().unwrap(); } }
use super::ids::Id; #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Size { MatchParent, WrapContent, Exact(u16), } #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Alignment { None, Above(Id), Below(Id), ToLeftOf(Id), ToRightOf(Id), AlignTop(Id), AlignBottom(Id), AlignLeft(Id), AlignRight(Id), AlignParentLeft, AlignParentRight, AlignParentTop, AlignParentBottom, } #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum BoundarySize { AllTheSame(i32), OrthoDirections(i32, i32), Distinct(i32, i32, i32, i32), } impl From<(i32, i32, i32, i32)> for BoundarySize { fn from(a: (i32, i32, i32, i32)) -> BoundarySize { let h = a.0 == a.2; let v = a.1 == a.3; if h && v { if a.0 == a.1 { BoundarySize::AllTheSame(a.0) } else { BoundarySize::OrthoDirections(a.0, a.1) } } else { BoundarySize::Distinct(a.0, a.1, a.2, a.3) } } } impl From<BoundarySize> for (i32, i32, i32, i32) { fn from(a: BoundarySize) -> (i32, i32, i32, i32) { match a { BoundarySize::AllTheSame(v) => (v, v, v, v), BoundarySize::OrthoDirections(lr, tb) => (lr, tb, lr, tb), BoundarySize::Distinct(l, t, r, b) => (l, t, r, b), } } } pub enum BoundarySizeParam { OrthoHorizontal(i32), OrthoVertical(i32), Left(i32), Top(i32), Right(i32), Bottom(i32), } impl ::std::ops::BitOr<BoundarySizeParam> for BoundarySizeParam { type Output = BoundarySize; fn bitor(self, rhs: BoundarySizeParam) -> Self::Output { let mut left = 0; let mut top = 0; let mut right = 0; let mut bottom = 0; match self { BoundarySizeParam::OrthoHorizontal(lr) => { left = lr; right = lr; } BoundarySizeParam::OrthoVertical(tb) => { top = tb; bottom = tb; } BoundarySizeParam::Left(l) => left = l, BoundarySizeParam::Top(t) => { top = t; } BoundarySizeParam::Right(r) => { right = r; } BoundarySizeParam::Bottom(b) => { bottom = b; } } match rhs { BoundarySizeParam::OrthoHorizontal(lr) => { left = lr; right = lr; } BoundarySizeParam::OrthoVertical(tb) => { top = tb; bottom = tb; } BoundarySizeParam::Left(l) => left = l, BoundarySizeParam::Top(t) => { top = t; } BoundarySizeParam::Right(r) => { right = r; } BoundarySizeParam::Bottom(b) => { bottom = b; } } (left, top, right, bottom).into() } } impl ::std::ops::BitOr<BoundarySizeParam> for BoundarySize { type Output = BoundarySize; fn bitor(self, rhs: BoundarySizeParam) -> Self::Output { let (mut left, mut top, mut right, mut bottom) = self.into(); match rhs { BoundarySizeParam::OrthoHorizontal(lr) => { left = lr; right = lr; } BoundarySizeParam::OrthoVertical(tb) => { top = tb; bottom = tb; } BoundarySizeParam::Left(l) => left = l, BoundarySizeParam::Top(t) => { top = t; } BoundarySizeParam::Right(r) => { right = r; } BoundarySizeParam::Bottom(b) => { bottom = b; } } (left, top, right, bottom).into() } } pub enum BoundarySizeArgs { Param(BoundarySizeParam), Set(BoundarySize), } impl From<BoundarySizeParam> for BoundarySizeArgs { fn from(a: BoundarySizeParam) -> BoundarySizeArgs { BoundarySizeArgs::Param(a) } } impl From<BoundarySizeParam> for BoundarySize { fn from(a: BoundarySizeParam) -> BoundarySize { BoundarySize::AllTheSame(0) | a } } impl From<BoundarySize> for BoundarySizeArgs { fn from(a: BoundarySize) -> BoundarySizeArgs { BoundarySizeArgs::Set(a) } } impl From<BoundarySizeArgs> for BoundarySize { fn from(a: BoundarySizeArgs) -> BoundarySize { match a { BoundarySizeArgs::Param(param) => param.into(), BoundarySizeArgs::Set(set) => set, } } } #[repr(u8)] #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Orientation { Horizontal, Vertical, } #[derive(Debug, Clone)] pub struct Attributes { pub width: Size, pub height: Size, } impl Default for Attributes { fn default() -> Attributes { Attributes { width: Size::MatchParent, height: Size::WrapContent, } } }
use hyper::{body, header, Body, Method, Request, Uri}; use serde_derive::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt::{Display, Formatter, Result}; mod auth; pub mod batch; pub mod cli; pub use auth::*; const DEFAULT_COUNT: u32 = 5000; #[derive(Serialize, Deserialize, Debug)] pub struct Item { given_url: String, resolved_url: Option<String>, given_title: String, resolved_title: Option<String>, favorite: String, status: String, } pub type ReadingList = BTreeMap<String, Item>; #[derive(Deserialize)] struct ReadingListResponse { list: ReadingList, } enum ResponseState { Parsed(ReadingListResponse), NoMore, Error(serde_json::Error), } enum Action { Archive, Favorite, Add, } #[derive(PartialEq)] pub enum FavoriteStatus { Favorited, NotFavorited, } #[derive(PartialEq)] pub enum Status { Read, Unread, } impl Display for Status { fn fmt(&self, f: &mut Formatter) -> Result { write!( f, "{}", match *self { Status::Read => "Read", Status::Unread => "Unread", } ) } } impl Item { pub fn url(&self) -> &str { if let Some(resolved) = &self.resolved_url { if !resolved.is_empty() { return resolved; } } &self.given_url } pub fn title(&self) -> &str { let title = self.resolved_title.as_ref().unwrap_or(&self.given_title); if title.is_empty() { self.url() } else { title } } pub fn favorite(&self) -> FavoriteStatus { if &self.favorite == "1" { FavoriteStatus::Favorited } else { FavoriteStatus::NotFavorited } } pub fn status(&self) -> Status { if &self.status == "1" { Status::Read } else { Status::Unread } } } impl Client { pub async fn mark_as_read<'a, T>(&self, ids: T) where T: IntoIterator<Item = &'a str>, { self.modify(Action::Archive, ids).await; } pub async fn mark_as_favorite<'a, T>(&self, ids: T) where T: IntoIterator<Item = &'a str>, { self.modify(Action::Favorite, ids).await; } pub async fn add_urls<'a, T>(&self, urls: T) where T: IntoIterator<Item = &'a str>, { self.modify(Action::Add, urls).await; } pub async fn list_all(&self) -> ReadingList { let mut reading_list: ReadingList = Default::default(); let mut offset = 0; loop { let method = url("/get"); let payload = format!( r##"{{ "consumer_key":"{}", "access_token":"{}", "sort":"site", "state":"all", "detailType":"simple", "count":"{}", "offset":"{}" }}"##, &self.consumer_key, &self.authorization_code, DEFAULT_COUNT, (offset * DEFAULT_COUNT) ); let response = self.request(method, payload).await; match parse_all_response(&response) { ResponseState::NoMore => break, ResponseState::Parsed(parsed_response) => { offset += 1; reading_list.extend(parsed_response.list.into_iter()) } ResponseState::Error(e) => panic!("Failed to parse the payload: {:?}", e), } } reading_list } async fn modify<'a, T>(&self, action: Action, ids: T) where T: IntoIterator<Item = &'a str>, { let method = url("/send"); let action_verb = match action { Action::Favorite => "favorite", Action::Archive => "archive", Action::Add => "add", }; let item_key = match action { Action::Add => "url", _ => "item_id", }; let time = chrono::Utc::now().timestamp(); let actions: Vec<String> = ids .into_iter() .map(|id| { format!( r##"{{ "action": "{}", "{}": "{}", "time": "{}" }}"##, action_verb, item_key, id, time ) }) .collect(); let payload = format!( r##"{{ "consumer_key":"{}", "access_token":"{}", "actions": [{}] }}"##, &self.consumer_key, &self.authorization_code, actions.join(", ") ); self.request(method, payload).await; } async fn request(&self, uri: Uri, payload: String) -> String { let client = auth::https_client(); let req = Request::builder() .method(Method::POST) .uri(uri) .header(header::CONTENT_TYPE, "application/json") .header(header::CONNECTION, "close") .body(Body::from(payload.clone())) .unwrap(); let res = client .request(req) .await .unwrap_or_else(|_| panic!("Could not make request with payload: {}", &payload)); let body_bytes = body::to_bytes(res.into_body()) .await .expect("Could not read the HTTP request's body"); String::from_utf8(body_bytes.to_vec()).expect("Response was not valid UTF-8") } } fn parse_all_response(response: &str) -> ResponseState { match serde_json::from_str::<ReadingListResponse>(response) { Ok(r) => ResponseState::Parsed(r), Err(e) => { if e.is_data() { ResponseState::NoMore } else { ResponseState::Error(e) } } } } fn fixup_blogspot(url: &str) -> String { let split: Vec<_> = url.split(".blogspot.").collect(); if split.len() == 2 { format!("{}.blogspot.com", split[0]) } else { url.into() } } fn start_domain_from(url: &str) -> usize { if url.starts_with("www.") { 4 } else { 0 } } fn cleanup_path(path: &str) -> &str { path.trim_end_matches("index.html") .trim_end_matches("index.php") .trim_end_matches('/') } pub fn cleanup_url(url: &str) -> String { if let Ok(parsed) = url.parse::<Uri>() { let current_host = parsed.host().expect("Cleaned up an url without a host"); let starts_from = start_domain_from(current_host); format!( "https://{}{}", fixup_blogspot(&current_host[starts_from..]), cleanup_path(parsed.path()) ) } else { url.into() } } #[cfg(test)] mod test { use super::*; #[test] fn test_clean_url_hash() { let url_ = "http://example.com#asdfas.fsa"; assert_eq!(cleanup_url(url_), "https://example.com"); } #[test] fn test_clean_url_query() { let url_ = "http://example.com?"; assert_eq!(cleanup_url(url_), "https://example.com"); } #[test] fn test_clean_url_keep_same_url() { let url_ = "http://another.example.com"; assert_eq!(cleanup_url(url_), "https://another.example.com"); } #[test] fn test_clean_url_keep_https() { let url = "https://another.example.com"; assert_eq!(cleanup_url(url), "https://another.example.com"); } #[test] fn test_cleanup_blogspot_first_tld() { let url = "https://this-is-a.blogspot.cl/asdf/asdf/asdf?asdf=1"; assert_eq!( cleanup_url(url), "https://this-is-a.blogspot.com/asdf/asdf/asdf" ); } #[test] fn test_cleanup_blogspot_second_tld() { let url = "https://this-is-a.blogspot.com.br/asdf/asdf/asdf?asdf=1"; assert_eq!( cleanup_url(url), "https://this-is-a.blogspot.com/asdf/asdf/asdf" ); } #[test] fn test_cleanup_www() { let url = "https://www.this-is-a.blogspot.com.br/asdf/asdf/asdf?asdf=1"; assert_eq!( cleanup_url(url), "https://this-is-a.blogspot.com/asdf/asdf/asdf" ); } #[test] fn test_cleanup_https_redirection() { let url = "http://www.this-is-a.blogspot.com.br/asdf/asdf/asdf?asdf=2"; assert_eq!( cleanup_url(url), "https://this-is-a.blogspot.com/asdf/asdf/asdf" ); } #[test] fn test_cleanup_urls_are_the_same() { let url1 = cleanup_url("https://example.com/hello"); let url2 = cleanup_url("https://example.com/hello/"); assert_eq!(url1, url2); } #[test] fn test_cleanup_urls_without_index() { let url = "https://example.com/index.php"; assert_eq!(cleanup_url(url), "https://example.com"); } #[test] fn test_cleanup_urls_without_index_html() { let url = "https://example.com/index.html"; assert_eq!(cleanup_url(url), cleanup_url("https://example.com/")); } #[test] fn test_dot_on_files() { assert_eq!( cleanup_url("https://jenkins.io/2.0/index.html"), cleanup_url("https://jenkins.io/2.0/") ); } } #[test] fn test_decoding_empty_object_list() { let response = r#"{ "list": {}}"#; match parse_all_response(&response) { ResponseState::Parsed(_) => (), _ => panic!("This should have been parsed"), } } #[test] fn test_decoding_empty_pocket_list() { let response = r#"{ "list": []}"#; match parse_all_response(&response) { ResponseState::NoMore => (), _ => panic!("This should signal an empty list"), } } #[test] fn test_decoding_error() { let response = r#"{ "list": "#; match parse_all_response(&response) { ResponseState::Error(_) => (), _ => panic!("This should fail to parse"), } }
pub mod get_account_balance; pub mod get_incoming; pub mod get_outgoing; pub mod get_transactions_with_currency; pub mod get_counterparties; pub mod get_aggregates; pub use api::client::{TellerClient, ApiServiceResult, Transaction, Account}; pub use self::get_account_balance::*; pub use self::get_incoming::*; pub use self::get_outgoing::*; pub use self::get_transactions_with_currency::*; pub use self::get_counterparties::*; pub use self::get_aggregates::*; #[derive(Debug)] pub struct Money { amount: String, currency: String, } impl Money { pub fn new<S: Into<String>>(amount: S, currency: S) -> Money { Money { amount: amount.into(), currency: currency.into(), } } pub fn get_balance_for_display(&self, hide_currency: &bool) -> String { if *hide_currency { self.amount.to_owned() } else { let balance_with_currency = format!("{} {}", self.amount, self.currency); balance_with_currency.to_owned() } } } #[cfg(test)] mod tests { use super::Money; #[test] fn can_instantiate_money() { let expected_amount = "10.00"; let expected_currency = "GBP"; let money = Money::new(expected_amount, expected_currency); assert_eq!(expected_amount, money.amount); assert_eq!(expected_currency, money.currency); } #[test] fn given_money_get_balance_for_display() { let amount = "10.00"; let currency = "GBP"; let money = Money::new(amount, currency); let money_with_currency = money.get_balance_for_display(&false); let money_without_currency = money.get_balance_for_display(&true); assert_eq!(format!("{} {}", amount, currency), money_with_currency); assert_eq!(amount, money_without_currency); } }
#![feature (nll)] extern crate codecophony; extern crate codecophony_editor_shared as shared; extern crate serde_json; extern crate portaudio; extern crate dsp; extern crate ordered_float; use std::thread; use std::io::{self, BufRead, Write}; use std::sync::mpsc::{Sender, Receiver, channel}; //use std::time::Duration; use std::cmp::{min, max}; use std::sync::Arc; use dsp::sample::{ToFrameSliceMut, Frame as DspFrame}; use portaudio::{StreamCallbackResult}; use ordered_float::NotNaN; use codecophony::{FrameTime, FluidsynthDirectlyRenderableMIDINote, FluidsynthDirectlyRenderableMIDIInstrument}; use shared::{MessageToBackend, MessageToFrontend, Note, PlaybackScript}; type Output = f32; const CHANNELS: usize = 2; const SAMPLE_HZ: f64 = 44100.0; const FRAMES_PER_BUFFER: usize = 256; const FADEIN_TIME: f64 = 0.01; const FADEIN_FRAMES: FrameTime = (FADEIN_TIME*SAMPLE_HZ) as FrameTime; const FADEOUT_TIME: f64 = 0.25; const FADEOUT_FRAMES: FrameTime = (FADEOUT_TIME*SAMPLE_HZ) as FrameTime; type Frame = [Output; CHANNELS]; fn note_frames(note: & Note)->Arc <[Frame]> { codecophony::with_rendered_midi_note (& FluidsynthDirectlyRenderableMIDINote { duration: NotNaN::new(note.duration).unwrap(), pitch: note.pitch, velocity: 100, instrument: FluidsynthDirectlyRenderableMIDIInstrument::pitched (1), }, SAMPLE_HZ, | frames| frames.clone()) } struct PortaudioThread { notes: Vec<PlaybackNote>, next_frame_time: FrameTime, receiver: Receiver <MessageToPortaudioThread>, sender: Sender <MessageToRenderThread>, } enum MessageToPortaudioThread { Stop, AddNote(PlaybackNote), } enum MessageToRenderThread { PlaybackReachedTime(FrameTime), ReplaceScript (PlaybackScript), RestartPlaybackAt (Option<f64>), } struct PlaybackNote { frames: Arc<[Frame]>, first_sample_time: FrameTime, fadein_start: Option<FrameTime>, fadeout_end: Option<FrameTime>, } impl PlaybackNote { fn start_time(&self)->FrameTime {self.fadein_start.unwrap_or (self.first_sample_time)} fn end_time(&self)->FrameTime {self.fadeout_end.unwrap_or (self.first_sample_time + self.frames.len() as FrameTime)} } impl PortaudioThread { fn call(&mut self, portaudio::OutputStreamCallbackArgs { buffer: output_buffer, .. }: portaudio::OutputStreamCallbackArgs <Output>) -> StreamCallbackResult { let output_buffer: &mut [Frame] = output_buffer.to_frame_slice_mut().unwrap(); dsp::slice::equilibrium(output_buffer); while let Ok (message) = self.receiver.try_recv() { match message { MessageToPortaudioThread::Stop => { let time = self.next_frame_time; let finish = time + FADEOUT_FRAMES; self.notes.retain(|note| note.start_time() < time); for note in &mut self.notes { if finish < note.end_time() { note.fadeout_end = Some (note.fadeout_end.map_or(finish, |a| min(a, finish))); } } }, MessageToPortaudioThread::AddNote (note) => { self.notes.push (note); }, } } let end_time = self.next_frame_time + FRAMES_PER_BUFFER as FrameTime; for note in &self.notes { let note_start_time = max (note.start_time(), self.next_frame_time); let note_end_time = min (note.end_time(), end_time); let start_sample_offset = note_start_time - note.first_sample_time; let duration = note_end_time - note_start_time; let end_sample_offset = start_sample_offset + duration; //eprintln!(" doing note {:?} ", (duration, end_time, note.end_time())); if duration <= 0 {continue;} for (frame_time, (output, sample)) in (note_start_time..note_end_time) .zip ( output_buffer [(note_start_time - self.next_frame_time) as usize..(note_end_time - self.next_frame_time) as usize].iter_mut() .zip ( & note.frames[start_sample_offset as usize..end_sample_offset as usize] ) ) { let mut factor = 1.0; if let Some(fadein_start) = note.fadein_start { factor *= max(0, min(FADEIN_FRAMES, frame_time - fadein_start)) as f32/ FADEIN_FRAMES as f32; } if let Some(fadeout_end) = note.fadeout_end { factor *= max(0, min(FADEOUT_FRAMES, fadeout_end - frame_time)) as f32/ FADEOUT_FRAMES as f32; } *output = output.add_amp(sample.scale_amp(factor)); } } self.notes.retain(|note| { note.end_time() > end_time }); self.next_frame_time = end_time; //eprintln!("output {:?}", output_buffer); self.sender.send (MessageToRenderThread::PlaybackReachedTime(end_time)).unwrap() ; portaudio::Continue } } /*enum PlaybackProgressState { StalledAtScriptTime(f64), Playing{script_start: f64, frame_start: FrameTime}, }*/ struct RenderPreparingNote { note: Note, duration_from_start: f64, } struct RenderThread { receiver: Receiver <MessageToRenderThread>, portaudio_sender: Sender <MessageToPortaudioThread>, main_sender: Sender <MessageToFrontend>, script: PlaybackScript, render_queue: Vec<RenderPreparingNote>, playback_queue: Vec<RenderPreparingNote>, latest_playback_reached: FrameTime, renders_queued_until: f64, // duration from stall/start specified_playback_start_script_time: Option<f64>, actual_playback_start_frame_time: Option<FrameTime>, } impl RenderThread { fn render_loop (&mut self) { while let Ok (message) = self.receiver.recv() { self.process_message (message); while self.render_step() { if let Ok (message) = self.receiver.try_recv() {self.process_message (message);} } } } fn process_message (&mut self, message: MessageToRenderThread) { match message { MessageToRenderThread::PlaybackReachedTime (playback_time) => { self.latest_playback_reached = playback_time; }, MessageToRenderThread::RestartPlaybackAt (script_time) => { self.stall(script_time); }, MessageToRenderThread::ReplaceScript (script) => { self.script = script; self.stall (self.specified_playback_start_script_time.map (| script_start | { if let Some(frame_time) = self.actual_playback_start_frame_time { let duration = (self.latest_playback_reached - frame_time) as f64/SAMPLE_HZ as f64; script_start + duration } else { script_start } })); }, } } fn stall(&mut self, stall_time: Option<f64>) { self.render_queue.clear(); self.playback_queue.clear(); self.actual_playback_start_frame_time = None; self.specified_playback_start_script_time = stall_time; self.renders_queued_until = 0.0; self.portaudio_sender.send (MessageToPortaudioThread::Stop).unwrap(); self.main_sender.send (MessageToFrontend::PlaybackStalledAt(stall_time)).unwrap(); if let Some(stall_time) = stall_time { for note in & self.script.notes { let duration_from_start = note.start_time - stall_time; if duration_from_start < 0.0 && note.end_time() > stall_time { self.render_queue.push (RenderPreparingNote {note: note.clone(), duration_from_start}); } } } } fn render_step (&mut self)-> bool { let start_script_time = match self.specified_playback_start_script_time { Some (a) => a, None => return false }; if let Some(next) = self.render_queue.pop() { note_frames(& next.note); self.playback_queue.push(next); return true; } let next_scheduled_termination: Option<FrameTime> = None; match self.actual_playback_start_frame_time { Some(frame_start) => { if let Some(next) = self.playback_queue.pop() { let note_frame_time = frame_start + (next.duration_from_start * SAMPLE_HZ).round() as FrameTime; if note_frame_time > self.latest_playback_reached + FRAMES_PER_BUFFER as FrameTime { //eprintln!(" Sending frames {:?} ", note_frames (& next.note).len()); self.portaudio_sender.send (MessageToPortaudioThread::AddNote(PlaybackNote { frames: note_frames(& next.note), first_sample_time: note_frame_time, fadein_start: if note_frame_time < frame_start { Some(frame_start) } else { None }, fadeout_end: next_scheduled_termination.and_then (| termination | if termination < note_frame_time + note_frames(& next.note).len() as FrameTime {Some (termination)} else {None}), })).unwrap(); } else { //self.playback_queue.push (next); self.stall(Some(next.note.start_time)); } return true; } if self.renders_queued_until > (self.latest_playback_reached - frame_start) as f64 / SAMPLE_HZ as f64 + 5.0 { return false; } } None => { if self.renders_queued_until > start_script_time + 0.1 { self.actual_playback_start_frame_time = Some(self.latest_playback_reached + FRAMES_PER_BUFFER as FrameTime*2); self.main_sender.send (MessageToFrontend::PlaybackResumed).unwrap(); } } } let queue_until = self.renders_queued_until + 0.1; for note in & self.script.notes { let duration_from_start = note.start_time - start_script_time; if !(duration_from_start < self.renders_queued_until) && duration_from_start < queue_until { self.render_queue.push (RenderPreparingNote {note: note.clone(), duration_from_start}); } } self.renders_queued_until = queue_until; return true; } } fn main() { //println!("Hello from backend (stdout)"); eprintln!("Hello from backend (stderr)"); let (send_to_frontend, receive_for_frontend) = channel(); let (send_to_render_thread, receive_on_render_thread) = channel(); let (send_to_portaudio_thread, receive_on_portaudio_thread) = channel(); let mut portaudio_thread = PortaudioThread { notes: Vec::new(), next_frame_time: 0, receiver: receive_on_portaudio_thread, sender: send_to_render_thread.clone(), }; let mut render_thread = RenderThread { receiver: receive_on_render_thread, portaudio_sender: send_to_portaudio_thread, main_sender: send_to_frontend, script: PlaybackScript::default(), render_queue: Vec::new(), playback_queue: Vec::new(), latest_playback_reached: 0, renders_queued_until: 0.0, specified_playback_start_script_time: None, actual_playback_start_frame_time: None, }; thread::spawn(move || { let stdout = io::stdout(); let mut stdout = stdout.lock(); while let Ok (message) = receive_for_frontend.recv() { serde_json::to_writer (&mut stdout, &message).unwrap(); write!(stdout, "\n").unwrap(); } }); thread::spawn(move || render_thread.render_loop()); let pa = portaudio::PortAudio::new().unwrap(); //eprintln!("def output: {:?}", (pa.default_output_device(), pa.device_info(pa.default_output_device().unwrap()))); /*let mut foo = "".to_string(); for device in pa.devices().unwrap() { let (idx, info) = device.unwrap(); foo = format!("{}{:?}\n", foo, (idx, info.name, info.max_input_channels, info.max_output_channels)); } eprintln!("All devices: {}", foo);*/ let settings = pa.default_output_stream_settings::<Output>( CHANNELS as i32, SAMPLE_HZ, FRAMES_PER_BUFFER as u32, ).unwrap(); /*let device = portaudio::DeviceIndex(4); let settings = portaudio::OutputStreamSettings::new( portaudio::StreamParameters::new( device, CHANNELS as i32, true, pa.device_info(device).unwrap().default_low_output_latency ), SAMPLE_HZ, FRAMES_PER_BUFFER as u32 );*/ let mut stream = pa.open_non_blocking_stream(settings, move |p| portaudio_thread.call(p)).unwrap(); stream.start().unwrap(); let stdin = io::stdin(); let stdin = stdin.lock(); for line in stdin.lines() { let line = line.unwrap(); //eprintln!("Received message from frontend: {}", line); if let Ok(message) = serde_json::from_str(&line) { match message { MessageToBackend::RestartPlaybackAt(script_time) => { send_to_render_thread.send(MessageToRenderThread::RestartPlaybackAt(script_time)).unwrap(); }, MessageToBackend::ReplacePlaybackScript(script) => { send_to_render_thread.send(MessageToRenderThread::ReplaceScript(script)).unwrap(); }, } } else { eprintln!("Received invalid message from frontend: {}", line); } //thread::sleep(Duration::from_millis(50)); } eprintln!("exiting backend"); }
use front::tokens::Token; use loc::Loc; #[derive(Debug, PartialEq)] pub enum SyntaxError { UnparsableNumberLiteral(String, Loc), UnparsableCharacterLiteral(String, Loc), UnrecognizedCharacterSequence(String, Loc), UnrecognizedToken(Token, Loc), UnrecognizedCharacterInInput(char, Loc), UnterminatedMultilineComment(Loc), UnterminatedStringLiteral(Loc), UnbalancedParens(Loc), } impl SyntaxError { pub fn display(&self) -> String { use self::SyntaxError::*; match self { UnparsableNumberLiteral(s, ..) => format!("Unparsable number literal: {}", s), UnparsableCharacterLiteral(s, ..) => format!("Unparsable character literal: {}", s), UnrecognizedCharacterSequence(s, ..) => { format!("Unrecognized character sequence: {}", s) } UnrecognizedToken(t, ..) => format!("Unrecognized token: {}", t.display()), UnrecognizedCharacterInInput(ch, ..) => { format!("Unrecognized character in input: {}", ch) } UnterminatedMultilineComment(..) => "Unterminated multiline comment".to_string(), UnterminatedStringLiteral(..) => "Unterminated string literal".to_string(), UnbalancedParens(..) => "Unbalanced parentheses".to_string(), } } pub fn loc(&self) -> Loc { use self::SyntaxError::*; match self { UnparsableNumberLiteral(_, l) => l.clone(), UnparsableCharacterLiteral(_, l) => l.clone(), UnrecognizedCharacterSequence(_, l) => l.clone(), UnrecognizedToken(_, l) => l.clone(), UnrecognizedCharacterInInput(_, l) => l.clone(), UnterminatedMultilineComment(l) => l.clone(), UnterminatedStringLiteral(l) => l.clone(), UnbalancedParens(l) => l.clone(), } } }
fn main() { let input = std::fs::read_to_string("../input.txt").unwrap(); let sum: usize = input .split("\n\n") .filter(|i| !i.is_empty()) .map(|group| { let mut set = std::collections::HashSet::new(); for person in group.split("\n") { for answer in person.chars() { set.insert(answer); } } set.len() }) .sum(); println!("{}", sum); }
use std::fmt; #[derive(Debug, PartialEq)] pub enum MoveState { Win, Lose, CanMove { vertical: bool, horizontal: bool }, } #[derive(Debug, PartialEq)] pub enum Cell { Empty, Cell(u16), } #[derive(Debug, PartialEq)] pub struct GameState { cells: [u16; 16], pub four_percentage: u8, } impl GameState { pub fn new() -> GameState { GameState::from_cells([0; 16]) } pub fn from_cells(cells: [u16; 16]) -> GameState { GameState { cells, four_percentage: 5, } } pub fn get_empty_cells(&self) -> Vec<(usize, usize)> { (0..16) .filter(|i| self.cells[*i] == 0_u16) .map(|i| { let r = i / 4; let c = i % 4; (r, c) }) .collect() } fn get_index(row: usize, col: usize) -> usize { row * 4 + col } pub fn get_cell(&self, row: usize, col: usize) -> Option<Cell> { if row > 3 || col > 3 { return None; } let v = self.cells[GameState::get_index(row, col)]; Some(match v { 0 => Cell::Empty, _ => Cell::Cell(v), }) } pub fn set_cell(&mut self, row: usize, col: usize, value: Cell) { let i = GameState::get_index(row, col); let v = match value { Cell::Empty => 0, Cell::Cell(v) => v, }; self.cells[i] = v; } pub fn swap_cells(&mut self, from_row: usize, from_col: usize, to_row: usize, to_col: usize) { let fi = GameState::get_index(from_row, from_col); let ti = GameState::get_index(to_row, to_col); self.cells.swap(fi, ti); } } #[cfg(test)] mod test_state { use state::*; #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn get_empty_cells() { let mut state = GameState::new(); state.cells = [ 0, 4, 0, 4 , 4, 0, 4, 0 , 0, 4, 0, 4 , 4, 0, 4, 0]; assert_eq!(state.get_empty_cells(), vec![ (0, 0), (0, 2), (1, 1), (1, 3), (2, 0), (2, 2), (3, 1), (3, 3) ]); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn swap_cells_on_row() { let mut state = GameState::from_cells( [ 0, 1, 2, 3 , 4, 5, 6, 7 , 8, 9,10,11 ,12,13,14,15]); let expected = GameState::from_cells( [ 0, 1, 2, 3 , 4, 5, 6, 7 , 8, 9,11,10 ,12,13,14,15]); state.swap_cells(2, 2, 2, 3); assert_eq!(state, expected); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn swap_cells_on_col() { let mut state = GameState::from_cells( [ 0, 1, 2, 3 , 4, 5, 6, 7 , 8, 9,10,11 ,12,13,14,15]); let expected = GameState::from_cells( [ 0, 1, 2, 3 , 4, 5, 6, 7 , 8, 9,14,11 ,12,13,10,15]); state.swap_cells(2, 2, 3, 2); assert_eq!(state, expected); } } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Cell::Empty => write!(f, " "), Cell::Cell(n) => write!(f, "{: >4}", n), } } } #[cfg_attr(rustfmt, rustfmt_skip)] impl fmt::Display for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "\ ┏━━━━┯━━━━┯━━━━┯━━━━┓ ┃{00}│{01}│{02}│{03}┃ ┠────┼────┼────┼────┨ ┃{04}│{05}│{06}│{07}┃ ┠────┼────┼────┼────┨ ┃{08}│{09}│{10}│{11}┃ ┠────┼────┼────┼────┨ ┃{12}│{13}│{14}│{15}┃ ┗━━━━┷━━━━┷━━━━┷━━━━┛", self.get_cell(0, 0).unwrap(), self.get_cell(0, 1).unwrap(), self.get_cell(0, 2).unwrap(), self.get_cell(0, 3).unwrap(), self.get_cell(1, 0).unwrap(), self.get_cell(1, 1).unwrap(), self.get_cell(1, 2).unwrap(), self.get_cell(1, 3).unwrap(), self.get_cell(2, 0).unwrap(), self.get_cell(2, 1).unwrap(), self.get_cell(2, 2).unwrap(), self.get_cell(2, 3).unwrap(), self.get_cell(3, 0).unwrap(), self.get_cell(3, 1).unwrap(), self.get_cell(3, 2).unwrap(), self.get_cell(3, 3).unwrap() ) } } #[cfg(test)] mod test_display { use state::*; #[test] fn cell_empty() { let cell = Cell::Empty; assert_eq!(format!("{}", cell), " ".to_owned()); } #[test] fn cell_digit_one() { let cell = Cell::Cell(2); assert_eq!(format!("{}", cell), " 2".to_owned()); } #[test] fn cell_digit_two() { let cell = Cell::Cell(64); assert_eq!(format!("{}", cell), " 64".to_owned()); } #[test] fn cell_digit_three() { let cell = Cell::Cell(512); assert_eq!(format!("{}", cell), " 512".to_owned()); } #[test] fn cell_digit_four() { let cell = Cell::Cell(2048); assert_eq!(format!("{}", cell), "2048".to_owned()); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn state() { let mut state = GameState::new(); state.cells = [ 2, 512, 0, 256 , 0, 4, 128, 0 , 0, 64, 8, 2048 , 32, 0, 1024, 16]; assert_eq!(format!("{}", state), "\ ┏━━━━┯━━━━┯━━━━┯━━━━┓ ┃ 2│ 512│ │ 256┃ ┠────┼────┼────┼────┨ ┃ │ 4│ 128│ ┃ ┠────┼────┼────┼────┨ ┃ │ 64│ 8│2048┃ ┠────┼────┼────┼────┨ ┃ 32│ │1024│ 16┃ ┗━━━━┷━━━━┷━━━━┷━━━━┛".to_owned()); } }
pub mod layer0; pub mod layer1; pub mod layer2; pub mod layer3; pub mod layer4; pub mod layer5; use anyhow::{anyhow, Result}; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; pub fn find_input(haystack: &str) -> Result<Vec<u8>> { let needle = "==[ Payload ]==============================================="; haystack .find(needle) .map(|idx| haystack[idx..].trim().as_bytes().to_vec()) .ok_or_else(|| anyhow!("Couldn't find payload delimeter: {}", needle)) } pub fn write_output(path: &str, bytes: &[u8]) -> Result<()> { let mut output_path = PathBuf::from("out"); output_path.push(path); let mut f = File::create(output_path)?; f.write_all(bytes)?; Ok(()) } pub fn read_initial_input() -> Result<Vec<u8>> { let mut f = File::open("input.txt")?; let mut buffer = f .metadata() .map_or_else(|_| Vec::new(), |m| Vec::with_capacity(m.len() as usize)); f.read_to_end(&mut buffer)?; Ok(buffer) }
// Primitive str = Immutable fixed-length string somewhere in memory //String = Growable heap allocated data structure - Use when you need to modify or own string data // pus onto string like array // used for systems programming pub fn run(){ let mut hello = String::from("Hello "); //Get Length println!("Length: {}", hello.len()); //push method for single chars hello.push('W'); //pushStr will push whole strings hello.push_str("orld!"); //Capacity in bytes println!("Capacity: {}", hello.capacity()); //check if empty println!("Is empty: {}", hello.is_empty()); //contains sub string println!("Contains 'World' {}", hello.contains("World")); //Replace println!("Replace: {}",hello.replace("World","There")); //Loop through said string for word in hello.split_whitespace(){ println!("{}",word) } //string with capacity let mut s = String::with_capacity(10); s.push('a'); s.push('b'); //Assertion testing assert_eq!(2,s.len());// returns bool assert_eq!(10,s.capacity()); println!("{}",s) }
use std::io::Read; use rocket::{Data, Request}; use rocket::data::{self, FromDataSimple}; use rocket::http::Status; use rocket::outcome::Outcome::{Failure, Success}; use rocket::response::content; use crate::user::token; use crate::user::token::change_user_refresh_token; #[post("/login", data = "<_user>")] pub fn login(_user: super::User) -> Result<content::Json<String>, Status> { if !super::user_exist(_user.username.clone()) { return Err(Status::BadRequest); } let hashed_password = super::hash_password(_user.password); let user_db = super::get_user(_user.username.clone()); if user_db.password != hashed_password { return Err(Status::BadRequest); } let token = token::create_token(_user.username.clone()); let refresh_token = token::generate_first_refresh_token(_user.username); return Ok(content::Json(format!("{}\ \"access_token\": \"{}\",\ \"refresh_token\": \"{}\"\ {}", "{", token, refresh_token, "}"))) } #[post("/is_logged")] pub fn is_logged(_user: super::User) -> Status { Status::Ok } pub struct Token { token: String } impl FromDataSimple for Token { type Error = String; fn from_data(_: &Request, data: Data) -> data::Outcome<Token, String> { let mut string = String::new(); //Read data if let Err(e) = data.open().take(256).read_to_string(&mut string) { return Failure((Status::InternalServerError, format!("{:?}", e))); } //Parse data into json let json_res = match json::parse(&string) { Ok(t) => t, Err(_e) => return Failure((Status::UnprocessableEntity, ":".into())) }; //Check for all fields in json let refresh_token = json_res["refresh_token"].to_string(); if refresh_token == "null" { return Failure((Status::UnprocessableEntity, ":".into())) } //return Success with user Success(Token { token: refresh_token }) } } #[post("/refresh_token", data = "<_token>")] pub fn refresh_token(_token: Token) -> content::Json<String> { let (refresh_token, access_token) = change_user_refresh_token(_token.token); return content::Json(format!("{}\ \"access_token\": \"{}\",\ \"refresh_token\": \"{}\" {}", "{", access_token, refresh_token, "}")) } /* -------------------- UNIT TESTS -------------------- */ #[cfg(test)] mod test { use rocket::http::Status; use rocket::local::Client; use super::super::super::rocket; #[test] fn test_login_ok() { let client = Client::new(rocket()).expect("valid src instance"); let response = client.post("/user/login").body(r#"{ "username": "tester_static", "password": "G00DP4SSW0RD" }"#).dispatch(); assert_eq!(response.status(), Status::Ok); } }
pub mod state; pub mod blob; pub mod world; use std::time::{Instant, Duration}; use winit::event::{Event, VirtualKeyCode}; use winit::event_loop::{EventLoop, ControlFlow}; pub use blob::Blob; pub use state::AppState; pub use world::World; const FRAME_TIME: u64 = 1000 / 60; const CONFIG_REFRESH_RATE: Duration = Duration::from_secs(5); pub struct App { world: World, last_event: Instant, last_frame: Instant, last_config_refresh: Instant, } impl App { pub fn new(world: World) -> Self { Self { world, last_event: Instant::now(), last_frame: Instant::now(), last_config_refresh: Instant::now(), } } pub fn run(mut self) -> ! { let event_loop = EventLoop::new(); let mut state = AppState::new(self.world.width as u32, self.world.height as u32, &event_loop).unwrap(); self.last_frame = Instant::now(); event_loop.run(move |event, _, control_flow| { let current_event = Instant::now(); let delta_time = (current_event - self.last_event).as_secs_f64(); self.last_event = current_event; if current_event - self.last_config_refresh >= CONFIG_REFRESH_RATE { let _ = self.world.refresh_config(); self.last_config_refresh = current_event; } // Draw the current frame if let Event::RedrawRequested(_) = event { let current_frame = Instant::now(); if current_frame - self.last_frame >= Duration::from_millis(FRAME_TIME) { self.last_frame = current_frame; self.world.draw(state.pixels.get_frame()); if state.pixels .render() .map_err(|e| log::error!("pixels.render() failed: {}", e)) .is_err() { *control_flow = ControlFlow::Exit; return; } } } // Handle input events if state.input.update(&event) { // Close events if state.input.key_pressed(VirtualKeyCode::Escape) || state.input.quit() { *control_flow = ControlFlow::Exit; return; } // Resize the window if let Some(size) = state.input.window_resized() { state. pixels.resize(size.width, size.height); } if state.input.mouse_released(0) { if let Some((x, y)) = state.input.mouse() { let x = (x / 2.0) as f64; let y = (y / 2.0) as f64; self.world.add_blob(x, y); } } } // Update internal state and request a redraw self.world.update(delta_time); state.window.request_redraw(); }); } }
extern crate ez_io; pub mod decompression; pub mod direct; pub mod error; pub mod file; use crate::decompression::{CompressInfo, CompressedData}; use crate::direct::files::Packing; use crate::direct::DPac; use crate::file::DataType; use crate::file::File; /// Result type that ties to general Error used in this crate pub type Result<T> = ::std::result::Result<T, error::PacError>; /// Main Pac type #[derive(Clone)] pub struct Pac { /// Contains general info about the file pub files: Vec<File>, } // Would be nice to implement some kind of iterator so that it does not take 2x the size of th entire pac file impl Pac { pub fn from_direct(direct: DPac) -> Result<Pac> { let nb_files = direct.header.file_cnt as usize; let mut files = Vec::with_capacity(nb_files); for file_index in 0..nb_files { // Get path as a UTF-8 String let path = { let mut first_zero = None; for (i, character) in direct.files.files_info[file_index].path.iter().enumerate() { if *character == 0 { first_zero = Some(i); } } let len = match first_zero { None => 264, Some(i) => i, }; String::from_utf8(direct.files.files_info[file_index].path[0..len].to_vec())? }; // Get correct flavour of data (compressed or not) let packed_data = match &direct.files.files_packing[file_index] { Packing::Direct => { DataType::Uncompressed(direct.files.files_data[file_index].clone()) // That is going to be a lot of data } Packing::Compressed(c) => { DataType::Compressed(CompressedData { data: direct.files.files_data[file_index].clone(), // Here too info: { let mut info = Vec::with_capacity(c.info.len()); for direct_info in &c.info { info.push(CompressInfo { offset: direct_info.offset as usize, // Lossy decompressed_size: direct_info.unpack_size as usize, // Lossy }); } info }, total_decompressed_size: direct.files.files_info[file_index].unpack_size as usize, // Lossy }) } }; files.push(File { path, packed_data }); } Ok(Pac { files }) } }
#[cfg(test)] #[path = "../../../tests/unit/solver/population/greedy_test.rs"] mod greedy_test; use crate::algorithms::nsga2::Objective; use crate::models::Problem; use crate::solver::population::{Individual, SelectionPhase}; use crate::solver::{Population, Statistics}; use std::cmp::Ordering; use std::fmt::{Display, Formatter}; use std::iter::{empty, repeat}; use std::sync::Arc; /// A population which keeps track of the best known individuals only. /// If solutions are equal, prefers to keep first discovered. pub struct Greedy { problem: Arc<Problem>, selection_size: usize, best_known: Option<Individual>, } impl Population for Greedy { fn add_all(&mut self, individuals: Vec<Individual>) -> bool { #[allow(clippy::unnecessary_fold)] individuals.into_iter().fold(false, |acc, individual| acc || self.add(individual)) } fn add(&mut self, individual: Individual) -> bool { if let Some(best_known) = &self.best_known { if self.problem.objective.total_order(best_known, &individual) != Ordering::Greater { return false; } } self.best_known = Some(individual); true } fn on_generation(&mut self, _: &Statistics) {} fn cmp(&self, a: &Individual, b: &Individual) -> Ordering { self.problem.objective.total_order(a, b) } fn select<'a>(&'a self) -> Box<dyn Iterator<Item = &Individual> + 'a> { if let Some(best_known) = self.best_known.as_ref() { Box::new(repeat(best_known).take(self.selection_size)) } else { Box::new(empty()) } } fn ranked<'a>(&'a self) -> Box<dyn Iterator<Item = (&Individual, usize)> + 'a> { Box::new(self.best_known.iter().map(|individual| (individual, 0))) } fn size(&self) -> usize { if self.best_known.is_some() { 1 } else { 0 } } fn selection_phase(&self) -> SelectionPhase { SelectionPhase::Exploitation } } impl Display for Greedy { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let values = if let Some(best_known) = &self.best_known { best_known.get_fitness_values().map(|v| format!("{:.7}", v)).collect::<Vec<_>>().join(",") } else { "".to_string() }; write!(f, "[{}],", values) } } impl Greedy { /// Creates a new instance of `Greedy`. pub fn new(problem: Arc<Problem>, selection_size: usize, best_known: Option<Individual>) -> Self { Self { problem, selection_size, best_known } } }
/// Cpu addressing modes #[derive(Debug, Copy, Clone, PartialEq)] pub enum AddrMode { None, // For KIL operations Imp, // Implied Imm, // Immediate Zp0, // Zero page Zpx, // Zero page with X Zpy, // Zero page with Y Rel, // Relative Abs, // Absolute Abx, // Absolute with X AbxW, // Absolute with X (Write) Aby, // Absolute with Y AbyW, // Absolute with Y (Write) Ind, // Indirect Izx, // Indirect with X Izy, // Indirect with Y IzyW, // Indirect with Y (Write) } impl std::fmt::Display for AddrMode { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { AddrMode::None => write!(f, "None"), AddrMode::Imp => write!(f, "IMP"), AddrMode::Imm => write!(f, "IMM"), AddrMode::Zp0 => write!(f, "ZP0"), AddrMode::Zpx => write!(f, "ZPX"), AddrMode::Zpy => write!(f, "ZPY"), AddrMode::Rel => write!(f, "REL"), AddrMode::Abs => write!(f, "ABS"), AddrMode::Abx => write!(f, "ABX"), AddrMode::AbxW => write!(f, "ABXW"), AddrMode::Aby => write!(f, "ABY"), AddrMode::AbyW => write!(f, "ABYW"), AddrMode::Ind => write!(f, "IND"), AddrMode::Izx => write!(f, "IZX"), AddrMode::Izy => write!(f, "IZY"), AddrMode::IzyW => write!(f, "IZYW"), } } }
pub mod managers; pub mod world; pub mod entity; pub mod entity_query;
use anyhow::Result; use std::str::FromStr; #[derive(Debug)] struct Record; impl FromStr for Record { type Err = anyhow::Error; fn from_str(_s: &str) -> Result<Self, Self::Err> { Ok(Record) } } fn main() -> Result<()> { let input: Vec<Record> = INPUT.lines().map(|l| l.parse().unwrap()).collect(); dbg!(input); Ok(()) } const INPUT: &str = r#""#;
#[derive(Clone, Default)] pub struct SampleStatistics { max: f64, min: f64, samples: u32, sum: f64, sum_of_squares: f64, } impl SampleStatistics { pub fn put(&mut self, v: f64) { if self.samples == 0 { self.min.clone_from(&v); self.max = v; } else if self.min > v { self.min = v; } else if self.max < v { self.max = v; } self.samples += 1; self.sum += v; self.sum_of_squares += v.powi(2); } pub fn max(&self) -> f64 { self.max } pub fn min(&self) -> f64 { self.min } pub fn mean(&self) -> f64 { #![allow(clippy::float_cmp)] if self.samples < 1 { std::f64::NAN } else if self.min == self.max { self.min } else { self.sum / f64::from(self.samples) } } pub fn variance(&self) -> f64 { #![allow(clippy::float_cmp)] if self.samples < 2 { std::f64::NAN } else if self.min == self.max { 0. } else { let n = f64::from(self.samples); // may become slightly negative because of rounding: (self.sum_of_squares - self.sum.powi(2) / n).max(0.) / (n - 1.) } } pub fn deviation(&self) -> f64 { self.variance().sqrt() } } #[cfg(test)] mod tests { #![allow(clippy::float_cmp)] use super::*; #[test] fn stats_0() { let s: SampleStatistics = Default::default(); assert!(s.mean().is_nan()); assert!(s.variance().is_nan()); assert!(s.deviation().is_nan()); } #[test] fn stats_1() { let mut s: SampleStatistics = Default::default(); s.put(-1.0); assert_eq!(s.mean(), -1.0); assert!(s.variance().is_nan()); assert!(s.deviation().is_nan()); } #[test] fn stats_2() { let mut s: SampleStatistics = Default::default(); s.put(-1.0); s.put(1.0); assert_eq!(s.mean(), 0.0); assert_eq!(s.variance(), 2.0); assert_eq!(s.deviation(), 2.0_f64.sqrt()); } #[test] fn stats_3() { let mut s: SampleStatistics = Default::default(); s.put(89.0); s.put(90.0); s.put(91.0); assert_eq!(s.mean(), 90.0); assert_eq!(s.variance(), 1.0); assert_eq!(s.deviation(), 1.0); } #[test] fn stats_9() { let mut s: SampleStatistics = Default::default(); s.put(2.0); s.put(4.0); s.put(4.0); s.put(4.0); s.put(5.0); s.put(5.0); s.put(5.0); s.put(7.0); s.put(9.0); assert_eq!(s.mean(), 5.0); assert_eq!(s.variance(), 4.0); assert_eq!(s.deviation(), 2.0); } } #[cfg(test)] mod proptests { extern crate proptest; use self::proptest::prelude::*; use super::*; proptest! { #[test] fn put_1(x in proptest::num::f64::NORMAL) { let mut s: SampleStatistics = Default::default(); s.put(x); assert!(s.mean() >= s.min()); assert!(s.mean() <= s.max()); } #[test] fn put_2(x in proptest::num::f64::NORMAL, y in proptest::num::f64::NORMAL) { let mut s: SampleStatistics = Default::default(); s.put(x); s.put(y); assert!(s.mean() >= s.min()); assert!(s.mean() <= s.max()); assert!(s.variance() >= 0.); assert!(s.deviation() <= (s.max() - s.min()) * 1.5); } #[test] fn put_n(i in 2..99, x in proptest::num::f64::NORMAL) { let mut s: SampleStatistics = Default::default(); for _ in 0..i { s.put(x); } assert!(s.mean() >= s.min()); assert!(s.mean() <= s.max()); assert!(s.variance() >= 0.); assert!(s.deviation() <= (s.max() - s.min())); } } }
extern crate dmbc; extern crate exonum; extern crate exonum_testkit; extern crate hyper; extern crate iron; extern crate iron_test; extern crate mount; extern crate serde_json; pub mod dmbc_testkit; use std::collections::HashMap; use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi}; use exonum::crypto; use exonum::messages::Message; use hyper::status::StatusCode; use dmbc::currency::api::history_offers::{HistoryOffersResponse, HistoryOffersInfo, HistoryOfferInfo, HistoryOfferResult}; use dmbc::currency::api::error::ApiError; use dmbc::currency::offers::history::{HistoryOffers, HistoryOffer}; use dmbc::currency::transactions::builders::transaction; use dmbc::currency::assets::TradeAsset; use dmbc::currency::wallet::Wallet; //use dmbc::currency::offers::{Offer}; #[test] fn history_offers() { let fixed = 10; let units = 2; let balance = 1000; let meta_data = "asset data"; let (user1_pk, user1_sk) = crypto::gen_keypair(); let (user2_pk, user2_sk) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &user1_pk, ); let mut testkit = DmbcTestApiBuilder::new() .add_wallet_value(&user1_pk, Wallet::new(balance, vec![])) .add_wallet_value(&user2_pk, Wallet::new(balance, vec![])) .add_asset_to_wallet(&user1_pk, (asset.clone(), info)) .create(); let api = testkit.api(); let tx_bid_offer = transaction::Builder::new() .keypair(user1_pk, user1_sk.clone()) .tx_offer() .asset(TradeAsset::from_bundle(asset.clone(), 100)) .data_info("bid") .bid_build(); let (status, _) = api.post_tx(&tx_bid_offer); testkit.create_block(); assert_eq!(status, StatusCode::Created); let tx_ask_offer = transaction::Builder::new() .keypair(user2_pk, user2_sk.clone()) .tx_offer() .asset(TradeAsset::new(asset.id(), asset.amount() * 2, 100)) .data_info("ask") .ask_build(); let (status, _) = api.post_tx(&tx_ask_offer); testkit.create_block(); assert_eq!(status, StatusCode::Created); let mut offers_info = HashMap::new(); offers_info.insert(tx_bid_offer.hash(), HistoryOfferInfo{tx_amount: 1}); offers_info.insert(tx_ask_offer.hash(), HistoryOfferInfo{tx_amount: 1}); let (status, response): (StatusCode, HistoryOffersResponse) = api.get_with_status("/v1/history/offers"); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok( HistoryOffersInfo{ total:2, count:2, offer_info: offers_info, } )); } #[test] fn history_offers_invalid() { let testkit = DmbcTestApiBuilder::new().create(); let api = testkit.api(); let (status, response): (StatusCode, HistoryOfferResult) = api.get_with_status("/v1/history/offers/123"); assert_eq!(status, StatusCode::BadRequest); assert_eq!(response, Err(ApiError::TransactionHashInvalid)) } #[test] fn history_offers_by_tx_hash() { let fixed = 10; let units = 2; let balance = 1000; let meta_data = "asset data"; let (user1_pk, user1_sk) = crypto::gen_keypair(); let (user2_pk, user2_sk) = crypto::gen_keypair(); let (asset, info) = dmbc_testkit::create_asset( meta_data, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &user1_pk, ); let mut testkit = DmbcTestApiBuilder::new() .add_wallet_value(&user1_pk, Wallet::new(balance, vec![])) .add_wallet_value(&user2_pk, Wallet::new(balance, vec![])) .add_asset_to_wallet(&user1_pk, (asset.clone(), info)) .create(); let api = testkit.api(); let tx_bid_offer = transaction::Builder::new() .keypair(user1_pk, user1_sk.clone()) .tx_offer() .asset(TradeAsset::from_bundle(asset.clone(), 100)) .data_info("bid") .bid_build(); let (status, _) = api.post_tx(&tx_bid_offer); testkit.create_block(); assert_eq!(status, StatusCode::Created); let tx_ask_offer = transaction::Builder::new() .keypair(user2_pk, user2_sk.clone()) .tx_offer() .asset(TradeAsset::new(asset.id(), asset.amount() * 2, 100)) .data_info("ask") .ask_build(); let (status, _) = api.post_tx(&tx_ask_offer); testkit.create_block(); assert_eq!(status, StatusCode::Created); let endpoint = "/v1/history/offers/".to_string() + &tx_bid_offer.hash().to_string(); let history_offers = HistoryOffers::new(vec![HistoryOffer::new(&tx_ask_offer.hash(), 2)]); let (status, response): (StatusCode, HistoryOfferResult) = api.get_with_status(&endpoint); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Some(history_offers))); }
use crate::command::Command; use dyn_clone::{clone_trait_object, DynClone}; use glium::Frame; impl<T> Drawable for T where T: Fn(&mut Frame) + Clone + Send + Sync + 'static {} pub trait Drawable: DynClone + Fn(&mut Frame) + Send + Sync + 'static {} clone_trait_object!(Drawable); #[derive(Clone)] pub struct Drawer(Box<dyn Drawable>); impl Drawer { pub fn new(f: impl Drawable) -> Self { Drawer(Box::new(f)) } pub fn call(&self, frame: &mut Frame) { (self.0)(frame); } } pub type DrawerCommand = Command<Drawer>;
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use std::f64::consts::PI; static STOP_CONDITION: f64 = 1e-6; //停止条件 #[no_mangle] pub fn add(a : i32, b : i32) -> i32 { a + b } #[wasm_bindgen] pub fn norm(a : &[f64], b : &[f64]) -> f64 { let mut sum : f64 = 0.0; for i in 0..a.len() { let sub = a[i] - b[i]; let pow = sub * sub; sum += pow; } let ans = sum.sqrt(); return ans; } #[wasm_bindgen] pub fn substruct(a : &mut[f64], b: &mut [f64]) { let offset = vec![0.1, 0.1, 0.1]; for i in 0..a.len() { a[i] -= b[i] + offset[i]; } } #[wasm_bindgen] pub fn wrap_remez(order : usize, f_pass : f64, f_stop : f64, coefficients : &mut [f64], axis_freq : &mut[f64], magnitude_response : &mut [f64]) -> f64 { let mut error : f64 = 0.0; let coef = remez(order, f_pass, f_stop, &mut error); let delta = 0.5 / (magnitude_response.len() - 1) as f64; //magnitude response for i in 0..magnitude_response.len() { let f = delta * i as f64; axis_freq[i] = f; magnitude_response[i] = magnitude(&coef, f).abs(); magnitude_response[i] = 20.0 * magnitude_response[i].log10() } //copy for i in 0..(coef.len() - 1) { coefficients[i] = coef[(coef.len() - 1) - i] / 2.0; coefficients[(coefficients.len() - 1) - i] = coefficients[i]; } coefficients[coef.len() - 1] = coef[0]; return error; } fn magnitude(coefficients: &Vec<f64>, f: f64) -> f64 { let mut ans: f64 = 0.0; for i in 0..coefficients.len() { let omega_n = 2.0 * PI * f * i as f64; ans += coefficients[i] * omega_n.cos(); } ans } fn grad_magnitude(coefficients: &Vec<f64>, f: f64) -> f64 { let mut ans: f64 = 0.0; for i in 1..coefficients.len() { let omega_n = 2.0 * PI * f * i as f64; ans -= coefficients[i] * omega_n.sin() * 2.0 * PI * i as f64; } ans } fn hess_magnitude(coefficients: &Vec<f64>, f: f64) -> f64 { let mut ans: f64 = 0.0; for i in 0..coefficients.len() { let omega_n = 2.0 * PI * f * i as f64; ans -= coefficients[i] * omega_n.cos() * i as f64 * i as f64 * 4.0 * PI * PI; } ans } fn newton_method(coefficients: &Vec<f64>, x_n: f64) -> f64 { let mut old_point = x_n + 1.0; let mut new_point = x_n; while (new_point - old_point).abs() > STOP_CONDITION { old_point = new_point; new_point = -grad_magnitude(coefficients, old_point) / hess_magnitude(coefficients, old_point) + old_point; } new_point } fn divide_approximation_band( length: usize, f_pass: f64, f_stop: f64, index_edge: &mut usize, ) -> Vec<f64> { let mut frequency: Vec<f64> = Vec::with_capacity(length); let pass_band_division: usize = (f_pass / (0.5 - (f_stop - f_pass)) * length as f64) as usize + 1; let stop_band_division: usize = length - pass_band_division; let delta_pass_band: f64 = f_pass / (pass_band_division as f64 - 1.0); let delta_stop_band: f64 = (0.5 - f_stop) / (stop_band_division as f64 - 1.0); for i in 0..pass_band_division { frequency.push(i as f64 * delta_pass_band); } for i in 0..stop_band_division { frequency.push(i as f64 * delta_stop_band + f_stop); } *index_edge = pass_band_division; frequency } fn divide_equally(length: usize) -> Vec<f64> { let mut frequency: Vec<f64> = Vec::with_capacity(length); let delta: f64 = 0.5 / (length - 1) as f64; for i in 0..length { frequency.push(delta * i as f64); } frequency } fn judge_convergence (extremal_frequency: &Vec<f64>, old_extremal_frequency: &Vec<f64>) -> f64 { let mut max = 0.0; for i in 0..extremal_frequency.len() { let buffer = (extremal_frequency[i] - old_extremal_frequency[i]).abs(); if max < buffer { max = buffer; } } max } fn desired_resonse (response: &mut Vec<f64>, extremal_frequency: &Vec<f64>, f_pass: f64) { for i in 0..response.len() { if extremal_frequency[i] <= f_pass { response[i] = 1.0; } else { response[i] = 0.0; } } } fn judge_sign(a: f64, b: f64) -> isize { let sign_a: isize = if a >= 0.0 { 1 } else { -1 }; let sign_b: isize = if b >= 0.0 { 1 } else { -1 }; return if sign_a == sign_b { 1 } else { -1 }; } fn adjust_candidate (candidates: &mut Vec<f64>, length: usize, f_pass: f64, f_stop: f64) { if length - 1 == candidates.len() { let mut pass_min = std::f64::MAX; let mut pass_index: usize = 0; for i in 0..candidates.len() { let buff = (candidates[i] - f_pass).abs(); if pass_min > buff { pass_min = buff; pass_index = i; } } let mut stop_min = std::f64::MAX; let mut stop_index: usize = 0; for i in 0..candidates.len() { let buff = (candidates[i] - f_stop).abs(); if stop_min > buff { stop_min = buff; stop_index = i; } } if stop_min > pass_min { candidates[pass_index] = f_pass; candidates.insert(pass_index + 1, f_stop) } else { candidates[stop_index] = f_stop; candidates.insert(stop_index, f_pass); } } else if length - 2 == candidates.len() { let mut pass_min = std::f64::MAX; let mut pass_index: usize = 0; for i in 0..candidates.len() { let buff = (candidates[i] - f_pass).abs(); if pass_min > buff { pass_min = buff; pass_index = i; } } if candidates[pass_index] > f_pass { candidates.insert(pass_index, f_pass); } else { candidates.insert(pass_index + 1, f_pass); } let mut stop_min = std::f64::MAX; let mut stop_index: usize = 0; for i in 0..candidates.len() { let buff = (candidates[i] - f_stop).abs(); if stop_min > buff { stop_min = buff; stop_index = i; } } if candidates[stop_index] > f_stop { candidates.insert(stop_index, f_stop); } else { candidates.insert(stop_index + 1, f_stop); } } } fn gauss_method(matrix: &mut Vec<Vec<f64>>, vector: &mut Vec<f64>) -> i32 { let dimention = vector.len(); for i in 0..(dimention - 1) { let mut pivot = i; let mut pivot_max = matrix[i][i].abs(); for j in (i + 1)..vector.len() { let fact_abs = matrix[j][i].abs(); if fact_abs > pivot_max { pivot_max = fact_abs; pivot = j; } } if pivot_max == 0.0 { return -1; } if i != pivot { for j in 0..dimention { let buffer = matrix[i][j]; matrix[i][j] = matrix[pivot][j]; matrix[pivot][j] = buffer; } let buffer = vector[i]; vector[i] = vector[pivot]; vector[pivot] = buffer; } let coefficient = 1.0 / matrix[i][i]; matrix[i][i] = 1.0; for j in (i + 1)..dimention { matrix[i][j] *= coefficient; } vector[i] *= coefficient; for j in (i + 1)..dimention { let coeff = matrix[j][i]; for k in (i + 1)..dimention { matrix[j][k] -= coeff * matrix[i][k]; } matrix[j][i] = 0.0; vector[j] -= coeff * vector[i]; } } vector[dimention - 1] /= matrix[dimention - 1][dimention - 1]; for i in (0..dimention).rev() { for j in (i + 1)..dimention { vector[i] -= matrix[i][j] * vector[j]; } } return 0; } fn remez(order: usize, f_pass: f64, f_stop: f64, error : &mut f64) -> Vec<f64> { let length = order + 2; let mut index_edge: usize = 0; let mut cnt : usize = 0; let mut old_extremal_frequency: Vec<f64> = vec![0.0; length]; let mut matrix: Vec<Vec<f64>> = Vec::with_capacity(length); let mut desired_vector: Vec<f64> = vec![0.0; length]; let mut extremal_frequency: Vec<f64> = divide_approximation_band(length, f_pass, f_stop, &mut index_edge); let divided_frequency: Vec<f64> = divide_equally(length * 10); let mut coef: Vec<f64> = vec![0.0; length - 1]; let mut grad = vec![0.0; 2]; for i in 0..length { let vector = Vec::with_capacity(length); matrix.push(vector); for _j in 0..length { matrix[i].push(0.0); } } while judge_convergence (&extremal_frequency, &old_extremal_frequency) > STOP_CONDITION { desired_resonse(&mut desired_vector, &extremal_frequency, f_pass); for i in 0..length { matrix[i][0] = 1.0; for j in 1..(length - 1) { let omega_n = 2.0 * PI * j as f64 * extremal_frequency[i]; matrix[i][j] = omega_n.cos(); } matrix[i][length - 1] = if i % 2 == 1 { -1.0 } else { 1.0 }; } gauss_method(&mut matrix, &mut desired_vector); for i in 0..length { old_extremal_frequency[i] = extremal_frequency[i]; } for i in 0..coef.len() { coef[i] = desired_vector[i]; } let mut candidate: Vec<f64> = Vec::new(); grad[1] = grad_magnitude(&coef, divided_frequency[1]); //勾配 candidate.push(0.0); for i in 2..(divided_frequency.len() - 1) { grad[0] = grad_magnitude(&coef, divided_frequency[i]); if judge_sign(grad[0], grad[1]) == -1 { candidate.push( newton_method(&coef, divided_frequency[i - 1])); } grad[1] = grad[0]; } candidate.push(0.5); adjust_candidate(&mut candidate, length, f_pass, f_stop); //println!("ite:{}", iteration); //println!("{:?}", candidate); //println!("len:{}", candidate.len()); for i in 0..length { extremal_frequency[i] = candidate[i]; } cnt += 1; if cnt >= 100 { break; } } for i in 0..(length - 1) { coef[i] = desired_vector[i]; } *error = desired_vector[coef.len()].abs(); //println!("coefficient : {:?}", coef); //println!("Error : {}", desired_vector[coef.len()].abs()); return coef; }
use super::Axial; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Default, Copy, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)] pub struct Hexagon { pub center: Axial, pub radius: i32, } impl Hexagon { pub fn new(center: Axial, radius: i32) -> Self { Self { center, radius } } pub fn from_radius(radius: i32) -> Self { debug_assert!(radius >= 0); Self { radius, center: Axial::new(radius, radius), } } pub fn contains(self, point: Axial) -> bool { let point = point - self.center; let [x, y, z] = point.hex_axial_to_cube(); let r = self.radius.abs(); x.abs() <= r && y.abs() <= r && z.abs() <= r } pub fn iter_edge(self) -> impl Iterator<Item = Axial> { debug_assert!( self.radius > 0, "not-positive radius will not work as expected" ); const STARTS: [Axial; 6] = [ Axial::new(0, -1), Axial::new(1, -1), Axial::new(1, 0), Axial::new(0, 1), Axial::new(-1, 1), Axial::new(-1, 0), ]; const DELTAS: [Axial; 6] = [ Axial::new(1, 0), Axial::new(0, 1), Axial::new(-1, 1), Axial::new(-1, 0), Axial::new(0, -1), Axial::new(1, -1), ]; let radius = self.radius; let center = self.center; (0..6).flat_map(move |di| { // iterating over `deltas` is a compile error because they're freed at the end of this // funciton... let delta = DELTAS[di]; let pos = center + STARTS[di] * radius; (0..radius).map(move |j| pos + delta * j) }) } pub fn area(self) -> usize { debug_assert!(self.radius >= 0); (1 + 3 * self.radius * (self.radius + 1)) as usize } /// points will spiral out from the center pub fn iter_points(self) -> impl Iterator<Item = Axial> { let center: Axial = self.center; // radius =0 doesn't yield any points Some(center) .into_iter() .chain((1..=self.radius).flat_map(move |r| Hexagon::new(center, r).iter_edge())) } pub fn with_center(mut self, center: Axial) -> Self { self.center = center; self } pub fn with_offset(mut self, offset: Axial) -> Self { self.center += offset; self } pub fn with_radius(mut self, radius: i32) -> Self { self.radius = radius; self } } /// Rounds the given Axial coorinates to the nearest hex pub fn hex_round(point: [f32; 2]) -> Axial { let x = point[0]; let z = point[1]; let y = -x - z; let cube = cube_round([x, y, z]); Axial::hex_cube_to_axial(cube) } /// Rounds the Cube representation of a hexagon to the nearest hex pub fn cube_round(point: [f32; 3]) -> [i32; 3] { let mut rx = point[0].round(); let mut ry = point[1].round(); let mut rz = point[2].round(); let dx = (rx - point[0]).abs(); let dy = (ry - point[1]).abs(); let dz = (rz - point[2]).abs(); if dx > dy && dx > dz { rx = -ry - rz; } else if dy > dz { ry = -rx - rz; } else { rz = -rx - ry; } [rx as i32, ry as i32, rz as i32] } #[cfg(test)] mod tests { use super::*; #[test] fn hex_iter_points_are_inside_itself() { let hex = Hexagon::from_radius(3).with_center(Axial::default()); dbg!(hex .with_center(Axial::default()) .with_radius(2) .iter_points() .collect::<Vec<_>>()); for (i, p) in hex.iter_points().enumerate() { dbg!(p); assert!(hex.contains(p), "{} {:?} {:?}", i, p, hex); } } #[test] fn test_iter_edge() { let pos = Axial::new(0, 0); let radius = 4; let hex = Hexagon::new(pos, radius); let edge: Vec<_> = hex.iter_edge().collect(); dbg!(hex, &edge); assert_eq!(edge.len(), 6 * radius as usize); for (i, p) in edge.iter().copied().enumerate() { assert_eq!( p.hex_distance(pos), radius as u32, "Hex #{} {:?} is out of range", i, p ); } } }
#[doc = "Register `CICR` reader"] pub type R = crate::R<CICR_SPEC>; #[doc = "Register `CICR` writer"] pub type W = crate::W<CICR_SPEC>; #[doc = "Field `LSIRDYC` reader - LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done."] pub type LSIRDYC_R = crate::BitReader<LSIRDYC_A>; #[doc = "LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LSIRDYC_A { #[doc = "1: Clear interrupt flag"] Clear = 1, } impl From<LSIRDYC_A> for bool { #[inline(always)] fn from(variant: LSIRDYC_A) -> Self { variant as u8 != 0 } } impl LSIRDYC_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<LSIRDYC_A> { match self.bits { true => Some(LSIRDYC_A::Clear), _ => None, } } #[doc = "Clear interrupt flag"] #[inline(always)] pub fn is_clear(&self) -> bool { *self == LSIRDYC_A::Clear } } #[doc = "Field `LSIRDYC` writer - LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done."] pub type LSIRDYC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, LSIRDYC_A>; impl<'a, REG, const O: u8> LSIRDYC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clear interrupt flag"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(LSIRDYC_A::Clear) } } #[doc = "Field `LSERDYC` reader - LSE ready interrupt clear Set by software to clear LSERDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as LSERDYC_R; #[doc = "Field `HSIRDYC` reader - HSI ready interrupt clear Set by software to clear HSIRDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as HSIRDYC_R; #[doc = "Field `HSERDYC` reader - HSE ready interrupt clear Set by software to clear HSERDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as HSERDYC_R; #[doc = "Field `CSIRDYC` reader - CSI ready interrupt clear Set by software to clear CSIRDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as CSIRDYC_R; #[doc = "Field `HSI48RDYC` reader - HSI48 ready interrupt clear Set by software to clear HSI48RDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as HSI48RDYC_R; #[doc = "Field `PLL1RDYC` reader - PLL1 ready interrupt clear Set by software to clear PLL1RDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as PLL1RDYC_R; #[doc = "Field `PLL2RDYC` reader - PLL2 ready interrupt clear Set by software to clear PLL2RDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as PLL2RDYC_R; #[doc = "Field `PLL3RDYC` reader - PLL3 ready interrupt clear Set by software to clear PLL3RDYF. Reset by hardware when clear done."] pub use LSIRDYC_R as PLL3RDYC_R; #[doc = "Field `LSECSSC` reader - LSE clock security system interrupt clear Set by software to clear LSECSSF. Reset by hardware when clear done."] pub use LSIRDYC_R as LSECSSC_R; #[doc = "Field `HSECSSC` reader - HSE clock security system interrupt clear Set by software to clear HSECSSF. Reset by hardware when clear done."] pub use LSIRDYC_R as HSECSSC_R; #[doc = "Field `LSERDYC` writer - LSE ready interrupt clear Set by software to clear LSERDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as LSERDYC_W; #[doc = "Field `HSIRDYC` writer - HSI ready interrupt clear Set by software to clear HSIRDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as HSIRDYC_W; #[doc = "Field `HSERDYC` writer - HSE ready interrupt clear Set by software to clear HSERDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as HSERDYC_W; #[doc = "Field `CSIRDYC` writer - CSI ready interrupt clear Set by software to clear CSIRDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as CSIRDYC_W; #[doc = "Field `HSI48RDYC` writer - HSI48 ready interrupt clear Set by software to clear HSI48RDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as HSI48RDYC_W; #[doc = "Field `PLL1RDYC` writer - PLL1 ready interrupt clear Set by software to clear PLL1RDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as PLL1RDYC_W; #[doc = "Field `PLL2RDYC` writer - PLL2 ready interrupt clear Set by software to clear PLL2RDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as PLL2RDYC_W; #[doc = "Field `PLL3RDYC` writer - PLL3 ready interrupt clear Set by software to clear PLL3RDYF. Reset by hardware when clear done."] pub use LSIRDYC_W as PLL3RDYC_W; #[doc = "Field `LSECSSC` writer - LSE clock security system interrupt clear Set by software to clear LSECSSF. Reset by hardware when clear done."] pub use LSIRDYC_W as LSECSSC_W; #[doc = "Field `HSECSSC` writer - HSE clock security system interrupt clear Set by software to clear HSECSSF. Reset by hardware when clear done."] pub use LSIRDYC_W as HSECSSC_W; impl R { #[doc = "Bit 0 - LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done."] #[inline(always)] pub fn lsirdyc(&self) -> LSIRDYC_R { LSIRDYC_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - LSE ready interrupt clear Set by software to clear LSERDYF. Reset by hardware when clear done."] #[inline(always)] pub fn lserdyc(&self) -> LSERDYC_R { LSERDYC_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - HSI ready interrupt clear Set by software to clear HSIRDYF. Reset by hardware when clear done."] #[inline(always)] pub fn hsirdyc(&self) -> HSIRDYC_R { HSIRDYC_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - HSE ready interrupt clear Set by software to clear HSERDYF. Reset by hardware when clear done."] #[inline(always)] pub fn hserdyc(&self) -> HSERDYC_R { HSERDYC_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - CSI ready interrupt clear Set by software to clear CSIRDYF. Reset by hardware when clear done."] #[inline(always)] pub fn csirdyc(&self) -> CSIRDYC_R { CSIRDYC_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - HSI48 ready interrupt clear Set by software to clear HSI48RDYF. Reset by hardware when clear done."] #[inline(always)] pub fn hsi48rdyc(&self) -> HSI48RDYC_R { HSI48RDYC_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - PLL1 ready interrupt clear Set by software to clear PLL1RDYF. Reset by hardware when clear done."] #[inline(always)] pub fn pll1rdyc(&self) -> PLL1RDYC_R { PLL1RDYC_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - PLL2 ready interrupt clear Set by software to clear PLL2RDYF. Reset by hardware when clear done."] #[inline(always)] pub fn pll2rdyc(&self) -> PLL2RDYC_R { PLL2RDYC_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - PLL3 ready interrupt clear Set by software to clear PLL3RDYF. Reset by hardware when clear done."] #[inline(always)] pub fn pll3rdyc(&self) -> PLL3RDYC_R { PLL3RDYC_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - LSE clock security system interrupt clear Set by software to clear LSECSSF. Reset by hardware when clear done."] #[inline(always)] pub fn lsecssc(&self) -> LSECSSC_R { LSECSSC_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - HSE clock security system interrupt clear Set by software to clear HSECSSF. Reset by hardware when clear done."] #[inline(always)] pub fn hsecssc(&self) -> HSECSSC_R { HSECSSC_R::new(((self.bits >> 10) & 1) != 0) } } impl W { #[doc = "Bit 0 - LSI ready interrupt clear Set by software to clear LSIRDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn lsirdyc(&mut self) -> LSIRDYC_W<CICR_SPEC, 0> { LSIRDYC_W::new(self) } #[doc = "Bit 1 - LSE ready interrupt clear Set by software to clear LSERDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn lserdyc(&mut self) -> LSERDYC_W<CICR_SPEC, 1> { LSERDYC_W::new(self) } #[doc = "Bit 2 - HSI ready interrupt clear Set by software to clear HSIRDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn hsirdyc(&mut self) -> HSIRDYC_W<CICR_SPEC, 2> { HSIRDYC_W::new(self) } #[doc = "Bit 3 - HSE ready interrupt clear Set by software to clear HSERDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn hserdyc(&mut self) -> HSERDYC_W<CICR_SPEC, 3> { HSERDYC_W::new(self) } #[doc = "Bit 4 - CSI ready interrupt clear Set by software to clear CSIRDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn csirdyc(&mut self) -> CSIRDYC_W<CICR_SPEC, 4> { CSIRDYC_W::new(self) } #[doc = "Bit 5 - HSI48 ready interrupt clear Set by software to clear HSI48RDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn hsi48rdyc(&mut self) -> HSI48RDYC_W<CICR_SPEC, 5> { HSI48RDYC_W::new(self) } #[doc = "Bit 6 - PLL1 ready interrupt clear Set by software to clear PLL1RDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn pll1rdyc(&mut self) -> PLL1RDYC_W<CICR_SPEC, 6> { PLL1RDYC_W::new(self) } #[doc = "Bit 7 - PLL2 ready interrupt clear Set by software to clear PLL2RDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn pll2rdyc(&mut self) -> PLL2RDYC_W<CICR_SPEC, 7> { PLL2RDYC_W::new(self) } #[doc = "Bit 8 - PLL3 ready interrupt clear Set by software to clear PLL3RDYF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn pll3rdyc(&mut self) -> PLL3RDYC_W<CICR_SPEC, 8> { PLL3RDYC_W::new(self) } #[doc = "Bit 9 - LSE clock security system interrupt clear Set by software to clear LSECSSF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn lsecssc(&mut self) -> LSECSSC_W<CICR_SPEC, 9> { LSECSSC_W::new(self) } #[doc = "Bit 10 - HSE clock security system interrupt clear Set by software to clear HSECSSF. Reset by hardware when clear done."] #[inline(always)] #[must_use] pub fn hsecssc(&mut self) -> HSECSSC_W<CICR_SPEC, 10> { HSECSSC_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 = "\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cicr::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 [`cicr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CICR_SPEC; impl crate::RegisterSpec for CICR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cicr::R`](R) reader structure"] impl crate::Readable for CICR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cicr::W`](W) writer structure"] impl crate::Writable for CICR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CICR to value 0"] impl crate::Resettable for CICR_SPEC { const RESET_VALUE: Self::Ux = 0; }
fn main() { let mut args = std::env::args(); let _ = args.next(); let path = args.next().expect("First argument must be a file path"); let path = std::path::Path::new(&path); if !path.exists() { panic!("First argument must be a file path"); } let js = std::fs::read_to_string(path).expect("Couldn't read the path provide"); for item in ress::Scanner::new(&js) { println!("{:?}", item.expect("failed to lex token")); } }
use auto_impl::auto_impl; trait AllExt { fn foo(&self, _: i32); } impl<T> AllExt for T { fn foo(&self, _: i32) {} } // This will expand to: // // impl<T: Foo> Foo for &T { // fn foo(&self, _x: bool) { // T::foo(self, _x) // } // } // // With this test we want to make sure, that the call `T::foo` is always // unambiguous. Luckily, Rust is nice here. And if we only know `T: Foo`, then // other global functions are not even considered. Having a test for this // doesn't hurt though. #[auto_impl(&)] trait Foo { fn foo(&self, _x: bool); } fn main() {}
use std::os::raw::{c_char, c_int, c_void}; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct CCaDiCaL { _unused: [u8; 0], } extern "C" { pub fn ccadical_signature() -> *const c_char; pub fn ccadical_init() -> *mut CCaDiCaL; pub fn ccadical_release(arg1: *mut CCaDiCaL); pub fn ccadical_add(arg1: *mut CCaDiCaL, lit: c_int); pub fn ccadical_assume(arg1: *mut CCaDiCaL, lit: c_int); pub fn ccadical_solve(arg1: *mut CCaDiCaL) -> c_int; pub fn ccadical_val(arg1: *mut CCaDiCaL, lit: c_int) -> c_int; pub fn ccadical_failed(arg1: *mut CCaDiCaL, lit: c_int) -> c_int; pub fn ccadical_set_terminate( arg1: *mut CCaDiCaL, state: *mut c_void, terminate: Option<unsafe extern "C" fn(state: *mut c_void) -> c_int>, ); pub fn ccadical_set_option(arg1: *mut CCaDiCaL, name: *const c_char, val: c_int); pub fn ccadical_get_option(arg1: *mut CCaDiCaL, name: *const c_char) -> c_int; pub fn ccadical_limit(arg1: *mut CCaDiCaL, name: *const c_char, limit: c_int); pub fn ccadical_print_statistics(arg1: *mut CCaDiCaL); pub fn ccadical_active(arg1: *mut CCaDiCaL) -> i64; pub fn ccadical_irredundant(arg1: *mut CCaDiCaL) -> i64; pub fn ccadical_fixed(arg1: *mut CCaDiCaL, lit: c_int) -> c_int; pub fn ccadical_terminate(arg1: *mut CCaDiCaL); pub fn ccadical_freeze(arg1: *mut CCaDiCaL, lit: c_int); pub fn ccadical_frozen(arg1: *mut CCaDiCaL, lit: c_int) -> c_int; pub fn ccadical_melt(arg1: *mut CCaDiCaL, lit: c_int); pub fn ccadical_simplify(arg1: *mut CCaDiCaL) -> c_int; }
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct IrcConfig { pub servers: Vec<Server>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct UserData { pub nickname: String, pub username: String, pub realname: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Server { pub user_data: UserData, pub hostname: String, pub port: u16, pub password: String, pub use_tls: bool, pub use_hostserv: bool, pub sasl: SaslConfig, pub nickserv: NickServConfig, pub ctcp: CtcpConfig, #[serde(default)] pub channels: Vec<ChannelConfig>, pub privmsg_plugins: Vec<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct SaslConfig { pub enabled: bool, pub user: String, pub password: String, pub terminate_failed: bool, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NickServConfig { pub enabled: bool, pub password: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CtcpConfig { pub enabled: Vec<String>, pub version: String, pub source: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ChannelConfig { pub name: String, pub password: String, }
use memory::LinkedList; use crust::capalloc; use core; use mantle::kernel; use mantle::KError; use kobject::*; use core::cell::{RefCell, RefMut}; use core::ops::DerefMut; struct Subblock { ut: Option<Untyped>, us: Option<UntypedSet>, paddr: usize, size_bits: u8 } impl Subblock { pub fn start(&self) -> usize { self.paddr } pub fn len(&self) -> usize { 1 << (self.size_bits as usize) } pub fn mid(&self) -> usize { self.paddr + (1 << ((self.size_bits - 1) as usize)) } pub fn end(&self) -> usize { self.paddr + self.len() } pub fn contains(&self, addr: usize) -> bool { self.start() <= addr && addr < self.end() } pub fn is_available(&self) -> bool { self.ut.is_some() } pub fn take(&mut self) -> Untyped { core::mem::replace(&mut self.ut, None).unwrap() } pub fn return_taken(&mut self, ut: Untyped) { assert!(self.size_bits == ut.size_bits()); assert!(self.ut.is_none()); assert!(self.us.is_none()); self.ut = Some(ut); } pub fn split(&mut self) -> core::result::Result<(Subblock, Subblock), KError> { let ut = self.take(); match ut.split(1, capalloc::allocate_cap_slots(2)?) { Ok(mut uset) => { assert!(self.us.is_none()); let earlier = uset.take_front().unwrap(); let later = uset.take_front().unwrap(); self.us = Some(uset); Ok((Subblock { ut: Some(earlier), us: None, paddr: self.start(), size_bits: self.size_bits - 1 }, Subblock { ut: Some(later), us: None, paddr: self.mid(), size_bits: self.size_bits - 1 })) } Err((err, ut, slots)) => { assert!(self.ut.is_none()); self.ut = Some(ut); capalloc::free_cap_slots(slots); Err(err) } } } pub fn unsplit(&mut self, earlierblk: Subblock, laterblk: Subblock) { let mut uset = core::mem::replace(&mut self.us, None).unwrap(); uset.readd(laterblk.ut.unwrap()); uset.readd(earlierblk.ut.unwrap()); let (untyped, capslotset) = uset.free(); capalloc::free_cap_slots(capslotset); self.return_taken(untyped); } pub fn needs_split(&self) -> bool { assert!(self.size_bits >= kernel::PAGE_4K_BITS); self.size_bits != kernel::PAGE_4K_BITS } pub fn try_use_as_page(&mut self) -> core::result::Result<core::result::Result<Untyped, (Subblock, Subblock)>, KError> { if self.needs_split() { Ok(Err(self.split()?)) } else { Ok(Ok(self.take())) } } } impl core::fmt::Display for Subblock { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { if let Some(ref ut) = self.ut { assert!(self.us.is_none()); write!(f, "Subblock {} @ {:#X}-{:#X}", ut, self.start(), self.end()) } else if let Some(ref us) = self.us { write!(f, "Subblock split {} @ {:#X}-{:#X}", us, self.start(), self.end()) } else { write!(f, "Subblock taken {}-bit {:#X}-{:#X}", self.size_bits, self.start(), self.end()) } } } pub struct DeviceBlock { caps: LinkedList<RefCell<Subblock>>, // invariant: subblocks always come BEFORE superblocks size_bits: u8, paddr: usize } impl DeviceBlock { pub fn new(ut: Untyped, paddr: usize) -> DeviceBlock { let bits = ut.size_bits(); match LinkedList::empty().push(RefCell::new(Subblock { ut: Some(ut), us: None, paddr, size_bits: bits })) { Ok(ll) => DeviceBlock { caps: ll, size_bits: bits, paddr }, Err(_) => panic!("could not allocate memory for DeviceBlock") } } pub fn start(&self) -> usize { self.paddr } pub fn len(&self) -> usize { 1 << (self.size_bits as usize) } pub fn end(&self) -> usize { self.paddr + self.len() } pub fn contains(&self, addr: usize) -> bool { self.start() <= addr && addr < self.end() } fn device_scan<'a>(&'a self, ll: &'a LinkedList<RefCell<Subblock>>, addr: usize) -> core::result::Result<usize, KError> { assert!(self.caps.is_empty()); // not currently valid assert!(self.contains(addr)); if let Some((index, found)) = ll.find_and_index(|b| b.borrow().contains(addr)) { if found.borrow().is_available() { Ok(index) } else { debug!("failed lookup of {} due to lack of availability", addr); Err(KError::FailedLookup) } } else { // should be guaranteed to find it, since everything is just a subblock of the overall // thing, and that containment should already be checked. panic!("could not look up expected address {:#X}", addr); } } /** * This takes an earlier-in-memory subblock and a later-in-memory subblock, adds them to the * list, and returns a reference to the one that includes paddr. */ // the implicit RefMut is the first element of the linked list fn device_split_iter<'a>(ll: LinkedList<RefCell<Subblock>>, earlier: Subblock, later: Subblock, paddr: usize) -> core::result::Result<LinkedList<RefCell<Subblock>>, (Subblock, Subblock, LinkedList<RefCell<Subblock>>)> { let later_has_paddr: bool = later.contains(paddr); assert!(earlier.contains(paddr) != later_has_paddr); if later_has_paddr { match ll.push(RefCell::new(earlier)) { Ok(ll) => { match ll.push(RefCell::new(later)) { Ok(ll) => Ok(ll), Err((ll, later)) => { let (earlier, ll2) = ll.pop().unwrap(); Err((earlier.into_inner(), later.into_inner(), ll2)) } } } Err((ll, earlier)) => { Err((earlier.into_inner(), later, ll)) } } } else { match ll.push(RefCell::new(later)) { Ok(ll) => { match ll.push(RefCell::new(earlier)) { Ok(ll) => Ok(ll), Err((ll, earlier)) => { let (later, ll2) = ll.pop().unwrap(); Err((earlier.into_inner(), later.into_inner(), ll2)) } } } Err((ll, later)) => { Err((earlier, later.into_inner(), ll)) } } } } fn iter_i(i: usize, ll: LinkedList<RefCell<Subblock>>, addr: usize) -> core::result::Result<core::result::Result<(Untyped, LinkedList<RefCell<Subblock>>), LinkedList<RefCell<Subblock>>>, (KError, LinkedList<RefCell<Subblock>>)> { let page = ll.get(i).unwrap().borrow_mut().deref_mut().try_use_as_page(); if let Err(err) = page { return Err((page.err().unwrap(), ll)); } let rest = page.ok().unwrap(); if let Ok(ut) = rest { return Ok(Ok((ut, ll))); } let (earlier, later) = rest.err().unwrap(); match DeviceBlock::device_split_iter(ll, earlier, later, addr) { Ok(ncur) => { Ok(Err(ncur)) } Err((earlier, later, ll)) => { ll.get(i).unwrap().borrow_mut().deref_mut().unsplit(earlier, later); Err((KError::NotEnoughMemory, ll)) } } } fn get_device_page_untyped_ll(&mut self, ll: LinkedList<RefCell<Subblock>>, addr: usize) -> (core::result::Result<Untyped, KError>, LinkedList<RefCell<Subblock>>) { assert!(self.caps.is_empty()); // not currently valid assert!(self.size_bits >= kernel::PAGE_4K_BITS); // be very careful with try! here. let mut ri = match self.device_scan(&ll, addr) { Ok(ri) => ri, Err(err) => { return (Err(err), ll); } }; let mut cur: LinkedList<RefCell<Subblock>> = ll; loop { match DeviceBlock::iter_i(ri, cur, addr) { Ok(Ok((ut, ll2))) => { return (Ok(ut), ll2); } Ok(Err(iter)) => { cur = iter; ri = 0; } Err((err, ll2)) => { return (Err(err), ll2); } }; } } pub fn get_device_page_untyped(&mut self, addr: usize) -> core::result::Result<Untyped, KError> { assert!(self.contains(addr)); let ll = core::mem::replace(&mut self.caps, LinkedList::Empty); let (res, ll) = self.get_device_page_untyped_ll(ll, addr); self.caps = ll; res } pub fn return_device_page_untyped(&mut self, addr: usize, untyped: Untyped) { // TODO: check this logic... I'm not sure things are being returned to the exact correct places... assert!(self.size_bits >= kernel::PAGE_4K_BITS); assert!(untyped.size_bits() == kernel::PAGE_4K_BITS); assert!(self.contains(addr)); let mut foundref: RefMut<Subblock> = self.caps.find(|b| b.borrow().contains(addr)).unwrap().borrow_mut(); let found: &mut Subblock = foundref.deref_mut(); assert!(!found.is_available()); assert!(found.size_bits == kernel::PAGE_4K_BITS); found.return_taken(untyped); } pub fn get_device_page(&mut self, addr: usize, slot: CapSlot) -> core::result::Result<Page4K, (KError, CapSlot)> { match self.get_device_page_untyped(addr) { Ok(untyped) => { match untyped.become_page_4k(slot) { Ok(page) => Ok(page), Err((err, untyped, slot)) => { self.return_device_page_untyped(addr, untyped); Err((err, slot)) } } } Err(err) => { Err((err, slot)) } } } pub fn return_device_page(&mut self, addr: usize, page: Page4K) -> CapSlot { let (ut, cs) = page.free(); self.return_device_page_untyped(addr, ut); cs } } impl ::core::fmt::Display for DeviceBlock { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { if self.caps.is_empty() { write!(f, "[malformed")?; } else { write!(f, "[{}", *self.caps.head().unwrap().borrow())?; for iter in self.caps.tail().unwrap() { let elem: RefMut<Subblock> = iter.borrow_mut(); write!(f, ", {}", *elem)?; } } write!(f, "] => {:#X}-{:#X}", self.start(), self.end()) } } impl ::core::fmt::Debug for DeviceBlock { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { if self.caps.is_empty() { write!(f, "[malformed")?; } else { write!(f, "DeviceBlock([{}", *self.caps.head().unwrap().borrow())?; for iter in self.caps.tail().unwrap() { let elem: RefMut<Subblock> = iter.borrow_mut(); write!(f, ", {}", *elem)?; } } write!(f, " => {:#X}-{:#X})", self.start(), self.end()) } } // ordered from lowest address to highest address static mut DEVICES: Option<::memory::LinkedList<DeviceBlock>> = None; pub fn get_device_list() -> &'static mut ::memory::LinkedList<DeviceBlock> { let dev: &mut Option<::memory::LinkedList<DeviceBlock>> = unsafe { &mut DEVICES }; if let &mut Some(ref mut out) = dev { out } else { panic!("device listing not yet initialized!"); } } pub fn get_containing_block(addr: usize) -> Option<&'static mut DeviceBlock> { get_device_list().find_mut(|dev| dev.contains(addr)) } pub fn get_device_page(addr: usize) -> core::result::Result<Page4K, KError> { if let Some(block) = get_containing_block(addr) { let slot = capalloc::allocate_cap_slot()?; match block.get_device_page(addr, slot) { Ok(page) => Ok(page), Err((err, slot)) => { capalloc::free_cap_slot(slot); Err(err) } } } else { debug!("failed to lookup {:#X} due to block unavailable", addr); Err(KError::FailedLookup) } } pub fn return_device_page(addr: usize, page: Page4K) { if let Some(block) = get_containing_block(addr) { let slot = block.return_device_page(addr, page); capalloc::free_cap_slot(slot); } else { panic!("attempt to return device page to block that never existed"); } } pub fn get_mapped_device_page(addr: usize) -> core::result::Result<RegionMappedPage4K, KError> { let page = get_device_page(addr)?; match page.map_into_vspace(true) { Ok(mapping) => { Ok(mapping) } Err((page, err)) => { debug!("CANCELLING PAGE MAPPING"); return_device_page(addr, page); Err(err) } } } pub fn return_mapped_device_page(addr: usize, page: RegionMappedPage4K) { return_device_page(addr, page.unmap()); } pub fn init_untyped(untyped: CapRange, untyped_list: [kernel::UntypedDesc; 230usize]) { let count = untyped.len(); // these are sorted! let mut devices = ::memory::LinkedList::empty(); let mut last_addr: usize = (-1 as isize) as usize; for ir in 0..count { let i = count - 1 - ir; let ent = untyped_list[i]; if ent.is_device != 0 { let newblock = DeviceBlock::new(Untyped::from_cap(untyped.nth(i).assert_populated(), ent.size_bits), ent.paddr as usize); assert!(newblock.end() <= last_addr); last_addr = newblock.start(); devices = match devices.push(newblock) { Ok(devs) => devs, Err(_) => panic!("could not allocate memory for device list") }; } } for dev in &devices { debug!("dev {} of {} bits", dev, dev.size_bits); } unsafe { assert!(DEVICES.is_none()); DEVICES = Some(devices); } }
extern crate gtk; use gtk::Builder; pub struct GladeObjectFactory { builder: Builder } impl GladeObjectFactory { pub fn new() -> GladeObjectFactory { // Load glade file let glade_str = include_str!("ui.glade"); let builder = Builder::new_from_string(glade_str); GladeObjectFactory { builder: builder } } pub fn get<T: gtk::IsA<gtk::Object>>(&self, name: &'static str) -> T { if let Some(gtk_obj) = self.builder.get_object(name) { return gtk_obj; } panic!(format!("UI file corrupted. Unknown element of this type '{}'", name)); } }
use crate::util::file; use super::cartridge::cartridge; use crate::nes::cartridge::cartridge::Cartridge; /* An iNES file consists of the following sections, in order: Header (16 bytes) Trainer, if present (0 or 512 bytes) PRG ROM data (16384 * x bytes) CHR ROM data, if present (8192 * y bytes) PlayChoice INST-ROM, if present (0 or 8192 bytes) PlayChoice PROM, if present (16 bytes Data, 16 bytes CounterOut) (this is often missing, see PC10 ROM-Images for details) Some ROM-Images additionally contain a 128-byte (or sometimes 127-byte) title at the end of the file. The format of the header is as follows: 0-3: Constant $4E $45 $53 $1A ("NES" followed by MS-DOS end-of-file) 4: Size of PRG ROM in 16 KB units 5: Size of CHR ROM in 8 KB units (Value 0 means the board uses CHR RAM) 6: Flags 6 - Mapper, mirroring, battery, trainer 7: Flags 7 - Mapper, VS/Playchoice, NES 2.0 8: Flags 8 - PRG-RAM size (rarely used extension) 9: Flags 9 - TV system (rarely used extension) 10: Flags 10 - TV system, PRG-RAM presence (unofficial, rarely used extension) 11-15: Unused padding (should be filled with zero, but some rippers put their name across bytes 7-15) */ const INES_PREFIX: [u8; 4] = [0x4e, 0x45, 0x53, 0x1a]; const PRG_ROM_CHUNK_COUNT_OFFSET: usize = 4; pub const PRG_ROM_CHUNK_SIZE: usize = 0x4000; const CHR_ROM_SIZE_OFFSET: usize = 5; const CHR_ROM_CHUNK_SIZE: usize = 0x2000; const HEADER_SIZE: usize = 0x10; const TRAINER_SIZE: usize = 0x200; const FLAGS_6_OFFSET: usize = 6; const FLAGS_6_MIRRORING_MASK: u8 = 1; const FLAGS_6_BATTERY_MASK: u8 = 2; const FLAGS_6_TRAINER_MASK: u8 = 4; const FLAGS_6_IGNORE_MIRRORING_MASK: u8 = 8; const FLAGS_7_OFFSET: usize = 7; // const FLAGS_8_OFFSET: usize = 8; // const FLAGS_9_OFFSET: usize = 9; const FLAGS_10_OFFSET: usize = 7; const FLAGS_10_TV_SYSTEM_MASK:u8 = 0x3; pub fn open_ines(path: &String) -> Result<(Cartridge), String> { let file_data = file::read_file(path); let header = &file_data[0..HEADER_SIZE]; let ines_prefix = &header[0..4]; if !ines_prefix.eq(&INES_PREFIX) { return Err(format!("Not a valid iNES file")); } let prg_size = header[PRG_ROM_CHUNK_COUNT_OFFSET]; let chr_size = header[CHR_ROM_SIZE_OFFSET]; let mirroring= header[FLAGS_6_OFFSET] & FLAGS_6_MIRRORING_MASK; let battery_ram = (header[FLAGS_6_OFFSET] & FLAGS_6_BATTERY_MASK) > 0; let trainer_present = (header[FLAGS_6_OFFSET] & FLAGS_6_TRAINER_MASK) > 0; let ignore_mirroring = header[FLAGS_6_OFFSET] & FLAGS_6_IGNORE_MIRRORING_MASK > 0; let mapper = (header[FLAGS_7_OFFSET] & 0xF0) + (header[FLAGS_6_OFFSET] >> 4); let tv_system = header[FLAGS_10_OFFSET] & FLAGS_10_TV_SYSTEM_MASK; let mut offset = if trainer_present { TRAINER_SIZE + HEADER_SIZE } else { HEADER_SIZE }; let mut prg_rom_vec = Vec::new(); for _i in 0..prg_size { prg_rom_vec.push(&file_data[offset..offset + PRG_ROM_CHUNK_SIZE]); offset += PRG_ROM_CHUNK_SIZE; } let mut chr_rom_vec = Vec::new(); for _i in 0..chr_size { chr_rom_vec.push(&file_data[offset..offset + CHR_ROM_CHUNK_SIZE]); offset += CHR_ROM_CHUNK_SIZE; } #[cfg(debug_assertions)] { println!("Parsed iNES: {}", path); println!("==========================="); println!("PRG size: {} kb", prg_size as usize * PRG_ROM_CHUNK_SIZE); println!("CHR size: {}", chr_size as usize * CHR_ROM_CHUNK_SIZE); println!("Mirroring: {}", mirroring); println!("Battery present: {}", battery_ram); println!("Trainer present: {}", trainer_present); println!("Ignore mirroring: {}", ignore_mirroring); println!("Mapper: {}", mapper); println!("TV-system: {}", tv_system); println!("==========================="); } let cartridge = cartridge::create_cartridge_from_ines(mapper, prg_rom_vec, chr_rom_vec, mirroring)?; Ok(cartridge) }
use std::convert::TryInto; use std::io::{stdin, stdout, Write}; fn main() { let number = get_number_from_user(); let split_numbers: Vec<_> = number .to_string() .chars() .map(|n| n.to_digit(10).unwrap()) .collect(); let power = split_numbers.len(); let mut sum = 0; for num in &split_numbers { sum += num.pow(power.try_into().unwrap()); } if sum == number.try_into().unwrap() { println!("The number is an armstrong number."); } else { println!("The given number is not an armstrong number."); } } fn get_number_from_user() -> i32 { let mut s = String::new(); print!("Please enter some text: "); let _ = stdout().flush(); stdin() .read_line(&mut s) .expect("Did not enter a correct string"); let num: i32 = s .trim() .parse() .expect("please give me correct string number!"); return num; }
use crate::bus::Bus; #[derive(Debug, Clone, Copy)] pub struct Ppu<B: Bus> { pub(crate) bus: B, } impl<B: Bus> Ppu<B> { pub fn new(bus: B) -> Ppu<B> { Ppu { bus } } pub fn reset(&mut self) {} pub fn step(&mut self) {} pub fn read(&mut self, address: u16) -> u8 { 0 } pub fn write(&mut self, address: u16, data: u8) {} }
extern crate minifb; extern crate rand; use minifb::{Key, Scale, WindowOptions}; use rand::Rng; const WIDTH: usize = 640; const HEIGHT: usize = 360; #[derive(Copy, Clone)] struct Star { x: f64, y: f64, z: f64, speed: f64 } fn gen_star() -> Star { let mut rng = rand::thread_rng(); Star { x: rng.gen_range::<f64>(-30.0, 30.0) * (WIDTH as f64), y: rng.gen_range::<f64>(-30.0, 30.0) * (HEIGHT as f64), z: rng.gen_range::<f64>(50.0, 100.0), speed: rng.gen_range::<f64>(1.0, 5.0), } } fn main() { let blank_buffer: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut window = match minifb::Window::new("Test - ESC to exit", WIDTH, HEIGHT, WindowOptions::default()) { Ok(win) => win, Err(err) => { println!("Unable to create window {}", err); return; } }; let mut stars = Vec::<Star>::new(); for _ in 0..100 { stars.push(gen_star()); } while window.is_open() && !window.is_key_down(Key::Escape) { buffer = blank_buffer.clone(); for star in stars.iter_mut() { let x = (star.x / star.z + (WIDTH as f64 / 2.0)) as usize; let y = (star.y / star.z + (HEIGHT as f64 / 2.0)) as usize; if x >= WIDTH || y >= HEIGHT { *star = gen_star(); continue; } let index = x + y*WIDTH; let color: u32 = ((90.0 + 164.0 / (100.0 / star.z)) as u8) as u32; //println!("1: {}", format!("{0:#x}", color)); let color: u32 = color + (color << 8) + (color << 16) + (color << 24); //println!("2: {}", format!("{0:#x}", color)); for y2 in 0..(2 as usize) { for x2 in 0..(2 as usize) { let index = index + x2 + WIDTH * y2; if index >= WIDTH * HEIGHT { break; } buffer[index] = color; } } star.z -= star.speed; if star.z <= 0.0 { *star = gen_star(); } } window.update_with_buffer(&buffer); } }
//! Makes drawing on ncurses windows easier. use std::cmp::min; use backend::Backend; use B; use theme::{ColorStyle, Effect, Theme}; use vec::{ToVec2, Vec2}; /// Convenient interface to draw on a subset of the screen. #[derive(Clone)] pub struct Printer { /// Offset into the window this printer should start drawing at. pub offset: Vec2, /// Size of the area we are allowed to draw on. pub size: Vec2, /// Whether the view to draw is currently focused or not. pub focused: bool, /// Currently used theme pub theme: Theme, } impl Printer { /// Creates a new printer on the given window. pub fn new<T: ToVec2>(size: T, theme: Theme) -> Self { Printer { offset: Vec2::zero(), size: size.to_vec2(), focused: true, theme: theme, } } // TODO: use &mut self? We don't *need* it, but it may make sense. // We don't want people to start calling prints in parallel? /// Prints some text at the given position relative to the window. pub fn print<S: ToVec2>(&self, pos: S, text: &str) { let p = pos.to_vec2(); if p.y >= self.size.y || p.x >= self.size.x { return; } // Do we have enough room for the entire line? let room = self.size.x - p.x; // We want the number of CHARACTERS, not bytes. // (Actually we want the "width" of the string, see unicode-width) let text = match text.char_indices().nth(room) { Some((i, _)) => &text[..i], _ => text, }; let p = p + self.offset; if text.contains('%') { B::print_at((p.x, p.y), &text.replace("%", "%%")); } else { B::print_at((p.x, p.y), text); } } /// Prints a vertical line using the given character. pub fn print_vline<T: ToVec2>(&self, start: T, len: usize, c: &str) { let p = start.to_vec2(); if p.y > self.size.y || p.x > self.size.x { return; } let len = min(len, self.size.y - p.y); let p = p + self.offset; for y in 0..len { B::print_at((p.x, (p.y + y)), c); } } /// Prints a horizontal line using the given character. pub fn print_hline<T: ToVec2>(&self, start: T, len: usize, c: &str) { let p = start.to_vec2(); if p.y > self.size.y || p.x > self.size.x { return; } let len = min(len, self.size.x - p.x); let p = p + self.offset; for x in 0..len { B::print_at((p.x + x, p.y), c); } } /// Call the given closure with a colored printer, /// that will apply the given color on prints. /// /// # Examples /// /// ```no_run /// # use cursive::printer::Printer; /// # use cursive::theme; /// # let printer = Printer::new((6,4), theme::load_default()); /// printer.with_color(theme::ColorStyle::Highlight, |printer| { /// printer.print((0,0), "This text is highlighted!"); /// }); /// ``` pub fn with_color<F>(&self, c: ColorStyle, f: F) where F: FnOnce(&Printer) { B::with_color(c, || f(self)); } /// Same as `with_color`, but apply a ncurses style instead, /// like `ncurses::A_BOLD()` or `ncurses::A_REVERSE()`. /// /// Will probably use a cursive enum some day. pub fn with_effect<F>(&self, effect: Effect, f: F) where F: FnOnce(&Printer) { B::with_effect(effect, || f(self)); } /// Prints a rectangular box. /// /// # Examples /// /// ``` /// # use cursive::printer::Printer; /// # use cursive::theme; /// # let printer = Printer::new((6,4), theme::load_default()); /// printer.print_box((0,0), (6,4)); /// ``` pub fn print_box<T: ToVec2>(&self, start: T, size: T) { let start_v = start.to_vec2(); let size_v = size.to_vec2() - (1, 1); self.print(start_v, "┌"); self.print(start_v + size_v.keep_x(), "┐"); self.print(start_v + size_v.keep_y(), "└"); self.print(start_v + size_v, "┘"); self.print_hline(start_v + (1, 0), size_v.x - 1, "─"); self.print_vline(start_v + (0, 1), size_v.y - 1, "│"); self.print_hline(start_v + (1, 0) + size_v.keep_y(), size_v.x - 1, "─"); self.print_vline(start_v + (0, 1) + size_v.keep_x(), size_v.y - 1, "│"); } pub fn with_selection<F: FnOnce(&Printer)>(&self, selection: bool, f: F) { self.with_color(if selection { if self.focused { ColorStyle::Highlight } else { ColorStyle::HighlightInactive } } else { ColorStyle::Primary }, f); } pub fn print_hdelim<T: ToVec2>(&self, start: T, len: usize) { let start = start.to_vec2(); self.print(start, "├"); self.print_hline(start + (1, 0), len - 2, "─"); self.print(start + (len - 1, 0), "┤"); } /// Returns a printer on a subset of this one's area. pub fn sub_printer<S: ToVec2>(&self, offset: S, size: S, focused: bool) -> Printer { let offset_v = offset.to_vec2(); Printer { offset: self.offset + offset_v, // We can't be larger than what remains size: Vec2::min(self.size - offset_v, size.to_vec2()), focused: self.focused && focused, theme: self.theme.clone(), } } }
#![feature(no_std)] #![feature(core)] #![no_std] //! Toggle the blue LED (PC8) at 1 Hz. The timing is handled by the TIM7 timer. The main thread //! sleeps most of the time, and only wakes up on TIM7's interrupts to toggle the LED. //extern crate cortex; extern crate core; extern crate nrf51822; extern crate cortex; use nrf51822::interrupt::IntVector; use cortex::nvic::iser0; const CC0VAL: u32 = 16384; pub fn get_nvic_iser0_mask(vector: IntVector) -> iser0::Bit { match vector { nrf51822::interrupt::IntVector::RTC0Irqn => iser0::Bit::_11 } } pub fn sys_init() { let clock = nrf51822::peripheral::clock(); clock.tasks_lfclkstart.set(1); } #[no_mangle] pub fn main() { let gpio = nrf51822::peripheral::gpio(); let rtc0 = nrf51822::peripheral::rtc0(); let nvic = cortex::peripheral::nvic(); sys_init(); rtc0.power.set(1); rtc0.intenset.update(|intenset| { use nrf51822::rtc::intenset::prelude::*; intenset | COMPARE0 }); rtc0.cc0.set(CC0VAL); // unmask RTC0 interrupt nvic.iser0.set({ //int_mask get_nvic_iser0_mask(IntVector::RTC0Irqn) }); gpio.dir_set.update(|dir_set| { use nrf51822::gpio::dir_set::prelude::*; dir_set | PIN25 | PIN24 }); let mut state: bool = true; rtc0.tasks_start.set(1); loop { if state { gpio.out_set.update(|out_set| { use nrf51822::gpio::out_set::prelude::*; out_set | PIN25 | PIN24 }); } else { gpio.out_clr.update(|out_clr| { use nrf51822::gpio::out_clr::prelude::*; out_clr | PIN25 | PIN24 }); } cortex::asm::wfi(); if state == true { state = false; rtc0.cc0.set(CC0VAL); } else { state = true; rtc0.cc0.set(CC0VAL); } rtc0.tasks_clear.set(1); rtc0.tasks_start.set(1); } } #[no_mangle] pub extern fn rtc0() { let rtc0 = nrf51822::peripheral::rtc0(); rtc0.events_compare0.set(0); rtc0.tasks_stop.set(1); }
use std::mem; pub struct List { head: Link, size: i32, } enum Link { Empty, More(Box<Node>), } struct Node { elem: i32, next: Link, } impl List { pub fn new() -> Self { List { head: Link::Empty, size: 0, } } pub fn push(&mut self, elem: i32) { let new_node = Node { elem, next: mem::replace(&mut self.head, Link::Empty), }; self.head = Link::More(Box::new(new_node)); self.size += 1; } pub fn pop(&mut self) -> Option<i32> { match mem::replace(&mut self.head, Link::Empty) { Link::Empty => None, Link::More(node) => { self.head = node.next; self.size -= 1; Some(node.elem) } } } } #[cfg(test)] mod tests { use super::List; #[test] fn test_new() { let l = List::new(); assert_eq!(l.size, 0); } #[test] fn test_push() { let mut l = List::new(); l.push(1); assert_eq!(l.size, 1); assert_eq!(l.pop(), Some(1)); } #[test] fn test_pop() { let mut l = List::new(); l.push(1); assert_eq!(l.size, 1); let v = l.pop(); assert_eq!(l.size, 0); assert_eq!(v, Some(1)); } }
#[doc = "Register `R4CFGR` reader"] pub type R = crate::R<R4CFGR_SPEC>; #[doc = "Register `R4CFGR` writer"] pub type W = crate::W<R4CFGR_SPEC>; #[doc = "Field `REG_EN` reader - region on-the-fly decryption enable Note: Garbage is decrypted if region context (version, key, nonce) is not valid when this bit is set."] pub type REG_EN_R = crate::BitReader; #[doc = "Field `REG_EN` writer - region on-the-fly decryption enable Note: Garbage is decrypted if region context (version, key, nonce) is not valid when this bit is set."] pub type REG_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CONFIGLOCK` reader - region config lock Note: This bit is set once. If this bit is set, it can only be reset to 0 if OTFDEC is reset. Setting this bit forces KEYLOCK bit to 1."] pub type CONFIGLOCK_R = crate::BitReader; #[doc = "Field `CONFIGLOCK` writer - region config lock Note: This bit is set once. If this bit is set, it can only be reset to 0 if OTFDEC is reset. Setting this bit forces KEYLOCK bit to 1."] pub type CONFIGLOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `KEYLOCK` reader - region key lock Note: This bit is set once: if this bit is set, it can only be reset to 0 if the OTFDEC is reset."] pub type KEYLOCK_R = crate::BitReader; #[doc = "Field `KEYLOCK` writer - region key lock Note: This bit is set once: if this bit is set, it can only be reset to 0 if the OTFDEC is reset."] pub type KEYLOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MODE` reader - operating mode This bitfield selects the OTFDEC operating mode for this region: Others: Reserved When MODE ≠ 11, the standard AES encryption mode is activated. When either of the MODE bits are changed, the region key and associated CRC are zeroed."] pub type MODE_R = crate::FieldReader; #[doc = "Field `MODE` writer - operating mode This bitfield selects the OTFDEC operating mode for this region: Others: Reserved When MODE ≠ 11, the standard AES encryption mode is activated. When either of the MODE bits are changed, the region key and associated CRC are zeroed."] pub type MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `KEYCRC` reader - region key 8-bit CRC When KEYLOCK = 0, KEYCRC bitfield is automatically computed by hardware while loading the key of this region in this exact sequence: KEYR0 then KEYR1 then KEYR2 then finally KEYR3 (all written once). A new computation starts as soon as a new valid sequence is initiated, and KEYCRC is read as zero until a valid sequence is completed. When KEYLOCK = 1, KEYCRC remains unchanged until the next reset. CRC computation is an 8-bit checksum using the standard CRC-8-CCITT algorithm X8 + X2 + X + 1 (according the convention). Source code is available in . This field is read only. Note: CRC information is updated only after the last bit of the key has been written."] pub type KEYCRC_R = crate::FieldReader; #[doc = "Field `REGx_VERSION` reader - region firmware version This 16-bit bitfield must be correctly initialized before the region corresponding REG_EN bit is set in OTFDEC_RxCFGR."] pub type REGX_VERSION_R = crate::FieldReader<u16>; #[doc = "Field `REGx_VERSION` writer - region firmware version This 16-bit bitfield must be correctly initialized before the region corresponding REG_EN bit is set in OTFDEC_RxCFGR."] pub type REGX_VERSION_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>; impl R { #[doc = "Bit 0 - region on-the-fly decryption enable Note: Garbage is decrypted if region context (version, key, nonce) is not valid when this bit is set."] #[inline(always)] pub fn reg_en(&self) -> REG_EN_R { REG_EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - region config lock Note: This bit is set once. If this bit is set, it can only be reset to 0 if OTFDEC is reset. Setting this bit forces KEYLOCK bit to 1."] #[inline(always)] pub fn configlock(&self) -> CONFIGLOCK_R { CONFIGLOCK_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - region key lock Note: This bit is set once: if this bit is set, it can only be reset to 0 if the OTFDEC is reset."] #[inline(always)] pub fn keylock(&self) -> KEYLOCK_R { KEYLOCK_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 4:5 - operating mode This bitfield selects the OTFDEC operating mode for this region: Others: Reserved When MODE ≠ 11, the standard AES encryption mode is activated. When either of the MODE bits are changed, the region key and associated CRC are zeroed."] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 8:15 - region key 8-bit CRC When KEYLOCK = 0, KEYCRC bitfield is automatically computed by hardware while loading the key of this region in this exact sequence: KEYR0 then KEYR1 then KEYR2 then finally KEYR3 (all written once). A new computation starts as soon as a new valid sequence is initiated, and KEYCRC is read as zero until a valid sequence is completed. When KEYLOCK = 1, KEYCRC remains unchanged until the next reset. CRC computation is an 8-bit checksum using the standard CRC-8-CCITT algorithm X8 + X2 + X + 1 (according the convention). Source code is available in . This field is read only. Note: CRC information is updated only after the last bit of the key has been written."] #[inline(always)] pub fn keycrc(&self) -> KEYCRC_R { KEYCRC_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:31 - region firmware version This 16-bit bitfield must be correctly initialized before the region corresponding REG_EN bit is set in OTFDEC_RxCFGR."] #[inline(always)] pub fn regx_version(&self) -> REGX_VERSION_R { REGX_VERSION_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bit 0 - region on-the-fly decryption enable Note: Garbage is decrypted if region context (version, key, nonce) is not valid when this bit is set."] #[inline(always)] #[must_use] pub fn reg_en(&mut self) -> REG_EN_W<R4CFGR_SPEC, 0> { REG_EN_W::new(self) } #[doc = "Bit 1 - region config lock Note: This bit is set once. If this bit is set, it can only be reset to 0 if OTFDEC is reset. Setting this bit forces KEYLOCK bit to 1."] #[inline(always)] #[must_use] pub fn configlock(&mut self) -> CONFIGLOCK_W<R4CFGR_SPEC, 1> { CONFIGLOCK_W::new(self) } #[doc = "Bit 2 - region key lock Note: This bit is set once: if this bit is set, it can only be reset to 0 if the OTFDEC is reset."] #[inline(always)] #[must_use] pub fn keylock(&mut self) -> KEYLOCK_W<R4CFGR_SPEC, 2> { KEYLOCK_W::new(self) } #[doc = "Bits 4:5 - operating mode This bitfield selects the OTFDEC operating mode for this region: Others: Reserved When MODE ≠ 11, the standard AES encryption mode is activated. When either of the MODE bits are changed, the region key and associated CRC are zeroed."] #[inline(always)] #[must_use] pub fn mode(&mut self) -> MODE_W<R4CFGR_SPEC, 4> { MODE_W::new(self) } #[doc = "Bits 16:31 - region firmware version This 16-bit bitfield must be correctly initialized before the region corresponding REG_EN bit is set in OTFDEC_RxCFGR."] #[inline(always)] #[must_use] pub fn regx_version(&mut self) -> REGX_VERSION_W<R4CFGR_SPEC, 16> { REGX_VERSION_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 = "OTFDEC region 4 configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`r4cfgr::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 [`r4cfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct R4CFGR_SPEC; impl crate::RegisterSpec for R4CFGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`r4cfgr::R`](R) reader structure"] impl crate::Readable for R4CFGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`r4cfgr::W`](W) writer structure"] impl crate::Writable for R4CFGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets R4CFGR to value 0"] impl crate::Resettable for R4CFGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use async_trait::async_trait; use sc_client_api::AuxStore; use sc_consensus_subspace::archiver::SegmentHeadersStore; use subspace_archiving::archiver::is_piece_valid; use subspace_core_primitives::crypto::kzg::Kzg; use subspace_core_primitives::{Piece, PieceIndex}; use subspace_networking::libp2p::PeerId; use subspace_networking::utils::piece_provider::PieceValidator; use subspace_networking::Node; use tracing::{error, warn}; pub struct SegmentCommitmentPieceValidator<'a, AS> { dsn_node: &'a Node, kzg: &'a Kzg, segment_headers_store: &'a SegmentHeadersStore<AS>, } impl<'a, AS> SegmentCommitmentPieceValidator<'a, AS> where AS: AuxStore + Send + Sync + 'static, { /// Segment headers must be in order from 0 to the last one that exists pub fn new( dsn_node: &'a Node, kzg: &'a Kzg, segment_headers_store: &'a SegmentHeadersStore<AS>, ) -> Self { Self { dsn_node, kzg, segment_headers_store, } } } #[async_trait] impl<'a, AS> PieceValidator for SegmentCommitmentPieceValidator<'a, AS> where AS: AuxStore + Send + Sync + 'static, { async fn validate_piece( &self, source_peer_id: PeerId, piece_index: PieceIndex, piece: Piece, ) -> Option<Piece> { if source_peer_id != self.dsn_node.id() { let segment_index = piece_index.segment_index(); let maybe_segment_header = self.segment_headers_store.get_segment_header(segment_index); let segment_commitment = match maybe_segment_header { Some(segment_header) => segment_header.segment_commitment(), None => { error!(%segment_index, "No segment commitment in the cache."); return None; } }; if !is_piece_valid( self.kzg, &piece, &segment_commitment, piece_index.position(), ) { warn!( %piece_index, %source_peer_id, "Received invalid piece from peer" ); // We don't care about result here let _ = self.dsn_node.ban_peer(source_peer_id).await; return None; } } Some(piece) } }
pub mod score; pub mod utils; pub mod align; pub mod filter; pub mod reference_library;
#![no_std] #![crate_type="lib"] #![crate_name="startup"] #![feature(lang_items, no_std, core, start)] pub static NO_DEAD_CODE: u32 = 0; #[macro_use] extern crate core; extern crate libc; extern crate rlibc; pub mod lang_items; pub mod mem; #[start] #[lang = "start"] fn start(main: *const u8, _argc: isize, _argv: *const *const u8) -> isize { use core::intrinsics::transmute; unsafe { let main: fn() = transmute(main); main(); }; 0 }
use ndarray::Array; pub type NdArray = Array<f32, ndarray::IxDyn>; pub trait MNISTModel { fn new() -> Self; fn train(&self); fn validate(&self) -> f64; fn load_model(&mut self) -> Result<(), std::io::Error>; }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Control"] pub ctl: CTL, _reserved1: [u8; 4usize], #[doc = "0x08 - RTC Read Write register"] pub rtc_rw: RTC_RW, #[doc = "0x0c - Oscillator calibration for absolute frequency"] pub cal_ctl: CAL_CTL, #[doc = "0x10 - Status"] pub status: STATUS, #[doc = "0x14 - Calendar Seconds, Minutes, Hours, Day of Week"] pub rtc_time: RTC_TIME, #[doc = "0x18 - Calendar Day of Month, Month, Year"] pub rtc_date: RTC_DATE, #[doc = "0x1c - Alarm 1 Seconds, Minute, Hours, Day of Week"] pub alm1_time: ALM1_TIME, #[doc = "0x20 - Alarm 1 Day of Month, Month"] pub alm1_date: ALM1_DATE, #[doc = "0x24 - Alarm 2 Seconds, Minute, Hours, Day of Week"] pub alm2_time: ALM2_TIME, #[doc = "0x28 - Alarm 2 Day of Month, Month"] pub alm2_date: ALM2_DATE, #[doc = "0x2c - Interrupt request register"] pub intr: INTR, #[doc = "0x30 - Interrupt set request register"] pub intr_set: INTR_SET, #[doc = "0x34 - Interrupt mask register"] pub intr_mask: INTR_MASK, #[doc = "0x38 - Interrupt masked request register"] pub intr_masked: INTR_MASKED, #[doc = "0x3c - 32kHz oscillator counter"] pub osccnt: OSCCNT, #[doc = "0x40 - 128Hz tick counter"] pub ticks: TICKS, #[doc = "0x44 - PMIC control register"] pub pmic_ctl: PMIC_CTL, #[doc = "0x48 - Backup reset register"] pub reset: RESET, _reserved18: [u8; 4020usize], #[doc = "0x1000 - Backup register region"] pub breg: [BREG; 64], _reserved19: [u8; 60928usize], #[doc = "0xff00 - Trim Register"] pub trim: TRIM, } #[doc = "Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"] pub type CTL = crate::Reg<u32, _CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CTL; #[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"] impl crate::Readable for CTL {} #[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"] impl crate::Writable for CTL {} #[doc = "Control"] pub mod ctl; #[doc = "RTC Read Write register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rtc_rw](rtc_rw) module"] pub type RTC_RW = crate::Reg<u32, _RTC_RW>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RTC_RW; #[doc = "`read()` method returns [rtc_rw::R](rtc_rw::R) reader structure"] impl crate::Readable for RTC_RW {} #[doc = "`write(|w| ..)` method takes [rtc_rw::W](rtc_rw::W) writer structure"] impl crate::Writable for RTC_RW {} #[doc = "RTC Read Write register"] pub mod rtc_rw; #[doc = "Oscillator calibration for absolute frequency\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [cal_ctl](cal_ctl) module"] pub type CAL_CTL = crate::Reg<u32, _CAL_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CAL_CTL; #[doc = "`read()` method returns [cal_ctl::R](cal_ctl::R) reader structure"] impl crate::Readable for CAL_CTL {} #[doc = "`write(|w| ..)` method takes [cal_ctl::W](cal_ctl::W) writer structure"] impl crate::Writable for CAL_CTL {} #[doc = "Oscillator calibration for absolute frequency"] pub mod cal_ctl; #[doc = "Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [status](status) module"] pub type STATUS = crate::Reg<u32, _STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _STATUS; #[doc = "`read()` method returns [status::R](status::R) reader structure"] impl crate::Readable for STATUS {} #[doc = "Status"] pub mod status; #[doc = "Calendar Seconds, Minutes, Hours, Day of Week\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rtc_time](rtc_time) module"] pub type RTC_TIME = crate::Reg<u32, _RTC_TIME>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RTC_TIME; #[doc = "`read()` method returns [rtc_time::R](rtc_time::R) reader structure"] impl crate::Readable for RTC_TIME {} #[doc = "`write(|w| ..)` method takes [rtc_time::W](rtc_time::W) writer structure"] impl crate::Writable for RTC_TIME {} #[doc = "Calendar Seconds, Minutes, Hours, Day of Week"] pub mod rtc_time; #[doc = "Calendar Day of Month, Month, Year\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rtc_date](rtc_date) module"] pub type RTC_DATE = crate::Reg<u32, _RTC_DATE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RTC_DATE; #[doc = "`read()` method returns [rtc_date::R](rtc_date::R) reader structure"] impl crate::Readable for RTC_DATE {} #[doc = "`write(|w| ..)` method takes [rtc_date::W](rtc_date::W) writer structure"] impl crate::Writable for RTC_DATE {} #[doc = "Calendar Day of Month, Month, Year"] pub mod rtc_date; #[doc = "Alarm 1 Seconds, Minute, Hours, Day of Week\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [alm1_time](alm1_time) module"] pub type ALM1_TIME = crate::Reg<u32, _ALM1_TIME>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ALM1_TIME; #[doc = "`read()` method returns [alm1_time::R](alm1_time::R) reader structure"] impl crate::Readable for ALM1_TIME {} #[doc = "`write(|w| ..)` method takes [alm1_time::W](alm1_time::W) writer structure"] impl crate::Writable for ALM1_TIME {} #[doc = "Alarm 1 Seconds, Minute, Hours, Day of Week"] pub mod alm1_time; #[doc = "Alarm 1 Day of Month, Month\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [alm1_date](alm1_date) module"] pub type ALM1_DATE = crate::Reg<u32, _ALM1_DATE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ALM1_DATE; #[doc = "`read()` method returns [alm1_date::R](alm1_date::R) reader structure"] impl crate::Readable for ALM1_DATE {} #[doc = "`write(|w| ..)` method takes [alm1_date::W](alm1_date::W) writer structure"] impl crate::Writable for ALM1_DATE {} #[doc = "Alarm 1 Day of Month, Month"] pub mod alm1_date; #[doc = "Alarm 2 Seconds, Minute, Hours, Day of Week\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [alm2_time](alm2_time) module"] pub type ALM2_TIME = crate::Reg<u32, _ALM2_TIME>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ALM2_TIME; #[doc = "`read()` method returns [alm2_time::R](alm2_time::R) reader structure"] impl crate::Readable for ALM2_TIME {} #[doc = "`write(|w| ..)` method takes [alm2_time::W](alm2_time::W) writer structure"] impl crate::Writable for ALM2_TIME {} #[doc = "Alarm 2 Seconds, Minute, Hours, Day of Week"] pub mod alm2_time; #[doc = "Alarm 2 Day of Month, Month\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [alm2_date](alm2_date) module"] pub type ALM2_DATE = crate::Reg<u32, _ALM2_DATE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ALM2_DATE; #[doc = "`read()` method returns [alm2_date::R](alm2_date::R) reader structure"] impl crate::Readable for ALM2_DATE {} #[doc = "`write(|w| ..)` method takes [alm2_date::W](alm2_date::W) writer structure"] impl crate::Writable for ALM2_DATE {} #[doc = "Alarm 2 Day of Month, Month"] pub mod alm2_date; #[doc = "Interrupt request register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr](intr) module"] pub type INTR = crate::Reg<u32, _INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR; #[doc = "`read()` method returns [intr::R](intr::R) reader structure"] impl crate::Readable for INTR {} #[doc = "`write(|w| ..)` method takes [intr::W](intr::W) writer structure"] impl crate::Writable for INTR {} #[doc = "Interrupt request register"] pub mod intr; #[doc = "Interrupt set request register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_set](intr_set) module"] pub type INTR_SET = crate::Reg<u32, _INTR_SET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_SET; #[doc = "`read()` method returns [intr_set::R](intr_set::R) reader structure"] impl crate::Readable for INTR_SET {} #[doc = "`write(|w| ..)` method takes [intr_set::W](intr_set::W) writer structure"] impl crate::Writable for INTR_SET {} #[doc = "Interrupt set request register"] pub mod intr_set; #[doc = "Interrupt mask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_mask](intr_mask) module"] pub type INTR_MASK = crate::Reg<u32, _INTR_MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASK; #[doc = "`read()` method returns [intr_mask::R](intr_mask::R) reader structure"] impl crate::Readable for INTR_MASK {} #[doc = "`write(|w| ..)` method takes [intr_mask::W](intr_mask::W) writer structure"] impl crate::Writable for INTR_MASK {} #[doc = "Interrupt mask register"] pub mod intr_mask; #[doc = "Interrupt masked request register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [intr_masked](intr_masked) module"] pub type INTR_MASKED = crate::Reg<u32, _INTR_MASKED>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR_MASKED; #[doc = "`read()` method returns [intr_masked::R](intr_masked::R) reader structure"] impl crate::Readable for INTR_MASKED {} #[doc = "Interrupt masked request register"] pub mod intr_masked; #[doc = "32kHz oscillator counter\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [osccnt](osccnt) module"] pub type OSCCNT = crate::Reg<u32, _OSCCNT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OSCCNT; #[doc = "`read()` method returns [osccnt::R](osccnt::R) reader structure"] impl crate::Readable for OSCCNT {} #[doc = "32kHz oscillator counter"] pub mod osccnt; #[doc = "128Hz tick counter\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ticks](ticks) module"] pub type TICKS = crate::Reg<u32, _TICKS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TICKS; #[doc = "`read()` method returns [ticks::R](ticks::R) reader structure"] impl crate::Readable for TICKS {} #[doc = "128Hz tick counter"] pub mod ticks; #[doc = "PMIC control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [pmic_ctl](pmic_ctl) module"] pub type PMIC_CTL = crate::Reg<u32, _PMIC_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PMIC_CTL; #[doc = "`read()` method returns [pmic_ctl::R](pmic_ctl::R) reader structure"] impl crate::Readable for PMIC_CTL {} #[doc = "`write(|w| ..)` method takes [pmic_ctl::W](pmic_ctl::W) writer structure"] impl crate::Writable for PMIC_CTL {} #[doc = "PMIC control register"] pub mod pmic_ctl; #[doc = "Backup reset register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [reset](reset) module"] pub type RESET = crate::Reg<u32, _RESET>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RESET; #[doc = "`read()` method returns [reset::R](reset::R) reader structure"] impl crate::Readable for RESET {} #[doc = "`write(|w| ..)` method takes [reset::W](reset::W) writer structure"] impl crate::Writable for RESET {} #[doc = "Backup reset register"] pub mod reset; #[doc = "Backup register region\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [breg](breg) module"] pub type BREG = crate::Reg<u32, _BREG>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BREG; #[doc = "`read()` method returns [breg::R](breg::R) reader structure"] impl crate::Readable for BREG {} #[doc = "`write(|w| ..)` method takes [breg::W](breg::W) writer structure"] impl crate::Writable for BREG {} #[doc = "Backup register region"] pub mod breg; #[doc = "Trim Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [trim](trim) module"] pub type TRIM = crate::Reg<u32, _TRIM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _TRIM; #[doc = "`read()` method returns [trim::R](trim::R) reader structure"] impl crate::Readable for TRIM {} #[doc = "`write(|w| ..)` method takes [trim::W](trim::W) writer structure"] impl crate::Writable for TRIM {} #[doc = "Trim Register"] pub mod trim;
#[doc = "Register `TDWR` writer"] pub type W = crate::W<TDWR_SPEC>; #[doc = "Field `TDB0` writer - 8-bit transmit data (earliest byte on I3C bus)"] pub type TDB0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `TDB1` writer - 8-bit transmit data (next byte after TDB0\\[7:0\\] on I3C bus)."] pub type TDB1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `TDB2` writer - 8-bit transmit data (next byte after TDB1\\[7:0\\] on I3C bus)."] pub type TDB2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `TDB3` writer - 8-bit transmit data (latest byte on I3C bus)."] pub type TDB3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; impl W { #[doc = "Bits 0:7 - 8-bit transmit data (earliest byte on I3C bus)"] #[inline(always)] #[must_use] pub fn tdb0(&mut self) -> TDB0_W<TDWR_SPEC, 0> { TDB0_W::new(self) } #[doc = "Bits 8:15 - 8-bit transmit data (next byte after TDB0\\[7:0\\] on I3C bus)."] #[inline(always)] #[must_use] pub fn tdb1(&mut self) -> TDB1_W<TDWR_SPEC, 8> { TDB1_W::new(self) } #[doc = "Bits 16:23 - 8-bit transmit data (next byte after TDB1\\[7:0\\] on I3C bus)."] #[inline(always)] #[must_use] pub fn tdb2(&mut self) -> TDB2_W<TDWR_SPEC, 16> { TDB2_W::new(self) } #[doc = "Bits 24:31 - 8-bit transmit data (latest byte on I3C bus)."] #[inline(always)] #[must_use] pub fn tdb3(&mut self) -> TDB3_W<TDWR_SPEC, 24> { TDB3_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 = "I3C transmit data word register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tdwr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TDWR_SPEC; impl crate::RegisterSpec for TDWR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`tdwr::W`](W) writer structure"] impl crate::Writable for TDWR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TDWR to value 0"] impl crate::Resettable for TDWR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use hacspec_lib::prelude::*; #[test] fn test_byte_sequences() { let msg = PublicByteSeq::from_hex("0388dace60b6a392f328c2b971b2fe78"); let msg_u32 = PublicSeq::<u32>::from_native_slice(&[0x0388dace, 0x60b6a392, 0xf328c2b9, 0x71b2fe78]); for i in 0..msg.num_chunks(4) { let (l, chunk) = msg.clone().get_chunk(4, i); assert_eq!(l, 4); assert_eq!((msg_u32[i] & 0xFF) as u8, chunk[3]); assert_eq!(((msg_u32[i] & 0xFF00) >> 8) as u8, chunk[2]); assert_eq!(((msg_u32[i] & 0xFF0000) >> 16) as u8, chunk[1]); assert_eq!(((msg_u32[i] & 0xFF000000) >> 24) as u8, chunk[0]); } } #[test] fn test_seq_poly() { let x = PublicSeq::<u128>::from_native_slice(&[5, 2, 7, 8, 9]); let y = PublicSeq::<u128>::from_native_slice(&[2, 1, 0, 2, 4]); let z = x.clone() + y.clone(); let z = z.clone() - x.clone(); assert_eq!(z[0..y.len()], y[0..y.len()]); assert_eq!(z.iter().skip(y.len()).fold(0, |acc, x| acc + x), 0); let _z = x.clone() * y.clone(); } #[test] fn test_sequences_comparison() { let a = PublicByteSeq::from_native_slice(&[1, 2, 3]); let b = PublicByteSeq::from_native_slice(&[1, 2, 3]); assert_eq!(a, b); } #[test] fn test_public_not() { let seq = PublicByteSeq::from_hex("c59380b20ba8fcd203e447fd1c5c7b87"); let not_output = !seq; // output of NOT to be checked for correctness let expected = PublicByteSeq::from_hex("3a6c7f4df457032dfc1bb802e3a38478"); assert_eq!(expected, not_output); } #[test] fn test_public_or() { let seq1 = PublicByteSeq::from_hex("c59380b20ba8fcd203e447fd1c5c7b87"); let seq2 = PublicByteSeq::from_hex("3a6c7f4df457032dfc1bb802e3a38478"); let or_output = seq1 | seq2; // output of OR to be checked for correctness let expected = PublicByteSeq::from_hex("ffffffffffffffffffffffffffffffff"); assert_eq!(expected, or_output); } #[test] fn test_public_xor() { let seq1 = PublicByteSeq::from_hex("3544de28f9d7d48ee7b318f6c541ff35"); let seq2 = PublicByteSeq::from_hex("a4b13aa347b72f6c22870170fcb0cda3"); let xor_output = seq1 ^ seq2; // output of XOR to be checked for correctness let expected = PublicByteSeq::from_hex("91f5e48bbe60fbe2c534198639f13296"); assert_eq!(expected, xor_output); } #[test] fn test_public_and() { let seq1 = PublicByteSeq::from_hex("c59380b20ba8fcd203e447fd1c5c7b87"); let seq2 = PublicByteSeq::from_hex("3a6c7f4df457032dfc1bb802e3a38478"); let and_output = seq1 & seq2; // output of AND to be checked for correctness let expected = PublicByteSeq::from_hex("00000000000000000000000000000000"); assert_eq!(expected, and_output); }
use juniper; use super::root::Context; use crate::schema::users; /// User #[derive(Default, Debug, Queryable, Insertable)] #[table_name = "users"] pub struct User { pub id: String, pub name: String, pub email: String, } #[derive(GraphQLInputObject)] #[graphql(description = "User Input")] pub struct UserInput { pub name: String, pub email: String, } #[juniper::object(Context = Context)] impl User { fn id(&self) -> &str { &self.id } fn name(&self) -> &str { &self.name } fn email(&self) -> &str { &self.email } }
#[macro_use] extern crate lazy_static; extern crate rustc_serialize; mod config; mod timeseries; mod graphiteapi; mod nagios; fn main() { let body = graphiteapi::http_fetch(); let mrl = timeseries::MetricResult::parse(body); if mrl.len() == 0 { println!("no such metric."); nagios::exit(nagios::EXIT_UNKNOWN); } for mr in &mrl { check_metric_result(&mr); } } fn check_metric_result(mr: &timeseries::MetricResult) { let flag_ignore_last_none = config::ARGS.flag_ignore_last_none; let start: usize = 0; let mut end: usize = mr.datapoints.len() - 1; // Calc end position { let stop_pos = end - flag_ignore_last_none as usize; let mut pos = end; while pos > stop_pos { if mr.datapoints[pos].value != None { break } pos = pos - 1; } end = pos; } // Check let mut is_warning: bool = true; let mut is_critical: bool = true; for i in start..end { let dp = &mr.datapoints[i]; match dp.value { None => { if ! config::ARGS.flag_ignore_none { println!("the data point {} is null.", dp.timestamp); nagios::exit(nagios::EXIT_CRITICAL) } }, Some(i) => { if i < config::ARGS.flag_warning { is_warning = false; } if i < config::ARGS.flag_critical { is_critical = false; } }, } } // Result if is_critical { println!("The last value is {}.", &mr.datapoints[end - 1].value_string()); nagios::exit(nagios::EXIT_CRITICAL); } else if is_warning { println!("The last value is {}.", &mr.datapoints[end - 1].value_string()); nagios::exit(nagios::EXIT_WARNING); } else { println!("OK"); nagios::exit(nagios::EXIT_OK); } }
use super::super::file; use std::path::PathBuf; use std::process::Command; const EXE_VARIABLE: &str = "{{EXE_PATH}}"; const LOG_VARIABLE: &str = "{{LOG_FILE_PATH}}"; const ERROR_LOG_VARIABLE: &str = "{{ERROR_LOG_FILE_PATH}}"; const PLIST_FILENAME: &str = "launch-port-snippet"; const PLIST_FILEPATH: &str = "~/Library/LaunchAgents/launch-port-snippet.plist"; const PLIST_TEMPLATE: &str = r#" <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>launch-port-snippet</string> <key>ProgramArguments</key> <array> <string>{{EXE_PATH}}</string> <string>AUTO_LAUNCH</string> </array> <key>RunAtLoad</key> <true/> <key>StandardOutPath</key> <string>{{LOG_FILE_PATH}}</string> <key>StandardErrorPath</key> <string>{{ERROR_LOG_FILE_PATH}}</string> </dict> </plist> "#; struct LogPaths { standard: PathBuf, error: PathBuf, } // ログファイルのパスを取得する fn get_log_path(exe_path: &PathBuf) -> LogPaths { let mut log_dir = exe_path.clone(); log_dir.pop(); log_dir.push(".log"); let mut log_path = log_dir.clone(); log_path.push("standard.log"); // > ./(exe)/.log/standard.log let mut error_log_path = log_dir.clone(); error_log_path.push("error.log"); // > ./(exe)/.log/error.log return LogPaths { standard: log_path, error: error_log_path, }; } // plistに変数を注入する fn inject_variables(mut plist: String, exe_path: PathBuf) -> String { let log_paths = get_log_path(&exe_path); let exe_path = std::fs::canonicalize(exe_path).expect("cannot get current_exe"); let exe_path_string = exe_path .into_os_string() .into_string() .expect("cannot get current_exe"); plist = plist.replace(EXE_VARIABLE, &exe_path_string); plist = plist.replace( LOG_VARIABLE, &log_paths .standard .to_str() .expect("something went wrong: cannot convert PathBuf → str"), ); plist = plist.replace( ERROR_LOG_VARIABLE, &log_paths .error .to_str() .expect("something went wrong: cannot convert PathBuf → str"), ); return plist; } // launchdを操作する fn operate_launchd(mode: &str, arg: &str) { let launchctl = Command::new("launchctl") .arg(mode) .arg(arg) .output() .expect("cannot run launchctl"); let result_message = launchctl.stdout; println!("{}\n...\n", std::str::from_utf8(&result_message).unwrap()); } // daemonを登録 pub fn register(need_run: bool) { let home_dir = std::env::var("HOME").unwrap(); let exe_path = std::env::current_exe().expect("cannot get current_exe"); let mut plist = PLIST_TEMPLATE.to_string(); plist = inject_variables(plist, exe_path); let plist_filepath_string = PLIST_FILEPATH.replace("~", &home_dir); let plist_filepath = PathBuf::from(&plist_filepath_string); file::write_file(&plist_filepath, plist); println!("> launchctl load {}", &plist_filepath_string); if need_run { run(); } } // 完了メッセージ pub fn get_complete_messages() -> String { return format!( "{}\n{}\n\nA plist file is saved as \"{}\"!\n", "Daemon setup is now completed!", "When you logs in a new launchd, PortSnippet process will be started by launchd.", PLIST_FILEPATH ); } // PortSnippetをlaunchd経由で起動する pub fn run() { let home_dir = std::env::var("HOME").unwrap(); let plist_filepath_string = PLIST_FILEPATH.replace("~", &home_dir); operate_launchd("unload", plist_filepath_string.as_str()); operate_launchd("load", plist_filepath_string.as_str()); } // PortSnippetを停止する pub fn stop() { operate_launchd("stop", PLIST_FILENAME); }
use crate::{ num::{DurationExt, Natural, NaturalRatio, Real}, source::Source, }; use std::time::Duration; #[derive(Debug, Clone)] pub struct LinearFadeOut<S> where S: Source, { inner: S, channels: u16, channel: u16, step: Real, curr_vol: Real, final_vol: Real, } impl<S> Iterator for LinearFadeOut<S> where S: Source, { type Item = Real; fn next(&mut self) -> Option<Self::Item> { let value = self.inner.next()? * self.curr_vol; self.channel = self.channel.saturating_sub(1); if self.channel == 0 { self.channel = self.channels(); if self.curr_vol > self.final_vol { self.curr_vol = (self.curr_vol - self.step).max(0.0); } } Some(value) } } impl<S> Source for LinearFadeOut<S> where S: Source, { fn len(&self) -> Option<usize> { self.inner.len() } fn duration(&self) -> Option<Duration> { self.inner.duration() } fn channels(&self) -> u16 { self.channels } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } } pub struct LinearFadeOutBuilder { iterations: usize, final_vol: Real, } impl Default for LinearFadeOutBuilder { fn default() -> Self { Self { iterations: 0, final_vol: 0.0 } } } impl LinearFadeOutBuilder { pub fn iterations(&mut self, iterations: usize) -> &mut Self { self.iterations = iterations; self } pub fn final_vol(&mut self, final_vol: Real) -> &mut Self { self.final_vol = final_vol; self } pub fn get_iterations(&self) -> usize { self.iterations } pub fn get_final_vol(&self) -> Real { self.final_vol } pub fn finish<S>(&self, source: S) -> LinearFadeOut<S> where S: Source, { let len = source.len().unwrap_or(self.iterations); let channels = source.channels(); LinearFadeOut { channels, channel: channels, inner: source, curr_vol: 1.0, final_vol: self.final_vol, step: (1.0 - self.final_vol) / len as Real, } } } #[derive(Debug, Clone)] pub struct Take<S> where S: Source, { inner: S, channels: u16, channel: u16, rem_samples: usize, } impl<S> Take<S> where S: Source, { pub(crate) fn new(inner: S, samples: usize) -> Self { let channels = inner.channels(); Self { channels, channel: channels, inner, rem_samples: samples } } pub fn max_duration(&self) -> Duration { let sample_time = NaturalRatio::new( Duration::from_secs(1).as_nanos(), self.sample_rate() as Natural, ); let len = NaturalRatio::from(self.rem_samples as Natural); let nanos = (len * sample_time).round().to_integer(); Duration::from_raw_nanos(nanos) } pub fn max_len(&self) -> usize { self.rem_samples } } impl<S> Iterator for Take<S> where S: Source, { type Item = Real; fn next(&mut self) -> Option<Self::Item> { if self.rem_samples == 0 { return None; } self.channel = self.channel.saturating_sub(1); if self.channel == 0 { self.channel = self.channels(); self.rem_samples -= 1; if self.rem_samples == 0 { return None; } } self.inner.next() } } impl<S> Source for Take<S> where S: Source, { fn len(&self) -> Option<usize> { let ret = match self.inner.len() { Some(len) => len.min(self.max_len()), None => self.max_len(), }; Some(ret) } fn duration(&self) -> Option<Duration> { let ret = match self.inner.duration() { Some(duration) => duration.min(self.max_duration()), None => self.max_duration(), }; Some(ret) } fn channels(&self) -> u16 { self.channels } fn sample_rate(&self) -> u32 { self.inner.sample_rate() } }
//! `amethyst` rendering ecs resources use std::sync::Arc; use crossbeam::sync::MsQueue; use futures::{Async, Future, Poll}; use futures::sync::oneshot::{channel, Receiver, Sender}; use gfx::traits::Pod; use renderer::{Error, Material, MaterialBuilder, Texture, TextureBuilder}; use renderer::Rgba; use renderer::mesh::{Mesh, MeshBuilder, VertexDataSet}; use smallvec::SmallVec; use winit::Window; pub(crate) trait Exec: Send { fn exec(self: Box<Self>, factory: &mut ::renderer::Factory); } /// A factory future. pub struct FactoryFuture<A, E>(Receiver<Result<A, E>>); impl<A, E> Future for FactoryFuture<A, E> { type Item = A; type Error = E; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.0.poll().expect("Sender destroyed") { Async::Ready(x) => x.map(Async::Ready), Async::NotReady => Ok(Async::NotReady), } } } /// The factory abstraction, which allows to access the real /// factory and returns futures. #[derive(Clone)] pub struct Factory { pub(crate) jobs: Arc<MsQueue<Box<Exec>>>, } impl Factory { /// Creates a new factory resource. pub fn new() -> Self { Factory { jobs: Arc::new(MsQueue::new()), } } /// Creates a mesh asynchronously. pub fn create_mesh<T>(&self, mb: MeshBuilder<T>) -> MeshFuture where T: VertexDataSet + Send + 'static, { self.execute(move |f| mb.build(f)) } /// Creates a texture asynchronously. pub fn create_texture<D, T>(&self, tb: TextureBuilder<D, T>) -> TextureFuture where D: AsRef<[T]> + Send + 'static, T: Pod + Send + Copy + 'static, { self.execute(move |f| tb.build(f)) } /// Creates a mesh asynchronously. pub fn create_material<DA, TA, DE, TE, DN, TN, DM, TM, DR, TR, DO, TO, DC, TC>( &self, mb: MaterialBuilder<DA, TA, DE, TE, DN, TN, DM, TM, DR, TR, DO, TO, DC, TC>, ) -> MaterialFuture where DA: AsRef<[TA]> + Send + 'static, TA: Pod + Send + Copy + 'static, DE: AsRef<[TE]> + Send + 'static, TE: Pod + Send + Copy + 'static, DN: AsRef<[TN]> + Send + 'static, TN: Pod + Send + Copy + 'static, DM: AsRef<[TM]> + Send + 'static, TM: Pod + Send + Copy + 'static, DR: AsRef<[TR]> + Send + 'static, TR: Pod + Send + Copy + 'static, DO: AsRef<[TO]> + Send + 'static, TO: Pod + Send + Copy + 'static, DC: AsRef<[TC]> + Send + 'static, TC: Pod + Send + Copy + 'static, { self.execute(|f| mb.build(f)) } /// Execute a closure which takes in the real factory. pub fn execute<F, T, E>(&self, fun: F) -> FactoryFuture<T, E> where F: FnOnce(&mut ::renderer::Factory) -> Result<T, E> + Send + 'static, T: Send + 'static, E: Send + 'static, { let (send, recv) = channel(); struct Job<F, T, E>(F, Sender<Result<T, E>>); impl<F, T, E> Exec for Job<F, T, E> where F: FnOnce(&mut ::renderer::Factory) -> Result<T, E> + Send + 'static, T: Send + 'static, E: Send + 'static, { fn exec(self: Box<Self>, factory: &mut ::renderer::Factory) { let job = *self; let Job(closure, sender) = job; let r = closure(factory); let _ = sender.send(r); } } self.jobs.push(Box::new(Job(fun, send))); FactoryFuture(recv) } } /// A texture which may not have been created yet. pub type TextureFuture = FactoryFuture<Texture, Error>; /// A material which may not have been created yet. pub type MaterialFuture = FactoryFuture<Material, Error>; /// A mesh which may not have been created yet. pub type MeshFuture = FactoryFuture<Mesh, Error>; /// The ambient color of a scene #[derive(Clone, Debug, Default)] pub struct AmbientColor(pub Rgba); impl AsRef<Rgba> for AmbientColor { fn as_ref(&self) -> &Rgba { &self.0 } } /// This specs resource with id 0 permits sending commands to the /// renderer internal window. pub struct WindowMessages { // It's unlikely we'll get more than one command per frame // 1 Box also makes this the same size as a Vec, so this costs // no more space in the structure than a Vec would. // // NOTE TO FUTURE AUTHORS: This could be an FnOnce but that's not possible // right now as of 2017-10-02 because FnOnce isn't object safe. It might // be possible as soon as FnBox stabilizes. For now I'll use FnMut instead. pub(crate) queue: SmallVec<[Box<FnMut(&Window) + Send + Sync + 'static>; 2]>, } impl WindowMessages { /// Create a new `WindowMessages` pub fn new() -> Self { Self { queue: SmallVec::new(), } } /// Execute this closure on the `winit::Window` next frame. pub fn send_command<F>(&mut self, command: F) where F: FnMut(&Window) + Send + Sync + 'static, { self.queue.push(Box::new(command)); } }
fn main() { basic(); number(); boolean(); char_and_string(); tuple(); instantiate(); } fn basic() { let mut a_number = 10; let a_boolean = true; println!("the number is {}", a_number); a_number = 15; println!("and now the number is {}", a_number); let a_number = a_number * 2; println!("The number is {}", a_number); println!("the boolean is {}", a_boolean); let number: u32 = "42".parse().expect("Not a number!"); println!("u32 number {}", number); } fn number() { // Number // Addition println!("1 + 2 = {}", 1u32 + 2); // Substraction println!("1 - 2 = {}", 1i32 - 2); // Interger Division println!("9 / 2 = {}", 9u32 / 2); // Float Division println!("9 / 2 = {}", 9.0 / 2.0); // Multiplication println!("3 * 6 = {}", 3 * 6); } fn boolean() { // Boolean let is_bigger = 1 > 4; println!("{}", is_bigger); } fn char_and_string() { // Character and String // char let c = 'z'; let z = 'Z'; let heart_eyes_cat = '😻'; println!("{} {} {}", c, z, heart_eyes_cat); // String let mut hello = String::from("Hello, "); hello.push('w'); hello.push_str("orld!"); println!("{}", hello); } fn tuple() { // Tuple let tuple = ("hello", 5, 'c'); assert_eq!(tuple.0, "hello"); assert_eq!(tuple.1, 5); assert_eq!(tuple.2, 'c'); } // Struct struct Person { name: String, age: u8, likes_oranges: bool } struct Point2D(u32, u32); struct Unit; fn instantiate() { let person = Person { name: String::from("Adam"), likes_oranges: true, age: 25 }; let origin = Point2D(0, 0); let unit = Unit; } // Enum enum WebEvent { PageLoad, PageUnload, KeyPress(KeyPress), Paste(String), Click(Click), } struct Click { x: i64, y: i64 } struct KeyPress(char);
pub mod contract; pub mod interface; pub mod utils; use super::primitive; use super::network; use super::mempool; use super::blockchain; use super::db;
use super::super::objects; pub const TRUE: objects::Boolean = objects::Boolean { value: true }; pub const FALSE: objects::Boolean = objects::Boolean { value: false }; pub const NULL: objects::Null = objects::Null {};
#[doc = "Reader of register RCC_APB3RSTSETR"] pub type R = crate::R<u32, super::RCC_APB3RSTSETR>; #[doc = "Writer for register RCC_APB3RSTSETR"] pub type W = crate::W<u32, super::RCC_APB3RSTSETR>; #[doc = "Register RCC_APB3RSTSETR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_APB3RSTSETR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "LPTIM2RST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LPTIM2RST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<LPTIM2RST_A> for bool { #[inline(always)] fn from(variant: LPTIM2RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LPTIM2RST`"] pub type LPTIM2RST_R = crate::R<bool, LPTIM2RST_A>; impl LPTIM2RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM2RST_A { match self.bits { false => LPTIM2RST_A::B_0X0, true => LPTIM2RST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LPTIM2RST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LPTIM2RST_A::B_0X1 } } #[doc = "Write proxy for field `LPTIM2RST`"] pub struct LPTIM2RST_W<'a> { w: &'a mut W, } impl<'a> LPTIM2RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LPTIM2RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LPTIM2RST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LPTIM2RST_A::B_0X1) } #[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 = "LPTIM3RST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LPTIM3RST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<LPTIM3RST_A> for bool { #[inline(always)] fn from(variant: LPTIM3RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LPTIM3RST`"] pub type LPTIM3RST_R = crate::R<bool, LPTIM3RST_A>; impl LPTIM3RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM3RST_A { match self.bits { false => LPTIM3RST_A::B_0X0, true => LPTIM3RST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LPTIM3RST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LPTIM3RST_A::B_0X1 } } #[doc = "Write proxy for field `LPTIM3RST`"] pub struct LPTIM3RST_W<'a> { w: &'a mut W, } impl<'a> LPTIM3RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LPTIM3RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LPTIM3RST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LPTIM3RST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "LPTIM4RST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LPTIM4RST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<LPTIM4RST_A> for bool { #[inline(always)] fn from(variant: LPTIM4RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LPTIM4RST`"] pub type LPTIM4RST_R = crate::R<bool, LPTIM4RST_A>; impl LPTIM4RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM4RST_A { match self.bits { false => LPTIM4RST_A::B_0X0, true => LPTIM4RST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LPTIM4RST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LPTIM4RST_A::B_0X1 } } #[doc = "Write proxy for field `LPTIM4RST`"] pub struct LPTIM4RST_W<'a> { w: &'a mut W, } impl<'a> LPTIM4RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LPTIM4RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LPTIM4RST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LPTIM4RST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "LPTIM5RST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LPTIM5RST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<LPTIM5RST_A> for bool { #[inline(always)] fn from(variant: LPTIM5RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LPTIM5RST`"] pub type LPTIM5RST_R = crate::R<bool, LPTIM5RST_A>; impl LPTIM5RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM5RST_A { match self.bits { false => LPTIM5RST_A::B_0X0, true => LPTIM5RST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LPTIM5RST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LPTIM5RST_A::B_0X1 } } #[doc = "Write proxy for field `LPTIM5RST`"] pub struct LPTIM5RST_W<'a> { w: &'a mut W, } impl<'a> LPTIM5RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LPTIM5RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LPTIM5RST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LPTIM5RST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "SAI4RST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SAI4RST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<SAI4RST_A> for bool { #[inline(always)] fn from(variant: SAI4RST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SAI4RST`"] pub type SAI4RST_R = crate::R<bool, SAI4RST_A>; impl SAI4RST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SAI4RST_A { match self.bits { false => SAI4RST_A::B_0X0, true => SAI4RST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == SAI4RST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == SAI4RST_A::B_0X1 } } #[doc = "Write proxy for field `SAI4RST`"] pub struct SAI4RST_W<'a> { w: &'a mut W, } impl<'a> SAI4RST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SAI4RST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(SAI4RST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(SAI4RST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "SYSCFGRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYSCFGRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<SYSCFGRST_A> for bool { #[inline(always)] fn from(variant: SYSCFGRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SYSCFGRST`"] pub type SYSCFGRST_R = crate::R<bool, SYSCFGRST_A>; impl SYSCFGRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYSCFGRST_A { match self.bits { false => SYSCFGRST_A::B_0X0, true => SYSCFGRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == SYSCFGRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == SYSCFGRST_A::B_0X1 } } #[doc = "Write proxy for field `SYSCFGRST`"] pub struct SYSCFGRST_W<'a> { w: &'a mut W, } impl<'a> SYSCFGRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYSCFGRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(SYSCFGRST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(SYSCFGRST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "VREFRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum VREFRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<VREFRST_A> for bool { #[inline(always)] fn from(variant: VREFRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `VREFRST`"] pub type VREFRST_R = crate::R<bool, VREFRST_A>; impl VREFRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> VREFRST_A { match self.bits { false => VREFRST_A::B_0X0, true => VREFRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == VREFRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == VREFRST_A::B_0X1 } } #[doc = "Write proxy for field `VREFRST`"] pub struct VREFRST_W<'a> { w: &'a mut W, } impl<'a> VREFRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: VREFRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(VREFRST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(VREFRST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "TMPSENSRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TMPSENSRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<TMPSENSRST_A> for bool { #[inline(always)] fn from(variant: TMPSENSRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TMPSENSRST`"] pub type TMPSENSRST_R = crate::R<bool, TMPSENSRST_A>; impl TMPSENSRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TMPSENSRST_A { match self.bits { false => TMPSENSRST_A::B_0X0, true => TMPSENSRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TMPSENSRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TMPSENSRST_A::B_0X1 } } #[doc = "Write proxy for field `TMPSENSRST`"] pub struct TMPSENSRST_W<'a> { w: &'a mut W, } impl<'a> TMPSENSRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TMPSENSRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TMPSENSRST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TMPSENSRST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "PMBCTRLRST\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PMBCTRLRST_A { #[doc = "0: Writing has no effect, reading means\r\n that the block reset is released"] B_0X0 = 0, #[doc = "1: Writing asserts the block reset,\r\n reading means that the block reset is\r\n asserted"] B_0X1 = 1, } impl From<PMBCTRLRST_A> for bool { #[inline(always)] fn from(variant: PMBCTRLRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PMBCTRLRST`"] pub type PMBCTRLRST_R = crate::R<bool, PMBCTRLRST_A>; impl PMBCTRLRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PMBCTRLRST_A { match self.bits { false => PMBCTRLRST_A::B_0X0, true => PMBCTRLRST_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == PMBCTRLRST_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == PMBCTRLRST_A::B_0X1 } } #[doc = "Write proxy for field `PMBCTRLRST`"] pub struct PMBCTRLRST_W<'a> { w: &'a mut W, } impl<'a> PMBCTRLRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PMBCTRLRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the block reset is released"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(PMBCTRLRST_A::B_0X0) } #[doc = "Writing asserts the block reset, reading means that the block reset is asserted"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(PMBCTRLRST_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } impl R { #[doc = "Bit 0 - LPTIM2RST"] #[inline(always)] pub fn lptim2rst(&self) -> LPTIM2RST_R { LPTIM2RST_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - LPTIM3RST"] #[inline(always)] pub fn lptim3rst(&self) -> LPTIM3RST_R { LPTIM3RST_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - LPTIM4RST"] #[inline(always)] pub fn lptim4rst(&self) -> LPTIM4RST_R { LPTIM4RST_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - LPTIM5RST"] #[inline(always)] pub fn lptim5rst(&self) -> LPTIM5RST_R { LPTIM5RST_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 8 - SAI4RST"] #[inline(always)] pub fn sai4rst(&self) -> SAI4RST_R { SAI4RST_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 11 - SYSCFGRST"] #[inline(always)] pub fn syscfgrst(&self) -> SYSCFGRST_R { SYSCFGRST_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 13 - VREFRST"] #[inline(always)] pub fn vrefrst(&self) -> VREFRST_R { VREFRST_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 16 - TMPSENSRST"] #[inline(always)] pub fn tmpsensrst(&self) -> TMPSENSRST_R { TMPSENSRST_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - PMBCTRLRST"] #[inline(always)] pub fn pmbctrlrst(&self) -> PMBCTRLRST_R { PMBCTRLRST_R::new(((self.bits >> 17) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - LPTIM2RST"] #[inline(always)] pub fn lptim2rst(&mut self) -> LPTIM2RST_W { LPTIM2RST_W { w: self } } #[doc = "Bit 1 - LPTIM3RST"] #[inline(always)] pub fn lptim3rst(&mut self) -> LPTIM3RST_W { LPTIM3RST_W { w: self } } #[doc = "Bit 2 - LPTIM4RST"] #[inline(always)] pub fn lptim4rst(&mut self) -> LPTIM4RST_W { LPTIM4RST_W { w: self } } #[doc = "Bit 3 - LPTIM5RST"] #[inline(always)] pub fn lptim5rst(&mut self) -> LPTIM5RST_W { LPTIM5RST_W { w: self } } #[doc = "Bit 8 - SAI4RST"] #[inline(always)] pub fn sai4rst(&mut self) -> SAI4RST_W { SAI4RST_W { w: self } } #[doc = "Bit 11 - SYSCFGRST"] #[inline(always)] pub fn syscfgrst(&mut self) -> SYSCFGRST_W { SYSCFGRST_W { w: self } } #[doc = "Bit 13 - VREFRST"] #[inline(always)] pub fn vrefrst(&mut self) -> VREFRST_W { VREFRST_W { w: self } } #[doc = "Bit 16 - TMPSENSRST"] #[inline(always)] pub fn tmpsensrst(&mut self) -> TMPSENSRST_W { TMPSENSRST_W { w: self } } #[doc = "Bit 17 - PMBCTRLRST"] #[inline(always)] pub fn pmbctrlrst(&mut self) -> PMBCTRLRST_W { PMBCTRLRST_W { w: self } } }
use std::error::Error as StdError; use std::fmt::{self, Display}; use serde::de::value::{MapDeserializer, SeqDeserializer}; use serde::de::{ Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as DeError, IntoDeserializer, Unexpected, VariantAccess, Visitor, }; use serde::forward_to_deserialize_any; use super::{Array, Entry, Table, Value}; pub struct ValueDeserializer<'de>(&'de Value); impl<'de> ValueDeserializer<'de> { pub fn new(value: &'de Value) -> Self { Self(value) } pub fn deserialize_entry<V>(self, entry: &'de Entry, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { visitor.visit_str(&entry.0) } pub fn deserialize_array<V>(self, array: &'de Array, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { let mut deserializer = SeqDeserializer::new(array.into_iter()); let seq = visitor.visit_seq(&mut deserializer)?; deserializer.end()?; Ok(seq) } pub fn deserialize_table<V>(self, table: &'de Table, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { let iter = table .into_iter() .map(|(key, value)| (key.to_owned(), value)); let mut deserializer = MapDeserializer::new(iter); let map = visitor.visit_map(&mut deserializer)?; deserializer.end()?; Ok(map) } } impl<'de> Deserializer<'de> for ValueDeserializer<'de> { type Error = Error; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Entry(entry) => self.deserialize_entry(entry, visitor), Value::Array(array) => self.deserialize_array(array, visitor), Value::Table(table) => self.deserialize_table(table, visitor), } } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as bool")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as bool")), Value::Entry(entry) => match entry.0.parse::<bool>() { Ok(value) => visitor.visit_bool(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as i8")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as i8")), Value::Entry(entry) => match entry.0.parse::<i8>() { Ok(value) => visitor.visit_i8(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as i16")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as i16")), Value::Entry(entry) => match entry.0.parse::<i16>() { Ok(value) => visitor.visit_i16(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as i32")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as i32")), Value::Entry(entry) => match entry.0.parse::<i32>() { Ok(value) => visitor.visit_i32(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as i64")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as i64")), Value::Entry(entry) => match entry.0.parse::<i64>() { Ok(value) => visitor.visit_i64(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as i128")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as i128")), Value::Entry(entry) => match entry.0.parse::<i128>() { Ok(value) => visitor.visit_i128(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as u8")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as u8")), Value::Entry(entry) => match entry.0.parse::<u8>() { Ok(value) => visitor.visit_u8(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as u16")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as u16")), Value::Entry(entry) => match entry.0.parse::<u16>() { Ok(value) => visitor.visit_u16(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as u32")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as u32")), Value::Entry(entry) => match entry.0.parse::<u32>() { Ok(value) => visitor.visit_u32(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as u64")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as u64")), Value::Entry(entry) => match entry.0.parse::<u64>() { Ok(value) => visitor.visit_u64(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as u128")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as u128")), Value::Entry(entry) => match entry.0.parse::<u128>() { Ok(value) => visitor.visit_u128(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as f32")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as f32")), Value::Entry(entry) => match entry.0.parse::<f32>() { Ok(value) => visitor.visit_f32(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as f64")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as f64")), Value::Entry(entry) => match entry.0.parse::<f64>() { Ok(value) => visitor.visit_f64(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as char")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as char")), Value::Entry(entry) => match entry.0.parse::<char>() { Ok(value) => visitor.visit_char(value), Err(err) => Err(Error::custom(format!("{}", err))), }, } } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as str")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as str")), Value::Entry(entry) => visitor.visit_str(&entry.0), } } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match self.0 { Value::Array(_) => Err(Error::custom("cannot deserialize array variant as string")), Value::Table(_) => Err(Error::custom("cannot deserialize table variant as string")), Value::Entry(entry) => visitor.visit_str(&entry.0), } } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { let (variant, value) = match self.0 { Value::Entry(entry) => (&entry.0, None), Value::Table(table) => { let mut iter = table.into_iter(); let (variant, value) = match iter.next() { Some(v) => v, None => { return Err(Error::invalid_value( Unexpected::Map, &"map with a single key", )); } }; if iter.next().is_some() { return Err(Error::invalid_value( Unexpected::Map, &"map with a single key", )); } (variant, Some(value)) } other => { return Err(Error::invalid_type(other.unexpected(), &"string or map")); } }; visitor.visit_enum(EnumDeserializer { variant, value }) } forward_to_deserialize_any! { bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct identifier ignored_any } } impl Value { fn unexpected(&self) -> Unexpected { match *self { Value::Entry(ref s) => Unexpected::Str(&s.0), Value::Array(_) => Unexpected::Seq, Value::Table(_) => Unexpected::Map, } } } struct EnumDeserializer<'de> { variant: &'de str, value: Option<&'de Value>, } impl<'de> EnumAccess<'de> for EnumDeserializer<'de> { type Error = Error; type Variant = VariantDeserializer<'de>; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error> where V: DeserializeSeed<'de>, { let variant = self.variant.into_deserializer(); let visitor = VariantDeserializer { value: self.value }; seed.deserialize(variant).map(|v| (v, visitor)) } } struct VariantDeserializer<'de> { value: Option<&'de Value>, } impl<'de> VariantAccess<'de> for VariantDeserializer<'de> { type Error = Error; fn unit_variant(self) -> Result<(), Error> { match self.value { Some(value) => Deserialize::deserialize(ValueDeserializer::new(value)), None => Ok(()), } } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> where T: DeserializeSeed<'de>, { match self.value { Some(value) => seed.deserialize(ValueDeserializer::new(value)), None => Err(Error::invalid_type( Unexpected::UnitVariant, &"newtype variant", )), } } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { match self.value { Some(Value::Array(array)) => { Deserializer::deserialize_any(SeqDeserializer::new(array.into_iter()), visitor) } Some(other) => Err(Error::invalid_type(other.unexpected(), &"tuple variant")), None => Err(Error::invalid_type( Unexpected::UnitVariant, &"tuple variant", )), } } fn struct_variant<V>( self, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value, Error> where V: Visitor<'de>, { match self.value { Some(Value::Table(table)) => { let iter = table .into_iter() .map(|(key, value)| (key.to_owned(), value)); Deserializer::deserialize_any(MapDeserializer::new(iter), visitor) } Some(other) => Err(Error::invalid_type(other.unexpected(), &"struct variant")), _ => Err(Error::invalid_type( Unexpected::UnitVariant, &"struct variant", )), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error(String); impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl StdError for Error {} impl DeError for Error { fn custom<T: Display>(msg: T) -> Self { Self(msg.to_string()) } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{commands::*, sg_client_proxy::SGClientProxy}; /// Major command for block explorer operations. pub struct BlockCommand {} impl Command for BlockCommand { fn get_aliases(&self) -> Vec<&'static str> { vec!["block", "b"] } fn get_description(&self) -> &'static str { "Block explorer operations" } fn execute(&self, client: &mut SGClientProxy, params: &[&str]) { let commands: Vec<Box<dyn Command>> = vec![ Box::new(BlockLatestHeight {}), Box::new(BlockList {}), Box::new(BlockDetail {}), Box::new(BlockDifficulty {}), ]; subcommand_execute(&params[0], commands, client, &params[1..]); } } /// Sub command to query latest Height pub struct BlockLatestHeight {} impl Command for BlockLatestHeight { fn get_aliases(&self) -> Vec<&'static str> { vec!["height", "h"] } fn get_description(&self) -> &'static str { "Query latest height of block chain." } fn execute(&self, client: &mut SGClientProxy, _params: &[&str]) { println!(">> Query latest height"); match client.latest_height() { Ok(height) => println!("latest height is : {:?}", height), Err(e) => report_error("Error query latest height", e), } } } /// Sub command to query block list pub struct BlockList {} impl Command for BlockList { fn get_aliases(&self) -> Vec<&'static str> { vec!["blocklist", "bl"] } fn get_description(&self) -> &'static str { "[block_id]" } fn execute(&self, client: &mut SGClientProxy, params: &[&str]) { println!(">> Query block summary list"); let block_id = if params.len() > 1 { Some(params[1]) } else { None }; match client.get_block_summary_list_request(block_id) { Ok(list) => { for (index, block_summary) in list.blocks.iter().enumerate() { println!( "#{} height {} block {} id {:?} parent {} accumulator {:?} \ state {:?} miner {:?} nonce {} target {} algo {}", index, block_summary.height, hex::encode(block_summary.block_id.to_vec()), block_summary.block_id, hex::encode(block_summary.parent_id.to_vec()), block_summary.accumulator_root_hash, block_summary.state_root_hash, block_summary.miner, block_summary.nonce, block_summary.target, block_summary.algo, ); } } Err(e) => report_error("Error query block list", e), } } } pub struct BlockDetail {} impl Command for BlockDetail { fn get_aliases(&self) -> Vec<&'static str> { vec!["blockdetail", "bd"] } fn get_description(&self) -> &'static str { "<block_id>" } fn execute(&self, client: &mut SGClientProxy, params: &[&str]) { println!(">> Query block info"); match client.block_detail(params) { Ok(block_detail) => println!("block detail : {:?}", block_detail), Err(e) => report_error("Error query block detail", e), } } } pub struct BlockDifficulty {} impl Command for BlockDifficulty { fn get_aliases(&self) -> Vec<&'static str> { vec!["blockdifficulty", "d"] } fn get_description(&self) -> &'static str { "Block Difficulty" } fn execute(&self, client: &mut SGClientProxy, params: &[&str]) { println!(">> Query block difficulty"); match client.block_difficulty(params) { Ok(block_difficulty) => println!("block difficulty : {:?}", block_difficulty), Err(e) => report_error("Error query block difficulty", e), } } }
use iron::mime; use iron::prelude::*; use iron::status; use iron::AfterMiddleware; use std::fs; use std::path::Path; const PAGE_404: &str = "<h2>404</h2><p>Content could not found</p>"; const PAGE_50X: &str = "<h2>50x</h2><p>SERVICE is temporarily unavailable due an unexpected error</p>"; /// Custom Error pages middleware for Iron pub struct ErrorPage { /// HTML file content for 404 errors. pub page404: String, /// HTML file content for 50x errors. pub page50x: String, } impl ErrorPage { /// Create a new instance of `ErrorPage` middleware with a given html pages. pub fn new<P: AsRef<Path>>(page_404_path: P, page_50x_path: P) -> ErrorPage { let page404 = if Path::new(&page_404_path.as_ref()).exists() { fs::read_to_string(page_404_path).unwrap() } else { String::from(PAGE_404) }; let page50x = if Path::new(&page_50x_path.as_ref()).exists() { fs::read_to_string(page_50x_path).unwrap() } else { String::from(PAGE_50X) }; ErrorPage { page404, page50x } } } impl AfterMiddleware for ErrorPage { fn after(&self, req: &mut Request, resp: Response) -> IronResult<Response> { let mut no_status_error = false; let content_type = "text/html" .parse::<mime::Mime>() .expect("Unable to create a default content type header"); let mut resp = match resp.status { Some(status::NotFound) => { Response::with((content_type, status::NotFound, self.page404.as_str())) } Some(status::InternalServerError) => Response::with(( content_type, status::InternalServerError, self.page50x.as_str(), )), Some(status::BadGateway) => { Response::with((content_type, status::BadGateway, self.page50x.as_str())) } Some(status::ServiceUnavailable) => Response::with(( content_type, status::ServiceUnavailable, self.page50x.as_str(), )), Some(status::GatewayTimeout) => { Response::with((content_type, status::GatewayTimeout, self.page50x.as_str())) } _ => { no_status_error = true; resp } }; // Empty response body only on HEAD requests and status error (404,50x) if req.method == iron::method::Head && !no_status_error { resp.set_mut(vec![]); } Ok(resp) } }
use crate::helpers::*; use proc_macro2::TokenStream; use quote::quote; use syn::parse_quote; use syn::{Data, DeriveInput}; pub fn bounds_impl(mut input: DeriveInput) -> TokenStream { let name = input.ident; let path = quote!(rtk::geometry); let mut generics_mut = input.generics.clone(); if let Err(err) = parse_impl_generics(&input.attrs, &mut input.generics, parse_quote!(#path::Bounds)) { return err.to_compile_error().into(); } if let Err(err) = parse_impl_generics(&input.attrs, &mut generics_mut, parse_quote!(#path::BoundsMut)) { return err.to_compile_error().into(); } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let (impl_generics_mut, ty_generics_mut, where_clause_mut) = generics_mut.split_for_impl(); let expanded = match &input.data { Data::Struct(data) => match find_field_in_struct(data, &name, "Rect", "bounds") { Ok(field) => Ok(quote! { impl #impl_generics #path::Bounds for #name #ty_generics #where_clause { #[inline] fn get_position(&self) -> #path::Position { #path::Bounds::get_position(&self.#field) } #[inline] fn get_size(&self) -> #path::Size { #path::Bounds::get_size(&self.#field) } #[inline] fn get_bounds(&self) -> #path::Rect { #path::Bounds::get_bounds(&self.#field) } } impl #impl_generics_mut #path::BoundsMut for #name #ty_generics_mut #where_clause_mut { #[inline] fn set_position(&mut self, position: #path::Position) { #path::BoundsMut::set_position(&mut self.#field, position) } #[inline] fn set_size(&mut self, size: #path::Size) { #path::BoundsMut::set_size(&mut self.#field, size) } #[inline] fn set_bounds(&mut self, bounds: #path::Rect) { #path::BoundsMut::set_bounds(&mut self.#field, bounds) } } }), Err(FieldFindError::NotFound(rerr, rname)) => { let pos_res = find_field_in_struct(data, &name, "Position", "position"); let size_res = find_field_in_struct(data, &name, "Size", "size"); match (pos_res, size_res) { (Ok(pos), Ok(size)) => Ok(quote! { impl #impl_generics #path::Bounds for #name #ty_generics #where_clause { #[inline] fn get_position(&self) -> #path::Position { self.#pos } #[inline] fn get_size(&self) -> #path::Size { self.#size } } impl #impl_generics_mut #path::BoundsMut for #name #ty_generics_mut #where_clause_mut { #[inline] fn set_position(&mut self, position: #path::Position) { self.#pos = position; } #[inline] fn set_size(&mut self, size: #path::Size) { self.#size = size; } } }), (Ok(_), Err(err)) | (Err(err), Ok(_)) => Err(err), (Err(_), Err(_)) => Err(FieldFindError::NotFound(rerr, rname)), } } other => other, }, Data::Enum(data) => match_patterns_for_enum(data, &name).map(|patterns| { quote! { impl #impl_generics #path::Bounds for #name #ty_generics #where_clause { #[inline] fn get_position(&self) -> #path::Position { match self { #(#patterns => #path::Bounds::get_position(a),)* } } #[inline] fn get_size(&self) -> #path::Size { match self { #(#patterns => #path::Bounds::get_size(a),)* } } #[inline] fn get_bounds(&self) -> #path::Rect { match self { #(#patterns => #path::Bounds::get_bounds(a),)* } } } impl #impl_generics_mut #path::BoundsMut for #name #ty_generics_mut #where_clause_mut { #[inline] fn set_position(&mut self, position: #path::Position) { match self { #(#patterns => #path::BoundsMut::set_position(a, position),)* } } #[inline] fn set_size(&mut self, size: #path::Size) { match self { #(#patterns => #path::BoundsMut::set_size(a, size),)* } } #[inline] fn set_bounds(&mut self, bounds: #path::Rect) { match self { #(#patterns => #path::BoundsMut::set_bounds(a, bounds),)* } } } } }), Data::Union(data) => Err(FieldFindError::Unsupported(data.union_token.span, "union")), }; expanded.unwrap_or_else(|err| err.to_error("Bounds").to_compile_error()) }
extern crate libpasta; use libpasta::rpassword::*; struct User { // ... password_hash: String, } fn auth_user(user: &User) { let password = prompt_password_stdout("Enter password:").unwrap(); if libpasta::verify_password(&user.password_hash, &password) { println!("The password is correct!"); // ~> Handle correct password } else { println!("Incorrect password."); // ~> Handle incorrect password } } fn main() { let user = User { password_hash: libpasta::hash_password("hunter2"), }; auth_user(&user); }
use crate::prelude::*; use azure_core::prelude::*; use azure_core::{Request as HttpRequest, Response as HttpResponse}; use chrono::{DateTime, Utc}; #[derive(Debug, Clone)] pub struct DeleteDocumentOptions<'a> { if_match_condition: Option<IfMatchCondition<'a>>, if_modified_since: Option<IfModifiedSince<'a>>, consistency_level: Option<ConsistencyLevel>, allow_tentative_writes: TentativeWritesAllowance, } impl<'a> DeleteDocumentOptions<'a> { pub fn new() -> DeleteDocumentOptions<'a> { Self { if_match_condition: None, if_modified_since: None, consistency_level: None, allow_tentative_writes: TentativeWritesAllowance::Deny, } } setters! { consistency_level: ConsistencyLevel => Some(consistency_level), if_match_condition: IfMatchCondition<'a> => Some(if_match_condition), allow_tentative_writes: TentativeWritesAllowance, if_modified_since: &'a DateTime<Utc> => Some(IfModifiedSince::new(if_modified_since)), } pub fn decorate_request( &self, request: &mut HttpRequest, serialized_partition_key: &str, ) -> crate::Result<()> { azure_core::headers::add_optional_header2(&self.if_match_condition, request)?; azure_core::headers::add_optional_header2(&self.if_modified_since, request)?; azure_core::headers::add_optional_header2(&self.consistency_level, request)?; azure_core::headers::add_mandatory_header2(&self.allow_tentative_writes, request)?; crate::cosmos_entity::add_as_partition_key_header_serialized2( serialized_partition_key, request, ); Ok(()) } } use crate::headers::from_headers::*; use azure_core::headers::session_token_from_headers; #[derive(Debug, Clone)] pub struct DeleteDocumentResponse { pub charge: f64, pub activity_id: uuid::Uuid, pub session_token: String, } impl DeleteDocumentResponse { pub async fn try_from(response: HttpResponse) -> crate::Result<Self> { let (_status_code, headers, _pinned_stream) = response.deconstruct(); let charge = request_charge_from_headers(&headers)?; let activity_id = activity_id_from_headers(&headers)?; let session_token = session_token_from_headers(&headers)?; Ok(Self { charge, activity_id, session_token, }) } }
//! This module declares the low-level implentation of an instruction. //! //! Unlike `builder::Instr` which is supposed to accomodata all architectures, //! this module emits platform-specific code. #![allow(non_upper_case_globals)] use std::fmt::{self, Display, Formatter}; use std::io::Write; /// The size of a value. pub type Size = u16; /// The description (name, size) of a parameter. pub type Parameter = (String, Size); // //==========================================================================// // // OPERAND // // //==========================================================================// /// An `Instruction` operand. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Operand { /// Empty operand. None, /// Register operand. Register(Size), /// Stack-allocated operand. Stack(usize, Size), /// Offset relative to the start of the instruction. RelativeOffset(isize, Size), /// Offset relative to the start of the procedure. AbsoluteOffset(isize, Size) }
// Copyright 2019, 2020 Wingchain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use proc_macro::TokenStream; use syn::{ parse_macro_input, FnArg, Ident, ImplItem, ImplItemMethod, ItemImpl, Meta, NestedMeta, Type, }; use quote::quote; use std::collections::{HashMap, HashSet}; /// Contract method validate_xxx will be treated as the validator of method xxx const VALIDATE_METHOD_PREFIX: &str = "validate_"; #[proc_macro_attribute] pub fn call(_attr: TokenStream, item: TokenStream) -> TokenStream { item } #[proc_macro_attribute] pub fn init(_attr: TokenStream, item: TokenStream) -> TokenStream { item } #[proc_macro_attribute] pub fn contract(_attr: TokenStream, item: TokenStream) -> TokenStream { let impl_item = parse_macro_input!(item as ItemImpl); let type_name = get_module_ident(&impl_item); let init_methods = get_module_init_methods(&impl_item); let call_methods = get_module_call_methods(&impl_item); let get_validate_ts_vec = |methods: &Vec<ModuleMethod>| { methods .iter() .map(|x| { let method_ident = &x.method_ident; let params_ident = x.params_ident.clone(); let is_payable = x.payable; let validate = match &x.validate_ident { Some(validate_ident) => quote! { self.#validate_ident(params) }, None => quote! {Ok(())}, }; quote! { stringify!(#method_ident) => { if pay_value > 0 { if !#is_payable { return Err(ContractError::NotPayable); } } let params : #params_ident = serde_json::from_slice(&params).map_err(|_|ContractError::InvalidParams)?; #validate }, } }) .collect::<Vec<_>>() }; let validate_init_ts_vec = get_validate_ts_vec(&init_methods); let validate_call_ts_vec = get_validate_ts_vec(&call_methods); let get_execute_ts_vec = |methods: &Vec<ModuleMethod>| { methods .iter() .map(|x| { let method_ident = &x.method_ident; let is_payable = x.payable; quote! { stringify!(#method_ident) => { if pay_value > 0 { if #is_payable { import::pay(); } else{ return Err(ContractError::NotPayable); } } let params = serde_json::from_slice(&params).map_err(|_|ContractError::InvalidParams)?; let result = self.#method_ident(params)?; let result = serde_json::to_vec(&result).map_err(|_|ContractError::Serialize)?; Ok(result) }, } }) .collect::<Vec<_>>() }; let execute_init_ts_vec = get_execute_ts_vec(&init_methods); let execute_call_ts_vec = get_execute_ts_vec(&call_methods); let gen = quote! { #impl_item impl #type_name { fn validate_init(&self, method: &str, params: Vec<u8>, pay_value: Balance) -> ContractResult<()> { match method { #(#validate_init_ts_vec)* other => Err(ContractError::InvalidMethod), } } fn validate_call(&self, method: &str, params: Vec<u8>, pay_value: Balance) -> ContractResult<()> { match method { #(#validate_call_ts_vec)* other => Err(ContractError::InvalidMethod), } } fn execute_init(&self, method: &str, params: Vec<u8>, pay_value: Balance) -> ContractResult<Vec<u8>> { match method { #(#execute_init_ts_vec)* other => Err(ContractError::InvalidMethod), } } fn execute_call(&self, method: &str, params: Vec<u8>, pay_value: Balance) -> ContractResult<Vec<u8>> { match method { #(#execute_call_ts_vec)* other => Err(ContractError::InvalidMethod), } } } fn get_method() -> ContractResult<String> { let share_id = std::ptr::null::<u8>() as u64; import::method_read(share_id); let len = import::share_len(share_id); let method = vec![0u8; len as usize]; import::share_read(share_id, method.as_ptr() as _); let method = String::from_utf8(method).map_err(|_|ContractError::InvalidMethod)?; Ok(method) } fn get_params() -> ContractResult<Vec<u8>> { let share_id = std::ptr::null::<u8>() as u64; import::params_read(share_id); let len = import::share_len(share_id); let params = vec![0u8; len as usize]; import::share_read(share_id, params.as_ptr() as _); let params = if params.len() == 0 { "null".as_bytes().to_vec() } else { params }; Ok(params) } fn get_pay_value() -> ContractResult<Balance> { let pay_value = import::pay_value_read(); Ok(pay_value) } fn set_result(result: ContractResult<()>) { match result { Ok(_) => (), Err(e) => { let error = e.to_string().into_bytes(); import::error_return(error.len() as _, error.as_ptr() as _); } } } fn inner_validate_init() -> ContractResult<()> { let method = get_method()?; let params = get_params()?; let pay_value = get_pay_value()?; let contract = #type_name::new()?; contract.validate_init(&method, params, pay_value)?; Ok(()) } fn inner_validate_call() -> ContractResult<()> { let method = get_method()?; let params = get_params()?; let pay_value = get_pay_value()?; let contract = #type_name::new()?; contract.validate_call(&method, params, pay_value)?; Ok(()) } fn inner_execute_init() -> ContractResult<()> { let method = get_method()?; let params = get_params()?; let pay_value = get_pay_value()?; let contract = #type_name::new()?; let result = contract.execute_init(&method, params, pay_value)?; import::result_write(result.len() as _, result.as_ptr() as _); Ok(()) } fn inner_execute_call() -> ContractResult<()> { let method = get_method()?; let params = get_params()?; let pay_value = get_pay_value()?; let contract = #type_name::new()?; let result = contract.execute_call(&method, params, pay_value)?; import::result_write(result.len() as _, result.as_ptr() as _); Ok(()) } #[wasm_bindgen] pub fn validate_init() { let result = inner_validate_init(); set_result(result); } #[wasm_bindgen] pub fn validate_call() { let result = inner_validate_call(); set_result(result); } #[wasm_bindgen] pub fn execute_init() { let result = inner_execute_init(); set_result(result); } #[wasm_bindgen] pub fn execute_call() { let result = inner_execute_call(); set_result(result); } }; gen.into() } fn get_module_ident(impl_item: &ItemImpl) -> Ident { match &*impl_item.self_ty { Type::Path(type_path) => type_path.path.segments[0].ident.clone(), _ => panic!("Module ident not found"), } } fn get_module_init_methods(impl_item: &ItemImpl) -> Vec<ModuleMethod> { get_module_methods_by_name(impl_item, "init") } fn get_module_call_methods(impl_item: &ItemImpl) -> Vec<ModuleMethod> { get_module_methods_by_name(impl_item, "call") } fn get_module_methods_by_name(impl_item: &ItemImpl, name: &str) -> Vec<ModuleMethod> { let methods = impl_item .items .iter() .filter_map(|item| { if let ImplItem::Method(method) = item { let call_method = method.attrs.iter().find_map(|attr| { let meta = attr.parse_meta().unwrap(); match meta { Meta::Path(word) => { if word.segments[0].ident == name { Some(ModuleMethod { payable: false, validate_ident: None, method_ident: method.sig.ident.clone(), params_ident: get_method_params_ident(&method), method: method.clone(), }) } else { None } } Meta::List(list) => { if list.path.segments[0].ident == name { let payable = list.nested.iter().find_map(|nm| match nm { NestedMeta::Meta(Meta::NameValue(nv)) if nv.path.segments[0].ident == "payable" => { match &nv.lit { syn::Lit::Bool(value) => Some(value.value), _ => panic!("Payable should have a bool value"), } } _ => None, }); let payable = payable.unwrap_or(false); Some(ModuleMethod { payable, validate_ident: None, method_ident: method.sig.ident.clone(), params_ident: get_method_params_ident(&method), method: method.clone(), }) } else { None } } _ => None, } }); call_method } else { None } }) .collect::<Vec<_>>(); let method_names = methods .iter() .map(|x| x.method_ident.to_string()) .collect::<HashSet<_>>(); let method_validates = impl_item .items .iter() .filter_map(|item| { if let ImplItem::Method(method) = item { let method_name = method.sig.ident.to_string(); if method_name.starts_with(VALIDATE_METHOD_PREFIX) { let method_name = method_name.trim_start_matches(VALIDATE_METHOD_PREFIX); if method_names.contains(method_name) { Some((method_name.to_string(), method.sig.ident.clone())) } else { None } } else { None } } else { None } }) .collect::<HashMap<_, _>>(); methods .into_iter() .map(|mut method| { let method_name = method.method_ident.to_string(); method.validate_ident = method_validates.get(&method_name).cloned(); method }) .collect::<Vec<_>>() } fn get_method_params_ident(method: &ImplItemMethod) -> Ident { if method.sig.inputs.len() == 2 { let params = &method.sig.inputs[1]; let pat_type = match params { FnArg::Typed(pat_type) => pat_type, _ => unreachable!(), }; let params_ident = if let Type::Path(path) = &*pat_type.ty { path.path .get_ident() .expect("No params ident found") .clone() } else { panic!("No params type found") }; params_ident } else { panic!("Call method args should be (&self, params: Type)"); } } struct ModuleMethod { #[allow(dead_code)] method: ImplItemMethod, method_ident: Ident, params_ident: Ident, payable: bool, validate_ident: Option<Ident>, }
/* * 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 */ /// DistributionWidgetDefinition : The Distribution visualization is another way of showing metrics aggregated across one or several tags, such as hosts. Unlike the heat map, a distribution graph’s x-axis is quantity rather than time. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DistributionWidgetDefinition { /// (Deprecated) The widget legend was replaced by a tooltip and sidebar. #[serde(rename = "legend_size", skip_serializing_if = "Option::is_none")] pub legend_size: Option<String>, /// List of markers. #[serde(rename = "markers", skip_serializing_if = "Option::is_none")] pub markers: Option<Vec<crate::models::WidgetMarker>>, /// Array of one request object to display in the widget. See the dedicated [Request JSON schema documentation](https://docs.datadoghq.com/dashboards/graphing_json/request_json) to learn how to build the `REQUEST_SCHEMA`. #[serde(rename = "requests")] pub requests: Vec<crate::models::DistributionWidgetRequest>, /// (Deprecated) The widget legend was replaced by a tooltip and sidebar. #[serde(rename = "show_legend", skip_serializing_if = "Option::is_none")] pub show_legend: Option<bool>, #[serde(rename = "time", skip_serializing_if = "Option::is_none")] pub time: Option<Box<crate::models::WidgetTime>>, /// Title of the widget. #[serde(rename = "title", skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(rename = "title_align", skip_serializing_if = "Option::is_none")] pub title_align: Option<crate::models::WidgetTextAlign>, /// Size of the title. #[serde(rename = "title_size", skip_serializing_if = "Option::is_none")] pub title_size: Option<String>, #[serde(rename = "type")] pub _type: crate::models::DistributionWidgetDefinitionType, #[serde(rename = "xaxis", skip_serializing_if = "Option::is_none")] pub xaxis: Option<Box<crate::models::DistributionWidgetXAxis>>, #[serde(rename = "yaxis", skip_serializing_if = "Option::is_none")] pub yaxis: Option<Box<crate::models::DistributionWidgetYAxis>>, } impl DistributionWidgetDefinition { /// The Distribution visualization is another way of showing metrics aggregated across one or several tags, such as hosts. Unlike the heat map, a distribution graph’s x-axis is quantity rather than time. pub fn new(requests: Vec<crate::models::DistributionWidgetRequest>, _type: crate::models::DistributionWidgetDefinitionType) -> DistributionWidgetDefinition { DistributionWidgetDefinition { legend_size: None, markers: None, requests, show_legend: None, time: None, title: None, title_align: None, title_size: None, _type, xaxis: None, yaxis: None, } } }
//! The `thin_client` module is a client-side object that interfaces with //! a server-side TPU. Client code should use this object instead of writing //! messages to the network directly. The binary encoding of its messages are //! unstable and may change in future releases. use bincode::{deserialize, serialize}; use hash::Hash; use request::{Request, Response}; use signature::{KeyPair, PublicKey, Signature}; use std::collections::HashMap; use std::io; use std::net::{SocketAddr, UdpSocket}; use transaction::Transaction; /// An object for querying and sending transactions to the network. pub struct ThinClient { requests_addr: SocketAddr, requests_socket: UdpSocket, transactions_addr: SocketAddr, transactions_socket: UdpSocket, last_id: Option<Hash>, transaction_count: u64, balances: HashMap<PublicKey, Option<i64>>, } impl ThinClient { /// Create a new ThinClient that will interface with Rpu /// over `requests_socket` and `transactions_socket`. To receive responses, the caller must bind `socket` /// to a public address before invoking ThinClient methods. pub fn new( requests_addr: SocketAddr, requests_socket: UdpSocket, transactions_addr: SocketAddr, transactions_socket: UdpSocket, ) -> Self { let client = ThinClient { requests_addr, requests_socket, transactions_addr, transactions_socket, last_id: None, transaction_count: 0, balances: HashMap::new(), }; client } pub fn recv_response(&self) -> io::Result<Response> { let mut buf = vec![0u8; 1024]; trace!("start recv_from"); self.requests_socket.recv_from(&mut buf)?; trace!("end recv_from"); let resp = deserialize(&buf).expect("deserialize balance in thin_client"); Ok(resp) } pub fn process_response(&mut self, resp: Response) { match resp { Response::Balance { key, val } => { trace!("Response balance {:?} {:?}", key, val); self.balances.insert(key, val); } Response::LastId { id } => { info!("Response last_id {:?}", id); self.last_id = Some(id); } Response::TransactionCount { transaction_count } => { info!("Response transaction count {:?}", transaction_count); self.transaction_count = transaction_count; } } } /// Send a signed Transaction to the server for processing. This method /// does not wait for a response. pub fn transfer_signed(&self, tx: Transaction) -> io::Result<usize> { let data = serialize(&tx).expect("serialize Transaction in pub fn transfer_signed"); self.transactions_socket .send_to(&data, &self.transactions_addr) } /// Creates, signs, and processes a Transaction. Useful for writing unit-tests. pub fn transfer( &self, n: i64, keypair: &KeyPair, to: PublicKey, last_id: &Hash, ) -> io::Result<Signature> { let tx = Transaction::new(keypair, to, n, *last_id); let sig = tx.sig; self.transfer_signed(tx).map(|_| sig) } /// Request the balance of the user holding `pubkey`. This method blocks /// until the server sends a response. If the response packet is dropped /// by the network, this method will hang indefinitely. pub fn get_balance(&mut self, pubkey: &PublicKey) -> io::Result<i64> { trace!("get_balance"); let req = Request::GetBalance { key: *pubkey }; let data = serialize(&req).expect("serialize GetBalance in pub fn get_balance"); self.requests_socket .send_to(&data, &self.requests_addr) .expect("buffer error in pub fn get_balance"); let mut done = false; while !done { let resp = self.recv_response()?; trace!("recv_response {:?}", resp); if let Response::Balance { key, .. } = &resp { done = key == pubkey; } self.process_response(resp); } self.balances[pubkey].ok_or(io::Error::new(io::ErrorKind::Other, "nokey")) } /// Request the transaction count. If the response packet is dropped by the network, /// this method will hang. pub fn transaction_count(&mut self) -> u64 { info!("transaction_count"); let req = Request::GetTransactionCount; let data = serialize(&req).expect("serialize GetTransactionCount in pub fn transaction_count"); self.requests_socket .send_to(&data, &self.requests_addr) .expect("buffer error in pub fn transaction_count"); let mut done = false; while !done { let resp = self.recv_response().expect("transaction count dropped"); info!("recv_response {:?}", resp); if let &Response::TransactionCount { .. } = &resp { done = true; } self.process_response(resp); } self.transaction_count } /// Request the last Entry ID from the server. This method blocks /// until the server sends a response. pub fn get_last_id(&mut self) -> Hash { info!("get_last_id"); let req = Request::GetLastId; let data = serialize(&req).expect("serialize GetLastId in pub fn get_last_id"); self.requests_socket .send_to(&data, &self.requests_addr) .expect("buffer error in pub fn get_last_id"); let mut done = false; while !done { let resp = self.recv_response().expect("get_last_id response"); if let &Response::LastId { .. } = &resp { done = true; } self.process_response(resp); } self.last_id.expect("some last_id") } pub fn poll_get_balance(&mut self, pubkey: &PublicKey) -> io::Result<i64> { use std::time::Instant; let mut balance; let now = Instant::now(); loop { balance = self.get_balance(pubkey); if balance.is_ok() || now.elapsed().as_secs() > 1 { break; } } balance } } #[cfg(test)] mod tests { use super::*; use bank::Bank; use budget::Budget; use crdt::TestNode; use logger; use mint::Mint; use server::Server; use signature::{KeyPair, KeyPairUtil}; use std::io::sink; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::sleep; use std::time::Duration; use transaction::{Instruction, Plan}; #[test] fn test_thin_client() { logger::setup(); let leader = TestNode::new(); let alice = Mint::new(10_000); let bank = Bank::new(&alice); let bob_pubkey = KeyPair::new().pubkey(); let exit = Arc::new(AtomicBool::new(false)); let server = Server::new_leader( bank, Some(Duration::from_millis(30)), leader.data.clone(), leader.sockets.requests, leader.sockets.transaction, leader.sockets.broadcast, leader.sockets.respond, leader.sockets.gossip, exit.clone(), sink(), ); sleep(Duration::from_millis(900)); let requests_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut client = ThinClient::new( leader.data.requests_addr, requests_socket, leader.data.transactions_addr, transactions_socket, ); let last_id = client.get_last_id(); let _sig = client .transfer(500, &alice.keypair(), bob_pubkey, &last_id) .unwrap(); let balance = client.poll_get_balance(&bob_pubkey); assert_eq!(balance.unwrap(), 500); exit.store(true, Ordering::Relaxed); for t in server.thread_hdls { t.join().unwrap(); } } #[test] fn test_bad_sig() { logger::setup(); let leader = TestNode::new(); let alice = Mint::new(10_000); let bank = Bank::new(&alice); let bob_pubkey = KeyPair::new().pubkey(); let exit = Arc::new(AtomicBool::new(false)); let server = Server::new_leader( bank, Some(Duration::from_millis(30)), leader.data.clone(), leader.sockets.requests, leader.sockets.transaction, leader.sockets.broadcast, leader.sockets.respond, leader.sockets.gossip, exit.clone(), sink(), ); sleep(Duration::from_millis(300)); let requests_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); requests_socket .set_read_timeout(Some(Duration::new(5, 0))) .unwrap(); let transactions_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut client = ThinClient::new( leader.data.requests_addr, requests_socket, leader.data.transactions_addr, transactions_socket, ); let last_id = client.get_last_id(); let tx = Transaction::new(&alice.keypair(), bob_pubkey, 500, last_id); let _sig = client.transfer_signed(tx).unwrap(); let last_id = client.get_last_id(); let mut tr2 = Transaction::new(&alice.keypair(), bob_pubkey, 501, last_id); if let Instruction::NewContract(contract) = &mut tr2.instruction { contract.tokens = 502; contract.plan = Plan::Budget(Budget::new_payment(502, bob_pubkey)); } let _sig = client.transfer_signed(tr2).unwrap(); let balance = client.poll_get_balance(&bob_pubkey); assert_eq!(balance.unwrap(), 500); exit.store(true, Ordering::Relaxed); for t in server.thread_hdls { t.join().unwrap(); } } }
use std::io; fn main() { println!("Please enter degrees in C°: "); let mut cdegrees = String::new(); io::stdin().read_line(&mut cdegrees).expect("Failed to read line!"); let cdegrees: i32 = cdegrees.trim().parse().expect("Please enter a number!"); let mut fdegrees = (cdegrees * 9/5) + 32; println!("In F° that is: {}", fdegrees); }
use std::net::{TcpListener, TcpStream}; use std::io::{Read, Write}; fn main() { let host_ip = "127.0.0.1:3333"; let listener = TcpListener::bind(host_ip).unwrap(); println!("server running {}", host_ip); for stream in listener.incoming() { match stream { Err(e) => { println!("Accept Error {}", e); } Ok(stream) => { handle_client(stream); } } } } fn handle_client(mut stream: TcpStream) { let mut buffer = [0; 1024]; loop { let len = match stream.read(&mut buffer) { Err(_) => break, Ok(message) => { if message == 0 { break; } message } }; match stream.write_all(&buffer[..len]) { Err(_) => break, Ok(_) => continue, } } }
use super::super::domain; use super::super::repository; pub fn index(page: i32, page_size: i32) -> (Vec<domain::designer::DomainDesigner>, i32) { let repository_design = repository::designer::RepositoryDesigner::new(); let total = repository_design.find_designers_total(page_size); let domain_designers = repository_design.find_designers(page, page_size); (domain_designers, total) }
use decimal; encoding_struct! { /// Fee data for specific kind of operations. struct Fee { fixed: u64, fraction: decimal::UFract64, } } encoding_struct! { /// Third party fee data, part of `AssetInfo`. struct Fees { trade: Fee, exchange: Fee, transfer: Fee, } } impl Fee { /// Calculate fee value for specific price. pub fn for_price(&self, price: u64) -> u64 { self.fixed() + self.fraction() * price } }
use crate::prelude::Address; use crate::test_utils; use crate::types::{Wei, ERC20_MINT_SELECTOR}; use secp256k1::SecretKey; const INITIAL_BALANCE: Wei = Wei::new_u64(1000); const INITIAL_NONCE: u64 = 0; const TRANSFER_AMOUNT: Wei = Wei::new_u64(123); /// Tests we can transfer Eth from one account to another and that the balances are correctly /// updated. #[test] fn test_eth_transfer_success() { // set up Aurora runner and accounts let (mut runner, mut source_account, dest_address) = initialize_transfer(); let source_address = test_utils::address_from_secret_key(&source_account.secret_key); // validate pre-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); // perform transfer runner .submit_with_signer(&mut source_account, |nonce| { test_utils::transfer(dest_address, TRANSFER_AMOUNT, nonce) }) .unwrap(); // validate post-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE - TRANSFER_AMOUNT, (INITIAL_NONCE + 1).into(), ); test_utils::validate_address_balance_and_nonce( &runner, dest_address, TRANSFER_AMOUNT, 0.into(), ); } /// Tests the case where the transfer amount is larger than the address balance #[test] fn test_eth_transfer_insufficient_balance() { let (mut runner, mut source_account, dest_address) = initialize_transfer(); let source_address = test_utils::address_from_secret_key(&source_account.secret_key); // validate pre-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); // attempt transfer let err = runner .submit_with_signer(&mut source_account, |nonce| { // try to transfer more than we have test_utils::transfer(dest_address, INITIAL_BALANCE + INITIAL_BALANCE, nonce) }) .unwrap_err(); let error_message = format!("{:?}", err); assert!(error_message.contains("ERR_OUT_OF_FUND")); // validate post-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, // the nonce is still incremented even though the transfer failed (INITIAL_NONCE + 1).into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); } /// Tests the case where the nonce on the transaction does not match the address #[test] fn test_eth_transfer_incorrect_nonce() { let (mut runner, mut source_account, dest_address) = initialize_transfer(); let source_address = test_utils::address_from_secret_key(&source_account.secret_key); // validate pre-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); // attempt transfer let err = runner .submit_with_signer(&mut source_account, |nonce| { // creating transaction with incorrect nonce test_utils::transfer(dest_address, TRANSFER_AMOUNT, nonce + 1) }) .unwrap_err(); let error_message = format!("{:?}", err); assert!(error_message.contains("ERR_INCORRECT_NONCE")); // validate post-state (which is the same as pre-state in this case) test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); } #[test] fn test_eth_transfer_not_enough_gas() { let (mut runner, mut source_account, dest_address) = initialize_transfer(); let source_address = test_utils::address_from_secret_key(&source_account.secret_key); let transaction = |nonce| { let mut tx = test_utils::transfer(dest_address, TRANSFER_AMOUNT, nonce); tx.gas = 10_000.into(); // this is not enough gas tx }; // validate pre-state test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); // attempt transfer let err = runner .submit_with_signer(&mut source_account, transaction) .unwrap_err(); let error_message = format!("{:?}", err); assert!(error_message.contains("ERR_INTRINSIC_GAS")); // validate post-state (which is the same as pre-state in this case) test_utils::validate_address_balance_and_nonce( &runner, source_address, INITIAL_BALANCE, INITIAL_NONCE.into(), ); test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into()); } fn initialize_transfer() -> (test_utils::AuroraRunner, test_utils::Signer, Address) { // set up Aurora runner and accounts let mut runner = test_utils::deploy_evm(); let mut rng = rand::thread_rng(); let source_account = SecretKey::random(&mut rng); let source_address = test_utils::address_from_secret_key(&source_account); runner.create_address(source_address, INITIAL_BALANCE, INITIAL_NONCE.into()); let dest_address = test_utils::address_from_secret_key(&SecretKey::random(&mut rng)); let mut signer = test_utils::Signer::new(source_account); signer.nonce = INITIAL_NONCE; (runner, signer, dest_address) } use sha3::Digest; #[test] fn check_selector() { // Selector to call mint function in ERC 20 contract // // keccak("mint(address,uint256)".as_bytes())[..4]; let mut hasher = sha3::Keccak256::default(); hasher.update(b"mint(address,uint256)"); assert_eq!(hasher.finalize()[..4].to_vec(), ERC20_MINT_SELECTOR); }
use tokio::process::Command; use anyhow::{Result, Context}; use async_trait::async_trait; use crate::{ services::model::{Nameable, Ensurable, is_binary_present}, helpers::ExitStatusIntoUnit }; static NAME: &str = "k9s"; #[derive(Default)] pub struct K9s {} impl Nameable for K9s { fn name(&self) -> &'static str { NAME } } #[async_trait] impl Ensurable for K9s { async fn is_present(&self) -> Result<bool> { is_binary_present(self).await } async fn make_present(&self) -> Result<()> { Command::new("curl") .arg("-LO") .arg("https://github.com/derailed/k9s/releases/download/v0.22.1/k9s_Linux_x86_64.tar.gz") .status().await .status_to_unit() .context("Unable to curl the k9s tarball.")?; Command::new("tar") .arg("-xvf") .arg("./k9s_Linux_x86_64.tar.gz") .status().await .status_to_unit() .context("Unable to untar the k9s tarball.")?; Command::new("rm") .arg("-f") .arg("k9s_Linux_x86_64.tar.gz") .arg("LICENSE") .arg("README.md") .status().await .status_to_unit() .context("Unable to remove the k9s tarball.")?; Command::new("chmod") .arg("+x") .arg("./k9s") .status().await .status_to_unit() .context("Unable to change executable permissions on the k9s binary.")?; Command::new("mv") .arg("./k9s") .arg("/usr/local/bin/k9s") .status().await .status_to_unit() .context("Unable to copy the k9s binary (might need sudo).")?; Command::new("k9s") .arg("version") .status().await .status_to_unit() .context("Unable to use k9s after supposed install.")?; Ok(()) } }