text
stringlengths
8
4.13M
use crate::{ ast::{ dec::{Dec, MemberSpecifier}, ty::TypeList, }, wasm::frame::frame::FrameAccess, }; use super::laze_type::{LazeType, LazeTypeList}; #[derive(Clone, Debug, PartialEq)] pub struct EntryMap { data: Vec<(String, EnvEntry)>, } impl EntryMap { pub fn new() -> Self { EntryMap { data: vec![] } } pub fn enter_scope(&mut self) { self.data.push(("<mark>".to_string(), EnvEntry::None)); } pub fn exit_scope(&mut self) { while let Some(last) = self.data.last() { if last.0 == "<mark>".to_string() { self.data.pop(); break; } else { self.data.pop(); } } } pub fn get_data(&self, id: &String) -> Option<&EnvEntry> { for pair in self.data.iter().rev() { if pair.0 == *id { return Some(&pair.1); } } return None; } pub fn remove_data(&mut self, id: &String) { let mut found_index: i32 = -1; for (index, pair) in self.data.iter().rev().enumerate() { if pair.0 == *id { found_index = index as i32; } } if found_index >= 0 { self.data.remove(found_index as usize); } } pub fn get_mut_data(&mut self, id: &String) -> Option<&mut EnvEntry> { for pair in self.data.iter_mut().rev() { if pair.0 == *id { return Some(&mut pair.1); } } return None; } pub fn get_data_clone(&self, id: &String) -> Option<EnvEntry> { for pair in self.data.iter().rev() { if pair.0 == *id { return Some(pair.1.clone()); } } return None; } pub fn add_data(&mut self, id: String, data: EnvEntry) { self.data.push((id, data)); } pub fn add_data_return_mut(&mut self, id: String, data: EnvEntry) -> &mut EnvEntry { self.data.push((id, data)); &mut self.data.last_mut().unwrap().1 } } #[derive(Clone, Debug, PartialEq)] pub enum EnvEntry { // var_type: LazeType, var_access: FrameAccess Var(LazeType, FrameAccess), // func_num: i32, params: LazeTypeList, return_type: LazeType, return_var_access: FrameAccess, func_frame: Frame Func(i32, LazeTypeList, LazeType), // base_dec: Dec, template_map: TemplateMap, venv_when_declared: EntryMap, type_params: Vec<String> Template(Dec, TemplateMap, EntryMap, Vec<String>), // class_name: String, members: Entrymap, size: i32 Class(String, EntryMap, i32), // type_var_value: LazeType Poly(LazeType), // specifier: MemberSpecifier, member_type: LazeType, offset: i32 Member(MemberSpecifier, LazeType, i32), // specifier: MemberSpecifier, func_num: i32, params: LazeTypeList, return_type: LazeType, return_var_access: FrameAccess, func_frame: Frame Method(MemberSpecifier, i32, LazeTypeList, LazeType), None, } #[derive(Clone, Debug, PartialEq)] pub struct TemplateMap { map: Vec<(TypeList, EnvEntry)>, } impl TemplateMap { pub fn new() -> TemplateMap { TemplateMap { map: vec![] } } pub fn get_data<'a>(&'a self, type_param: &TypeList) -> Option<&'a EnvEntry> { for data in &self.map { if type_param == &data.0 { return Some(&data.1); } } None } pub fn add_data(&mut self, type_param: TypeList, entry: EnvEntry) { self.map.push((type_param, entry)); } pub fn add_data_return_mut(&mut self, type_param: TypeList, entry: EnvEntry) -> &mut EnvEntry { self.map.push((type_param, entry)); &mut self.map.last_mut().unwrap().1 } }
use crate::{ dispose::Dispose, hex::{pointer::HexPointer, render::renderer::HexRenderer}, world::RhombusViewerWorld, }; use amethyst::{ecs::prelude::*, prelude::*}; use rhombus_core::hex::{ coordinates::{axial::AxialVector, direction::HexagonalDirection}, field_of_view::FieldOfView, storage::hash::RectHashStorage, }; use std::{collections::HashSet, sync::Arc}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum HexState { Open, Wall, } pub struct HexData { state: HexState, } impl Dispose for HexData { fn dispose(&mut self, _data: &mut StateData<'_, GameData<'_, '_>>) {} } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum FovState { Partial, Full, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum MoveMode { StraightAhead, StrafeLeftAhead, StrafeLeftBack, StrafeRightAhead, StrafeRightBack, StraightBack, } enum CustomMode { Hex(usize), Corridor, } const MODES: [CustomMode; 3] = [CustomMode::Hex(0), CustomMode::Hex(1), CustomMode::Corridor]; pub struct World<R: HexRenderer> { hexes: RectHashStorage<(HexData, R::Hex)>, renderer: R, renderer_dirty: bool, pointer: Option<(HexPointer, FovState)>, mode: usize, } impl<R: HexRenderer> World<R> { pub fn new(renderer: R) -> Self { Self { hexes: RectHashStorage::new(), renderer, renderer_dirty: false, pointer: None, mode: 0, } } pub fn reset_world(&mut self, data: &mut StateData<'_, GameData<'_, '_>>) { let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); self.clear(data, &world); } pub fn clear( &mut self, data: &mut StateData<'_, GameData<'_, '_>>, world: &RhombusViewerWorld, ) { self.delete_pointer(data, world); self.renderer.clear(data); self.hexes.dispose(data); } fn delete_pointer( &mut self, data: &mut StateData<'_, GameData<'_, '_>>, world: &RhombusViewerWorld, ) { if let Some((mut pointer, _)) = self.pointer.take() { pointer.delete_entities(data, world); } } pub fn next_mode(&mut self) { self.mode = (self.mode + 1) % MODES.len(); } pub fn grow_custom(&mut self) { match MODES[self.mode] { CustomMode::Hex(radius) => self.grow_hex(radius), CustomMode::Corridor => self.grow_corridor(), } } fn grow_hex(&mut self, radius: usize) { for r in 0..=radius { for pos in AxialVector::default().ring_iter(r) { self.hexes.insert( pos, ( HexData { state: HexState::Open, }, self.renderer.new_hex(false, true), ), ); } } for pos in AxialVector::default().ring_iter(radius + 1) { self.hexes.insert( pos, ( HexData { state: HexState::Wall, }, self.renderer.new_hex(true, true), ), ); } self.renderer_dirty = true; } fn grow_corridor(&mut self) { for (q, r) in [(0, 0), (1, 0)].iter() { self.hexes.insert( AxialVector::new(*q, *r), ( HexData { state: HexState::Open, }, self.renderer.new_hex(false, true), ), ); } for (q, r) in [(0, 1), (1, 1), (2, 0), (2, -1), (2, -1), (1, -1)].iter() { self.hexes.insert( AxialVector::new(*q, *r), ( HexData { state: HexState::Wall, }, self.renderer.new_hex(true, true), ), ); } self.renderer_dirty = true; } fn find_open_hex(&self) -> Option<AxialVector> { let mut r = 0; loop { let mut end = true; for pos in AxialVector::default().ring_iter(r) { let hex_data = self.hexes.get(pos).map(|hex| &hex.0); match hex_data { Some(HexData { state: HexState::Open, .. }) => return Some(pos), Some(..) => end = false, None => (), } } if end { return None; } r += 1; } } pub fn create_pointer( &mut self, fov_state: FovState, data: &mut StateData<'_, GameData<'_, '_>>, ) { let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); self.delete_pointer(data, &world); if let Some(hex) = self.find_open_hex() { let mut pointer = HexPointer::new_with_level_height(1.0); pointer.set_position(hex, 0, data, &world); pointer.create_entities(data, &world); self.pointer = Some((pointer, fov_state)); self.renderer_dirty = true; } } pub fn increment_direction(&mut self, data: &StateData<'_, GameData<'_, '_>>) { if let Some((pointer, _)) = &mut self.pointer { let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); pointer.increment_direction(data, &world); } } pub fn decrement_direction(&mut self, data: &StateData<'_, GameData<'_, '_>>) { if let Some((pointer, _)) = &mut self.pointer { let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); pointer.decrement_direction(data, &world); } } pub fn next_position(&mut self, mode: MoveMode, data: &mut StateData<'_, GameData<'_, '_>>) { if let Some((pointer, _)) = &mut self.pointer { let direction = match mode { MoveMode::StraightAhead => pointer.direction(), MoveMode::StrafeLeftAhead => (pointer.direction() + 5) % 6, MoveMode::StrafeLeftBack => (pointer.direction() + 4) % 6, MoveMode::StrafeRightAhead => (pointer.direction() + 1) % 6, MoveMode::StrafeRightBack => (pointer.direction() + 2) % 6, MoveMode::StraightBack => (pointer.direction() + 3) % 6, }; let next = pointer.position().neighbor(direction); if let Some(HexData { state: HexState::Open, .. }) = self.hexes.get(next).map(|hex| &hex.0) { let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); pointer.set_position(next, 0, data, &world); self.renderer_dirty = true; } } } pub fn change_field_of_view(&mut self, fov_state: FovState) { if let Some((_, pointer_fov_state)) = &mut self.pointer { *pointer_fov_state = fov_state; self.renderer_dirty = true; } } pub fn update_renderer_world( &mut self, force: bool, data: &mut StateData<'_, GameData<'_, '_>>, ) { if !self.renderer_dirty { return; } let (visible_positions, visible_only) = if let Some((pointer, fov_state)) = &self.pointer { let mut visible_positions = HashSet::new(); visible_positions.insert(pointer.position()); let mut fov = FieldOfView::default(); fov.start(pointer.position()); let is_obstacle = |pos| { let hex_data = self.hexes.get(pos).map(|hex| &hex.0); match hex_data { Some(HexData { state: HexState::Open, .. }) => false, Some(HexData { state: HexState::Wall, .. }) => true, None => false, } }; loop { let prev_len = visible_positions.len(); for pos in fov.iter() { let key = pointer.position() + pos; if self.hexes.contains_position(key) { let inserted = visible_positions.insert(key); debug_assert!(inserted); } } if visible_positions.len() == prev_len { break; } fov.next_radius(&is_obstacle); } ( Some(visible_positions), match fov_state { FovState::Partial => false, FovState::Full => true, }, ) } else { (None, false) }; let world = (*data.world.read_resource::<Arc<RhombusViewerWorld>>()).clone(); self.renderer.update_world( &mut self.hexes, |_, hex| hex.0.state != HexState::Open, |pos, _| { visible_positions .as_ref() .map_or(true, |vp| vp.contains(&pos)) }, |hex| &mut hex.1, visible_only, force, data, &world, ); self.renderer_dirty = false; } }
use bc::{block, BlockChain, BLOCKCHAIN}; use ctx; use futures::Future; use grpcio::{Environment, Error, Server, ServerBuilder}; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; use p2p::{self, api, api::RequestType}; use proto; use proto::{byzan, byzan_grpc}; use protobuf::RepeatedField; use std::sync::Arc; #[derive(Clone)] pub struct ByzanService; pub fn server() -> Result<Server, Error> { let context = ctx::CONTEXT.read().unwrap(); let env = Arc::new(Environment::new(context.threads)); let service = proto::byzan_grpc::create_block_chain(ByzanService); let server = ServerBuilder::new(env) .register_service(service) .bind(context.bind_host.clone(), context.bind_port) .build(); server } impl byzan_grpc::BlockChain for ByzanService { fn upsert(&self, ctx: RpcContext, req: byzan::NewBlock, sink: UnarySink<byzan::ResponseBlock>) { debug!("called upsert"); let new_block = block::NewBlock::from(req); match BLOCKCHAIN.lock().unwrap().push_new_block(new_block) { Ok(block) => { let lb: block::LightBlock = block.clone().into(); let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink .success(res) .map_err(|e| error!("error: upsert ({})", e)); ctx.spawn(f); let _ = p2p::CHANNEL .0 .lock() .unwrap() .send(api::payload(RequestType::New, lb)); } Err(e) => { let rpc_status = RpcStatus::new(RpcStatusCode::Unknown, Some(e)); let f = sink .fail(rpc_status) .map_err(|e| error!("error: upsert ({})", e)); ctx.spawn(f); } } } fn push(&self, ctx: RpcContext, req: byzan::Block, sink: UnarySink<byzan::ResponseBlock>) { debug!("called push"); let block = block::Block::from(req); match BLOCKCHAIN.lock().unwrap().push_block(block) { Ok(block) => { let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink.success(res).map_err(|e| error!("error: push ({})", e)); ctx.spawn(f); } Err(e) => { let rpc_status = RpcStatus::new(RpcStatusCode::InvalidArgument, Some(e)); let f = sink .fail(rpc_status) .map_err(|e| error!("error: push ({})", e)); ctx.spawn(f); } } } fn get_by_key( &self, ctx: RpcContext, req: byzan::BlockKey, sink: UnarySink<byzan::ResponseBlock>, ) { debug!("called get_by_key"); let key = req.get_key().to_string(); match BLOCKCHAIN.lock().unwrap().get_by_key(&key) { Some(block) => { let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink .success(res) .map_err(|e| error!("error: get_by_key ({})", e)); ctx.spawn(f); } None => { let e = format!("error: get_by_key ({})", key); let rpc_status = RpcStatus::new(RpcStatusCode::NotFound, Some(e)); let f = sink.fail(rpc_status).map_err(|e| error!("{}", e)); ctx.spawn(f); } } } fn get_by_id( &self, ctx: RpcContext, req: byzan::BlockId, sink: UnarySink<byzan::ResponseBlock>, ) { debug!("called get_by_id"); let id = req.get_id().to_string(); match BLOCKCHAIN.lock().unwrap().get_by_id(&id) { Some(block) => { let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink .success(res) .map_err(|e| error!("error: get_by_id ({})", e)); ctx.spawn(f); } None => { let e = format!("error: get_by_id ({})", id); let rpc_status = RpcStatus::new(RpcStatusCode::NotFound, Some(e)); let f = sink.fail(rpc_status).map_err(|e| error!("{}", e)); ctx.spawn(f); } } } fn get_by_idx( &self, ctx: RpcContext, req: byzan::BlockIdx, sink: UnarySink<byzan::ResponseBlock>, ) { debug!("called get_by_idx"); let idx = req.get_idx(); match BLOCKCHAIN.lock().unwrap().get_by_idx(idx) { Some(block) => { let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink .success(res) .map_err(|e| error!("error: get_by_idx ({})", e)); ctx.spawn(f); } None => { let e = format!("error: get_by_idx ({})", idx); let rpc_status = RpcStatus::new(RpcStatusCode::NotFound, Some(e)); let f = sink.fail(rpc_status).map_err(|e| error!("{}", e)); ctx.spawn(f); } } } fn history( &self, ctx: RpcContext, req: byzan::BlockKey, sink: UnarySink<byzan::ResponseBlocks>, ) { debug!("called history_by_key"); let key = req.get_key().to_string(); let history = BLOCKCHAIN.lock().unwrap().history_by_key(&key); let res_history: Vec<byzan::Block> = history.into_iter().map(|b| b.into()).collect(); let mut res = byzan::ResponseBlocks::new(); res.set_status(String::from("ok")); res.set_blocks(RepeatedField::<byzan::Block>::from(res_history)); let f = sink .success(res) .map_err(|e| error!("error: history ({})", e)); ctx.spawn(f); } fn last(&self, ctx: RpcContext, _req: byzan::Empty, sink: UnarySink<byzan::ResponseBlock>) { debug!("called last"); match BLOCKCHAIN.lock().unwrap().last() { Some(block) => { let res_block: byzan::Block = block.into(); let mut res = byzan::ResponseBlock::new(); res.set_status(String::from("ok")); res.set_block(res_block); let f = sink.success(res).map_err(|e| { println!("error {}", e); }); ctx.spawn(f); } None => { let e = format!("error: last()"); let rpc_status = RpcStatus::new(RpcStatusCode::NotFound, Some(e)); let f = sink.fail(rpc_status).map_err(|e| error!("{}", e)); ctx.spawn(f); } } } fn len(&self, ctx: RpcContext, _req: byzan::Empty, sink: UnarySink<byzan::ResponseLen>) { debug!("called len"); let mut res = byzan::ResponseLen::new(); res.set_status(String::from("ok")); res.set_len(BLOCKCHAIN.lock().unwrap().len() as u32); let f = sink.success(res).map_err(|e| error!("error: len ({})", e)); ctx.spawn(f); } fn range( &self, ctx: RpcContext, req: byzan::BlockRange, sink: UnarySink<byzan::ResponseBlocks>, ) { debug!("called range"); let first = req.get_first(); let last = req.get_last(); let res_blocks: Vec<byzan::Block> = BLOCKCHAIN .lock() .unwrap() .range(first, last) .into_iter() .map(|b| b.into()) .collect(); let mut res = byzan::ResponseBlocks::new(); res.set_status(String::from("ok")); res.set_blocks(RepeatedField::<byzan::Block>::from(res_blocks)); let f = sink .success(res) .map_err(|e| error!("errory: range ({})", e)); ctx.spawn(f); } fn till(&self, ctx: RpcContext, req: byzan::BlockTill, sink: UnarySink<byzan::ResponseBlocks>) { debug!("called till"); let first = req.get_first(); let res_blocks: Vec<byzan::Block> = BLOCKCHAIN .lock() .unwrap() .till(first) .into_iter() .map(|b| b.into()) .collect(); let mut res = byzan::ResponseBlocks::new(); res.set_status(String::from("ok")); res.set_blocks(RepeatedField::<byzan::Block>::from(res_blocks)); let f = sink.success(res).map_err(|e| error!("error: till ({})", e)); ctx.spawn(f); } }
extern crate rustty; use rustty::{ Terminal, Event, }; use rustty::ui::core::{ Widget, HorizontalAlign, VerticalAlign, ButtonResult, Button }; use rustty::ui::{ Dialog, Label, StdButton, VerticalLayout, HorizontalLayout }; fn boxify(vec: Vec<StdButton>) -> Vec<Box<Button>> { vec.into_iter().map(Box::new).map(|x| x as Box<Button>).collect() } fn create_maindlg() -> Dialog { let mut maindlg = Dialog::new(55, 12); // Text and alignment data to be used for displaying to dialog let mut label1 = Label::new(45, 2); label1.set_text("Hello! This is a showcase of the ui module! \ Here's a horizontal layout configuration."); // Text is aligned in respect to the label, usually don't want margins label1.align_text(HorizontalAlign::Middle, VerticalAlign::Top, (0, 0)); label1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Top, (0, 1)); maindlg.add_label(label1); let b1 = StdButton::new("Quit", 'q', ButtonResult::Ok); let b2 = StdButton::new("Foo!", 'f', ButtonResult::Custom(1)); let b3 = StdButton::new("Bar!", 'a', ButtonResult::Custom(2)); let b4 = StdButton::new("Juu!", 'j', ButtonResult::Custom(3)); let b5 = StdButton::new("Tuu!", 't', ButtonResult::Custom(4)); let b6 = StdButton::new("Boo!", 'b', ButtonResult::Custom(5)); let mut hlayout1 = HorizontalLayout::from_vec(boxify(vec![b1, b2, b3]), 1); hlayout1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0, 2)); maindlg.add_layout(hlayout1); let mut hlayout2 = HorizontalLayout::from_vec(boxify(vec![b4, b5, b6]), 1); hlayout2.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0, 3)); maindlg.add_layout(hlayout2); // Draw the outline for the dialog maindlg.draw_box(); maindlg } fn create_vdlg(rows: usize) -> Dialog { let mut vdlg = Dialog::new(20, rows/4); // Text and alignment data to be used for displaying to dialog let mut label = Label::from_str("Vertical layout"); label.pack(&vdlg, HorizontalAlign::Middle, VerticalAlign::Top, (0,1)); vdlg.add_label(label); let b1 = StdButton::new("Yhh!", 'y', ButtonResult::Custom(1)); let b2 = StdButton::new("Vpp!", 'v', ButtonResult::Custom(2)); let b3 = StdButton::new("Wgg!", 'w', ButtonResult::Custom(3)); let mut vlayout = VerticalLayout::from_vec(boxify(vec![b1, b2, b3]), 0); vlayout.pack(&vdlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0, 2)); vdlg.add_layout(vlayout); vdlg.draw_box(); vdlg } fn main() { let mut term = Terminal::new().unwrap(); let mut maindlg = create_maindlg(); let mut vdlg = create_vdlg(term.rows()); // Align main dialog frame with the middle of the screen, and vdlg with the bottom maindlg.pack(&term, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0)); vdlg.pack(&term, HorizontalAlign::Left, VerticalAlign::Middle, (0,0)); 'main: loop { while let Some(Event::Key(ch)) = term.get_event(0).unwrap() { match maindlg.result_for_key(ch) { Some(ButtonResult::Ok) => break 'main, Some(ButtonResult::Custom(i)) => { let msg = match i { 1 => "Foo!", 2 => "Bar!", 3 => "Juu!", 4 => "Too!", 5 => "Boo!", 6 => "Yhh!", 7 => "Vpp!", 8 => "Wgg!", _ => "" }; let mut result = Label::from_str(msg); result.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,1)); result.draw(maindlg.frame_mut()); }, _ => {}, } match vdlg.result_for_key(ch) { Some(ButtonResult::Custom(i)) => { let msg = match i { 1 => "Yhh!", 2 => "Vpp!", 3 => "Wgg!", _ => "" }; let mut result = Label::from_str(msg); result.pack(&vdlg, HorizontalAlign::Middle, VerticalAlign::Middle, (0,1)); result.draw(vdlg.frame_mut()); }, _ => {}, } } // Draw widgets to screen maindlg.draw(&mut term); vdlg.draw(&mut term); term.swap_buffers().unwrap(); } }
#![feature(test)] extern crate test; extern crate java_syntax; use std::env; use std::fs::File; use std::io::prelude::*; use java_syntax::*; use logos::Logos; use logos::Lexer; #[cfg(test)] mod tests { use super::*; use java_syntax::lexer::JavaTokenType::*; use java_syntax::lexer::JavaTokenType; #[test] fn test_int() { check_single("12", IntegerLiteral); } #[test] fn test_long_literal() { check_single("43l", IntegerLiteral); } #[test] fn test_long_literal_with_underscore() { check_single("11_23_2l", IntegerLiteral); } #[test] fn test_id() { check_single("foo", Identifier); } #[test] fn test_id_digits() { check_single("foo33", Identifier); } #[test] fn test_keyword() { check_single("break", BreakKw); } #[test] fn test_id_like_keyword() { check_single("breaking", Identifier); } // ERRORs should be united into single token // #[test] // fn test_errors() { // check_tokenize("####", vec![]); // } fn check_single(text: &str, token_type: JavaTokenType) { let mut lexer = JavaTokenType::lexer(text); let iterator = iter_for_lexer(lexer); let tokens: Vec<TokenInfo> = iterator.collect(); assert_eq!(tokens.len(), 1); assert_eq!(tokens[0].token, token_type); } fn check_tokenize(text: &str, expected: Vec<TokenInfo>) { let mut lexer: Lexer<JavaTokenType, &str> = JavaTokenType::lexer(text); let iterator = iter_for_lexer(lexer); let tokens: Vec<TokenInfo> = iterator.collect(); assert_eq!(expected, tokens); } // fn read_file() -> String { // let mut f = File::open("./benches/Main.java").unwrap(); // let mut contents = String::new(); // f.read_to_string(&mut contents).unwrap(); // contents // } }
#![allow(dead_code)] #![allow(unused_imports)] use std::collections::{HashMap, HashSet}; use std::io::{BufRead, BufReader, Error, Read, Write}; use std::net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream}; use std::str::{self, FromStr}; use std::thread; use crate::application::Application; use crate::data_dictionary::*; use crate::message::store::*; use regex::Regex; use crate::message::*; use crate::session::*; const ACCEPTOR_CONN_TYPE: &str = "acceptor"; const INITIATOR_CONN_TYPE: &str = "initiator"; pub trait Connecter { fn start(&self) -> Vec<thread::JoinHandle<()>>; fn stop(); } #[derive(Debug, PartialEq, Copy, Clone)] pub enum ConnectionType { ACCEPTOR, INITIATOR, } #[derive(Debug)] pub struct SocketConnector { connection_type: ConnectionType, session_map: HashMap<String, Session>, sockets: HashSet<SocketAddrV4>, } impl Default for SocketConnector { fn default() -> Self { Self { connection_type: ConnectionType::ACCEPTOR, session_map: HashMap::new(), sockets: HashSet::new(), } } } impl SocketConnector { pub fn new<M: MessageStore, L: LogStore, A: Application>( config: &mut SessionConfig, msg_store: &mut M, log_store: &mut L, app: A, ) -> Self { let mut socket_connector = SocketConnector::default(); socket_connector.create_sessions(config); socket_connector } pub fn send(&self, msg: Message) { println!("{}", msg); } pub fn recv(&self) -> Message { Message::new() } pub fn set_connection_type(&mut self, con_ty: String) { if con_ty.eq_ignore_ascii_case(ACCEPTOR_CONN_TYPE) { self.connection_type = ConnectionType::ACCEPTOR; } else if con_ty.eq_ignore_ascii_case(INITIATOR_CONN_TYPE) { self.connection_type = ConnectionType::INITIATOR; } else { panic!(format!( "Invalid connection type param. Only {} and {} are allowed", ACCEPTOR_CONN_TYPE, INITIATOR_CONN_TYPE )); } } pub fn get_connection_type(&self) -> ConnectionType { self.connection_type } pub fn set_session(&mut self, sid: String, session: Session) { self.session_map.insert(sid, session); } pub fn create_sessions(&mut self, config: &mut SessionConfig) { let default_setting = config.default_setting().clone(); let conn_type = default_setting.get_connection_type(); // if conn_type.is_none() { // panic!("No connection type provided"); // } // self.set_connection_type(conn_type.unwrap()); self.set_connection_type(conn_type); let settings_vec: Vec<&mut SessionSetting> = config.iter_mut().filter(|s| !s.is_empty()).collect(); for stng in settings_vec.into_iter() { println!("setting {:?}", stng); let merge_set = stng.merge_setting(&default_setting); let new_session = Session::with_settings(&merge_set); self.set_session(new_session.session_id.to_string(), new_session); let sock_addr: SocketAddrV4; if self.get_connection_type() == ConnectionType::ACCEPTOR { sock_addr = SocketAddrV4::new( Ipv4Addr::LOCALHOST, stng.get_socket_accept_port().expect("no port specified"), ); self.sockets.insert(sock_addr); } else { let ipv4 = Ipv4Addr::from_str( stng.get_socket_connect_host() .expect("no host specified") .as_ref(), ) .expect("cannot parse host to Ipv4Addr"); sock_addr = SocketAddrV4::new( ipv4, stng.get_socket_connect_port().expect("no port specified"), ); self.sockets.insert(sock_addr); } } } } struct FixReader<B: BufRead> { buf_reader: B, aux_buf: Vec<u8>, } impl<B: BufRead> FixReader<B> { fn new(buf_read: B) -> Self { Self { buf_reader: buf_read, aux_buf: Vec::with_capacity(64), } } fn read_message(&mut self, buff: &mut String) -> std::io::Result<usize> { // regular expression for end of fix message lazy_static! { static ref EOM_RE: Regex = // Regex::new(format!("{}10=\\d{{{}}}{}", SOH, 3, SOH).as_str()).unwrap(); Regex::new(format!("{}10=\\d+{}", SOH, SOH).as_str()).unwrap(); } let bytes_used = { let data_bytes = match self.buf_reader.fill_buf() { Ok(r) => r, Err(e) => return Err(e), }; let str_data = str::from_utf8(data_bytes).unwrap(); println!("str_data {}", str_data); match EOM_RE.find(str_data) { Some(mat) => { buff.push_str(&str_data[..mat.end()]); mat.end() } None => 0, } }; println!("bytes used {}", bytes_used); self.buf_reader.consume(bytes_used); Ok(bytes_used) } fn read_message_new(&mut self) -> std::io::Result<String> { // 8=FIX.4.4|9=5|35=0|10=10| let delim = &[SOH as u8]; // let mut fix_ver: [u8; 10] = [0; 10]; // this will include '=' after tag 9 let mut message = String::with_capacity(512); // this will fill 10 bytes atleast so fix version will be retrieved let ver_len = self.buf_reader.read_until(SOH as u8, &mut self.aux_buf)?; // println!("version {}", str::from_utf8(&self.aux_buf[..]).unwrap()); if ver_len == 0 || !self.aux_buf.ends_with(delim) { // either no data or partial data without any SOH is reached // this can only happen if connection is closed with no data or partial data // println!("version not proper"); return Err(Error::new( std::io::ErrorKind::UnexpectedEof, "partial message", )); } let body_len = self.buf_reader.read_until(SOH as u8, &mut self.aux_buf)?; // println!("body len field {}", str::from_utf8(&self.aux_buf[ver_len+2..ver_len+body_len-1]).unwrap()); if body_len == 0 || !self.aux_buf.ends_with(delim) { // println!("body len not proper"); return Err(Error::new( std::io::ErrorKind::UnexpectedEof, "partial message", )); } let mut body_len_bytes = 0u32; for byt in &self.aux_buf[ver_len + 2..ver_len + body_len - 1] { // parse bytes into an u16 body_len_bytes = body_len_bytes * 10 + (*byt as char).to_digit(10).unwrap(); // println!("curr len {}, prev byte {}, str rep {}", body_len_bytes, *byt, str::from_utf8(&[*byt]).unwrap()); } // println!("calculated body len {}", body_len_bytes); // now read exact bytes from bufreader let new_len = ver_len + body_len + body_len_bytes as usize; // 7 bytes for trailer self.aux_buf .resize(self.aux_buf.len() + body_len_bytes as usize, 0u8); self.buf_reader .read_exact(&mut self.aux_buf[ver_len + body_len..new_len])?; let trailer = self.buf_reader.read_until(SOH as u8, &mut self.aux_buf)?; if trailer == 0 || !self.aux_buf.ends_with(delim) { // println!("trailer not correct"); return Err(Error::new( std::io::ErrorKind::UnexpectedEof, "partial message", )); } message.push_str(str::from_utf8(&self.aux_buf[..]).unwrap()); self.aux_buf.clear(); Ok(message) } } impl Connecter for SocketConnector { fn start(&self) -> Vec<thread::JoinHandle<()>> { let mut join_handles: Vec<thread::JoinHandle<()>> = Vec::new(); for socket in &self.sockets { println!("Socket {}", socket); let listener = TcpListener::bind(socket).expect("could not bind to socket"); let new_thread = thread::Builder::new() .name(format!("thread for socket {}", socket)) .spawn(move || { for stream in listener.incoming() { let stream = stream.unwrap(); // let mut buff = String::with_capacity(512); let mut fix_reader = FixReader::new(BufReader::new(stream)); loop { // buff.clear(); match fix_reader.read_message_new() { Ok(s) => { println!("message read {}", s); thread::sleep(std::time::Duration::from_millis(5000)); } Err(_) => { println!("Connection terminated"); break; } } } } }) .unwrap(); join_handles.push(new_thread); } join_handles } fn stop() {} } mod validator { use super::*; pub fn validate_tag(msg: &str) { // validate that tag is correct according to data_dictionary // and value is permissible // get the message type // then iterate over list of tags/value and verify that each } } #[cfg(test)] mod networkio_tests { use super::*; use crate::application::*; use crate::message::store::*; use crate::message::*; use crate::session::*; use rand::prelude::*; use std::thread; use std::time::Duration; fn test_message() -> String { let mut msg = Message::new(); // let mut rng = rand::thread_rng(); msg.header_mut().set_string(49, "Gaurav".to_string()); msg.header_mut().set_string(56, "Tatke".to_string()); msg.header_mut().set_msg_type("A"); msg.body_mut().set_int(34, rand::random::<u32>()); msg.body_mut().set_float(44, rand::random::<f64>()); msg.body_mut().set_bool(654, rand::random::<bool>()); msg.body_mut().set_char(54, 'b'); msg.body_mut().set_string(1, "BOX_AccId".to_string()); let body_len = msg.to_string().len(); msg.header_mut().set_int(9, body_len as u16); msg.header_mut().set_string(8, "FIX.4.3".to_string()); msg.trailer_mut().set_int(10, rand::random::<u16>()); msg.to_string() } #[test] fn io_test() { let mut session_config = SessionConfig::from_toml("src/FixConfig.toml"); let mut log_store = DefaultLogStore::new(); let mut msg_store = DefaultMessageStore::new(); let app = DefaultApplication::new(); let mut acceptor = SocketConnector::new(&mut session_config, &mut msg_store, &mut log_store, app); let mut stream1 = TcpStream::connect("127.0.0.1:10114").expect("could not connect"); // let mut stream2 = TcpStream::connect("127.0.0.1:10115").expect("could not connect"); for i in 0..5 { let msg = test_message(); println!("sending message on {:?} : {}", stream1, msg); stream1.write(msg.as_bytes()).unwrap(); // let msg = test_message(); // println!("sending message on {:?} : {}", stream2, msg); // stream2.write(msg.as_bytes()).unwrap(); } } #[test] fn test_broken_message() { let mut stream1: TcpStream = TcpStream::connect("127.0.0.1:10114").expect("could not connect"); let msg = test_message(); let (msg_part1, msg_part2) = msg.split_at(msg.len() / 2); println!("Sending part 1 = {}", msg_part1); stream1.write_all(msg_part1.as_bytes()).unwrap(); thread::sleep(Duration::from_millis(10000)); println!("Sending part 2 = {}", msg_part2); stream1.write_all(msg_part2.as_bytes()).unwrap(); // stream1.write_all(b"8="); thread::sleep(Duration::from_millis(5000)); // stream1.write_all(b"FIX.4.3"); } }
use opencv::prelude::*; use opencv::imgproc::*; use opencv::core::*; use opencv::types::*; use vision_traits::{DynErrResult, input::InputSingular, Node, output::OutputSingular}; pub struct FindContours { } impl Node for FindContours { const NAME: &'static str = "FindContours"; type S = (); type I<'a> = InputSingular<'a, Mat>; type O = OutputSingular<VectorOfVectorOfPoint>; fn make(_: Self::S) -> DynErrResult<Self> { Ok(Self {}) } fn process(&mut self, mat: Self::I<'_>) -> DynErrResult<Self::O> { let mut contours = VectorOfVectorOfPoint::new(); find_contours(mat.val, &mut contours, RETR_EXTERNAL, CHAIN_APPROX_TC89_L1, Point::default())?; Ok(contours.into()) } }
/* array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N. bool The boolean type. char A character type. f32 The 32-bit floating point type. f64 The 64-bit floating point type. i16 The 16-bit signed integer type. i32 The 32-bit signed integer type. i64 The 64-bit signed integer type. i8 The 8-bit signed integer type. isize The pointer-sized signed integer type. pointer Raw, unsafe pointers, *const T, and *mut T. slice A dynamically-sized view into a contiguous sequence, [T]. str String slices. tuple A finite heterogeneous sequence, (T, U, ..). u16 The 16-bit unsigned integer type. u32 The 32-bit unsigned integer type. u64 The 64-bit unsigned integer type. u8 The 8-bit unsigned integer type. usize The pointer-sized unsigned integer type. */ fn main() { let age: u32 = 30; let score: f64 = std::f64::consts::PI; { let mut age_copy = age; age_copy = 15; println!("age_copy = {:?}\n", age_copy); } assert_eq!(30, age); println!("age = {:?}", age); println!("score = {:?}", score); // tuple let tuple = (1, 2, 3, 4); let (a, b, c, d) = tuple; println!("a = {:?}", a); println!("b = {:?}", b); println!("c = {:?}", c); println!("d = {:?}", d); }
#![cfg_attr(windows, windows_subsystem = "windows")] use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{prelude::*, BufRead, BufReader, Error, ErrorKind, Result}; use std::path::PathBuf; use std::process; use std::sync::mpsc::{sync_channel, SyncSender}; use std::thread; use log::*; use rand::prelude::*; use serde; use serde::Serialize; use serde_json::Value; struct Playlist(PathBuf); impl std::ops::Deref for Playlist { type Target = PathBuf; fn deref(&self) -> &Self::Target { &self.0 } } impl Playlist { fn walk(list: &mut Vec<PathBuf>, path: PathBuf) { if path.is_file() && !path.is_dir() { list.push(path); return; } for (ft, path) in path .read_dir() .unwrap() .filter_map(Result::ok) .filter_map(|s| s.file_type().ok().map(|ft| (ft, s.path()))) { match (ft.is_dir(), ft.is_file()) { (true, false) => Self::walk(list, path), (false, true) => list.push(path), _ => unreachable!(), } } } fn make_temp(files: &[PathBuf]) -> Result<Self> { let data = files .iter() .filter_map(|s| { s.extension() .and_then(std::ffi::OsStr::to_str) .and_then(|e| Some((s, e))) }) .filter(|(_, e)| match e.to_lowercase().as_str() { "jpg" | "jpeg" | "png" | "gif" | "heif" | "webp" | "tga" | "bpg" => false, _ => true, }) .filter_map(|(s, _)| s.to_str()) .collect::<Vec<_>>(); if data.is_empty() { return Err(Error::new( ErrorKind::InvalidInput, "file list contains no valid files", )); } let dir = std::env::temp_dir() .join(random_name(7)) .with_extension("mpv-playlist"); std::fs::write(&dir, data.join("\n"))?; Ok(Playlist(dir)) } } impl Drop for Playlist { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } #[derive(Debug, Copy, Clone, PartialEq)] enum Event { FileLoaded, Unpause, } impl Event { fn try_from_value(val: &Value) -> Option<Self> { match val.get("event")?.as_str()? { "file-loaded" => Some(Event::FileLoaded), "unpause" => Some(Event::Unpause), _ => None, } } } enum Command<S> { SetProperty(S, Value), GetProperty(S), } impl<S: Into<Value>> Command<S> { fn get(prop: S) -> Self { Command::GetProperty(prop) } fn set<V: Into<Value>>(prop: S, value: V) -> Self { Command::SetProperty(prop, value.into()) } fn into_values(self) -> Vec<Value> { match self { Command::SetProperty(prop, val) => vec!["set_property".into(), prop.into(), val], Command::GetProperty(prop) => vec!["get_property".into(), prop.into()], } } } #[derive(Serialize)] struct Request { command: Vec<Value>, request_id: u32, } impl Request { fn new<S: Into<Value>>(cmd: Command<S>) -> Self { Self { command: cmd.into_values(), request_id: thread_rng().next_u32(), } } } struct Mpv { child: process::Child, _playlist: Playlist, } impl Mpv { fn new(playlist: Playlist) -> Result<Self> { let name = crate::random_name(5); let child = process::Command::new("mpv") .arg(&format!("--input-ipc-server=tmp/{}", name)) .arg(&format!("--playlist={}", playlist.to_str().unwrap())) .arg("--pause") .spawn()?; let file = Self::try_connect(&format!(r#"\\.\\pipe\tmp\{}"#, name))?; thread::spawn(move || { State::run(file, |info| { #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] enum ItemKind { Local { artist: String, title: String, album: String, }, } impl From<SongInfo> for ItemKind { fn from( SongInfo { artist, title, album, }: SongInfo, ) -> Self { ItemKind::Local { artist, title, album, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "lowercase")] struct Item { pub kind: ItemKind, pub ts: i64, pub version: u32, } let ts = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap(); let data = serde_json::to_string(&Item { kind: info.into(), ts: (ts.as_secs() * 1000 + u64::from(ts.subsec_nanos()) / 1_000_000) as i64, version: 1, }) .map_err(|err| Error::new(ErrorKind::InvalidData, err))?; match ureq::post("http://localhost:50006/local") .send_string(&data) .synthetic_error() { Some(err) => Err(Error::new( ErrorKind::ConnectionRefused, format!("{}: {}", err.status(), err.status_text()), )), None => { debug!("sent song info"); Ok(()) } } }) }); Ok(Mpv { child, _playlist: playlist, }) } fn try_connect(fd: &str) -> Result<File> { if cfg!(not(windows)) { return File::open(&fd); } let mut count = 0; loop { match miow::pipe::connect(fd) { Ok(file) => { trace!("connected to pipe"); return Ok(file); } Err(..) if count < 5 => { debug!( "(attempt #{}) waiting a bit for the ipc pipe to be ready", count + 1 ); thread::sleep(std::time::Duration::from_millis(100)); count += 1; } Err(err) => { error!("cannot connect to the mpv ipc named pipe: {}", err); return Err(err); } } } } } impl Drop for Mpv { fn drop(&mut self) { debug!("dropping child: {}", self.child.id()); let _ = self.child.kill(); } } struct State { file: File, // this should really have a LRU eviction policy, // technically it currently has unbounded growth waiting: HashSet<u32>, } impl State { fn run<F>(file: File, func: F) -> Result<()> where F: Fn(SongInfo) -> Result<()>, { let mut this = Self { file: file.try_clone().unwrap(), waiting: HashSet::new(), }; let req = this.write_command(Command::set("pause", false))?; this.waiting.insert(req); let mut last = None; for msg in BufReader::new(file) .lines() .filter_map(Result::ok) .filter_map(|line| Message::parse(line).ok()) { match msg { Message::Unpause | Message::FileLoaded => { if let Err(err) = this.get_song_info() { error!("cannot get song info: {}", err) } } Message::Response(id, val) => { if let Response::Song(info) = match this.handle_resp(id, val) { Err(err) => { error!("cannot handle response: {}", err); continue; } Ok(req) => req, } { // TODO: this will stop any songs from repeating back to back (single song playlists..) if last.as_ref() == Some(&info) { continue; } last.replace(info.clone()); if let Err(err) = func(info) { error!("cannot send song info: {}", err) } } } Message::Unknown => (), } } Ok(()) } fn get_song_info(&mut self) -> Result<()> { let req = self.write_command(Command::get("filtered-metadata"))?; self.waiting.insert(req); Ok(()) } fn handle_resp(&mut self, id: u32, mut val: Value) -> Result<Response> { macro_rules! maybe { ($e:expr) => { match $e { Some(d) => d, None => return Ok(Response::Empty), } }; }; if !self.waiting.remove(&id) { return Ok(Response::Empty); } let data = maybe!(val.get_mut("data")); let mut map: HashMap<String, String> = maybe!(serde_json::from_value(data.take()).ok()); Ok(Response::Song(SongInfo { artist: maybe!(map.remove("Artist")), album: maybe!(map.remove("Album")), title: maybe!(map.remove("Title")), })) } fn write_command<S: Into<Value>>(&mut self, cmd: Command<S>) -> Result<u32> { let req = Request::new(cmd); let json = serde_json::to_string(&req).map_err(|err| { Error::new( ErrorKind::InvalidData, format!("failed to serialize json: {}", err), ) })?; trace!("writing: {}", json); self.file .write(json.as_bytes()) .and_then(|_| self.file.write_all(b"\n")) .and_then(|_| self.file.flush()) .and_then(|_| Ok(req.request_id)) } } #[derive(Debug)] enum Response { Song(SongInfo), Empty, } #[derive(Debug)] enum Message { FileLoaded, Unpause, Unknown, Response(u32, Value), } impl Message { fn parse(line: impl AsRef<str>) -> Result<Self> { let line = line.as_ref(); let val: Value = serde_json::from_str(&line) // .map_err(|err| Error::new(ErrorKind::InvalidData, err))?; if let Some(id) = val .get("request_id") .and_then(Value::as_u64) .map(|r| r as u32) { return Ok(Message::Response(id, val)); } let ok = Event::try_from_value(&val) .and_then(|ev| { Some(match ev { Event::Unpause => Message::Unpause, Event::FileLoaded => Message::FileLoaded, }) }) .unwrap_or(Message::Unknown); Ok(ok) } } #[derive(Serialize, PartialEq, Debug, Clone)] struct SongInfo { artist: String, title: String, album: String, } fn random_name(len: usize) -> String { std::iter::repeat_with(|| thread_rng().sample(rand::distributions::Alphanumeric)) .take(len) .collect() } fn create_drop_target(tx: SyncSender<PathBuf>) { use winit::ControlFlow; use winit::Event::WindowEvent; use winit::WindowEvent::{CloseRequested, DroppedFile}; let mut events_loop = winit::EventsLoop::new(); let _window = winit::WindowBuilder::new() .with_title("playlist generator for mpv") .with_dimensions((300., 200.).into()) .build(&events_loop) .unwrap(); events_loop.run_forever(|event| match event { WindowEvent { event: DroppedFile(path), .. } => { tx.send(path).unwrap(); ControlFlow::Continue } WindowEvent { event: CloseRequested, .. } => ControlFlow::Break, _ => ControlFlow::Continue, }); trace!("end of drop target") } fn main() { env_logger::Builder::from_default_env() .default_format_timestamp(false) .default_format_module_path(false) .init(); let (tx, rx) = sync_channel::<PathBuf>(2); let handle = thread::spawn(move || { let mut mpv = None; while let Ok(path) = rx.recv() { mpv.take(); // drop early let mut list = vec![]; Playlist::walk(&mut list, path); alphanumeric_sort::sort_path_slice(&mut list); match Playlist::make_temp(&list) { Ok(playlist) => { mpv.replace(Mpv::new(playlist)); } Err(err) => { error!("cannot make playlist: {}", err); continue; } } } trace!("ending recv loop"); }); create_drop_target(tx); let _ = handle.join(); } // fn playlist(&mut self) -> Option<Vec<String>> { // let count: u64 = self.get("playlist/count")?; // let list = (0..count) // .map(|i| format!("playlist/{}/filename", i)) // .filter_map(|f| self.get(&f)) // .collect(); // Some(list) // }
mod db; mod quadkey; mod web; use anyhow::Result; use clap::{App, Arg, SubCommand}; use log::info; use db::Database; #[macro_use] extern crate anyhow; #[tokio::main] async fn main() -> Result<()> { env_logger::init(); let matches = App::new("osm rust") .arg( Arg::with_name("db") .short("d") .long("db") .value_name("DB") .help("Path to sqlite db file") .default_value("osm.db") .takes_value(true), ) .subcommand( SubCommand::with_name("import") .about("imports OSM data") .arg( Arg::with_name("pbf") .help("Path to input osm.pbf file") .required(true), ), ) .get_matches(); let db_filename = matches.value_of("db").unwrap(); let database = Database::new(db_filename)?; if let Some(matches) = matches.subcommand_matches("import") { let pbf_filename = matches.value_of("pbf").unwrap(); database.import(pbf_filename)?; info!( "Nodes: {:?}, Links: {:?}", database.node_count()?, database.link_count()? ); } else { web::serve(database).await; } Ok(()) }
use crate::binding::{ blake2b_constant_BLAKE2B_KEYBYTES, blake2b_constant_BLAKE2B_OUTBYTES, blake2b_constant_BLAKE2B_PERSONALBYTES, blake2b_constant_BLAKE2B_SALTBYTES, blake2b_final, blake2b_init_key_with_param, blake2b_init_param, blake2b_param, blake2b_state, blake2b_update, }; use core::ffi::c_void; use core::mem::MaybeUninit; pub struct Blake2b { pub(crate) state: MaybeUninit<blake2b_state>, } impl Blake2b { pub fn uninit() -> Self { Blake2b { state: MaybeUninit::<blake2b_state>::uninit(), } } } pub struct Blake2bBuilder { pub(crate) param: blake2b_param, pub(crate) key_len: usize, pub(crate) key: [u8; blake2b_constant_BLAKE2B_KEYBYTES as usize], } impl Blake2bBuilder { /// In reality, most projects only use one or two blake2b hashers, /// which means there is not need to rebuild Blake2bBuilder again /// and again. This const function allows one to create a Rust /// constant builder, and use it across the project. Right now we /// only provide new_with_personal variant, since this is widely /// used in Nervos CKB. pub const fn new_with_personal( out_len: usize, personal: [u8; blake2b_constant_BLAKE2B_PERSONALBYTES as usize], ) -> Self { assert!(out_len >= 1 && out_len <= blake2b_constant_BLAKE2B_OUTBYTES as usize); let param = blake2b_param { digest_length: out_len as u8, key_length: 0, fanout: 1, depth: 1, leaf_length: 0, node_offset: 0, xof_length: 0, node_depth: 0, inner_length: 0, reserved: [0u8; 14usize], salt: [0u8; blake2b_constant_BLAKE2B_SALTBYTES as usize], personal, }; let key_len = 0; let key = [0u8; blake2b_constant_BLAKE2B_KEYBYTES as usize]; Blake2bBuilder { param, key_len, key, } } pub fn new(out_len: usize) -> Self { Self::new_with_personal( out_len, [0u8; blake2b_constant_BLAKE2B_PERSONALBYTES as usize], ) } pub fn salt(mut self, salt: &[u8]) -> Blake2bBuilder { let len = salt.len(); assert!(len <= blake2b_constant_BLAKE2B_SALTBYTES as usize); unsafe { ::core::ptr::copy_nonoverlapping(salt.as_ptr(), self.param.salt.as_mut_ptr(), len); } self } pub fn personal(mut self, personal: &[u8]) -> Blake2bBuilder { let len = personal.len(); assert!(len <= blake2b_constant_BLAKE2B_PERSONALBYTES as usize); unsafe { ::core::ptr::copy_nonoverlapping( personal.as_ptr(), self.param.personal.as_mut_ptr(), len, ); } self } pub fn key(mut self, key: &[u8]) -> Blake2bBuilder { let key_len = key.len(); assert!(key_len <= blake2b_constant_BLAKE2B_KEYBYTES as usize); self.param.key_length = key_len as u8; self.key_len = key_len; unsafe { ::core::ptr::copy_nonoverlapping(key.as_ptr(), self.key.as_mut_ptr(), key_len); } self } pub fn build(self) -> Blake2b { let mut blake2b = Blake2b::uninit(); self.build_from_ref(&mut blake2b); blake2b } /// Combined with new_with_personal, this can use the same builder /// to efficiently generate multiple different hashers. pub fn build_from_ref(&self, blake2b: &mut Blake2b) { if self.key_len == 0 { unsafe { blake2b_init_param( blake2b.state.as_mut_ptr(), &self.param as *const blake2b_param, ); } } else { unsafe { blake2b_init_key_with_param( blake2b.state.as_mut_ptr(), &self.param as *const blake2b_param, self.key.as_ptr() as *const c_void, self.key_len, ); } } } } impl Blake2b { pub fn update(&mut self, data: &[u8]) { unsafe { blake2b_update( self.state.as_mut_ptr(), data.as_ptr() as *const c_void, data.len(), ); } } pub fn finalize(mut self, dst: &mut [u8]) { self.finalize_from_ref(dst); } /// This is the same as finalize, but allows one to call the function /// via a mutable reference, which can result in better performance /// if one can manually control the times this function is invoked. pub fn finalize_from_ref(&mut self, dst: &mut [u8]) { unsafe { blake2b_final( self.state.as_mut_ptr(), dst.as_mut_ptr() as *mut c_void, dst.len(), ); } } } pub fn blake2b(key: &[u8], data: &[u8], dst: &mut [u8]) { let mut blake2b = Blake2bBuilder::new(dst.len()).key(key).build(); blake2b.update(data); blake2b.finalize(dst) } #[cfg(test)] mod tests { use super::Blake2bBuilder; use faster_hex::{hex_decode, hex_string}; use serde_derive::Deserialize; use std::fs::File; use std::io::BufReader; use std::path::Path; use std::string::String; use std::vec; use std::vec::Vec; #[derive(Deserialize, Debug)] struct TestItem { outlen: usize, out: String, input: String, key: String, salt: String, personal: String, } #[test] fn test_full() { let test_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/test.json"); let f = File::open(test_path).unwrap(); let reader = BufReader::new(f); let tests: Vec<TestItem> = serde_json::from_reader(reader).unwrap(); for test in tests { let mut hash = vec![0u8; test.outlen]; let mut blake2b = Blake2bBuilder::new(test.outlen) .key(&unhex(test.key.as_bytes())) .personal(&unhex(test.personal.as_bytes())) .salt(&unhex(test.salt.as_bytes())) .build(); blake2b.update(&unhex(test.input.as_bytes())); blake2b.finalize(&mut hash); assert_eq!(hex_string(&hash), test.out); } } fn unhex(src: &[u8]) -> Vec<u8> { let len = src.len() / 2; let mut ret = vec![0u8; len]; if !src.is_empty() { hex_decode(src, &mut ret).unwrap(); } ret } }
use crate::block::Block; use crate::chunk::ChunkGridCoordinate; pub const CHUNK_WIDTH: usize = 16; pub const CHUNK_DEPTH: usize = 16; pub const CHUNK_HEIGHT: usize = 256; const CHUNK_SIZE: usize = CHUNK_WIDTH * CHUNK_DEPTH * CHUNK_HEIGHT; type Blocks = Vec<Block>; /// computes flat array index from a 3d coordinate #[inline] fn at(x: usize, y: usize, z: usize) -> usize { (x * CHUNK_WIDTH) + (y * CHUNK_HEIGHT) + z } #[derive(Clone)] pub struct Chunk { blocks: Blocks, pub coords: ChunkGridCoordinate, } impl Chunk { pub fn new(coords: ChunkGridCoordinate) -> Self { Self { blocks: vec![Block { id: 0 }; CHUNK_SIZE], coords, } } /// returns the block at relative position x, y ,z pub fn block(&self, x: usize, y: usize, z: usize) -> Block { self.blocks[at(x, y, z)] } /// replaces the block at relative position x, y, z pub fn set_block(&mut self, x: usize, y: usize, z: usize, block: Block) { self.blocks[at(x, y, z)] = block } } #[cfg(test)] mod tests { use super::*; #[cfg(feature = "nightly")] use test::Bencher; #[test] fn at_returns_within_volume() { for x in 0..CHUNK_WIDTH { for z in 0..CHUNK_DEPTH { for y in 0..CHUNK_HEIGHT { let i = at(x, y, z); assert!((0..CHUNK_SIZE).contains(&i)); } } } } #[test] fn at_returns_unique_values() { let mut s = std::collections::HashSet::new(); for x in 0..CHUNK_WIDTH { for z in 0..CHUNK_DEPTH { for y in 0..CHUNK_HEIGHT { let i = at(x, y, z); assert!(!s.contains(&i)); s.insert(i); } } } } #[cfg(feature = "nightly")] #[bench] fn bench_at(b: &mut Bencher) { b.iter(|| { let mut chunk = Chunk::new(ChunkGridCoordinate { x: 0, z: 0 }); for x in 0..CHUNK_WIDTH { for z in 0..CHUNK_DEPTH { for y in 0..CHUNK_HEIGHT { chunk.set_block(x, y, z, Block { id: 1 }); } } } }) } #[cfg(feature = "nightly")] #[bench] fn bench_flat_vec(b: &mut Bencher) { b.iter(|| vec![Block { id: 0 }; CHUNK_SIZE]); } #[cfg(feature = "nightly")] #[bench] fn bench_nested_vec(b: &mut Bencher) { b.iter(|| vec![vec![vec![Block { id: 0 }; CHUNK_DEPTH]; CHUNK_HEIGHT]; CHUNK_WIDTH]); } }
use base64; use crypto::buffer::{BufferResult, ReadBuffer, WriteBuffer}; use crypto::{aes, blockmodes, buffer, symmetriccipher}; use rand::prelude::*; use rand::{OsRng, Rng}; use std::fs::File; use std::io::prelude::*; use std::io::BufRead; use std::io::BufReader; use std::str; // AES in ECB mode fn decrypt( encrypted_data: &[u8], key: &[u8], ) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> { let mut decryptor = aes::ecb_decryptor(aes::KeySize::KeySize128, key, blockmodes::NoPadding); let mut final_result = Vec::<u8>::new(); let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data); let mut buffer = [0; 4096]; let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer); loop { let result = try!(decryptor.decrypt(&mut read_buffer, &mut write_buffer, true)); final_result.extend( write_buffer .take_read_buffer() .take_remaining() .iter() .map(|&i| i), ); match result { BufferResult::BufferUnderflow => break, BufferResult::BufferOverflow => {} } } Ok(final_result) } #[cfg(test)] mod tests { use super::*; #[test] fn test_aes() { let mut f = File::open("1_challenge_7.txt").unwrap(); let mut buf_reader = BufReader::new(f); let mut buf = Vec::<u8>::new(); for line in buf_reader.lines() { buf.extend(line.unwrap().into_bytes().iter().cloned()) } let cipher = base64::decode(&buf).unwrap(); // println!("{:?}", cipher); let key = b"YELLOW SUBMARINE"; // let mut iv: [u8; 8] = [0; 8]; // let mut rng = OsRng::new().ok().unwrap(); // rng.fill_bytes(&mut iv); let decrypted_data = decrypt(&cipher, key).ok().unwrap(); println!("{:?}", String::from_utf8(decrypted_data).unwrap()); } }
use Unit::*; #[derive(Debug)] enum Unit { Op(char), Num(i32), } pub fn calculate(s: String) -> i32 { fn eval(stack: &mut Vec<Unit>) { let mut tmp = None; let mut tmpc = '+'; while let Some(unit) = stack.pop() { match unit { Num(i) => { if let Some(aa) = tmp { tmp = Some(match tmpc { '+' => aa + i, '-' => aa - i, _ => panic!(), }); } else { tmp = Some(i); } } Op(c) => { if c == ')' { break; } tmpc = c; } } } stack.push(Num(tmp.unwrap())) } let mut tmp_digit = 0; let mut tmp_order = 0; let mut stack = vec![Op(')')]; for c in s.chars().rev() { if '0' <= c && c <= '9' { tmp_digit += (c as u8 - '0' as u8) as i32 * 10i32.pow(tmp_order); tmp_order += 1; } else if c != ' ' { stack.push(Num(tmp_digit)); tmp_digit = 0; tmp_order = 0; stack.push(Op(c)); if c == '(' { stack.pop(); eval(&mut stack); } } } stack.push(Num(tmp_digit)); eval(&mut stack); if let Num(i) = stack[0] { i } else { 0 } }
use crate::util::Part; pub fn solve(input:String, part:Part) -> String { let result = match part { Part::Part1 => part1(input.as_str()), Part::Part2 => part2(input.as_str()) }; format!("{}",result) } fn part1(input:&str) -> String { let input = to_vec(input.trim()); fft(input, 100) } fn part2(input:&str) -> String { let input = to_vec(input); fft(input, 100) } const BASE_PATTERN:[i32;4] = [0,1,0,-1]; fn get_base_pattern(index:u32, output_index:u32) -> i32 { let pattern_len = 4 * output_index; let pattern_index = ((index) % pattern_len) / output_index; BASE_PATTERN[pattern_index as usize] } fn fft(input:Vec<i32>,steps:usize) -> String { let mut next_input = input.clone(); next_input.insert(0,0); for _ in 1..(steps+1) { let mut tmp = vec![]; tmp.insert(0, 0); for n in 1..next_input.len()+1 { let new_value : i32 = (next_input.iter().enumerate() .map(|(i, s)| s * get_base_pattern(i as u32, n as u32)) .sum::<i32>() % 10).abs(); tmp.push(new_value); } next_input = tmp; //next_input.remove(0); //next_input.iter_mut().enumerate().for_each( |(i, e)| *e = tmp[i] ); //println!("{:?}", next_input); } next_input.remove(0); next_input.iter().map(|num| num.to_string()).collect::<String>()[..8].to_string() } fn to_vec(input:&str) -> Vec<i32> { let vector : Vec<i32> = input.chars().map( |ch| (ch as i32 - 0x30)).collect(); vector } fn to_vec_times(input:&str,times:usize) -> Vec<i32> { let mut out:String = String::new(); for _ in 0..times { out.push_str(input.trim()); } out.chars().map(|ch| (ch as i32 - 0x30)).collect() } #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; const INPUT_DATA:&str ="59766299734185935790261115703620877190381824215209853207763194576128635631359682876612079355215350473577604721555728904226669021629637829323357312523389374096761677612847270499668370808171197765497511969240451494864028712045794776711862275853405465401181390418728996646794501739600928008413106803610665694684578514524327181348469613507611935604098625200707607292339397162640547668982092343405011530889030486280541249694798815457170337648425355693137656149891119757374882957464941514691345812606515925579852852837849497598111512841599959586200247265784368476772959711497363250758706490540128635133116613480058848821257395084976935351858829607105310340"; #[test] fn test1() { let mut v = vec![]; for i in 0..20 { v.push(get_base_pattern(i, 3)); } println!("{:?}",v); } #[test] fn test2() { let input = vec![1,2,3,4,5,6,7,8]; let res = fft(input, 4); println!("{:?}",res); assert_eq!("01029498", res); } #[test] fn test3() { let input = to_vec("80871224585914546619083218645595"); let res = fft(input, 100); println!("{:?}",res); assert_eq!("24176176", res); } #[test] fn test4() { let input = to_vec("19617804207202209144916044189917"); let res = fft(input, 100); println!("{:?}",res); assert_eq!("73745418", res); } #[test] fn test_part1() { let input = to_vec("59766299734185935790261115703620877190381824215209853207763194576128635631359682876612079355215350473577604721555728904226669021629637829323357312523389374096761677612847270499668370808171197765497511969240451494864028712045794776711862275853405465401181390418728996646794501739600928008413106803610665694684578514524327181348469613507611935604098625200707607292339397162640547668982092343405011530889030486280541249694798815457170337648425355693137656149891119757374882957464941514691345812606515925579852852837849497598111512841599959586200247265784368476772959711497363250758706490540128635133116613480058848821257395084976935351858829607105310340"); let res = fft(input, 100); println!("{:?}",res); assert_eq!("18933364", res); } #[test] fn test_part2_test2() { let input = to_vec_times(INPUT_DATA, 10); let res = fft(input, 10); println!("{:?}",res); } }
/********************************************** > File Name : maximumRequests.rs > Author : lunar > Email : lunar_ubuntu@qq.com > Created Time : Sun 02 Jan 2022 09:46:06 PM CST > Location : Shanghai > Copyright@ https://github.com/xiaoqixian **********************************************/ use std::collections::VecDeque; struct Edge { from: usize, to: usize, cap: i32, cost: i32 } impl Edge { fn new(from: usize, to: usize, cap: i32, cost: i32) -> Self { Self { from, to, cap, cost } } } struct Solution { edges: Vec<Edge>, edge_indice: [Vec<usize>; 22], dist: [i32; 22], prev: [usize; 22], increase_flow: [i32; 22], visited: [bool; 22], max_flow: i32, min_cost: i32 } impl Solution { fn new() -> Self { Self { edges: Vec::new(), edge_indice: Default::default(), dist: [0; 22], prev: [0; 22], increase_flow: [0; 22], visited: [false; 22], max_flow: 0, min_cost: 0 } } fn add_edge(&mut self, from: usize, to: usize, cap: i32, cost: i32) { self.edges.push(Edge::new(from, to, cap, cost)); self.edges.push(Edge::new(to, from, 0, -cost)); let size = self.edges.len(); self.edge_indice[from].push(size - 2); self.edge_indice[to].push(size - 1); println!("edge_indice[{}]: {:?}", from, self.edge_indice[from]); println!("edge_indice[{}]: {:?}", to, self.edge_indice[to]); } fn spfa(&mut self, s: usize, t: usize) -> i32 { let mut deq: VecDeque<usize> = VecDeque::new(); let inf = 0x3f3f3f3f; self.dist.fill(inf); self.dist[s] = 0; self.increase_flow[s] = inf; self.increase_flow[t] = 0; deq.push_back(s); loop { let v = match deq.pop_front() { None => {break;}, Some(v) => v }; self.visited[v] = false; for index in &self.edge_indice[v] { let v_edge = &self.edges[*index]; let to = v_edge.to; if v_edge.cap == 0 || self.dist[to] <= self.dist[v] + v_edge.cost { continue; } self.increase_flow[to] = if self.increase_flow[v] < v_edge.cap { self.increase_flow[v] } else { v_edge.cap }; self.dist[to] = self.dist[v] + v_edge.cost; self.prev[to] = *index; if !self.visited[to] { self.visited[to] = true; deq.push_back(to); } } } self.increase_flow[t] } fn update(&mut self, s: usize, t: usize) { self.max_flow += self.increase_flow[t]; let mut u = t; let f = self.increase_flow[t]; while u != s { self.edges[self.prev[u]].cap -= f; self.edges[self.prev[u] ^ 1].cap += f; self.min_cost += f * self.edges[self.prev[u]].cost; u = self.edges[self.prev[u] ^ 1].to; } } pub fn maximum_requests(n: i32, requests: Vec<Vec<i32>>) -> i32 { let mut so = Self::new(); let mut degrees = [0; 22]; let mut movement = [[0; 22]; 22]; let s = n as usize; let t = (n+1) as usize; for req in requests.iter() { let from = req[0] as usize; let to = req[1] as usize; movement[from][to] += 1; degrees[from] += 1; degrees[to] -= 1; } for i in 0..(n as usize - 1) { for k in 0..(n as usize - 1) { if i != k && movement[i][k] != 0 { so.add_edge(i, k, movement[i][k], 1); } } if degrees[i] > 0 { so.add_edge(s, i, degrees[i], 0); } else if degrees[i] < 0 { so.add_edge(i, t, -degrees[i], 0); } } while so.spfa(s, t) != 0 { so.update(s, t); } requests.len() as i32 - so.min_cost } } fn main() { let requests = vec![vec![0,1],vec![1,0],vec![0,1],vec![1,2],vec![2,0],vec![3,4]]; println!("{}", Solution::maximum_requests(20, requests)); }
use parse_display::Display; use semval::{context::Context as ValidationContext, Validate}; use serde::{Deserialize, Serialize}; #[derive( Copy, Clone, Debug, Default, Deserialize, Display, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, )] #[serde(transparent)] pub struct ItemId(u16); impl ItemId { #[inline] pub fn into_inner(self) -> u16 { self.0 } } impl From<u16> for ItemId { #[inline] fn from(comic_id: u16) -> Self { Self(comic_id) } } impl Validate for ItemId { type Invalidity = ItemIdInvalidity; fn validate(&self) -> semval::ValidationResult<Self::Invalidity> { ValidationContext::new() .invalidate_if(self.0 < 1, ItemIdInvalidity::MinValue) .into() } } #[derive(Copy, Clone, Debug, Display, Eq, PartialEq)] pub enum ItemIdInvalidity { #[display("itemId cannot be 0")] MinValue, }
use bls12_381::Scalar; mod bits_contract; mod vm; use bits_contract::load_zkvm; fn main() -> std::result::Result<(), vm::ZKVMError> { let mut vm = load_zkvm(); vm.setup(); let params = vec![( 0, Scalar::from_raw([ 0xb981_9dc8_2d90_607e, 0xa361_ee3f_d48f_df77, 0x52a3_5a8c_1908_dd87, 0x15a3_6d1f_0f39_0d88, ]), )]; vm.initialize(&params)?; let proof = vm.prove(); let public = vm.public(); assert_eq!(public.len(), 0); assert!(vm.verify(&proof, &public)); Ok(()) }
#![allow(missing_docs)] use std::cell::RefCell; use std::marker::PhantomData; use std::rc::Rc; use std::sync::mpsc::SyncSender; use super::reactor::Reactor; use super::SubgraphId; pub trait Give<T> { fn give(&self, t: T) -> bool; } pub struct Buffer<T>(pub(crate) Rc<RefCell<Vec<T>>>); impl<T> Give<T> for Buffer<T> { fn give(&self, t: T) -> bool { (*self.0).borrow_mut().push(t); true } } impl<T> Default for Buffer<T> { fn default() -> Self { Buffer(Rc::new(RefCell::new(Vec::new()))) } } impl<T> Clone for Buffer<T> { fn clone(&self) -> Self { Buffer(self.0.clone()) } } impl<T> Give<T> for SyncSender<T> { fn give(&self, t: T) -> bool { self.send(t).is_ok() } } // TODO(justin): this thing should probably give Vecs to the Givable, and buffer // stuff up and automatically flush, but postponing that until we have occasion // to benchmark it. pub struct Input<T, G> where G: Give<T>, { reactor: Reactor, sg_id: SubgraphId, givable: G, _marker: PhantomData<T>, } impl<T, G> Input<T, G> where G: Give<T>, { pub fn new(reactor: Reactor, sg_id: SubgraphId, givable: G) -> Self { Input { reactor, sg_id, givable, _marker: PhantomData, } } pub fn give(&self, t: T) { self.givable.give(t); } pub fn flush(&self) { self.reactor.trigger(self.sg_id).unwrap(/* TODO(justin) */); } }
use colored::*; use std::fmt::Write as FmtWrite; use std::io; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::process; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex}; use std::thread; use anyhow::{Context, Result}; pub use file::{set_exec_permision, File}; pub use var::{ generate_array_env_var, generate_env_var, generate_env_vars, var_name, EnvValue, EnvVar, ENV_ENVIRONMENT_VAR, ENV_SETUP_VAR, }; mod file; pub mod kind; mod var; #[derive(Debug)] pub struct Output { pub status: i32, pub stdout: String, pub stderr: String, } impl Output { pub fn new() -> Self { Self { status: 0, stdout: "".into(), stderr: "".into(), } } } impl From<process::Output> for Output { fn from(output: process::Output) -> Self { Self { status: output.status.code().map_or(0, |code| code), stderr: String::from_utf8_lossy(output.stderr.as_ref()).into_owned(), stdout: String::from_utf8_lossy(output.stdout.as_ref()).into_owned(), } } } pub fn run_as_stream(file: &PathBuf, vars: &Vec<EnvVar>, args: &Vec<String>) -> Result<Output> { let file = file.canonicalize()?; let mut command = Command::new(&file); for env_var in vars.iter() { command.env(env_var.var().to_env_var(), env_var.env_value().to_string()); } if let Some(parent) = file.parent() { command.current_dir(parent); } let mut child = command .stdout(Stdio::piped()) .stdin(Stdio::piped()) .stderr(Stdio::piped()) .args(args) .spawn() .context(format!("command {} fail", &file.to_string_lossy()))?; let mut command_stdin = child.stdin.take().expect("fail to get stdin"); let read_stdin = thread::spawn(move || loop { // /!\ Manually tested let mut buff_writer = BufWriter::new(&mut command_stdin); let mut buffer = String::new(); io::stdin().read_line(&mut buffer).unwrap(); buff_writer.write_all(buffer.as_str().as_bytes()).unwrap(); }); let output = Arc::new(Mutex::new(Output::new())); let read_stdout = if let Some(stdout) = child.stdout.take() { let output = Arc::clone(&output); Some(thread::spawn(move || { let buf = BufReader::new(stdout); let mut buffer = String::new(); for line in buf.lines() { let line = line.unwrap(); writeln!(&mut buffer, "{}", line).unwrap(); println!("{}", line.normal().clear()); } let mut output = output.lock().unwrap(); output.stdout = buffer; })) } else { None }; let read_err = if let Some(stderr) = child.stderr.take() { let output = Arc::clone(&output); Some(thread::spawn(move || { let buf = BufReader::new(stderr); let mut buffer = String::new(); for line in buf.lines() { let line = line.unwrap(); writeln!(&mut buffer, "{}", line).unwrap(); println!("{}", line.red()); } let mut output = output.lock().unwrap(); output.stderr = buffer; })) } else { None }; if let Some(read_err) = read_err { read_err.join().expect("fail to wait read_err"); } if let Some(read_stdout) = read_stdout { read_stdout.join().expect("fail to wait read_stdout"); } drop(read_stdin); let exit_status = child.wait().unwrap(); { let mut output = output.lock().unwrap(); output.status = exit_status.code().unwrap_or_default(); } let output = Arc::try_unwrap(output).unwrap(); let output = output.into_inner().unwrap(); Ok(output) } #[cfg(test)] mod tests { use std::path::PathBuf; use cli_integration_test::IntegrationTestEnvironment; use crate::run_file::run_as_stream; #[test] fn run_integration_test_stream() { let mut e = IntegrationTestEnvironment::new("run_integration_test"); e.add_file( "run.sh", r#"#!/bin/bash echo TEST echo ERR >> /dev/stderr "#, ); e.setup(); e.set_exec_permission("run.sh").unwrap(); let output = run_as_stream( &e.path().unwrap().join(PathBuf::from("run.sh")), &vec![], &vec![], ) .unwrap(); assert_eq!(output.stdout, "TEST\n".to_string()); assert_eq!(output.stderr, "ERR\n".to_string()); assert_eq!(output.status, 0); } #[test] fn run_integration_test_stream_with_args() { let mut e = IntegrationTestEnvironment::new("run_integration_test"); e.add_file( "run.sh", r#"#!/bin/bash echo ARG = $1 "#, ); e.setup(); e.set_exec_permission("run.sh").unwrap(); let output = run_as_stream( &e.path().unwrap().join(PathBuf::from("run.sh")), &vec![], &vec!["TEST_ARG".to_string()], ) .unwrap(); assert_eq!(output.stdout, "ARG = TEST_ARG\n".to_string()); assert_eq!(output.status, 0); } }
/* 3 5 ..... .#.#. ..... */ fn main() { // let h : i32 = 3; // let w : i32 = 5; // let mut lines = Vec::new(); // lines.push("....."); // lines.push(".#.#."); // lines.push("....."); let tmp = read_line(); let h = tmp[0]; let w = tmp[1]; let mut lines = Vec::new(); for _ in 0..h { let s = read_line_str(); lines.push(s); } let mut cells : Vec<Vec<i32>> = Vec::new(); for i in 0..h { let mut vec = Vec::new(); for j in lines[i as usize].chars() { if j == '.' { vec.push(0); } else { vec.push(-1); } } cells.push(vec); } for y in 0..h as i32 { for x in 0..w as i32 { if cells[y as usize][x as usize] == -1 { // search for dy in (-1 as i32)..2 { for dx in (-1 as i32)..2 { if dx == 0 && dy == 0 { continue; } let nx = x + dx; let ny = y + dy; if nx < 0 || ny < 0 || nx >= w || ny >= h { continue; } if cells[ny as usize][nx as usize] == -1 { continue; } cells[ny as usize][nx as usize] += 1; } } } } } for vec in cells { for v in vec { if v == -1 { print!("#"); } else { print!("{}", v); } } println!(""); } } fn read_line() -> Vec<i32> { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let v = s.trim() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect(); return v } fn read_line_str() -> String { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); return s.replace("\n", ""); }
mod dbus_helper; mod error; pub mod methods; mod runtime; pub mod signals; mod status; pub use self::error::DaemonError; pub use self::runtime::DaemonRuntime; pub use self::signals::SignalEvent; pub use self::status::DaemonStatus; use self::dbus_helper::DbusFactory; use crate::misc; use crate::recovery::{ self, ReleaseFlags as RecoveryReleaseFlags, UpgradeMethod as RecoveryUpgradeMethod, }; use crate::release::{self, FetchEvent, ReleaseError, UpgradeMethod as ReleaseUpgradeMethod}; use crate::{signal_handler, DBUS_IFACE, DBUS_NAME, DBUS_PATH}; use apt_cli_wrappers::apt_upgrade; use apt_fetcher::apt_uris::{apt_uris, AptUri}; use atomic::Atomic; use crossbeam_channel::{bounded, Receiver, Sender}; use dbus::tree::{Factory, Signal}; use dbus::{self, BusType, Connection, Message, NameFlag}; use logind_dbus::LoginManager; use num_traits::FromPrimitive; use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; use std::rc::Rc; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; use tokio::runtime::Runtime; #[derive(Debug)] pub enum Event { FetchUpdates { apt_uris: Vec<AptUri>, download_only: bool }, PackageUpgrade, RecoveryUpgrade(RecoveryUpgradeMethod), ReleaseUpgrade { how: ReleaseUpgradeMethod, from: String, to: String }, } pub struct Daemon { event_tx: Sender<Event>, dbus_rx: Receiver<SignalEvent>, connection: Arc<Connection>, status: Arc<Atomic<DaemonStatus>>, sub_status: Arc<Atomic<u8>>, fetching_state: Arc<Atomic<(u64, u64)>>, } impl Daemon { pub fn new(_factory: &DbusFactory) -> Result<Self, DaemonError> { let connection = Arc::new( Connection::get_private(BusType::System).map_err(DaemonError::PrivateConnection)?, ); connection .register_name(DBUS_NAME, NameFlag::ReplaceExisting as u32) .map_err(DaemonError::RegisterName)?; // Only accept one event at a time. let (event_tx, event_rx) = bounded(4); // Dbus events are checked at least once per second, so we will allow buffering some events. let (dbus_tx, dbus_rx) = bounded(64); // The status of the event loop thread, which indicates the current task, or lack thereof. let status = Arc::new(Atomic::new(DaemonStatus::Inactive)); // As well as the current sub-status, if relevant. let sub_status = Arc::new(Atomic::new(0u8)); // In case a UI is being constructed after a task has already started, it may request // for the curernt progress of a task. let prog_state = Arc::new(Atomic::new((0u64, 0u64))); { let status = status.clone(); let sub_status = sub_status.clone(); let prog_state = prog_state.clone(); info!("spawning background event thread"); thread::spawn(move || { let mut logind = match LoginManager::new() { Ok(logind) => Some(logind), Err(why) => { error!("failed to connect to logind: {}", why); None } }; // Create the tokio runtime to share between requests. let runtime = &mut Runtime::new().expect("failed to initialize tokio runtime"); let mut runtime = DaemonRuntime::new(runtime); let fetch_closure = Arc::new({ let prog_state_ = prog_state.clone(); let dbus_tx = dbus_tx.clone(); move |event| match event { FetchEvent::Fetched(uri) => { let (current, npackages) = prog_state_.load(Ordering::SeqCst); prog_state_.store((current + 1, npackages), Ordering::SeqCst); let _ = dbus_tx.send(SignalEvent::Fetched( uri.name, current as u32 + 1, npackages as u32, )); } FetchEvent::Fetching(uri) => { let _ = dbus_tx.send(SignalEvent::Fetching(uri.name)); } FetchEvent::Init(total) => { prog_state_.store((0, total as u64), Ordering::SeqCst); } } }); while let Ok(event) = event_rx.recv() { let _suspend_lock = logind.as_mut().and_then(|logind| { match logind .connect() .inhibit_suspend("pop-upgrade", "performing upgrade event") { Ok(lock) => Some(lock), Err(why) => { error!("failed to inhibit suspension: {}", why); None } } }); match event { Event::FetchUpdates { apt_uris, download_only } => { info!("fetching packages for {:?}", apt_uris); let npackages = apt_uris.len() as u32; prog_state.store((0, u64::from(npackages)), Ordering::SeqCst); let result = runtime.apt_fetch(apt_uris, fetch_closure.clone()); prog_state.store((0, 0), Ordering::SeqCst); let result = result.and_then(|_| { if download_only { Ok(()) } else { apt_upgrade(|event| { let _ = dbus_tx.send(SignalEvent::Upgrade(event)); }) .map_err(ReleaseError::Upgrade) } }); let _ = dbus_tx.send(SignalEvent::FetchResult(result.map(|_| ()))); } Event::PackageUpgrade => { info!("upgrading packages"); runtime.package_upgrade(|event| { let _ = dbus_tx.send(SignalEvent::Upgrade(event)); }); } Event::RecoveryUpgrade(action) => { info!("attempting recovery upgrade with {:?}", action); let prog_state_ = prog_state.clone(); let result = recovery::recovery( &action, { let dbus_tx = dbus_tx.clone(); move |p, t| { prog_state_.store((p, t), Ordering::SeqCst); let _ = dbus_tx .send(SignalEvent::RecoveryDownloadProgress(p, t)); } }, { let dbus_tx = dbus_tx.clone(); let sub_status = sub_status.clone(); move |status| { sub_status.store(status as u8, Ordering::SeqCst); let _ = dbus_tx.send(SignalEvent::RecoveryUpgradeEvent(status)); } }, ); let _ = dbus_tx.send(SignalEvent::RecoveryUpgradeResult(result)); } Event::ReleaseUpgrade { how, from, to } => { info!( "attempting release upgrade, using a {}", <&'static str>::from(how) ); let progress = { let dbus_tx = dbus_tx.clone(); let sub_status = sub_status.clone(); move |event| { let _ = dbus_tx.send(SignalEvent::ReleaseUpgradeEvent(event)); sub_status.store(event as u8, Ordering::SeqCst); } }; let result = runtime.upgrade( how, &from, &to, &progress, fetch_closure.clone(), &|event| { let _ = dbus_tx.send(SignalEvent::Upgrade(event)); }, ); let _ = dbus_tx.send(SignalEvent::ReleaseUpgradeResult(result)); } } status.store(DaemonStatus::Inactive, Ordering::SeqCst); info!("event processed"); } }); } Ok(Daemon { event_tx, dbus_rx, connection, fetching_state: prog_state, status, sub_status }) } pub fn init() -> Result<(), DaemonError> { info!("initializing daemon"); // TODO: Enable when ready // signal_handler::init(); let factory = Factory::new_fn::<()>(); let dbus_factory = DbusFactory::new(&factory); let daemon = Rc::new(RefCell::new(Self::new(&dbus_factory)?)); let fetch_result = Arc::new( dbus_factory.signal(signals::PACKAGE_FETCH_RESULT).sarg::<u8>("status").consume(), ); let fetching_package = Arc::new( dbus_factory.signal(signals::PACKAGE_FETCHING).sarg::<&str>("package").consume(), ); let fetched_package = Arc::new( dbus_factory .signal(signals::PACKAGE_FETCHED) .sarg::<&str>("package") .sarg::<u32>("completed") .sarg::<u32>("total") .consume(), ); let recovery_download_progress = Arc::new( dbus_factory .signal(signals::RECOVERY_DOWNLOAD_PROGRESS) .sarg::<u64>("current") .sarg::<u64>("total") .consume(), ); let recovery_event = Arc::new(dbus_factory.signal(signals::RECOVERY_EVENT).sarg::<u8>("event").consume()); let recovery_result = Arc::new(dbus_factory.signal(signals::RECOVERY_RESULT).sarg::<u8>("result").consume()); let release_event = Arc::new(dbus_factory.signal(signals::RELEASE_EVENT).sarg::<u8>("event").consume()); let release_result = Arc::new(dbus_factory.signal(signals::RELEASE_RESULT).sarg::<u8>("result").consume()); let upgrade_event = Arc::new( dbus_factory .signal(signals::PACKAGE_UPGRADE) .sarg::<HashMap<&str, String>>("event") .consume(), ); let interface = factory .interface(DBUS_IFACE, ()) .add_m(methods::fetch_updates(daemon.clone(), &dbus_factory)) .add_m(methods::package_upgrade(daemon.clone(), &dbus_factory)) .add_m(methods::recovery_upgrade_file(daemon.clone(), &dbus_factory)) .add_m(methods::recovery_upgrade_release(daemon.clone(), &dbus_factory)) .add_m(methods::release_check(daemon.clone(), &dbus_factory)) .add_m(methods::release_repair(daemon.clone(), &dbus_factory)) .add_m(methods::release_upgrade(daemon.clone(), &dbus_factory)) .add_m(methods::status(daemon.clone(), &dbus_factory)) .add_s(fetch_result.clone()) .add_s(fetched_package.clone()) .add_s(fetching_package.clone()) .add_s(recovery_download_progress.clone()) .add_s(recovery_event.clone()) .add_s(recovery_result.clone()) .add_s(upgrade_event.clone()); let (connection, receiver) = { let daemon = daemon.borrow(); (daemon.connection.clone(), daemon.dbus_rx.clone()) }; let tree = factory .tree(()) .add(factory.object_path(DBUS_PATH, ()).introspectable().add(interface)); tree.set_registered(&connection, true).map_err(DaemonError::TreeRegister)?; connection.add_handler(tree); info!("daemon registered -- listening for new events"); release::release_fetch_cleanup(); loop { connection.incoming(1000).next(); while let Ok(dbus_event) = receiver.try_recv() { Self::send_signal_message( &connection, match &dbus_event { SignalEvent::FetchResult(result) => Self::signal_message(&fetch_result) .append1(match result { Ok(_) => 0u8, Err(_) => 1, }), SignalEvent::Fetched(name, completed, total) => { info!("{}", dbus_event); Self::signal_message(&fetched_package).append3(&name, completed, total) } SignalEvent::Fetching(name) => { info!("{}", dbus_event); Self::signal_message(&fetching_package).append1(&name) } SignalEvent::RecoveryDownloadProgress(progress, total) => { Self::signal_message(&recovery_download_progress) .append2(progress, total) } SignalEvent::RecoveryUpgradeEvent(event) => { info!("{}", dbus_event); Self::signal_message(&recovery_event).append1(*event as u8) } SignalEvent::RecoveryUpgradeResult(result) => { info!("{}", dbus_event); Self::signal_message(&recovery_result).append1(match result { Ok(_) => 0u8, Err(_) => 1, }) } SignalEvent::ReleaseUpgradeEvent(event) => { info!("{}", dbus_event); Self::signal_message(&release_event).append1(*event as u8) } SignalEvent::ReleaseUpgradeResult(result) => { info!("{}", dbus_event); Self::signal_message(&release_result).append1(match result { Ok(_) => 0u8, Err(_) => 1, }) } SignalEvent::Upgrade(event) => { info!("{}", dbus_event); Self::signal_message(&upgrade_event) .append1(event.clone().into_dbus_map()) } }, ) } } } fn fetch_apt_uris(args: &[String]) -> Result<Vec<AptUri>, String> { apt_uris(&["full-upgrade"]) .and_then(|mut upgrades| { if args.is_empty() { return Ok(upgrades); } let args = { let mut targs = Vec::with_capacity(args.len() + 1); targs.push("install"); targs.extend(args.iter().map(|x| x.as_str())); targs }; let uris = apt_uris(&args)?; upgrades.extend_from_slice(&uris); Ok(upgrades) }) .map_err(|why| format!("unable to fetch apt URIs: {}", why)) } fn fetch_updates( &mut self, additional_packages: &[String], download_only: bool, ) -> Result<(bool, u32), String> { info!("fetching updates for the system, including {:?}", additional_packages); let apt_uris = Self::fetch_apt_uris(additional_packages)?; if apt_uris.is_empty() { info!("no updates available to fetch"); return Ok((false, 0)); } let npackages = apt_uris.len() as u32; let event = Event::FetchUpdates { apt_uris, download_only }; self.submit_event(event)?; Ok((true, npackages)) } fn package_upgrade(&mut self) -> Result<(), String> { info!("upgrading packages for the release"); self.submit_event(Event::PackageUpgrade)?; Ok(()) } fn recovery_upgrade_file(&mut self, path: &str) -> Result<(), String> { info!("using {} to upgrade the recovery partition", path); let event = Event::RecoveryUpgrade(RecoveryUpgradeMethod::FromFile(PathBuf::from(path))); self.submit_event(event)?; Ok(()) } fn recovery_upgrade_release( &mut self, version: &str, arch: &str, flags: u8, ) -> Result<(), String> { info!("upgrading the recovery partition to {}-{}", version, arch); let event = Event::RecoveryUpgrade(RecoveryUpgradeMethod::FromRelease { version: if version.is_empty() { None } else { Some(version.into()) }, arch: if arch.is_empty() { None } else { Some(arch.into()) }, flags: RecoveryReleaseFlags::from_bits_truncate(flags), }); self.submit_event(event)?; Ok(()) } fn release_check(&mut self) -> Result<(String, String, Option<u16>), String> { info!("performing a release check"); let (current, next, available) = release::check().map_err(|why| format!("{}", why))?; let mut buffer = String::new(); info!( "Release {{ current: \"{}\", next: \"{}\", available: {} }}", current, next, misc::format_build_number(available, &mut buffer) ); Ok((current, next, available)) } fn release_upgrade(&mut self, how: u8, from: &str, to: &str) -> Result<(), String> { info!("upgrading release from {} to {}, with {}", from, to, how); let how = ReleaseUpgradeMethod::from_u8(how) .ok_or("provided upgrade `how` value is out of range")?; let event = Event::ReleaseUpgrade { how, from: from.into(), to: to.into() }; self.submit_event(event)?; Ok(()) } fn release_repair(&mut self) -> Result<(), String> { crate::repair::repair().map_err(|why| format!("{}", why)) } fn send_signal_message(connection: &Connection, message: Message) { if let Err(()) = connection.send(message) { error!("failed to send dbus signal message"); } } fn set_status<T, E, F>(&mut self, status: DaemonStatus, mut func: F) -> Result<T, E> where F: FnMut(&mut Self, bool) -> Result<T, E>, { let already_active = self.status.swap(status, Ordering::SeqCst) == status; match func(self, already_active) { Ok(value) => Ok(value), Err(why) => { self.status.store(DaemonStatus::Inactive, Ordering::SeqCst); Err(why) } } } fn signal_message(signal: &Arc<Signal<()>>) -> Message { signal.msg(&DBUS_PATH.into(), &DBUS_NAME.into()) } fn submit_event(&self, event: Event) -> Result<(), String> { let desc = "too many requests sent -- refusing additional requests"; if self.event_tx.is_full() { warn!("{}", desc); return Err(desc.into()); } let _ = self.event_tx.send(event); Ok(()) } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ use core::fmt; use serde::Deserialize; use serde::Serialize; use syscalls::Errno; /// Context associated with [`Error`]. Useful for knowing which particular part /// of [`super::Command::spawn`] failed. #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] #[repr(u32)] pub enum Context { /// No context provided. Unknown, /// Setting CPU affinity failed. Affinity, /// The clone syscall failed. Clone, /// Setting up the tty failed. Tty, /// Setting up stdio failed. Stdio, /// Resetting signals failed. ResetSignals, /// Changing `/proc/{pid}/uid_map` failed. MapUid, /// Changing `/proc/{pid}/setgroups` or `/proc/{pid}/gid_map` failed. MapGid, /// Setting the hostname failed. Hostname, /// Setting the domainname failed. Domainname, /// Chroot failed. Chroot, /// Chdir failed. Chdir, /// Mounting failed. Mount, /// Network configuration failed. Network, /// The pre_exec callback(s) failed. PreExec, /// Setting the seccomp filter failed. Seccomp, /// Exec failed. Exec, } impl Context { /// Returns a string representation of the context. pub fn as_str(&self) -> &'static str { match self { Self::Unknown => "Unknown failure", Self::Affinity => "setting cpu affinity failed", Self::Clone => "clone failed", Self::Tty => "Setting the controlling tty failed", Self::Stdio => "Setting up stdio file descriptors failed", Self::ResetSignals => "Reseting signal handlers failed", Self::MapUid => "Setting UID map failed", Self::MapGid => "Setting GID map failed", Self::Hostname => "Setting hostname failed", Self::Domainname => "Setting domainname failed", Self::Chroot => "chroot failed", Self::Chdir => "chdir failed", Self::Mount => "mount failed", Self::Network => "network configuration failed", Self::PreExec => "pre_exec callback(s) failed", Self::Seccomp => "failed to install seccomp filter", Self::Exec => "execvp failed", } } } impl fmt::Display for Context { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Write::write_str(f, self.as_str()) } } /// An error from spawning a process. This is a thin wrapper around /// [`crate::Errno`], but with more context about what went wrong. #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct Error { errno: Errno, context: Context, } impl Error { /// Creates a new `Error`. pub fn new(errno: Errno, context: Context) -> Self { Self { errno, context } } /// Converts a value `S` into an `Error`. Useful for turning `libc` function /// return types into a `Result`. pub fn result<S>(value: S, context: Context) -> Result<S, Self> where S: syscalls::ErrnoSentinel + PartialEq<S>, { Errno::result(value).map_err(|err| Self::new(err, context)) } /// Gets the errno. pub fn errno(&self) -> Errno { self.errno } /// Gets the error context. pub fn context(&self) -> Context { self.context } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}: {}", self.context, self.errno) } } impl std::error::Error for Error {} impl From<Errno> for Error { fn from(err: Errno) -> Self { Self::new(err, Context::Unknown) } } impl From<Error> for Errno { fn from(err: Error) -> Errno { err.errno } } impl From<Error> for std::io::Error { fn from(err: Error) -> Self { std::io::Error::from(err.errno) } } impl From<[u8; 8]> for Error { /// Deserializes an `Error` from bytes. Useful for receiving the error /// through a pipe from the child process. fn from(bytes: [u8; 8]) -> Self { debug_assert_eq!(core::mem::size_of::<Self>(), 8); unsafe { core::mem::transmute(bytes) } } } impl From<Error> for [u8; 8] { /// Serializes an `Error` into bytes. Useful for sending the error through a /// pipe to the parent process. fn from(error: Error) -> Self { debug_assert_eq!(core::mem::size_of::<Self>(), 8); unsafe { core::mem::transmute(error) } } } pub(super) trait AddContext<T> { fn context(self, context: Context) -> Result<T, Error>; } impl<T> AddContext<T> for Result<T, Errno> { fn context(self, context: Context) -> Result<T, Error> { self.map_err(move |errno| Error::new(errno, context)) } } impl<T> AddContext<T> for Result<T, nix::errno::Errno> { fn context(self, context: Context) -> Result<T, Error> { self.map_err(move |errno| Error::new(Errno::new(errno as i32), context)) } } #[cfg(test)] mod tests { use super::*; #[test] fn to_bytes() { let bytes: [u8; 8] = Error::new(Errno::ENOENT, Context::Exec).into(); assert_eq!(Error::from(bytes), Error::new(Errno::ENOENT, Context::Exec)); } }
use rayon_adaptive::prelude::*; use rayon_adaptive::BasicPower; use std::iter::{once, Once}; /// pub struct Split<D, S, L> where D: Send, S: Fn(D) -> (D, D) + Sync + Send + Clone, L: Fn(&D) -> usize + Clone + Send, { pub data: D, pub splitter: S, pub length: L, } impl<D, S, L> Divisible for Split<D, S, L> where D: Send, S: Fn(D) -> (D, D) + Sync + Send + Clone, L: Fn(&D) -> usize + Clone + Send, { type Power = BasicPower; fn base_length(&self) -> Option<usize> { Some((self.length)(&self.data)) } #[allow(unused_variables)] fn divide_at(self, index: usize) -> (Self, Self) { let (d1, d2) = (self.splitter)(self.data); ( Split { data: d1, splitter: self.splitter.clone(), length: self.length.clone(), }, Split { data: d2, splitter: self.splitter, length: self.length, }, ) } } impl<D, S, L> ParallelIterator for Split<D, S, L> where D: Send, S: Fn(D) -> (D, D) + Sync + Send + Clone, L: Fn(&D) -> usize + Clone + Send, { type Item = D; type SequentialIterator = Once<D>; fn to_sequential(self) -> Self::SequentialIterator { once(self.data) } #[allow(unused_variables)] fn extract_iter(&mut self, size: usize) -> Self::SequentialIterator { panic!("extract_iter"); } } pub fn split<D, S, L>(data: D, splitter: S, length: L) -> Split<D, S, L> where D: Send, S: Fn(D) -> (D, D) + Sync + Send + Clone, L: Fn(&D) -> usize + Clone + Send, { Split { data: data, splitter: splitter, length: length, } }
mod gui; mod run; mod setup; mod systems; #[cfg(test)] mod test; extern crate cfg_if; extern crate slog; extern crate slog_async; extern crate slog_scope; extern crate slog_stdlog; extern crate slog_term; pub use common; pub use derive_deref; pub use fnv; pub use gfx_h; pub use nalgebra; pub use ncollide2d; pub use nphysics2d; pub use num_enum; pub use once_cell; pub use rand; pub use sdl2; pub use shrev; pub use specs; pub use specs_derive; pub use voronois; #[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] #[macro_use] extern crate log; #[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] extern crate android_log; /// int SDL_main(int argc, char *argv[]) #[no_mangle] pub extern "C" fn SDL_main( _argc: libc::c_int, _argv: *const *const libc::c_char, ) -> libc::c_int { main().unwrap(); return 0; } pub fn main() -> Result<(), String> { run::run() }
use std::sync::mpsc::{Sender, Receiver}; pub struct IntcodeVM { ip: usize, code: Vec<i64>, rel_base: i64, } impl IntcodeVM { pub fn new(code: Vec<i64>) -> IntcodeVM { let mut vm = IntcodeVM { ip: 0, code: code, rel_base: 0, }; vm.code.append(&mut vec![0; 1024]); return vm; } fn read_value(&self, a: i64, mode: u8) -> i64 { match mode { 0 => return self.code[a as usize], // Position mode 1 => return a, // Immediate mode 2 => return self.code[(a + self.rel_base) as usize], // Relative mode _ => panic!("Illegal read parameter mode: {}", mode), } } fn write_value(&mut self, a: i64, value: i64, mode: u8) { match mode { 0 => self.code[a as usize] = value, 1 => panic!("Cannot write in immediate mode..."), 2 => self.code[(a + self.rel_base) as usize] = value, _ => panic!("Illegal write parameter mode: {}", mode), } } pub fn run(&mut self, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) { #[inline(always)] fn add(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>3}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; let c = this.code[ip + 3]; // Add *a + *b, store in *c // println!("*{} = *{} + *{} = {} + {} = {}", c, a, b, this.code[a], this.code[b], this.code[a] + this.code[b]); this.write_value(c, this.read_value(a, parameter_modes[2]) + this.read_value(b, parameter_modes[1]), parameter_modes[0]); return ip+4; } #[inline(always)] fn mul(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>3}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; let c = this.code[ip + 3]; // Multiply *a * *b, store in *c // println!("*{} = *{} * *{} = {} * {} = {}", c, a, b, this.code[a], this.code[b], this.code[a] * this.code[b]); this.write_value(c, this.read_value(a, parameter_modes[2]) * this.read_value(b, parameter_modes[1]), parameter_modes[0]); return ip+4; } fn input(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>1}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; // let mut user_input = String::new(); // std::io::stdin().read_line(&mut user_input); // let value = user_input.trim().parse().unwrap(); // let value = data_input.remove(0); let value = data_input.recv().unwrap(); this.write_value(a, value, parameter_modes[0]); return ip+2; } fn output(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>1}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; // println!("{}", this.read_value(a, parameter_modes[0])); // data_output.push(this.read_value(a, parameter_modes[0])); data_output.send(this.read_value(a, parameter_modes[0])).unwrap(); return ip+2; } fn jump_if_true(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>2}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; if this.read_value(a, parameter_modes[1]) != 0 { return this.read_value(b, parameter_modes[0]) as usize; } return ip+3; } fn jump_if_false(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>2}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; if this.read_value(a, parameter_modes[1]) == 0 { return this.read_value(b, parameter_modes[0]) as usize; } return ip+3; } fn less_than(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>3}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; let c = this.code[ip + 3]; if this.read_value(a, parameter_modes[2]) < this.read_value(b, parameter_modes[1]) { this.write_value(c, 1, parameter_modes[0]); } else { this.write_value(c, 0, parameter_modes[0]); } return ip+4; } fn equal(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>3}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; let b = this.code[ip + 2]; let c = this.code[ip + 3]; if this.read_value(a, parameter_modes[2]) == this.read_value(b, parameter_modes[1]) { this.write_value(c, 1, parameter_modes[0]); } else { this.write_value(c, 0, parameter_modes[0]); } return ip+4; } fn add_rel_base(this: &mut IntcodeVM, ip: usize, parameter_modes: &str, data_input: &mut Receiver<i64>, data_output: &mut Sender<i64>) -> usize { let parameter_modes: Vec<u8> = format!("{:0>1}", parameter_modes).chars().map(|ch| ch.to_digit(10).unwrap() as u8).collect(); let a = this.code[ip + 1]; // Adjust relative base this.rel_base += this.read_value(a, parameter_modes[0]); return ip+2; } let opcode_functions: [&Fn(&mut IntcodeVM, usize, &str, &mut Receiver<i64>, &mut Sender<i64>) -> usize; 9] = [ &add, &mul, &input, &output, &jump_if_true, &jump_if_false, &less_than, &equal, &add_rel_base ]; loop { let opcode_str = format!("{:0>2}", self.code[self.ip].to_string()); let opcode: i64 = opcode_str[opcode_str.len()-2..].parse().unwrap(); let parameter_modes = &opcode_str[..opcode_str.len()-2]; let opcode_index = (opcode - 1) as usize; if opcode_index < opcode_functions.len() { self.ip = opcode_functions[opcode_index](self, self.ip, parameter_modes, data_input, data_output); } else { match opcode { 99 => break, _ => { println!("Invalid opcode: {}", opcode); break; }, } } } } }
//! Repos contains all info about working with countries use diesel; use diesel::connection::AnsiTransactionManager; use diesel::pg::Pg; use diesel::prelude::*; use diesel::query_dsl::RunQueryDsl; use diesel::sql_types::Bool; use diesel::Connection; use errors::Error; use failure::Error as FailureError; use std::sync::Arc; use stq_cache::cache::CacheSingle; use stq_types::{self, Alpha3, CountryLabel, UserId}; use models::authorization::*; use models::{get_country, Country, NewCountry, RawCountry}; use repos::acl; use repos::legacy_acl::{Acl, CheckScope}; use repos::types::RepoResult; use schema::countries::dsl::*; pub mod cache; pub use self::cache::*; #[derive(Serialize, Deserialize, Clone, Debug)] pub enum CountrySearch { Label(CountryLabel), Alpha2(stq_types::Alpha2), Alpha3(stq_types::Alpha3), Numeric(i32), } /// Countries repository, responsible for handling countries pub struct CountriesRepoImpl<'a, C, T> where C: CacheSingle<Country>, T: Connection<Backend = Pg, TransactionManager = AnsiTransactionManager> + 'static, { pub db_conn: &'a T, pub acl: Box<Acl<Resource, Action, Scope, FailureError, Country>>, pub cache: Arc<CountryCacheImpl<C>>, } pub trait CountriesRepo { /// Returns tree country fn find(&self, label_arg: Alpha3) -> RepoResult<Option<Country>>; /// Returns country by codes fn find_by(&self, search: CountrySearch) -> RepoResult<Option<Country>>; /// Creates new country fn create(&self, payload: NewCountry) -> RepoResult<Country>; /// Returns all countries as a tree fn get_all(&self) -> RepoResult<Country>; /// Returns all countries as a vec fn get_all_flatten(&self) -> RepoResult<Vec<Country>>; } impl<'a, C, T> CountriesRepoImpl<'a, C, T> where C: CacheSingle<Country>, T: Connection<Backend = Pg, TransactionManager = AnsiTransactionManager> + 'static, { pub fn new(db_conn: &'a T, acl: Box<Acl<Resource, Action, Scope, FailureError, Country>>, cache: Arc<CountryCacheImpl<C>>) -> Self { Self { db_conn, acl, cache } } } impl<'a, C, T> CountriesRepo for CountriesRepoImpl<'a, C, T> where C: CacheSingle<Country>, T: Connection<Backend = Pg, TransactionManager = AnsiTransactionManager> + 'static, { /// Find specific country by label fn find(&self, arg: Alpha3) -> RepoResult<Option<Country>> { debug!("Find in countries with aplha3 {}.", arg); acl::check(&*self.acl, Resource::Countries, Action::Read, self, None)?; self.get_all().map(|root| get_country(&root, &arg)) } fn find_by(&self, search: CountrySearch) -> RepoResult<Option<Country>> { debug!("Get countries by search: {:?}.", search); let search_exp: Box<BoxableExpression<countries, _, SqlType = Bool>> = match search.clone() { CountrySearch::Label(value) => Box::new(label.eq(value)), CountrySearch::Alpha2(value) => Box::new(alpha2.eq(value)), CountrySearch::Alpha3(value) => Box::new(alpha3.eq(value)), CountrySearch::Numeric(value) => Box::new(numeric.eq(value)), }; let query = countries.filter(search_exp); query .get_result(self.db_conn) .optional() .map_err(|e| Error::from(e).into()) .and_then(|raw_country: Option<RawCountry>| match raw_country { Some(raw_country) => { let country: Country = raw_country.into(); acl::check(&*self.acl, Resource::Countries, Action::Read, self, Some(&country))?; Ok(Some(country)) } None => Ok(None), }) .map_err(|e: FailureError| e.context(format!("Get countries by search: {:?}.", search)).into()) } /// Creates new country fn create(&self, payload: NewCountry) -> RepoResult<Country> { debug!("Create new country {:?}.", payload); self.cache.remove(); let query = diesel::insert_into(countries).values(&payload); query .get_result::<RawCountry>(self.db_conn) .map_err(|e| Error::from(e).into()) .map(From::from) .and_then(|country| acl::check(&*self.acl, Resource::Countries, Action::Create, self, Some(&country)).and_then(|_| Ok(country))) .map_err(|e: FailureError| e.context(format!("Create new country: {:?} error occured", payload)).into()) } fn get_all(&self) -> RepoResult<Country> { if let Some(country) = self.cache.get() { debug!("Get all countries from cache request."); Ok(country) } else { debug!("Get all countries from db request."); acl::check(&*self.acl, Resource::Countries, Action::Read, self, None) .and_then(|_| { let countries_ = countries.load::<RawCountry>(self.db_conn)?; let tree = create_tree(&countries_, None)?; let root = tree .into_iter() .nth(0) .ok_or_else(|| format_err!("Could not create countries tree"))?; self.cache.set(&root); Ok(root) }) .map_err(|e: FailureError| e.context("Get all countries error occured").into()) } } /// Returns all countries as a vec fn get_all_flatten(&self) -> RepoResult<Vec<Country>> { debug!("Get all countries as vec from db request."); acl::check(&*self.acl, Resource::Countries, Action::Read, self, None) .and_then(|_| { let countries_ = countries.load::<RawCountry>(self.db_conn)?; let all_countries = countries_.into_iter().map(Country::from).collect(); Ok(all_countries) }) .map_err(|e: FailureError| e.context("Get all flatten countries error occured").into()) } } fn create_tree(countries_: &[RawCountry], parent_arg: Option<Alpha3>) -> RepoResult<Vec<Country>> { let mut branch = vec![]; for country in countries_ { if country.parent == parent_arg { let childs = create_tree(countries_, Some(country.alpha3.clone()))?; let mut country_tree: Country = country.into(); country_tree.children = childs; branch.push(country_tree); } } Ok(branch) } pub fn create_tree_used_countries(countries_arg: &Country, used_countries_codes: &[Alpha3]) -> Vec<Country> { let available_countries = used_countries_codes .iter() .filter_map(|country_code| get_country(&countries_arg, country_code)) .collect::<Vec<Country>>(); let contains_all_countries = available_countries.iter().any(|country_| country_.parent == None); let mut result = vec![]; if contains_all_countries { result.push(countries_arg.clone()); } else { let mut countries_tree = countries_arg.clone(); let used_codes: Vec<Alpha3> = available_countries.iter().map(|c| c.alpha3.clone()).collect(); countries_tree = remove_unused_countries(countries_tree, &used_codes); result.push(countries_tree); } result } pub fn remove_unused_countries(mut country: Country, used_countries_codes: &[Alpha3]) -> Country { let mut children = vec![]; for country_child in country.children { if used_countries_codes.iter().any(|used_code| country_child.alpha3 == *used_code) { children.push(country_child); } else { let new_country = remove_unused_countries(country_child, used_countries_codes); if !new_country.children.is_empty() { children.push(new_country); } } } country.children = children; country } pub fn clear_child_countries(mut country: Country, stack_level: i32) -> Country { if stack_level == 0 { country.children.clear(); } else { let mut countries_ = vec![]; for country_child in country.children { let new_country = clear_child_countries(country_child, stack_level - 1); countries_.push(new_country); } country.children = countries_; } country } pub fn get_parent_country(country: &Country, child_code: &Alpha3, stack_level: i32) -> Option<Country> { if stack_level != 0 { country .children .iter() .find(|country_child| get_parent_country(country_child, child_code, stack_level - 1).is_some()) .and_then(|_| Some(country.clone())) } else if country.alpha3 == *child_code { Some(country.clone()) } else { None } } pub fn get_all_children_till_the_end(country: Country) -> Vec<Country> { let mut childless_entries = Vec::new(); add_all_children_till_the_end(country, &mut childless_entries); childless_entries } fn add_all_children_till_the_end(country: Country, accumulator: &mut Vec<Country>) { if country.children.is_empty() { accumulator.push(country); } else { for child in country.children { add_all_children_till_the_end(child, accumulator); } } } pub fn get_all_parent_codes(country: &Country, searched_country_id: &Alpha3, codes: &mut Vec<Alpha3>) { if country.alpha3 == *searched_country_id { codes.push(country.alpha3.clone()) } else { for child in &country.children { let old_len = codes.len(); get_all_parent_codes(child, searched_country_id, codes); if codes.len() > old_len { codes.push(country.alpha3.clone()); break; } } } } pub fn set_selected(country: &mut Country, selected_codes: &[Alpha3]) { if selected_codes.iter().any(|country_code| &country.alpha3 == country_code) { set_selected_till_end(country); } else { for child in &mut country.children { set_selected(child, selected_codes); } } } pub fn get_selected(country: &Country, codes: &mut Vec<Alpha3>) { if country.is_selected { codes.push(country.alpha3.clone()) } else { for child in &country.children { get_selected(child, codes); } } } pub fn set_selected_till_end(country: &mut Country) { country.is_selected = true; for child in &mut country.children { set_selected_till_end(child); } } pub fn contains_country_code(country: &Country, country_code: &Alpha3) -> bool { if country.alpha3 == country_code.clone() { true } else { country .children .iter() .any(|country_child| contains_country_code(country_child, country_code)) } } impl<'a, C, T> CheckScope<Scope, Country> for CountriesRepoImpl<'a, C, T> where C: CacheSingle<Country>, T: Connection<Backend = Pg, TransactionManager = AnsiTransactionManager> + 'static, { fn is_in_scope(&self, _user_label: UserId, scope: &Scope, _obj: Option<&Country>) -> bool { match *scope { Scope::All => true, Scope::Owned => false, } } } #[cfg(test)] mod tests { use super::*; use models::*; use stq_types::{Alpha2, Alpha3}; fn create_mock_countries_region1(parent_: Option<Alpha3>) -> Vec<Country> { vec![ Country { label: "Russia".to_string().into(), children: vec![], level: 2, parent: parent_.clone(), alpha2: Alpha2("RU".to_string()), alpha3: Alpha3("RUS".to_string()), numeric: 0, is_selected: false, }, Country { label: "Austria".to_string().into(), children: vec![], level: 2, parent: parent_.clone(), alpha2: Alpha2("AT".to_string()), alpha3: Alpha3("AUT".to_string()), numeric: 0, is_selected: false, }, ] } fn create_mock_countries_region2(parent_: Option<Alpha3>) -> Vec<Country> { vec![Country { label: "Brazil".to_string().into(), children: vec![], level: 2, parent: parent_, alpha2: Alpha2("BR".to_string()), alpha3: Alpha3("BRA".to_string()), numeric: 0, is_selected: false, }] } fn create_mock_region3(parent_: Option<Alpha3>) -> Country { Country { label: "North America".to_string().into(), children: vec![], level: 2, parent: parent_, alpha2: Alpha2("".to_string()), alpha3: Alpha3("XNA".to_string()), numeric: 0, is_selected: false, } } fn create_mock_countries() -> (Country, Alpha3) { let root_code = Alpha3("XAL".to_string()); let region1_alpha3 = Alpha3("XEU".to_string()); let region_1 = Country { label: "Europe".to_string().into(), children: create_mock_countries_region1(Some(region1_alpha3.clone())), level: 1, parent: Some(root_code.clone()), alpha2: Alpha2("".to_string()), alpha3: region1_alpha3, numeric: 0, is_selected: false, }; let region2_alpha3 = Alpha3("XSA".to_string()); let region_2 = Country { label: "South America".to_string().into(), children: create_mock_countries_region2(Some(region2_alpha3.clone())), level: 1, parent: Some(root_code.clone()), alpha2: Alpha2("".to_string()), alpha3: region2_alpha3, numeric: 0, is_selected: false, }; ( Country { label: "All".to_string().into(), level: 0, parent: None, children: vec![region_1, region_2], alpha2: Alpha2("".to_string()), alpha3: root_code.clone(), numeric: 0, is_selected: false, }, root_code, ) } #[test] fn test_parent_countries() { let (country, _) = create_mock_countries(); let child_code = Alpha3("RUS".to_string()); let new_country = country .children .into_iter() .find(|country_child| get_parent_country(&country_child, &child_code, 1).is_some()) .unwrap(); assert_eq!(new_country.label, "Europe".to_string().into()); } #[test] fn test_get_country() { let (country, _) = create_mock_countries(); let child_code = Alpha3("RUS".to_string()); let new_country = get_country(&country, &child_code).unwrap(); assert_eq!(new_country.alpha3, child_code.clone().into()); } #[test] fn test_used_only_one_region() { let (mut country, _) = create_mock_countries(); let region_alpha3 = Alpha3("XEU".to_string()); let used_codes: Vec<Alpha3> = vec![region_alpha3.clone()]; assert_eq!(country.children.len(), 2, "Mock countries not contains 2 regions"); country = remove_unused_countries(country, &used_codes); assert_eq!(country.children.len(), 1); assert_eq!(country.children[0].alpha3, region_alpha3); } #[test] fn test_used_only_one_country_from_region() { let (mut country, _) = create_mock_countries(); let region_code = Alpha3("XEU".to_string()); let country_code = Alpha3("RUS".to_string()); let used_codes = vec![country_code.clone()]; { let region = country .children .iter() .find(|c| c.alpha3 == region_code) .expect(&format!("Not found region with code {:?} before run test", region_code)); assert_eq!(region.children.len(), 2, "Mock countries not contains 2 countries"); } country = remove_unused_countries(country, &used_codes); let region = country .children .iter() .find(|c| c.alpha3 == region_code) .expect(&format!("Not found region with code {:?} after test", region_code)); assert_eq!(region.children.len(), 1); assert_eq!(region.children[0].alpha3, country_code); } #[test] fn test_used_country_from_region_plus_region() { let (mut country, root_code) = create_mock_countries(); country.children.push(create_mock_region3(Some(root_code))); let country_code = Alpha3("RUS".to_string()); let region_code2 = Alpha3("XSA".to_string()); let used_codes = vec![country_code.clone(), region_code2.clone()]; assert_eq!(country.children.len(), 3, "Mock countries not contains 3 regions before run test"); country = remove_unused_countries(country, &used_codes); assert_eq!(country.children.len(), 2, "Mock countries not contains 2 regions after run test"); } }
#[doc = "Reader of register DDRPHYC_BISTUDPR"] pub type R = crate::R<u32, super::DDRPHYC_BISTUDPR>; #[doc = "Writer for register DDRPHYC_BISTUDPR"] pub type W = crate::W<u32, super::DDRPHYC_BISTUDPR>; #[doc = "Register DDRPHYC_BISTUDPR `reset()`'s with value 0xffff_0000"] impl crate::ResetValue for super::DDRPHYC_BISTUDPR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xffff_0000 } } #[doc = "Reader of field `BUDP0`"] pub type BUDP0_R = crate::R<u16, u16>; #[doc = "Write proxy for field `BUDP0`"] pub struct BUDP0_W<'a> { w: &'a mut W, } impl<'a> BUDP0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `BUDP1`"] pub type BUDP1_R = crate::R<u16, u16>; #[doc = "Write proxy for field `BUDP1`"] pub struct BUDP1_W<'a> { w: &'a mut W, } impl<'a> BUDP1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0xffff << 16)) | (((value as u32) & 0xffff) << 16); self.w } } impl R { #[doc = "Bits 0:15 - BUDP0"] #[inline(always)] pub fn budp0(&self) -> BUDP0_R { BUDP0_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - BUDP1"] #[inline(always)] pub fn budp1(&self) -> BUDP1_R { BUDP1_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - BUDP0"] #[inline(always)] pub fn budp0(&mut self) -> BUDP0_W { BUDP0_W { w: self } } #[doc = "Bits 16:31 - BUDP1"] #[inline(always)] pub fn budp1(&mut self) -> BUDP1_W { BUDP1_W { w: self } } }
//! This crate provides Yew's procedural macro `html!` which allows using JSX-like syntax for generating html. //! It uses [proc_macro_hack](https://github.com/dtolnay/proc-macro-hack) in order to be used in the expression position. //! //! ``` //! # #[macro_use] extern crate yew; //! # use yew::prelude::*; //! # //! # struct Component; //! # #[derive(Default, Clone, PartialEq)] //! # struct Props { prop: String }; //! # enum Msg { Submit } //! # //! # impl yew::Component for Component { //! # type Message = Msg; //! # type Properties = Props; //! # fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { //! # unimplemented!() //! # } //! # //! # fn update(&mut self, msg: Self::Message) -> ShouldRender { //! # unimplemented!() //! # } //! # } //! # //! # impl Renderable<Component> for Component { //! # fn view(&self) -> Html<Self> { //! # //! html! { //! <div> //! <button onclick=|_| Msg::Submit>{ "Submit" }</button> //! <> //! <Component prop="first" /> //! <Component prop="second" /> //! </> //! </div> //! } //! # //! # } //! # } //! # //! # fn main() {} //! ``` //! //! Please refer to [https://github.com/DenisKolodin/yew](https://github.com/DenisKolodin/yew) for how to set this up. #![recursion_limit = "128"] extern crate proc_macro; mod html_tree; use html_tree::HtmlRoot; use proc_macro::TokenStream; use proc_macro_hack::proc_macro_hack; use quote::quote; use syn::buffer::Cursor; use syn::parse_macro_input; trait Peek<T> { fn peek(cursor: Cursor) -> Option<T>; } #[proc_macro_hack] pub fn html(input: TokenStream) -> TokenStream { let root = parse_macro_input!(input as HtmlRoot); TokenStream::from(quote! {#root}) }
wasm_bindgen_test_configure!(run_in_browser); // What's tested: // // Tests send to an echo server which just bounces back all data. // // ✔ WsMeta::connect: Verify error when connecting to a wrong port // ✔ WsMeta::connect: Verify error when connecting to a forbidden port // ✔ WsMeta::connect: Verify error when connecting to wss:// on ws:// server // ✔ WsMeta::connect: Verify error when connecting to a wrong scheme // ✔ Verify the state method // ✔ Verify closing from WsStream // ✔ Verify url method // ✔ Verify sending no subprotocols // note: we currently don't have a backend server that supports protocols, // so there is no test for testing usage of protocols // ✔ Verify closing with a valid code // ✔ Verify error upon closing with invalid code // ✔ Verify closing with a valid code and reason // ✔ Verfiy close_reason with an invalid close code // ✔ Verfiy close_reason with an invalid reason string // ✔ Verfiy Debug impl // use { futures :: { sink::SinkExt } , wasm_bindgen::prelude :: { * } , wasm_bindgen_test :: { * } , ws_stream_wasm :: { * } , log :: { * } , }; const URL: &str = "ws://127.0.0.1:3212/"; // WsMeta::connect: Verify error when connecting to a wrong port // #[ wasm_bindgen_test ] // async fn connect_wrong_port() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: connect_wrong_port" ); let err = WsMeta::connect( "ws://127.0.0.1:33212/", None ).await; assert!( err.is_err() ); let err = err.unwrap_err(); assert_eq! ( WsErr::ConnectionFailed { event: CloseEvent { was_clean: false, code : 1006 , reason : "".to_string(), } }, err ); } // WsMeta::connect: Verify error when connecting to a forbidden port // #[ wasm_bindgen_test ] // async fn connect_forbidden_port() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: connect_forbidden_port" ); let err = WsMeta::connect( "ws://127.0.0.1:6000/", None ).await; assert!( err.is_err() ); let err = err.unwrap_err(); assert!(matches!( err, WsErr::ConnectionFailed{..} )); } // WsMeta::connect: Verify error when connecting to wss:// on ws:// server // #[ wasm_bindgen_test ] // async fn connect_wrong_wss() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: connect_wrong_wss" ); let err = WsMeta::connect( "wss://127.0.0.1:3212/", None ).await; assert!( err.is_err() ); let err = err.unwrap_err(); assert_eq! ( WsErr::ConnectionFailed { event: CloseEvent { was_clean: false, code : 1006 , reason : "".to_string(), } }, err ); } // WsMeta::connect: Verify error when connecting to a wrong scheme // #[ wasm_bindgen_test ] // async fn connect_wrong_scheme() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: connect_wrong_scheme" ); let err = WsMeta::connect( "http://127.0.0.1:3212/", None ).await; assert!( err.is_err() ); let err = err.unwrap_err(); assert_eq!( WsErr::InvalidUrl{ supplied: "http://127.0.0.1:3212/".to_string() }, err ); } // Verify state method. // #[ wasm_bindgen_test ] // async fn state() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: state" ); let (ws, wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); assert_eq!( WsState::Open, ws .ready_state() ); assert_eq!( WsState::Open, wsio.ready_state() ); ws.wrapped().close().expect_throw( "close WebSocket" ); assert_eq!( WsState::Closing, ws .ready_state() ); assert_eq!( WsState::Closing, wsio.ready_state() ); ws.close().await.expect_throw( "close ws" ); assert_eq!( WsState::Closed, ws .ready_state() ); assert_eq!( WsState::Closed, wsio.ready_state() ); } // Verify closing from WsStream. // #[ wasm_bindgen_test ] // async fn close_from_wsio() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_from_wsio" ); let (ws, mut wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); assert_eq!( WsState::Open, ws.ready_state() ); SinkExt::close( &mut wsio ).await.expect( "close wsio sink" ); assert_eq!( WsState::Closed, wsio.ready_state() ); assert_eq!( WsState::Closed, ws .ready_state() ); } // Verify url method. // #[ wasm_bindgen_test ] // async fn url() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: url" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); assert_eq!( URL, ws.url() ); } // Verify protocols. // #[ wasm_bindgen_test ] // async fn no_protocols() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: no_protocols" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); assert_eq!( "", ws.protocol() ); } /* // Verify protocols. // This doesn't work with tungstenite for the moment. // #[ wasm_bindgen_test ] // async fn protocols_server_accept_none() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: protocols_server_accept_none" ); let (ws, _wsio) = WsMeta::connect( URL, vec![ "chat" ] ).await.expect_throw( "Could not create websocket" ); assert_eq!( "", ws.protocol() ); } */ // Verify close_code method. // #[ wasm_bindgen_test ] // async fn close_twice() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_twice" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close().await; assert!( res.is_ok() ); assert_eq!( ws.close () .await.unwrap_err(), WsErr::ConnectionNotOpen ); assert_eq!( ws.close_code ( 1000 ).await.unwrap_err(), WsErr::ConnectionNotOpen ); assert_eq!( ws.close_reason( 1000, "Normal shutdown" ).await.unwrap_err(), WsErr::ConnectionNotOpen ); } #[ wasm_bindgen_test ] // async fn close_code_valid() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_code_valid" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close_code( 1000 ).await; assert!( res.is_ok() ); } // Verify close_code method. // #[ wasm_bindgen_test ] // async fn close_code_invalid() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_code_invalid" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close_code( 500 ).await; assert_eq!( WsErr::InvalidCloseCode{ supplied: 500 }, res.unwrap_err() ); } // Verify close_code method. // #[ wasm_bindgen_test ] // async fn close_reason_valid() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_reason_valid" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close_reason( 1000, "Normal shutdown" ).await; assert!( res.is_ok() ); } // Verify close_code method. // #[ wasm_bindgen_test ] // async fn close_reason_invalid_code() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_reason_invalid_code" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close_reason( 500, "Normal Shutdown" ).await; assert_eq!( WsErr::InvalidCloseCode{ supplied: 500 }, res.unwrap_err() ); } // Verify close_code method. // #[ wasm_bindgen_test ] // async fn close_reason_invalid() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: close_reason_invalid" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); let res = ws.close_reason( 1000, vec![ "a"; 124 ].join( "" ) ).await; assert_eq!( WsErr::ReasonStringToLong, res.unwrap_err() ); } // Verify Debug impl. // #[ wasm_bindgen_test ] // async fn debug() { let _ = console_log::init_with_level( Level::Trace ); info!( "starting test: debug" ); let (ws, _wsio) = WsMeta::connect( URL, None ).await.expect_throw( "Could not create websocket" ); assert_eq!( format!( "WsMeta for connection: {URL}" ), format!( "{ws:?}" ) ); ws.close().await.expect_throw( "close" ); }
#[doc = "Reader of register RANGE_INTR_MASKED"] pub type R = crate::R<u32, super::RANGE_INTR_MASKED>; #[doc = "Reader of field `RANGE_MASKED`"] pub type RANGE_MASKED_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Logical and of corresponding request and mask bits."] #[inline(always)] pub fn range_masked(&self) -> RANGE_MASKED_R { RANGE_MASKED_R::new((self.bits & 0xffff) as u16) } }
use crate::system::{access, modified, AccessMode, Path}; use crate::{ qjs, Mut, Ref, Result, Rule, RuleState, Set, Time, Weak, WeakElement, WeakKey, WeakSet, }; use derive_deref::Deref; use either::{Left, Right}; use std::{ borrow::Borrow, collections::VecDeque, fmt, fmt::{Display, Formatter, Result as FmtResult}, hash::{Hash, Hasher}, iter::{empty, once}, marker::PhantomData, }; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, qjs::FromJs, qjs::IntoJs)] #[repr(u8)] pub enum ArtifactType { Source, Product, } impl Display for ArtifactType { fn fmt(&self, f: &mut Formatter) -> FmtResult { match self { Self::Source => "source", Self::Product => "product", } .fmt(f) } } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, qjs::FromJs, qjs::IntoJs)] #[repr(u8)] pub enum ArtifactKind { Actual, Phony, } impl Display for ArtifactKind { fn fmt(&self, f: &mut Formatter) -> FmtResult { match self { Self::Actual => "actual", Self::Phony => "phony", } .fmt(f) } } pub struct Internal { name: String, description: String, rule: Mut<Option<Rule>>, time: Mut<Time>, type_: ArtifactType, kind: ArtifactKind, } impl Drop for Internal { fn drop(&mut self) { log::debug!("Artifact::drop `{}`", self.name); } } impl Borrow<str> for Internal { fn borrow(&self) -> &str { &self.name } } impl Borrow<String> for Internal { fn borrow(&self) -> &String { &self.name } } impl PartialEq for Internal { fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl Eq for Internal {} impl Hash for Internal { fn hash<H: Hasher>(&self, state: &mut H) { self.name.hash(state); } } pub trait IsArtifactUsage { const NAME: &'static str; const TYPE: ArtifactType; fn reusable<U, K>(artifact: &Artifact<U, K>) -> bool; } pub struct Input; impl IsArtifactUsage for Input { const NAME: &'static str = "input"; const TYPE: ArtifactType = ArtifactType::Source; fn reusable<U, K>(_artifact: &Artifact<U, K>) -> bool { true } } pub struct Output; impl IsArtifactUsage for Output { const NAME: &'static str = "output"; const TYPE: ArtifactType = ArtifactType::Product; fn reusable<U, K>(artifact: &Artifact<U, K>) -> bool { artifact.type_() != ArtifactType::Source && !artifact.has_rule() } } pub trait IsArtifactKind { const NAME: &'static str; const KIND: ArtifactKind; fn get_store(store: &ArtifactStore) -> &Mut<WeakSet<WeakArtifact<(), Self>>> where Self: Sized; } pub struct Actual; impl IsArtifactKind for Actual { const NAME: &'static str = "actual"; const KIND: ArtifactKind = ArtifactKind::Actual; fn get_store(store: &ArtifactStore) -> &Mut<WeakSet<WeakArtifact<(), Self>>> { &store.actual } } pub struct Phony; impl IsArtifactKind for Phony { const NAME: &'static str = "phony"; const KIND: ArtifactKind = ArtifactKind::Phony; fn get_store(store: &ArtifactStore) -> &Mut<WeakSet<WeakArtifact<(), Self>>> { &store.phony } } #[repr(transparent)] pub struct Artifact<U = (), K = ()>(Ref<Internal>, PhantomData<(U, K)>); impl<U, K> Display for Artifact<U, K> { fn fmt(&self, f: &mut Formatter) -> FmtResult { write!( f, "Artifact(`{}`, {}, {}{})", self.name(), self.type_(), self.kind(), if self.has_rule() { ", rule" } else { "" } ) } } impl<U, K> fmt::Debug for Artifact<U, K> { fn fmt(&self, f: &mut Formatter) -> FmtResult { Display::fmt(self, f) } } impl<U, K> Clone for Artifact<U, K> { fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) } } impl<U, K> Borrow<str> for Artifact<U, K> { fn borrow(&self) -> &str { &self.0.name } } impl<U, K> Borrow<String> for Artifact<U, K> { fn borrow(&self) -> &String { &self.0.name } } impl<U, V, K> PartialEq<Artifact<V, K>> for Artifact<U, K> { fn eq(&self, other: &Artifact<V, K>) -> bool { self.0 == other.0 } } impl<U, K> Eq for Artifact<U, K> {} impl<U, K> Hash for Artifact<U, K> { fn hash<H: Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl<U, K> Artifact<U, K> where U: IsArtifactUsage, K: IsArtifactKind, { fn new_raw(name: impl Into<String>, description: impl Into<String>) -> Self { let name = name.into(); let description = description.into(); log::debug!("Artifact::new `{}`", name); Self( Ref::new(Internal { name, description, rule: Default::default(), time: Mut::new(Time::UNIX_EPOCH), type_: U::TYPE, kind: K::KIND, }), PhantomData, ) } pub fn new( set: impl AsRef<ArtifactStore>, name: impl Into<String>, description: impl Into<String>, ) -> Result<Self> { let set = K::get_store(set.as_ref()); let name = name.into(); let description = description.into(); { // try reuse already existing artifact if let Some(artifact) = set.read().get(&name) { return artifact.into_usage(); } } let artifact = Self::new_raw(name, description); set.write().insert(artifact.clone().into_usage_any()); Ok(artifact) } } impl Artifact<Input, Actual> { pub async fn new_init( set: impl AsRef<ArtifactStore>, name: impl Into<String>, description: impl Into<String>, ) -> Result<Self> { let artifact = Self::new(set, name.into(), description.into())?; artifact.init().await?; Ok(artifact) } pub async fn init(&self) -> Result<()> { let path = Path::new(self.name()); if !access(path, AccessMode::READ).await { return Err(format!("Unable to read input file `{}`", self.name()).into()); } let time = modified(path).await?; self.set_time(time); Ok(()) } } impl Artifact<Output, Actual> { pub async fn new_init( set: impl AsRef<ArtifactStore>, name: impl Into<String>, description: impl Into<String>, ) -> Result<Self> { let artifact = Self::new(set, name.into(), description.into())?; artifact.init().await?; Ok(artifact) } pub async fn init(&self) -> Result<()> { let path = Path::new(self.name()); if path.exists().await { if !access(path, AccessMode::WRITE).await { return Err(format!("Unable to write output file `{}`", self.name()).into()); } let time = modified(path).await?; self.set_time(time); } Ok(()) } } impl<U, K> Artifact<U, K> { pub fn into_usage<T: IsArtifactUsage>(self) -> Result<Artifact<T, K>> { if T::reusable(&self) { Ok(Artifact(self.0, PhantomData)) } else { Err(format!("Attempt to reuse {} as {}", self, T::NAME).into()) } } pub fn into_usage_any(self) -> Artifact<(), K> { Artifact(self.0, PhantomData) } pub fn into_kind<T: IsArtifactKind>(self) -> Result<Artifact<U, T>> { if T::KIND == self.0.kind { Ok(Artifact(self.0, PhantomData)) } else { Err(format!("Attempt to use {} as {}", self, T::KIND).into()) } } pub fn into_kind_any(self) -> Artifact<U, ()> { Artifact(self.0, PhantomData) } pub fn ctor() -> Self { unimplemented!() } pub fn name(&self) -> &String { &self.0.name } pub fn description(&self) -> &String { &self.0.description } pub fn type_(&self) -> ArtifactType { self.0.type_ } pub fn kind(&self) -> ArtifactKind { self.0.kind } pub fn time(&self) -> Time { *self.0.time.read() } pub fn has_rule(&self) -> bool { self.0.rule.read().is_some() } pub fn rule(&self) -> Option<Rule> { self.0.rule.read().clone() } pub fn weak(&self) -> WeakArtifact<U, K> { WeakArtifact(Ref::downgrade(&self.0), PhantomData) } pub fn is_source(&self) -> bool { self.type_() == ArtifactType::Source } pub fn is_phony(&self) -> bool { self.kind() == ArtifactKind::Phony } pub fn inputs(&self) -> impl Iterator<Item = Artifact<Input>> { self.0 .rule .read() .as_ref() .map(|rule| Right(rule.inputs().into_iter())) .unwrap_or(Left(empty())) } pub fn state(&self) -> RuleState { let rule = self.0.rule.read(); rule.as_ref().map(|rule| rule.state()).unwrap_or_default() } pub fn outdated(&self) -> bool { if self.is_source() { false } else { self.inputs() .any(|dep| dep.outdated() || dep.time() > self.time()) } } pub fn set_time(&self, time: Time) { *self.0.time.write() = time; } pub async fn update_time(&self, new_time: Option<Time>) -> Result<bool> { let cur_time = modified(Path::new(self.name())).await?; Ok(if cur_time > self.time() { self.set_time(new_time.unwrap_or(cur_time)); true } else { false }) } pub fn fmt_tree(&self, ident: usize, f: &mut Formatter) -> FmtResult { let spaces = ident * 4; write!(f, "{:ident$}{}", "", self.name(), ident = spaces)?; let text = self.description(); if !text.is_empty() { " // ".fmt(f)?; text.fmt(f)?; } '\n'.fmt(f)?; Ok(()) } fn fmt_node_name(&self, f: &mut Formatter) -> FmtResult { f.write_fmt(format_args!("{:?}", self.name())) } pub fn fmt_dot_edges(&self, ident: usize, f: &mut Formatter) -> FmtResult { if !self.is_source() { let mut deps = self.inputs(); if let Some(dep1) = deps.next() { let spaces = ident * 4; f.write_fmt(format_args!("{:ident$}", "", ident = spaces))?; if let Some(dep2) = deps.next() { '{'.fmt(f)?; dep1.fmt_node_name(f)?; ' '.fmt(f)?; dep2.fmt_node_name(f)?; for dep in deps { ' '.fmt(f)?; dep.fmt_node_name(f)?; } '}'.fmt(f)?; } else { dep1.fmt_node_name(f)?; } " -> ".fmt(f)?; self.fmt_node_name(f)?; if self.is_phony() { " [style=dashed]".fmt(f)?; } ";\n".fmt(f)?; } } Ok(()) } pub fn fmt_dot_node(&self, ident: usize, f: &mut Formatter) -> FmtResult { let spaces = ident * 4; f.write_fmt(format_args!( "{:ident$}{:?} [style=filled fillcolor={}];\n", "", self.name(), if self.is_source() { "aquamarine" } else if self.is_phony() { "goldenrod1" } else { "pink" }, ident = spaces, ))?; Ok(()) } pub fn process(&self, schedule: &mut impl FnMut(Rule)) -> bool { if self.is_source() { false } else if self .inputs() .map(|dep| dep.process(schedule) || dep.time() > self.time()) .fold(self.is_phony(), |pre, flag| pre || flag) { self.schedule_rule(schedule); true } else { false } } fn schedule_rule(&self, schedule: &mut impl FnMut(Rule)) { if let Some(rule) = &*self.0.rule.read() { log::trace!("Schedule rule for `{}`", self.name()); schedule(rule.clone()); } } } impl<K> From<Artifact<Input, K>> for Artifact<(), K> { fn from(artifact: Artifact<Input, K>) -> Self { Artifact(artifact.0, PhantomData) } } impl<K> From<Artifact<Output, K>> for Artifact<(), K> { fn from(artifact: Artifact<Output, K>) -> Self { Artifact(artifact.0, PhantomData) } } impl<K> From<Artifact<(), K>> for Artifact<Input, K> { fn from(artifact: Artifact<(), K>) -> Self { Artifact(artifact.0, PhantomData) } } impl<K> From<Artifact<Output, K>> for Artifact<Input, K> { fn from(artifact: Artifact<Output, K>) -> Self { Artifact(artifact.0, PhantomData) } } impl<K> Artifact<Output, K> { pub fn input(&self) -> Artifact<Input, K> { Artifact(self.0.clone(), PhantomData) } pub fn set_rule(&self, rule: impl Into<Rule>) { *self.0.rule.write() = Some(rule.into()); } } #[derive(Clone)] #[repr(transparent)] pub struct WeakArtifact<U = (), K = ()>(Weak<Internal>, PhantomData<(U, K)>); impl<U, K> WeakArtifact<U, K> { pub fn try_ref(&self) -> Option<Artifact<U, K>> { self.0.upgrade().map(|raw| Artifact(raw, PhantomData)) } } impl<U, K> WeakKey for WeakArtifact<U, K> { type Key = Internal; fn with_key<F, R>(view: &Self::Strong, f: F) -> R where F: FnOnce(&Self::Key) -> R, { f(&view.0) } } impl<U, K> WeakElement for WeakArtifact<U, K> { type Strong = Artifact<U, K>; fn new(view: &Self::Strong) -> Self { view.weak() } fn view(&self) -> Option<Self::Strong> { self.try_ref() } fn clone(view: &Self::Strong) -> Self::Strong { view.clone() } } pub type ArtifactWeakSet<K> = WeakSet<WeakArtifact<(), K>>; #[derive(Default)] pub struct StoreInternal { pub actual: Mut<ArtifactWeakSet<Actual>>, pub phony: Mut<ArtifactWeakSet<Phony>>, } #[derive(Default, Clone, Deref)] pub struct ArtifactStore(Ref<StoreInternal>); impl ArtifactStore { pub fn reset(&self) { *self.0.actual.write() = Default::default(); *self.0.phony.write() = Default::default(); } pub fn fmt_dot<F>(&self, matcher: F, f: &mut Formatter) -> FmtResult where F: Fn(&str) -> bool, { let mut queue: VecDeque<Vec<Artifact<Input>>> = { once( self.phony .read() .iter() .filter(|artifact| matcher(artifact.name())) .map(|a| a.into_kind_any().into_usage::<Input>().unwrap()) .collect(), ) .collect() }; let mut shown = Set::<Artifact<Input>>::default(); "digraph {\n".fmt(f)?; loop { if let Some(artifacts) = queue.pop_front() { for artifact in artifacts { if !shown.contains(&artifact) { artifact.fmt_dot_edges(1, f)?; let deps = artifact.inputs().collect::<Vec<_>>(); if !deps.is_empty() { queue.push_back(deps); } shown.insert(artifact); } } } else { break; } } for artifact in shown { artifact.fmt_dot_node(1, f)?; } "}\n".fmt(f)?; Ok(()) } } impl AsRef<ArtifactStore> for ArtifactStore { fn as_ref(&self) -> &ArtifactStore { &*self } } impl<'js, U: IsArtifactUsage> qjs::FromJs<'js> for Artifact<U> { fn from_js(ctx: qjs::Ctx<'js>, val: qjs::Value<'js>) -> qjs::Result<Self> { let artifact: Artifact = qjs::FromJs::from_js(ctx, val)?; if U::reusable(&artifact) { Ok(Artifact(artifact.0, PhantomData)) } else { Err(qjs::Error::new_from_js("artifact", U::NAME)) } } } impl<'js, K: IsArtifactKind> qjs::FromJs<'js> for Artifact<(), K> { fn from_js(ctx: qjs::Ctx<'js>, val: qjs::Value<'js>) -> qjs::Result<Self> { let artifact: Artifact = qjs::FromJs::from_js(ctx, val)?; if K::KIND == artifact.kind() { Ok(Artifact(artifact.0, PhantomData)) } else { Err(qjs::Error::new_from_js("artifact", K::NAME)) } } } impl<'js, U: IsArtifactUsage, K: IsArtifactKind> qjs::FromJs<'js> for Artifact<U, K> { fn from_js(ctx: qjs::Ctx<'js>, val: qjs::Value<'js>) -> qjs::Result<Self> { let artifact: Artifact<U> = qjs::FromJs::from_js(ctx, val)?; if K::KIND == artifact.kind() { Ok(Artifact(artifact.0, PhantomData)) } else { Err(qjs::Error::new_from_js("artifact", K::NAME)) } } } impl<'js, U: IsArtifactUsage> qjs::IntoJs<'js> for Artifact<U> { fn into_js(self, ctx: qjs::Ctx<'js>) -> qjs::Result<qjs::Value<'js>> { self.into_usage_any().into_js(ctx) } } impl<'js, K: IsArtifactKind> qjs::IntoJs<'js> for Artifact<(), K> { fn into_js(self, ctx: qjs::Ctx<'js>) -> qjs::Result<qjs::Value<'js>> { self.into_kind_any().into_js(ctx) } } impl<'js, U: IsArtifactUsage, K: IsArtifactKind> qjs::IntoJs<'js> for Artifact<U, K> { fn into_js(self, ctx: qjs::Ctx<'js>) -> qjs::Result<qjs::Value<'js>> { self.into_kind_any().into_usage_any().into_js(ctx) } } #[qjs::bind(module, public)] #[quickjs(bare)] mod js { pub use super::*; pub type AnyArtifact = Artifact; #[quickjs(rename = "Artifact", cloneable)] impl AnyArtifact { #[quickjs(rename = "new", hide)] pub fn ctor() -> Self {} #[quickjs(get, enumerable, hide)] pub fn name(&self) -> &String {} #[quickjs(get, enumerable, hide, rename = "type")] pub fn type_(&self) -> ArtifactType {} #[quickjs(get, enumerable, hide)] pub fn kind(&self) -> ArtifactKind {} #[quickjs(get, enumerable, hide)] pub fn description(&self) -> &String {} #[quickjs(get, enumerable, hide)] pub fn rule(&self) -> Option<Rule> {} #[quickjs(rename = "toString")] pub fn to_string_js(&self) -> String { self.to_string() } } }
extern crate cgmath; extern crate glium; use draw::planet::Planet; use draw::stars::Stars; use glium::*; use self::cgmath::{Vector4, Matrix4, Rad, SquareMatrix, Transform, Array}; //////////////////////////////////////////////////////////////////////////////// pub struct State { planet : Option<Planet>, stars : Option<Stars>, } impl State { pub fn new(display : &glium::Display) -> State { State { planet : Planet::new(display).map_err(|err| { println!("Couldn't construct Planet: {}", err)}).ok(), stars : Stars::new(display).map_err(|err| { println!("Couldn't construct Stars: {}", err)}).ok(), } } pub fn draw(&self, counter : i32, frame : &mut glium::Frame) { let dims = frame.get_dimensions(); frame.clear_color(0.0, 0.0, 0.0, 1.0); frame.clear_depth(1.0); let params = glium::DrawParameters { viewport: Some(Rect { left: 0, bottom : 0, width: dims.0*2, height: dims.1*2}), .. Default::default() }; self.stars.as_ref().map(|a| { a.draw(frame, &params) }); self.planet.as_ref().map(|p| { p.draw(counter, frame, &params) }); } }
use cli; pub struct Cidr { pub base_ip: String, pub fixed_bits: u8, } impl Cidr { pub fn from_args(args: cli::Args) -> Cidr { let cidr: String = args.arg_cidr; let cidr_parts = cidr.split('/'); let ip: String = cidr_parts.clone().nth(0).unwrap().to_string(); let fixed_bits: &str = cidr_parts.clone().nth(1).unwrap(); let parsed_fixed_bits: u8 = u8::from_str_radix(fixed_bits, 10).unwrap(); return Cidr { base_ip: ip, fixed_bits: parsed_fixed_bits, }; } }
// --------------------------if let // if let语法让我们以一种不那么冗长的方式结合if和let,来处理只匹配一个模式的值而忽略其他模式的情况 // 下面匹配一个Option<u8>值,并且只希望值为三时执行代码: // let some_u8_value = Some(0u8); // match some_u8_value { // Some(3) => println!("three"), // _ => (), // } // 我们可以使用if let这种更短的方式编写 // if let Some(3) = some_u8_value{ // println!("three"); // } // let mut count = 0; // match coin{ // Coin::Quarter(state) => println!("State quarter from {:?}!",state), // _ => count += 1, // } // 或者可以使用这样的if let和else表达式 let mut count = 0; if let Coin::Quarter(state) = coin{ println!( "State quarter from {:?}!", state ); }else{ count += 1; }
// Copyright 2021 IPSE Developer. // This file is part of IPSE // 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 alt_serde::de::{Error, Unexpected}; // declare_error_trait use alt_serde::{Deserialize, Deserializer}; use app_crypto::sr25519; use codec::{Decode, Encode}; use frame_support::{debug, Parameter}; use frame_support::{ traits::{Currency, LockableCurrency}, StorageMap, StorageValue, }; use frame_system::{self as system}; use hex; use pallet_authority_discovery as authority_discovery; use pallet_timestamp as timestamp; use sp_core::{crypto::KeyTypeId, offchain::Timestamp}; use sp_runtime::offchain::http; use sp_runtime::RuntimeAppPublic; use sp_std::{convert::TryInto, prelude::*}; pub const CONTRACT_ACCOUNT: &[u8] = b"ipsecontract"; pub const DESTROY_ACCOUNT: &[u8] = b"eosio.saving"; pub const CONTRACT_SYMBOL: &[u8] = b"POST"; pub const VERIFY_STATUS: &[u8] = b"verify_status"; pub const PENDING_TIME_OUT: &'static str = "Error in waiting http response back"; pub const WAIT_HTTP_CONVER_REPONSE: &'static str = "Error in waiting http_result convert response"; #[cfg_attr(feature = "std", derive())] #[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] pub enum AddressStatus { Active, InActive, } impl Default for AddressStatus { fn default() -> Self { Self::InActive } } #[serde(crate = "alt_serde")] #[derive(Deserialize, Encode, Decode, Clone, Debug, PartialEq, Eq, Default)] pub struct PostTxTransferData { pub code: u64, pub irreversible: bool, pub is_post_transfer: bool, #[serde(deserialize_with = "de_string_to_bytes")] pub contract_account: Vec<u8>, #[serde(deserialize_with = "de_string_to_bytes")] pub from: Vec<u8>, #[serde(deserialize_with = "de_string_to_bytes")] pub to: Vec<u8>, #[serde(deserialize_with = "de_string_to_bytes")] pub contract_symbol: Vec<u8>, #[serde(deserialize_with = "de_float_to_integer")] pub quantity: u64, #[serde(deserialize_with = "de_string_to_bytes")] pub memo: Vec<u8>, #[serde(deserialize_with = "de_string_decode_bytes")] pub pk: Vec<u8>, } pub fn de_string_to_bytes<'de, D>(de: D) -> Result<Vec<u8>, D::Error> where D: Deserializer<'de>, { let s: &str = Deserialize::deserialize(de)?; Ok(s.as_bytes().to_vec()) } pub fn de_string_decode_bytes<'de, D>(de: D) -> Result<Vec<u8>, D::Error> where D: Deserializer<'de>, { let s: &str = Deserialize::deserialize(de)?; if s.len() < 2 { return Err(D::Error::invalid_value(Unexpected::Str(s), &"0x...")) } match hex::decode(&s[2..]) { Ok(s_vec) => Ok(s_vec), Err(e) => { debug::error!("{:?}", e); Err(D::Error::invalid_value(Unexpected::Str(s), &"")) }, } // Ok(s.as_bytes().to_vec()) } pub fn de_float_to_integer<'de, D>(de: D) -> Result<u64, D::Error> where D: Deserializer<'de>, { let f: f64 = Deserialize::deserialize(de)?; Ok(f as u64) } pub(crate) const POST_KEYWORD: [&[u8]; 5] = [ b"{", // { b"\"", // " b"\":", // ": b",", // , b"}", // } ]; #[cfg_attr(feature = "std", derive(Debug, PartialEq, Eq))] #[derive(Encode, Decode, Clone)] pub struct FetchFailed<BlockNumber> { pub block_num: BlockNumber, pub tx: Vec<u8>, pub err: Vec<u8>, } pub type FetchFailedOf<T> = FetchFailed<<T as system::Trait>::BlockNumber>; pub type BlockNumberOf<T> = <T as system::Trait>::BlockNumber; // u32 pub type StdResult<T> = core::result::Result<T, &'static str>; pub type StrDispatchResult = core::result::Result<(), &'static str>; pub fn vecchars_to_vecbytes<I: IntoIterator<Item = char> + Clone>(it: &I) -> Vec<u8> { it.clone().into_iter().map(|c| c as u8).collect::<_>() } pub fn int_covert_str(inner: u64) -> Vec<u8> { let mut x: u32 = 0; let mut s: Vec<&str> = vec![]; loop { let r = inner / ((10 as u64).pow(x)); if r == 0 { s.reverse(); return s.join("").as_bytes().to_vec() } let r = r % 10; s.push(num_to_char(r)); x += 1; } } pub fn num_to_char<'a>(n: u64) -> &'a str { if n > 10 { return "" } match n { 0 => "0", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", _ => "", } } pub fn hex_to_u8(param: &[u8]) -> Vec<u8> { let hex_0x = "0x".as_bytes(); let tx_hex = hex::encode(param); let tx_vec = &[hex_0x, tx_hex.as_bytes()].concat(); return tx_vec.to_vec() } pub trait AccountIdPublicConver { type AccountId; fn into_account32(self) -> Self::AccountId; // 转化为accountId }
use std::ops::Range; /// A set of characters represented as a balanced binary tree of comparisons. /// This is used as an intermediate step in generating efficient code for /// matching a given character set. #[derive(PartialEq, Eq)] pub enum CharacterTree { Yes, Compare { value: char, operator: Comparator, consequence: Option<Box<CharacterTree>>, alternative: Option<Box<CharacterTree>>, }, } #[derive(PartialEq, Eq)] pub enum Comparator { Less, LessOrEqual, Equal, GreaterOrEqual, } impl CharacterTree { pub fn from_ranges(ranges: &[Range<char>]) -> Option<Self> { match ranges.len() { 0 => None, 1 => { let range = &ranges[0]; if range.start == range.end { Some(CharacterTree::Compare { operator: Comparator::Equal, value: range.start, consequence: Some(Box::new(CharacterTree::Yes)), alternative: None, }) } else { Some(CharacterTree::Compare { operator: Comparator::GreaterOrEqual, value: range.start, consequence: Some(Box::new(CharacterTree::Compare { operator: Comparator::LessOrEqual, value: range.end, consequence: Some(Box::new(CharacterTree::Yes)), alternative: None, })), alternative: None, }) } } len => { let mid = len / 2; let mid_range = &ranges[mid]; Some(CharacterTree::Compare { operator: Comparator::Less, value: mid_range.start, consequence: Self::from_ranges(&ranges[0..mid]).map(Box::new), alternative: Some(Box::new(CharacterTree::Compare { operator: Comparator::LessOrEqual, value: mid_range.end, consequence: Some(Box::new(CharacterTree::Yes)), alternative: Self::from_ranges(&ranges[(mid + 1)..]).map(Box::new), })), }) } } } #[cfg(test)] fn contains(&self, c: char) -> bool { match self { CharacterTree::Yes => true, CharacterTree::Compare { value, operator, alternative, consequence, } => { let condition = match operator { Comparator::Less => c < *value, Comparator::LessOrEqual => c <= *value, Comparator::Equal => c == *value, Comparator::GreaterOrEqual => c >= *value, }; if condition { consequence } else { alternative } .as_ref() .map_or(false, |a| a.contains(c)) } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_character_tree_simple() { let tree = CharacterTree::from_ranges(&['a'..'d', 'h'..'l', 'p'..'r', 'u'..'u', 'z'..'z']) .unwrap(); assert!(tree.contains('a')); assert!(tree.contains('b')); assert!(tree.contains('c')); assert!(tree.contains('d')); assert!(!tree.contains('e')); assert!(!tree.contains('f')); assert!(!tree.contains('g')); assert!(tree.contains('h')); assert!(tree.contains('i')); assert!(tree.contains('j')); assert!(tree.contains('k')); assert!(tree.contains('l')); assert!(!tree.contains('m')); assert!(!tree.contains('n')); assert!(!tree.contains('o')); assert!(tree.contains('p')); assert!(tree.contains('q')); assert!(tree.contains('r')); assert!(!tree.contains('s')); assert!(!tree.contains('s')); assert!(tree.contains('u')); assert!(!tree.contains('v')); } }
use super::{ JsonValue, comma::CommaExpression, json_object::JsonObjectExpression, name::NameExpression, property_assignment::PropertyAssignmentExpression, whitespace::WhitespaceExpression}; use crate::ast::json_array::JsonArrayExpression; use crate::ast::value::ValueExpression; pub trait ExpressionVisitor { fn visit_array(&mut self, expr: &mut JsonArrayExpression); fn visit_object(&mut self, expr: &mut JsonObjectExpression); fn visit_name(&mut self, expr: &mut NameExpression); fn visit_property_assignment(&mut self, expr: &mut PropertyAssignmentExpression); fn visit_comma_expression(&mut self, expr: &CommaExpression); fn visit_value(&mut self, expr: &mut ValueExpression); fn visit_whitespace_expression(&mut self, expr: &WhitespaceExpression); fn get_json(&self) -> &str; } pub struct JsonExpressionVisitor { pub json: String } impl JsonExpressionVisitor { pub fn new() -> impl ExpressionVisitor { JsonExpressionVisitor { json: String::new() } } } impl ExpressionVisitor for JsonExpressionVisitor { fn visit_array(&mut self, expr: &mut JsonArrayExpression) { self.json = format!("{}[", self.json); // TODO: Implement self.json = format!("{}]", self.json); } fn visit_object(&mut self, expr: &mut JsonObjectExpression) { self.json = format!("{}{{", self.json); for pae in expr.expressions.iter_mut() { pae.accept(self); } self.json = format!("{}}}", self.json); } fn visit_name(&mut self, expr: &mut NameExpression) { self.json = format!("{}\"{}\"", self.json, expr.name); } fn visit_property_assignment(&mut self, expr: &mut PropertyAssignmentExpression) { expr.name.accept(self); self.json = format!("{}: ", self.json); expr.value.accept(self); } fn visit_comma_expression(&mut self, _: &CommaExpression) { self.json = format!("{},", self.json); } fn visit_value(&mut self, expr: &mut ValueExpression) { self.json = match &expr.value { JsonValue::String(s) => format!("{}\"{}\"", self.json, *s), JsonValue::Number(d) => format!("{}{}", self.json, *d), JsonValue::Boolean(b) => format!("{}{}", self.json, *b) } } fn visit_whitespace_expression(&mut self, e: &WhitespaceExpression) { self.json = format!("{}{}", self.json, e.get_char()); } fn get_json(&self) -> &str { &self.json } }
mod cleanup_on_close; mod engine_force; mod gravitation; mod movement; mod player_position; pub use self::{ cleanup_on_close::CleanupOnCloseSystem, engine_force::EngineForceSystem, gravitation::GravitationSystem, movement::MovementSystem, player_position::PlayerPositionSystem, };
//! Contains the [`StorageBackend`](crate::storage::StorageBackend) trait that can be implemented to //! create virtual file systems for libunftp. //! //! Pre-made implementations exists on crates.io (search for `unftp-sbe-`) and you can define your //! own implementation to integrate your FTP(S) server with whatever storage mechanism you prefer. //! //! To create a new storage back-end: //! //! 1. Declare a dependency on the async-trait crate //! //! ```toml //! async-trait = "0.1.50" //! ``` //! //! 2. Implement the [`StorageBackend`](crate::storage::StorageBackend) trait and optionally the [`Metadata`](crate::storage::Metadata) trait: //! //! ```no_run //! use async_trait::async_trait; //! use libunftp::storage::{Fileinfo, Metadata, Result, StorageBackend}; //! use std::fmt::Debug; //! use std::path::{Path, PathBuf}; //! use libunftp::auth::DefaultUser; //! use std::time::SystemTime; //! //! #[derive(Debug)] //! pub struct Vfs {} //! //! #[derive(Debug)] //! pub struct Meta { //! inner: std::fs::Metadata, //! } //! //! impl Vfs { //! fn new() -> Vfs { Vfs{} } //! } //! //! #[async_trait] //! impl libunftp::storage::StorageBackend<DefaultUser> for Vfs { //! type Metadata = Meta; //! //! async fn metadata<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<Self::Metadata> { //! unimplemented!() //! } //! //! async fn list<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<Vec<Fileinfo<PathBuf, Self::Metadata>>> //! where //! <Self as StorageBackend<DefaultUser>>::Metadata: Metadata, //! { //! unimplemented!() //! } //! //! async fn get<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! start_pos: u64, //! ) -> Result<Box<dyn tokio::io::AsyncRead + Send + Sync + Unpin>> { //! unimplemented!() //! } //! //! async fn put< //! P: AsRef<Path> + Send + Debug, //! R: tokio::io::AsyncRead + Send + Sync + Unpin + 'static, //! >( //! &self, //! user: &DefaultUser, //! input: R, //! path: P, //! start_pos: u64, //! ) -> Result<u64> { //! unimplemented!() //! } //! //! async fn del<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<()> { //! unimplemented!() //! } //! //! async fn mkd<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<()> { //! unimplemented!() //! } //! //! async fn rename<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! from: P, //! to: P, //! ) -> Result<()> { //! unimplemented!() //! } //! //! async fn rmd<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<()> { //! unimplemented!() //! } //! //! async fn cwd<P: AsRef<Path> + Send + Debug>( //! &self, //! user: &DefaultUser, //! path: P, //! ) -> Result<()> { //! unimplemented!() //! } //! } //! //! impl Metadata for Meta { //! fn len(&self) -> u64 { //! self.inner.len() //! } //! //! fn is_dir(&self) -> bool { //! self.inner.is_dir() //! } //! //! fn is_file(&self) -> bool { //! self.inner.is_file() //! } //! //! fn is_symlink(&self) -> bool { //! self.inner.file_type().is_symlink() //! } //! //! fn modified(&self) -> Result<SystemTime> { //! self.inner.modified().map_err(|e| e.into()) //! } //! //! fn gid(&self) -> u32 { //! 0 //! } //! //! fn uid(&self) -> u32 { //! 0 //! } //! } //! ``` //! //! 3. Initialize it with the [`Server`](crate::Server): //! //! ```no_run //! # use unftp_sbe_fs::Filesystem; //! # struct Vfs{}; //! # impl Vfs { fn new() -> Filesystem { Filesystem::new("/") } } //! let vfs_provider = Box::new(|| Vfs::new()); //! let server = libunftp::Server::new(vfs_provider); //! ``` //! //! [`Server`]: ../struct.Server.html #![deny(missing_docs)] pub(crate) mod error; pub use error::{Error, ErrorKind}; pub(crate) mod storage_backend; pub use storage_backend::{Fileinfo, Metadata, Permissions, Result, StorageBackend, FEATURE_RESTART, FEATURE_SITEMD5};
use std::io; use std::os::raw::c_int; use std::os::unix::io::RawFd; use std::os::unix::prelude::CommandExt; use std::process::Command; use tokio::io::unix::AsyncFd; fn set_nonblocking(fd: RawFd) -> io::Result<()> { let r = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if r == -1 { return Err(io::Error::last_os_error()); } let r = unsafe { libc::fcntl(fd, libc::F_SETFL, r | libc::O_NONBLOCK) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(()) } fn set_cloexec(fd: RawFd) -> io::Result<()> { let r = unsafe { libc::fcntl(fd, libc::F_GETFD) }; if r == -1 { return Err(io::Error::last_os_error()); } let r = unsafe { libc::fcntl(fd, libc::F_SETFD, r | libc::FD_CLOEXEC) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(()) } fn set_nocloexec(fd: RawFd) -> io::Result<()> { let r = unsafe { libc::fcntl(fd, libc::F_GETFD) }; if r == -1 { return Err(io::Error::last_os_error()); } if r & libc::FD_CLOEXEC != 0 { let r = unsafe { libc::fcntl(fd, libc::F_SETFD, r ^ libc::FD_CLOEXEC) }; if r == -1 { return Err(io::Error::last_os_error()); } } Ok(()) } fn new_cloexec_nonblocking_pipe() -> io::Result<(c_int, c_int)> { let mut pair = [0; 2]; let r = unsafe { libc::pipe(pair.as_mut_ptr()) // no CLOEXEC (pipe2 does not exist on mac) }; if r == -1 { return Err(io::Error::last_os_error()); } for fd in pair { set_cloexec(fd)?; set_nonblocking(fd)?; } let [r, w] = pair; Ok((r, w)) } fn close(fd: RawFd) -> io::Result<()> { let r = unsafe { libc::close(fd) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(()) } /* fn dup(fd: RawFd) -> io::Result<RawFd> { let r = unsafe { libc::dup(fd) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(r) } */ fn dup2(fd: RawFd, newfd: RawFd) -> io::Result<()> { let r = unsafe { libc::dup2(fd, newfd) }; if r == -1 { return Err(io::Error::last_os_error()); } Ok(()) } #[tokio::test] async fn test_registered_fd_mai_not_be_inherit() -> io::Result<()> { // CLOEXEC, NONBLOCKINGなパイプを作成 let (r, w) = new_cloexec_nonblocking_pipe()?; // tokioのI/O Driverに登録 // Linuxはepoll, Macはkqueue let r = AsyncFd::new(r)?; // 3番目のファイル記述子をstatするpythonスクリプト let script = r#"#!/usr/bin/env python3 import os print(os.stat(3)) "#; let mut command = Command::new("python3"); command.args(["-c", script]); let mut child = unsafe { // AsyncFdから中で保持しているファイル記述子を取得 // AsyncFd自体は破棄しない let rfd = *r.get_ref(); command.pre_exec(move || { // pythonがstatする3番目のファイル記述子にセット if rfd == 3 { set_nocloexec(rfd)?; } else { dup2(rfd, 3)?; } Ok(()) }); let result = command.spawn(); // pre_execが呼び出されたらAsynFdをdrop drop(r); result }?; let ok = child.wait()?.success(); assert!(ok); close(w)?; Ok(()) }
pub mod color; pub mod libcore; pub mod math; pub mod utility; use libcore::material::Dielectric; use libcore::material::Lambertian; use libcore::material::Material; use libcore::material::Metallic; use color::{ray_color, transform_and_write_color, transform_to_u8_color, write_color, Color}; use libcore::camera::Camera; use libcore::hit::Hittable; use libcore::hittable_list::HittableList; use math::sphere::Sphere; use math::Point3; use math::Ray; use math::Vec3; use std::fs::File; use std::io::Result; use std::io::Write; use std::str::FromStr; use std::sync::Arc; use utility::{parse, ImageFormat, ThreadData}; extern crate image; use image::png::PNGEncoder; use image::ColorType; extern crate rayon; use rayon::prelude::*; extern crate rand; use rand::random; use rand::Rng; use std::time::Instant; pub fn main() { let mut image_width; let mut out_file; let mut format; let user_data = parse(); match &user_data { ImageFormat::PNG { width, filename } => { image_width = width; out_file = filename; format = "png".to_string(); } ImageFormat::PPM { width, filename } => { image_width = width; out_file = filename; format = "ppm".to_string(); } ImageFormat::Unknown => { writeln!(std::io::stderr(), "Unknown image file format"); panic!(); } } let aspect_ratio = 3.0 / 2.0; let image_height = *image_width as f64 / aspect_ratio; let image_width = *image_width; let samples_per_pixel = 500; let max_depth = 50; // Camera let lookfrom = Point3::with_values(13., 2., 3.); let lookat = Point3::with_values(0., 0., 0.); let vup = Vec3::with_values(0., 1., 0.); let dist_to_focus = 10.; let aperture = 0.1; let vfov = 20.; let cam = Camera::new( lookfrom, lookat, vup, vfov, aspect_ratio, aperture, dist_to_focus, ); let thread_shared = ThreadData { camera: &cam, image_height: image_height as usize, image_width, aspect_ratio, samples_per_pixel, max_depth, }; // World let ground_mat = Arc::new(Lambertian::new(Color::with_values(0.8, 0.8, 0.0))); let center_mat = Arc::new(Lambertian::new(Color::with_values(0.1, 0.2, 0.5))); let left_mat = Arc::new(Dielectric::new(1.5)); let right_mat = Arc::new(Metallic::new(Color::with_values(0.8, 0.6, 0.2), 0.0)); // let left_mat = Arc::new(Lambertian::new(Color::with_values(0., 0., 1.))); // let right_mat = Arc::new(Lambertian::new(Color::with_values(1., 0., 0.))); let mut world = HittableList::new(); // world.add(Arc::new(Sphere::new( // Point3::with_values(-R, 0., -1.0), // R, // left_mat.clone(), // ))); // world.add(Arc::new(Sphere::new( // Point3::with_values(R, 0., -1.0), // R, // right_mat.clone(), // ))); world.add(Arc::new(Sphere::new( Point3::with_values(0.0, -100.5, -1.0), 100.0, ground_mat.clone(), ))); world.add(Arc::new(Sphere::new( Point3::with_values(0.0, 0.0, -1.0), 0.5, center_mat.clone(), ))); world.add(Arc::new(Sphere::new( Point3::with_values(-1.0, 0.0, -1.0), -0.45, left_mat.clone(), ))); world.add(Arc::new(Sphere::new( Point3::with_values(-1.0, 0.0, -1.0), 0.5, left_mat.clone(), ))); world.add(Arc::new(Sphere::new( Point3::with_values(1.0, 0.0, -1.0), 0.5, right_mat.clone(), ))); // Render // let _ = func(&thread_shared, &out_file,Box::new(world)); // let _ = generate_as_ppm(&thread_shared, &out_file, Arc::new(world)); let world = random_scene(); let now = Instant::now(); match user_data { ImageFormat::PPM { .. } => { let _ = generate_as_ppm(&thread_shared, &out_file, &world); } ImageFormat::PNG { .. } => { let _ = generate_as_png(&thread_shared, &out_file, &world); } _ => panic!(), } let elapsed = now.elapsed(); println!("Done. Elapsed: {:.2?}", elapsed); } pub fn generate_as_png<T: Hittable + Sync>( data: &ThreadData, output: &String, world: &T, ) -> Result<()> { let image_width = data.image_width; let image_height = data.image_height; let mut pixels = vec![Color::new(); image_width * image_height as usize]; println!( "width: {:?} height: {:?} pixels: {:?}", image_width, image_height, image_height as usize * image_width ); // Old Crossbeam version horizontal bands // let threads = num_cpus::get(); // let rows_per_band = image_height as usize / threads + 1; // { // let bands: Vec<&mut [Color<u8>]> = pixels.chunks_mut(rows_per_band * image_width).collect(); // let _ = crossbeam::scope(|spawner| { // for (i, band) in bands.into_iter().enumerate() { // let top = rows_per_band * i; // let height = band.len() / image_width; // let band_bounds = (image_width, height); // spawner.spawn(move |_| { // render(band, band_bounds, top, *data); // }); // } // }); // } let bands: Vec<(usize, &mut [Color<u8>])> = pixels.chunks_mut(image_width).enumerate().collect(); bands.into_par_iter().for_each(|(i, band)| { let top = i; let band_bounds = (image_width, 1); render(band, band_bounds, top, data, world); }); write_image_png(output, &mut pixels, (image_width, image_height as usize)) } fn render( pixels: &mut [Color<u8>], bounds: (usize, usize), top: usize, data: &ThreadData, world: &dyn Hittable, ) { for j in 0..bounds.1 { for i in 0..bounds.0 { let mut pixel_color = Color::new(); for _ in 0..data.samples_per_pixel { let u = (i as f64 + random::<f64>()) / ((data.image_width - 1) as f64); let v = ((data.image_height - 1 - (j + top)) as f64 + random::<f64>()) / ((data.image_height - 1) as f64); let ray = data.camera.get_ray(u, v); pixel_color += &ray_color(&ray, world, data.max_depth); } pixels[j * bounds.1 + i] = transform_to_u8_color(&pixel_color, data.samples_per_pixel); } } } pub fn generate_as_ppm(data: &ThreadData, output: &String, world: &dyn Hittable) -> Result<()> { let mut file = match File::create(output) { Ok(f) => f, Err(err) => return Err(err), }; let aspect_ratio = data.aspect_ratio; let image_width = data.image_width; let image_height = image_width as f64 / aspect_ratio; // println!("P3\n{:?} {:?}\n255", image_width, image_height as u32); file.write_fmt(format_args!( "P3\n{:?} {:?}\n255\n", image_width, image_height as u32 )) .expect("Unable to write data"); for i in (0..(image_height as u64)).rev() { write!(std::io::stderr(), "\rScanlines remaining: {:?} ", i); for j in 0..image_width { let mut pixel_color = Color::<f64>::new(); for s in 0..data.samples_per_pixel { let u = (j as f64 + random::<f64>()) / ((image_width - 1) as f64); let v = (i as f64 + random::<f64>()) / (image_height - 1.0); let ray = data.camera.get_ray(u, v); pixel_color += &ray_color(&ray, world, data.max_depth); } transform_and_write_color(&mut file, &pixel_color, data.samples_per_pixel) .expect("Error writing to stdout") } } return Ok(()); } pub fn write_image_png(filename: &str, pixels: &[Color<u8>], bounds: (usize, usize)) -> Result<()> { let output = match File::create(filename) { Ok(f) => f, Err(err) => return Err(err), }; let encoder = PNGEncoder::new(output); // Flattening a big array takes a lot of time // TODO: Optimize this by making the render function // directly produce the rgb array // let pixels: Vec<&Color<u8>> = pixels.into_iter().rev().collect(); let pixels: Vec<u8> = pixels .iter() .flat_map(|s| s.as_std_vec().into_iter()) .collect(); match encoder.encode(&pixels, bounds.0 as u32, bounds.1 as u32, ColorType::Rgb8) { Ok(_) => Ok(()), Err(_) => Err(std::io::Error::new( std::io::ErrorKind::Other, "Could not encode png", )), } } pub fn hello_world() { let args: Vec<String> = std::env::args().collect(); let (width, height): (usize, usize) = parse_pair(&args[1], 'x').expect("error parsing image dimensions"); println!("P3\n{:?} {:?}\n255", width, height); for i in (0..height).rev() { write!(std::io::stderr(), "\rScanlines remaining: {:?} ", i); for j in 0..width { let c = transform_to_u8_color( &Color::with_values( (j as f64) / (width as f64 - 1.), (i as f64) / (height as f64 - 1.), 0.25, ), 100, ); let _ = write_color(&mut std::io::stdout(), &c); } } } fn parse_pair<T: FromStr>(s: &str, separator: char) -> Option<(T, T)> { match s.find(separator) { None => None, Some(index) => match (T::from_str(&s[..index]), T::from_str(&s[index + 1..])) { (Ok(l), Ok(r)) => Some((l, r)), _ => None, }, } } fn random_scene() -> HittableList<Sphere> { let mut world = HittableList::new(); let ground_mat = Arc::new(Lambertian::new(Color::with_values(0.5, 0.5, 0.5))); world.add(Arc::new(Sphere::new( Point3::with_values(0., -1000., 0.), 1000., ground_mat.clone(), ))); for a in -11..11 { for b in -11..11 { let choose_mat = random::<f64>(); let center = Point3::with_values( (a as f64) + 0.9 * random::<f64>(), 0.2, (b as f64) + 0.9 * random::<f64>(), ); if (center - Point3::with_values(4., 0.2, 0.)).length() > 0.9 { if choose_mat < 0.8 { // diffuse let albedo = random::<Color<f64>>() * random::<Color<f64>>(); let sphere_mat = Arc::new(Lambertian::new(albedo)); world.add(Arc::new(Sphere::new(center, 0.2, sphere_mat.clone()))); } else if choose_mat < 0.95 { // metal let mut rng = rand::thread_rng(); let albedo = Color::with_values( rng.gen_range(0., 0.5), rng.gen_range(0., 0.5), rng.gen_range(0., 0.5), ); let fuzz = rng.gen_range(0., 0.5); let sphere_mat = Arc::new(Metallic::new(albedo, fuzz)); world.add(Arc::new(Sphere::new(center, 0.2, sphere_mat.clone()))); } else { // glass let sphere_mat = Arc::new(Dielectric::new(1.5)); world.add(Arc::new(Sphere::new(center, 0.2, sphere_mat.clone()))); } } } } let mat1 = Arc::new(Dielectric::new(1.5)); world.add(Arc::new(Sphere::new( Point3::with_values(0., 1., 0.), 1.0, mat1.clone(), ))); let mat2 = Arc::new(Lambertian::new(Color::with_values(0.4, 0.2, 0.1))); world.add(Arc::new(Sphere::new( Point3::with_values(-4., 1., 0.), 1.0, mat2.clone(), ))); let mat3 = Arc::new(Metallic::new(Color::with_values(0.7, 0.6, 0.5), 0.)); world.add(Arc::new(Sphere::new( Point3::with_values(4., 1., 0.), 1.0, mat3.clone(), ))); return world; }
use super::TcpStream; #[cfg(debug_assertions)] use crate::poll::SelectorId; use crate::{event, sys, Interest, Registry, Token}; use std::fmt; use std::io; use std::net; use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; #[cfg(windows)] use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket}; /// A structure representing a socket server /// /// # Examples /// /// ``` /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// use mio::{Events, Interest, Poll, Token}; /// use mio::net::TcpListener; /// use std::time::Duration; /// /// let mut listener = TcpListener::bind("127.0.0.1:34255".parse()?)?; /// /// let mut poll = Poll::new()?; /// let mut events = Events::with_capacity(128); /// /// // Register the socket with `Poll` /// poll.registry().register(&mut listener, Token(0), Interest::READABLE)?; /// /// poll.poll(&mut events, Some(Duration::from_millis(100)))?; /// /// // There may be a socket ready to be accepted /// # Ok(()) /// # } /// ``` pub struct TcpListener { sys: sys::TcpListener, #[cfg(debug_assertions)] selector_id: SelectorId, } impl TcpListener { /// Convenience method to bind a new TCP listener to the specified address /// to receive new connections. /// /// This function will take the following steps: /// /// 1. Create a new TCP socket. /// 2. Set the `SO_REUSEADDR` option on the socket on Unix. /// 3. Bind the socket to the specified address. /// 4. Calls `listen` on the socket to prepare it to receive new connections. pub fn bind(addr: SocketAddr) -> io::Result<TcpListener> { sys::TcpListener::bind(addr).map(|sys| TcpListener { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), }) } /// Creates a new `TcpListener` from a standard `net::TcpListener`. /// /// This function is intended to be used to wrap a TCP listener from the /// standard library in the Mio equivalent. The conversion assumes nothing /// about the underlying listener; ; it is left up to the user to set it /// in non-blocking mode. pub fn from_std(listener: net::TcpListener) -> TcpListener { let sys = sys::TcpListener::from_std(listener); TcpListener { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } /// Accepts a new `TcpStream`. /// /// This may return an `Err(e)` where `e.kind()` is /// `io::ErrorKind::WouldBlock`. This means a stream may be ready at a later /// point and one should wait for an event before calling `accept` again. /// /// If an accepted stream is returned, the remote address of the peer is /// returned along with it. pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { self.sys .accept() .map(|(sys, addr)| (TcpStream::new(sys), addr)) } /// Returns the local socket address of this listener. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.sys.local_addr() } /// Creates a new independently owned handle to the underlying socket. /// /// The returned `TcpListener` is a reference to the same socket that this /// object references. Both handles can be used to accept incoming /// connections and options set on one listener will affect the other. pub fn try_clone(&self) -> io::Result<TcpListener> { self.sys.try_clone().map(|s| TcpListener { sys: s, #[cfg(debug_assertions)] selector_id: self.selector_id.clone(), }) } /// Sets the value for the `IP_TTL` option on this socket. /// /// This value sets the time-to-live field that is used in every packet sent /// from this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.sys.set_ttl(ttl) } /// Gets the value of the `IP_TTL` option for this socket. /// /// For more information about this option, see [`set_ttl`][link]. /// /// [link]: #method.set_ttl pub fn ttl(&self) -> io::Result<u32> { self.sys.ttl() } /// Get the value of the `SO_ERROR` option on this socket. /// /// This will retrieve the stored error in the underlying socket, clearing /// the field in the process. This can be useful for checking errors between /// calls. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.sys.take_error() } } impl event::Source for TcpListener { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate_selector(registry)?; self.sys.register(registry, token, interests) } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { self.sys.reregister(registry, token, interests) } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { self.sys.deregister(registry) } } impl fmt::Debug for TcpListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.sys, f) } } #[cfg(unix)] impl IntoRawFd for TcpListener { fn into_raw_fd(self) -> RawFd { self.sys.into_raw_fd() } } #[cfg(unix)] impl AsRawFd for TcpListener { fn as_raw_fd(&self) -> RawFd { self.sys.as_raw_fd() } } #[cfg(unix)] impl FromRawFd for TcpListener { unsafe fn from_raw_fd(fd: RawFd) -> TcpListener { TcpListener { sys: FromRawFd::from_raw_fd(fd), #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } } #[cfg(windows)] impl AsRawSocket for TcpListener { fn as_raw_socket(&self) -> RawSocket { self.sys.as_raw_socket() } } #[cfg(windows)] impl FromRawSocket for TcpListener { unsafe fn from_raw_socket(socket: RawSocket) -> TcpListener { TcpListener { sys: FromRawSocket::from_raw_socket(socket), #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } } #[cfg(windows)] impl IntoRawSocket for TcpListener { fn into_raw_socket(self) -> RawSocket { self.sys.into_raw_socket() } }
/// helper for turn a BufRead into a skim stream use std::env; use std::error::Error; use std::io::{BufRead, BufReader}; use std::process::{Child, Command, Stdio}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use crossbeam::channel::{bounded, Receiver, Sender}; use regex::Regex; use crate::field::FieldRange; use crate::helper::item::DefaultSkimItem; use crate::reader::CommandCollector; use crate::{SkimItem, SkimItemReceiver, SkimItemSender}; const CMD_CHANNEL_SIZE: usize = 1024; const ITEM_CHANNEL_SIZE: usize = 10240; const DELIMITER_STR: &str = r"[\t\n ]+"; const READ_BUFFER_SIZE: usize = 1024; pub enum CollectorInput { Pipe(Box<dyn BufRead + Send>), Command(String), } #[derive(Debug)] pub struct SkimItemReaderOption { buf_size: usize, use_ansi_color: bool, transform_fields: Vec<FieldRange>, matching_fields: Vec<FieldRange>, delimiter: Regex, line_ending: u8, show_error: bool, } impl Default for SkimItemReaderOption { fn default() -> Self { Self { buf_size: READ_BUFFER_SIZE, line_ending: b'\n', use_ansi_color: false, transform_fields: Vec::new(), matching_fields: Vec::new(), delimiter: Regex::new(DELIMITER_STR).unwrap(), show_error: false, } } } impl SkimItemReaderOption { pub fn buf_size(mut self, buf_size: usize) -> Self { self.buf_size = buf_size; self } pub fn line_ending(mut self, line_ending: u8) -> Self { self.line_ending = line_ending; self } pub fn ansi(mut self, enable: bool) -> Self { self.use_ansi_color = enable; self } pub fn delimiter(mut self, delimiter: &str) -> Self { if !delimiter.is_empty() { self.delimiter = Regex::new(delimiter).unwrap_or_else(|_| Regex::new(DELIMITER_STR).unwrap()); } self } pub fn with_nth(mut self, with_nth: &str) -> Self { if !with_nth.is_empty() { self.transform_fields = with_nth.split(',').filter_map(FieldRange::from_str).collect(); } self } pub fn transform_fields(mut self, transform_fields: Vec<FieldRange>) -> Self { self.transform_fields = transform_fields; self } pub fn nth(mut self, nth: &str) -> Self { if !nth.is_empty() { self.matching_fields = nth.split(',').filter_map(FieldRange::from_str).collect(); } self } pub fn matching_fields(mut self, matching_fields: Vec<FieldRange>) -> Self { self.matching_fields = matching_fields; self } pub fn read0(mut self, enable: bool) -> Self { if enable { self.line_ending = b'\0'; } else { self.line_ending = b'\n'; } self } pub fn show_error(mut self, show_error: bool) -> Self { self.show_error = show_error; self } pub fn build(self) -> Self { self } pub fn is_simple(&self) -> bool { !self.use_ansi_color && self.matching_fields.is_empty() && self.transform_fields.is_empty() } } pub struct SkimItemReader { option: Arc<SkimItemReaderOption>, } impl Default for SkimItemReader { fn default() -> Self { Self { option: Arc::new(Default::default()), } } } impl SkimItemReader { pub fn new(option: SkimItemReaderOption) -> Self { Self { option: Arc::new(option), } } pub fn option(mut self, option: SkimItemReaderOption) -> Self { self.option = Arc::new(option); self } } impl SkimItemReader { pub fn of_bufread(&self, source: impl BufRead + Send + 'static) -> SkimItemReceiver { if self.option.is_simple() { self.raw_bufread(source) } else { self.read_and_collect_from_command(Arc::new(AtomicUsize::new(0)), CollectorInput::Pipe(Box::new(source))) .0 } } /// helper: convert bufread into SkimItemReceiver fn raw_bufread(&self, mut source: impl BufRead + Send + 'static) -> SkimItemReceiver { let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = bounded(self.option.buf_size); let line_ending = self.option.line_ending; thread::spawn(move || { let mut buffer = Vec::with_capacity(1024); loop { buffer.clear(); // start reading match source.read_until(line_ending, &mut buffer) { Ok(n) => { if n == 0 { break; } if buffer.ends_with(&[b'\r', b'\n']) { buffer.pop(); buffer.pop(); } else if buffer.ends_with(&[b'\n']) || buffer.ends_with(&[b'\0']) { buffer.pop(); } let string = String::from_utf8_lossy(&buffer); let result = tx_item.send(Arc::new(string.into_owned())); if result.is_err() { break; } } Err(_err) => {} // String not UTF8 or other error, skip. } } }); rx_item } /// components_to_stop == 0 => all the threads have been stopped /// return (channel_for_receive_item, channel_to_stop_command) fn read_and_collect_from_command( &self, components_to_stop: Arc<AtomicUsize>, input: CollectorInput, ) -> (Receiver<Arc<dyn SkimItem>>, Sender<i32>) { let (command, mut source) = match input { CollectorInput::Pipe(pipe) => (None, pipe), CollectorInput::Command(cmd) => get_command_output(&cmd).expect("command not found"), }; let (tx_interrupt, rx_interrupt) = bounded(CMD_CHANNEL_SIZE); let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = bounded(ITEM_CHANNEL_SIZE); let started = Arc::new(AtomicBool::new(false)); let started_clone = started.clone(); let components_to_stop_clone = components_to_stop.clone(); let tx_item_clone = tx_item.clone(); let send_error = self.option.show_error; // listening to close signal and kill command if needed thread::spawn(move || { debug!("collector: command killer start"); components_to_stop_clone.fetch_add(1, Ordering::SeqCst); started_clone.store(true, Ordering::SeqCst); // notify parent that it is started let _ = rx_interrupt.recv(); // block waiting if let Some(mut child) = command { // clean up resources let _ = child.kill(); let _ = child.wait(); if send_error { let has_error = child .try_wait() .map(|os| os.map(|s| !s.success()).unwrap_or(true)) .unwrap_or(false); if has_error { let output = child.wait_with_output().expect("could not retrieve error message"); for line in String::from_utf8_lossy(&output.stderr).lines() { let _ = tx_item_clone.send(Arc::new(line.to_string())); } } } } components_to_stop_clone.fetch_sub(1, Ordering::SeqCst); debug!("collector: command killer stop"); }); while !started.load(Ordering::SeqCst) { // busy waiting for the thread to start. (components_to_stop is added) } let started = Arc::new(AtomicBool::new(false)); let started_clone = started.clone(); let tx_interrupt_clone = tx_interrupt.clone(); let option = self.option.clone(); thread::spawn(move || { debug!("collector: command collector start"); components_to_stop.fetch_add(1, Ordering::SeqCst); started_clone.store(true, Ordering::SeqCst); // notify parent that it is started let mut buffer = Vec::with_capacity(option.buf_size); loop { buffer.clear(); // start reading match source.read_until(option.line_ending, &mut buffer) { Ok(n) => { if n == 0 { break; } if buffer.ends_with(&[b'\r', b'\n']) { buffer.pop(); buffer.pop(); } else if buffer.ends_with(&[b'\n']) || buffer.ends_with(&[b'\0']) { buffer.pop(); } let line = String::from_utf8_lossy(&buffer).to_string(); let raw_item = DefaultSkimItem::new( line, option.use_ansi_color, &option.transform_fields, &option.matching_fields, &option.delimiter, ); match tx_item.send(Arc::new(raw_item)) { Ok(_) => {} Err(_) => { debug!("collector: failed to send item, quit"); break; } } } Err(_err) => {} // String not UTF8 or other error, skip. } } let _ = tx_interrupt_clone.send(1); // ensure the waiting thread will exit components_to_stop.fetch_sub(1, Ordering::SeqCst); debug!("collector: command collector stop"); }); while !started.load(Ordering::SeqCst) { // busy waiting for the thread to start. (components_to_stop is added) } (rx_item, tx_interrupt) } } impl CommandCollector for SkimItemReader { fn invoke(&mut self, cmd: &str, components_to_stop: Arc<AtomicUsize>) -> (SkimItemReceiver, Sender<i32>) { self.read_and_collect_from_command(components_to_stop, CollectorInput::Command(cmd.to_string())) } } type CommandOutput = (Option<Child>, Box<dyn BufRead + Send>); fn get_command_output(cmd: &str) -> Result<CommandOutput, Box<dyn Error>> { let shell = env::var("SHELL").unwrap_or_else(|_| "sh".to_string()); let mut command: Child = Command::new(shell) .arg("-c") .arg(cmd) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; let stdout = command .stdout .take() .ok_or_else(|| "command output: unwrap failed".to_owned())?; Ok((Some(command), Box::new(BufReader::new(stdout)))) }
use itertools::Itertools; use proconio::input; use proconio::marker::Usize1; fn main() { input! { n : usize, a : [Usize1; n] } let mut ans = vec![0]; for a in a.into_iter() { ans.push(ans[a] + 1); ans.push(ans[a] + 1); } println!("{}", ans.iter().join("\n")); }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `HSI16ON` reader - 16 MHz high-speed internal clock enable"] pub type HSI16ON_R = crate::BitReader<HSI16ON_A>; #[doc = "16 MHz high-speed internal clock enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSI16ON_A { #[doc = "0: Clock disabled"] Disabled = 0, #[doc = "1: Clock enabled"] Enabled = 1, } impl From<HSI16ON_A> for bool { #[inline(always)] fn from(variant: HSI16ON_A) -> Self { variant as u8 != 0 } } impl HSI16ON_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSI16ON_A { match self.bits { false => HSI16ON_A::Disabled, true => HSI16ON_A::Enabled, } } #[doc = "Clock disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == HSI16ON_A::Disabled } #[doc = "Clock enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == HSI16ON_A::Enabled } } #[doc = "Field `HSI16ON` writer - 16 MHz high-speed internal clock enable"] pub type HSI16ON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSI16ON_A>; impl<'a, REG, const O: u8> HSI16ON_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(HSI16ON_A::Disabled) } #[doc = "Clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(HSI16ON_A::Enabled) } } #[doc = "Field `HSI16KERON` reader - High-speed internal clock enable bit for some IP kernels"] pub use HSI16ON_R as HSI16KERON_R; #[doc = "Field `HSI16RDYF` reader - Internal high-speed clock ready flag"] pub type HSI16RDYF_R = crate::BitReader<HSI16RDYFR_A>; #[doc = "Internal high-speed clock ready flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSI16RDYFR_A { #[doc = "0: HSI 16 MHz oscillator not ready"] NotReady = 0, #[doc = "1: HSI 16 MHz oscillator ready"] Ready = 1, } impl From<HSI16RDYFR_A> for bool { #[inline(always)] fn from(variant: HSI16RDYFR_A) -> Self { variant as u8 != 0 } } impl HSI16RDYF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSI16RDYFR_A { match self.bits { false => HSI16RDYFR_A::NotReady, true => HSI16RDYFR_A::Ready, } } #[doc = "HSI 16 MHz oscillator not ready"] #[inline(always)] pub fn is_not_ready(&self) -> bool { *self == HSI16RDYFR_A::NotReady } #[doc = "HSI 16 MHz oscillator ready"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == HSI16RDYFR_A::Ready } } #[doc = "Field `HSI16RDYF` writer - Internal high-speed clock ready flag"] pub type HSI16RDYF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSI16RDYFR_A>; impl<'a, REG, const O: u8> HSI16RDYF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "HSI 16 MHz oscillator not ready"] #[inline(always)] pub fn not_ready(self) -> &'a mut crate::W<REG> { self.variant(HSI16RDYFR_A::NotReady) } #[doc = "HSI 16 MHz oscillator ready"] #[inline(always)] pub fn ready(self) -> &'a mut crate::W<REG> { self.variant(HSI16RDYFR_A::Ready) } } #[doc = "Field `HSI16DIVEN` reader - HSI16DIVEN"] pub type HSI16DIVEN_R = crate::BitReader<HSI16DIVEN_A>; #[doc = "HSI16DIVEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSI16DIVEN_A { #[doc = "0: no 16 MHz HSI division requested"] NotDivided = 0, #[doc = "1: 16 MHz HSI division by 4 requested"] Div4 = 1, } impl From<HSI16DIVEN_A> for bool { #[inline(always)] fn from(variant: HSI16DIVEN_A) -> Self { variant as u8 != 0 } } impl HSI16DIVEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSI16DIVEN_A { match self.bits { false => HSI16DIVEN_A::NotDivided, true => HSI16DIVEN_A::Div4, } } #[doc = "no 16 MHz HSI division requested"] #[inline(always)] pub fn is_not_divided(&self) -> bool { *self == HSI16DIVEN_A::NotDivided } #[doc = "16 MHz HSI division by 4 requested"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == HSI16DIVEN_A::Div4 } } #[doc = "Field `HSI16DIVEN` writer - HSI16DIVEN"] pub type HSI16DIVEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSI16DIVEN_A>; impl<'a, REG, const O: u8> HSI16DIVEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "no 16 MHz HSI division requested"] #[inline(always)] pub fn not_divided(self) -> &'a mut crate::W<REG> { self.variant(HSI16DIVEN_A::NotDivided) } #[doc = "16 MHz HSI division by 4 requested"] #[inline(always)] pub fn div4(self) -> &'a mut crate::W<REG> { self.variant(HSI16DIVEN_A::Div4) } } #[doc = "Field `HSI16DIVF` reader - HSI16DIVF"] pub type HSI16DIVF_R = crate::BitReader<HSI16DIVFR_A>; #[doc = "HSI16DIVF\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSI16DIVFR_A { #[doc = "0: 16 MHz HSI clock not divided"] NotDivided = 0, #[doc = "1: 16 MHz HSI clock divided by 4"] Div4 = 1, } impl From<HSI16DIVFR_A> for bool { #[inline(always)] fn from(variant: HSI16DIVFR_A) -> Self { variant as u8 != 0 } } impl HSI16DIVF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSI16DIVFR_A { match self.bits { false => HSI16DIVFR_A::NotDivided, true => HSI16DIVFR_A::Div4, } } #[doc = "16 MHz HSI clock not divided"] #[inline(always)] pub fn is_not_divided(&self) -> bool { *self == HSI16DIVFR_A::NotDivided } #[doc = "16 MHz HSI clock divided by 4"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == HSI16DIVFR_A::Div4 } } #[doc = "Field `HSI16OUTEN` reader - 16 MHz high-speed internal clock output enable"] pub type HSI16OUTEN_R = crate::BitReader<HSI16OUTEN_A>; #[doc = "16 MHz high-speed internal clock output enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSI16OUTEN_A { #[doc = "0: HSI output clock disabled"] Disabled = 0, #[doc = "1: HSI output clock enabled"] Enabled = 1, } impl From<HSI16OUTEN_A> for bool { #[inline(always)] fn from(variant: HSI16OUTEN_A) -> Self { variant as u8 != 0 } } impl HSI16OUTEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSI16OUTEN_A { match self.bits { false => HSI16OUTEN_A::Disabled, true => HSI16OUTEN_A::Enabled, } } #[doc = "HSI output clock disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == HSI16OUTEN_A::Disabled } #[doc = "HSI output clock enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == HSI16OUTEN_A::Enabled } } #[doc = "Field `HSI16OUTEN` writer - 16 MHz high-speed internal clock output enable"] pub type HSI16OUTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSI16OUTEN_A>; impl<'a, REG, const O: u8> HSI16OUTEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "HSI output clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(HSI16OUTEN_A::Disabled) } #[doc = "HSI output clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(HSI16OUTEN_A::Enabled) } } #[doc = "Field `MSION` reader - MSI clock enable bit"] pub use HSI16ON_R as MSION_R; #[doc = "Field `MSION` writer - MSI clock enable bit"] pub use HSI16ON_W as MSION_W; #[doc = "Field `MSIRDY` reader - MSI clock ready flag"] pub type MSIRDY_R = crate::BitReader<MSIRDYR_A>; #[doc = "MSI clock ready flag\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MSIRDYR_A { #[doc = "0: Oscillator is not stable"] NotReady = 0, #[doc = "1: Oscillator is stable"] Ready = 1, } impl From<MSIRDYR_A> for bool { #[inline(always)] fn from(variant: MSIRDYR_A) -> Self { variant as u8 != 0 } } impl MSIRDY_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSIRDYR_A { match self.bits { false => MSIRDYR_A::NotReady, true => MSIRDYR_A::Ready, } } #[doc = "Oscillator is not stable"] #[inline(always)] pub fn is_not_ready(&self) -> bool { *self == MSIRDYR_A::NotReady } #[doc = "Oscillator is stable"] #[inline(always)] pub fn is_ready(&self) -> bool { *self == MSIRDYR_A::Ready } } #[doc = "Field `HSEON` reader - HSE clock enable bit"] pub use HSI16ON_R as HSEON_R; #[doc = "Field `HSEON` writer - HSE clock enable bit"] pub use HSI16ON_W as HSEON_W; #[doc = "Field `HSERDY` reader - HSE clock ready flag"] pub use MSIRDY_R as HSERDY_R; #[doc = "Field `HSEBYP` reader - HSE clock bypass bit"] pub type HSEBYP_R = crate::BitReader<HSEBYP_A>; #[doc = "HSE clock bypass bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSEBYP_A { #[doc = "0: HSE oscillator not bypassed"] NotBypassed = 0, #[doc = "1: HSE oscillator bypassed"] Bypassed = 1, } impl From<HSEBYP_A> for bool { #[inline(always)] fn from(variant: HSEBYP_A) -> Self { variant as u8 != 0 } } impl HSEBYP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HSEBYP_A { match self.bits { false => HSEBYP_A::NotBypassed, true => HSEBYP_A::Bypassed, } } #[doc = "HSE oscillator not bypassed"] #[inline(always)] pub fn is_not_bypassed(&self) -> bool { *self == HSEBYP_A::NotBypassed } #[doc = "HSE oscillator bypassed"] #[inline(always)] pub fn is_bypassed(&self) -> bool { *self == HSEBYP_A::Bypassed } } #[doc = "Field `HSEBYP` writer - HSE clock bypass bit"] pub type HSEBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, HSEBYP_A>; impl<'a, REG, const O: u8> HSEBYP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "HSE oscillator not bypassed"] #[inline(always)] pub fn not_bypassed(self) -> &'a mut crate::W<REG> { self.variant(HSEBYP_A::NotBypassed) } #[doc = "HSE oscillator bypassed"] #[inline(always)] pub fn bypassed(self) -> &'a mut crate::W<REG> { self.variant(HSEBYP_A::Bypassed) } } #[doc = "Field `CSSHSEON` reader - Clock security system on HSE enable bit"] pub use HSI16ON_R as CSSHSEON_R; #[doc = "Field `CSSHSEON` writer - Clock security system on HSE enable bit"] pub use HSI16ON_W as CSSHSEON_W; #[doc = "Field `RTCPRE` reader - TC/LCD prescaler"] pub type RTCPRE_R = crate::FieldReader<RTCPRE_A>; #[doc = "TC/LCD prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum RTCPRE_A { #[doc = "0: HSE divided by 2"] Div2 = 0, #[doc = "1: HSE divided by 4"] Div4 = 1, #[doc = "2: HSE divided by 8"] Div8 = 2, #[doc = "3: HSE divided by 16"] Div16 = 3, } impl From<RTCPRE_A> for u8 { #[inline(always)] fn from(variant: RTCPRE_A) -> Self { variant as _ } } impl crate::FieldSpec for RTCPRE_A { type Ux = u8; } impl RTCPRE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RTCPRE_A { match self.bits { 0 => RTCPRE_A::Div2, 1 => RTCPRE_A::Div4, 2 => RTCPRE_A::Div8, 3 => RTCPRE_A::Div16, _ => unreachable!(), } } #[doc = "HSE divided by 2"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == RTCPRE_A::Div2 } #[doc = "HSE divided by 4"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == RTCPRE_A::Div4 } #[doc = "HSE divided by 8"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == RTCPRE_A::Div8 } #[doc = "HSE divided by 16"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == RTCPRE_A::Div16 } } #[doc = "Field `RTCPRE` writer - TC/LCD prescaler"] pub type RTCPRE_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O, RTCPRE_A>; impl<'a, REG, const O: u8> RTCPRE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "HSE divided by 2"] #[inline(always)] pub fn div2(self) -> &'a mut crate::W<REG> { self.variant(RTCPRE_A::Div2) } #[doc = "HSE divided by 4"] #[inline(always)] pub fn div4(self) -> &'a mut crate::W<REG> { self.variant(RTCPRE_A::Div4) } #[doc = "HSE divided by 8"] #[inline(always)] pub fn div8(self) -> &'a mut crate::W<REG> { self.variant(RTCPRE_A::Div8) } #[doc = "HSE divided by 16"] #[inline(always)] pub fn div16(self) -> &'a mut crate::W<REG> { self.variant(RTCPRE_A::Div16) } } #[doc = "Field `PLLON` reader - PLL enable bit"] pub use HSI16ON_R as PLLON_R; #[doc = "Field `PLLON` writer - PLL enable bit"] pub use HSI16ON_W as PLLON_W; #[doc = "Field `PLLRDY` reader - PLL clock ready flag"] pub type PLLRDY_R = crate::BitReader<PLLRDYR_A>; #[doc = "PLL clock ready flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PLLRDYR_A { #[doc = "0: PLL unlocked"] Unlocked = 0, #[doc = "1: PLL locked"] Locked = 1, } impl From<PLLRDYR_A> for bool { #[inline(always)] fn from(variant: PLLRDYR_A) -> Self { variant as u8 != 0 } } impl PLLRDY_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PLLRDYR_A { match self.bits { false => PLLRDYR_A::Unlocked, true => PLLRDYR_A::Locked, } } #[doc = "PLL unlocked"] #[inline(always)] pub fn is_unlocked(&self) -> bool { *self == PLLRDYR_A::Unlocked } #[doc = "PLL locked"] #[inline(always)] pub fn is_locked(&self) -> bool { *self == PLLRDYR_A::Locked } } impl R { #[doc = "Bit 0 - 16 MHz high-speed internal clock enable"] #[inline(always)] pub fn hsi16on(&self) -> HSI16ON_R { HSI16ON_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - High-speed internal clock enable bit for some IP kernels"] #[inline(always)] pub fn hsi16keron(&self) -> HSI16KERON_R { HSI16KERON_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Internal high-speed clock ready flag"] #[inline(always)] pub fn hsi16rdyf(&self) -> HSI16RDYF_R { HSI16RDYF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - HSI16DIVEN"] #[inline(always)] pub fn hsi16diven(&self) -> HSI16DIVEN_R { HSI16DIVEN_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - HSI16DIVF"] #[inline(always)] pub fn hsi16divf(&self) -> HSI16DIVF_R { HSI16DIVF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - 16 MHz high-speed internal clock output enable"] #[inline(always)] pub fn hsi16outen(&self) -> HSI16OUTEN_R { HSI16OUTEN_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 8 - MSI clock enable bit"] #[inline(always)] pub fn msion(&self) -> MSION_R { MSION_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - MSI clock ready flag"] #[inline(always)] pub fn msirdy(&self) -> MSIRDY_R { MSIRDY_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 16 - HSE clock enable bit"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - HSE clock bypass bit"] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Clock security system on HSE enable bit"] #[inline(always)] pub fn csshseon(&self) -> CSSHSEON_R { CSSHSEON_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bits 20:21 - TC/LCD prescaler"] #[inline(always)] pub fn rtcpre(&self) -> RTCPRE_R { RTCPRE_R::new(((self.bits >> 20) & 3) as u8) } #[doc = "Bit 24 - PLL enable bit"] #[inline(always)] pub fn pllon(&self) -> PLLON_R { PLLON_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - PLL clock ready flag"] #[inline(always)] pub fn pllrdy(&self) -> PLLRDY_R { PLLRDY_R::new(((self.bits >> 25) & 1) != 0) } } impl W { #[doc = "Bit 0 - 16 MHz high-speed internal clock enable"] #[inline(always)] #[must_use] pub fn hsi16on(&mut self) -> HSI16ON_W<CR_SPEC, 0> { HSI16ON_W::new(self) } #[doc = "Bit 2 - Internal high-speed clock ready flag"] #[inline(always)] #[must_use] pub fn hsi16rdyf(&mut self) -> HSI16RDYF_W<CR_SPEC, 2> { HSI16RDYF_W::new(self) } #[doc = "Bit 3 - HSI16DIVEN"] #[inline(always)] #[must_use] pub fn hsi16diven(&mut self) -> HSI16DIVEN_W<CR_SPEC, 3> { HSI16DIVEN_W::new(self) } #[doc = "Bit 5 - 16 MHz high-speed internal clock output enable"] #[inline(always)] #[must_use] pub fn hsi16outen(&mut self) -> HSI16OUTEN_W<CR_SPEC, 5> { HSI16OUTEN_W::new(self) } #[doc = "Bit 8 - MSI clock enable bit"] #[inline(always)] #[must_use] pub fn msion(&mut self) -> MSION_W<CR_SPEC, 8> { MSION_W::new(self) } #[doc = "Bit 16 - HSE clock enable bit"] #[inline(always)] #[must_use] pub fn hseon(&mut self) -> HSEON_W<CR_SPEC, 16> { HSEON_W::new(self) } #[doc = "Bit 18 - HSE clock bypass bit"] #[inline(always)] #[must_use] pub fn hsebyp(&mut self) -> HSEBYP_W<CR_SPEC, 18> { HSEBYP_W::new(self) } #[doc = "Bit 19 - Clock security system on HSE enable bit"] #[inline(always)] #[must_use] pub fn csshseon(&mut self) -> CSSHSEON_W<CR_SPEC, 19> { CSSHSEON_W::new(self) } #[doc = "Bits 20:21 - TC/LCD prescaler"] #[inline(always)] #[must_use] pub fn rtcpre(&mut self) -> RTCPRE_W<CR_SPEC, 20> { RTCPRE_W::new(self) } #[doc = "Bit 24 - PLL enable bit"] #[inline(always)] #[must_use] pub fn pllon(&mut self) -> PLLON_W<CR_SPEC, 24> { PLLON_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0x0300"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0x0300; }
use std::fs; use std::str::FromStr; pub fn file2vec<T: FromStr>(filename: &String)->Vec<Result<T, T::Err>>{ let contents = fs::read_to_string(filename) .expect("Something went wrong reading the file"); contents.split("\n") .map(|x: &str| x.parse::<T>()) .collect() } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Token { Atom(char), Op(char), Eof, } pub struct Lexer { tokens: Vec<Token>, } impl Lexer { fn new(input: &str) -> Lexer { let mut tokens = input .chars() .filter(|it| !it.is_ascii_whitespace()) .map(|c| match c { '0'..='9' | 'a'..='z' | 'A'..='Z' => Token::Atom(c), _ => Token::Op(c), }) .collect::<Vec<_>>(); tokens.reverse(); Lexer { tokens } } fn next(&mut self) -> Token { self.tokens.pop().unwrap_or(Token::Eof) } fn peek(&mut self) -> Token { self.tokens.last().copied().unwrap_or(Token::Eof) } }
/// Predicate classifying Infer modes #[rustc_on_unimplemented = "`{Self}` is not a valid Infer mode"] pub trait Mode {} /// Infer mode for operations #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Constant {} impl Mode for Thunk {} /// Infer mode for thunks #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum Thunk {} impl Mode for Constant {}
//! Dummy lib
extern crate slog; extern crate slog_term; use slog::*; use std::io::{self}; use std::path::Path; #[macro_use] extern crate prettytable; use prettytable::format; use prettytable::{Cell, Row, Table}; extern crate lazy_static; extern crate clap; use clap::{Arg, Command}; extern crate dirs; extern crate adr_core; use adr_core::adr_repo::Status; extern crate adr_config; use adr_config::config::AdrToolConfig; extern crate adr_search; fn get_logger() -> slog::Logger { let cfg: AdrToolConfig = adr_config::config::get_config(); let decorator = slog_term::TermDecorator::new().build(); let drain = slog_term::FullFormat::new(decorator).build().fuse(); let drain = slog_async::Async::new(drain).build().fuse(); let drain = slog::LevelFilter::new( drain, Level::from_usize(cfg.log_level).unwrap_or(Level::Debug), ) .fuse(); slog::Logger::root(drain, o!()) } pub fn list_all_adr() -> io::Result<()> { let cfg: AdrToolConfig = adr_config::config::get_config(); let mut table = Table::new(); table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.set_titles( row![b -> "ID", b -> "Title", b-> "Status", b -> "Date", b -> "File", b -> "Tags"], ); info!(get_logger(), "list all ADR from [{}]",&cfg.adr_src_dir); for entry in adr_core::adr_repo::list_all_adr(Path::new(&cfg.adr_src_dir))? { //table.add_row(row![entry.title, Fg->entry.status, entry.path, entry.tags]); let style = get_cell_style(entry.status); table.add_row(Row::new(vec![ Cell::new(&entry.file_id.to_string()), Cell::new(&entry.title).style_spec(style.as_str()), Cell::new(&entry.status.as_str()).style_spec(style.as_str()), Cell::new(&entry.date), Cell::new(&entry.path()), Cell::new(&entry.tags), ])); } // Print the table to stdout table.printstd(); Ok(()) } fn set_config(name: &str, value: &str) -> Result<()> { adr_config::config::set_config(name, value) } /** * default config will be stored in directories::ProjectDir::config_dir() (a.k.a ls -la $HOME/Library/Preferences/) * * TODO need to find a proper way to map to the config struct - could be managed with a macro */ fn list_all_config() -> Result<()> { info!(get_logger(), "list all configuration elements",); let cfg: AdrToolConfig = adr_config::config::get_config(); let mut table = Table::new(); table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.set_titles(row![b -> "Property", b -> "Value", b -> "Modifiable"]); //table.add_row(row![adr_config::config::ADR_ROOT_DIR, cfg.adr_root_dir, "Y"]); table.add_row(row![adr_config::config::ADR_SRC_DIR, cfg.adr_src_dir, "Y"]); table.add_row(row![ adr_config::config::ADR_TEMPLATE_DIR, cfg.adr_template_dir, "Y" ]); table.add_row(row![ adr_config::config::ADR_TEMPLATE_FILE, cfg.adr_template_file, "Y" ]); table.add_row(row![ adr_config::config::ADR_SEARCH_INDEX, cfg.adr_search_index, "N" ]); table.add_row(row![adr_config::config::LOG_LEVEL, cfg.log_level, "Y"]); table.add_row(row![ adr_config::config::USE_ID_PREFIX, cfg.use_id_prefix, "Y" ]); table.add_row(row![ adr_config::config::ID_PREFIX_WIDTH, cfg.id_prefix_width, "Y" ]); // Print the table to stdout table.printstd(); Ok(()) } fn list_all_tags() -> Result<()> { let cfg: AdrToolConfig = adr_config::config::get_config(); let mut table = Table::new(); table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.set_titles(row![b -> "Tags", b -> "Popularity"]); let popularity = adr_core::adr_repo::get_tags_popularity(Path::new(&cfg.adr_src_dir))?; for (key, val) in popularity.iter() { table.add_row(row![key, val]); } // Print the table to stdout table.printstd(); Ok(()) } fn build_index() -> Result<()> { let cfg: AdrToolConfig = adr_config::config::get_config(); let adrs = match adr_core::adr_repo::list_all_adr(Path::new(&cfg.adr_src_dir)) { Ok(e) => e, Err(why) => panic!("{:?}", why), }; adr_search::search::build_index(cfg.adr_search_index, adrs).unwrap(); Ok(()) } fn search(query: String) -> Result<()> { let cfg: AdrToolConfig = adr_config::config::get_config(); let mut table = Table::new(); table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.set_titles(row![b -> "Title", b -> "Status", b -> "Date", b -> "File", b -> "(Indexed) Tags"]); //TODO get limit value from AdrToolConfig let limit: usize = 100; let results = match adr_search::search::search(cfg.adr_search_index, query, limit) { Ok(e) => e, Err(why) => panic!("{:?}", why), }; let results_size = &results.len(); for entry in results { let status = &entry.status[0]; let status_as_enum = Status::from_str(String::from(status)); let style = get_cell_style(status_as_enum); table.add_row(Row::new(vec![ Cell::new(&entry.title[0]).style_spec(style.as_str()), Cell::new(&entry.status[0]).style_spec(style.as_str()), Cell::new(&entry.date[0]), Cell::new(&entry.path[0]), Cell::new(&entry.tags[0]), ])); } table.printstd(); println!("\n Displayed {:?} results - Results are limited to {:?} items - run adr config -h to change configuration", &results_size, &limit); Ok(()) } fn get_cell_style(status: Status) -> String { let style = match status { Status::WIP => "bFy", Status::DECIDED => "FG", Status::COMPLETED => "Fg", Status::COMPLETES => "Fg", _ => "FR", }; style.to_string() } /** * init based on config */ fn init() -> Result<()> { adr_config::config::init() } /// /// The main program - start the CLI ... fn main() { // let cmd = Command::new("adr") .version("0.1.0") .about("A CLI to help you manage your ADR in git") .subcommand( Command::new("list") .about("Lists all Decision Records") .version("0.1.0"), ) .subcommand( Command::new("init") .about("Init ADRust based on config") .version("0.1.0"), ) .subcommand( Command::new("config") .about("Manage Configuration Items") .subcommand_required(true) .subcommand( Command::new("set") .about("Update Configuration Item with specified value") .arg( Arg::new("name") .short('n') .long("name") .required(true) .takes_value(true) .help("the name of the property"), ) .arg( Arg::new("value") .short('v') .long("value") .required(true) .takes_value(true) .help("the value of the property"), ), ) .subcommand( Command::new("list").about("List All the Configuration Items"), ), ) .subcommand( Command::new("tags") .about("Manage Tags") .subcommand_required(true) .subcommand(Command::new("list").about("List All the Tags")), ) .subcommand( Command::new("lf") .about("Manages ADRs lifecycle") .subcommand_required(true) .subcommand( Command::new("new") .about("Creates a new Decision Record") .version("0.1.0") .arg( Arg::new("title") .short('t') .long("title") .takes_value(true) .required(true) .help("Give the title of your Decision Record"), ) .arg( Arg::new("path") .short('p') .long("path") .takes_value(true) .required(false) .help("Specify relative path (nested directories)"), ), ) .subcommand( Command::new("decided") .about("update the Status to Decide") .version("0.1.0") .arg( Arg::new("path") .short('p') .long("path") .takes_value(true) .required(true) .help("Give the path of your Decision Record"), ), ) .subcommand( Command::new("superseded-by") .about("Supersede the decision with another decision") .version("0.1.0") .arg( Arg::new("path") .short('p') .long("path") .takes_value(true) .required(true) .help("Give the path of your Decision Record"), ) .arg( Arg::new("by") .short('b') .long("by") .takes_value(true) .required(true) .help("Give the path of your Decision Record"), ), ) .subcommand( Command::new("completed-by") .about("Complete a decision with another decision") .version("0.1.0") .arg( Arg::new("path") .short('p') .long("path") .takes_value(true) .required(true) .help("Give the path of the DR which is completed by"), ) .arg( Arg::new("by") .short('b') .long("by") .takes_value(true) .required(true) .help("Give the path of the DR which completes"), ), ) .subcommand( Command::new("obsoleted") .about("Uodate the Status to Obsoleted") .version("0.1.0") .arg( Arg::new("path") .short('p') .long("path") .takes_value(true) .required(true) .help("Give the path of your Decision Record"), ), ), ) .subcommand( Command::new("search") .about("Search across all ADRs") .version("0.1.0") .args(&[ Arg::new("query") .short('q') .long("query") .takes_value(true) .required(true) .conflicts_with_all(&["build-index", "title"]) .help("Provide your search query. The following syntax can be used :\n\ \ta AND b OR c will search for documents containing terms (a and b) or c, \n\ \t-b will search documents that do not contain the term b, \n\ \t+c will search documents that must contain the term c, \n\ \ttags:a AND tags:b will search for documents that have the tags a and b, \n\ \ttitle:a will search on title of the document, \n\ \tdate:[2022-08-01T00:00:00Z TO 2023-10-02T18:00:00Z] AND tags:BPaaS will search between the specified range and date (and specified tag), \n\ \tstatus:decided will search for decided documents"), Arg::new("build-index") .short('b') .long("build-index") .takes_value(false) .required(true) .conflicts_with_all(&["query", "title"]) .help("Build the index based on available ADRs."), Arg::new("title") .short('t') .long("title") .takes_value(true) .required(true) .conflicts_with_all(&["build-index", "query"]) .help("Search on title property of ADR only"), ]), ); // let _matches = cmd.get_matches(); let subcommand = _matches.subcommand(); match subcommand { Some(("list", _matches)) => { list_all_adr().unwrap(); } Some(("init", _matches)) => { init().unwrap(); } Some(("lf", matches)) => match matches.subcommand() { Some(("new", matches)) => { if matches.is_present("title") { adr_core::adr_repo::create_adr( adr_config::config::get_config(), matches.value_of("path"), matches.value_of("title").unwrap(), ) .unwrap(); } } Some(("decided", set_matches)) => { if set_matches.is_present("path") { let file_path = set_matches.value_of("path").unwrap(); let cfg: AdrToolConfig = adr_config::config::get_config(); let base_path = Path::new(&cfg.adr_src_dir); adr_core::adr_repo::transition_to_decided(base_path, file_path).unwrap(); } } Some(("completed-by", set_matches)) => { if set_matches.is_present("path") && set_matches.is_present("by") { let cfg: AdrToolConfig = adr_config::config::get_config(); let base_path = Path::new(&cfg.adr_src_dir); let file_path = set_matches.value_of("path").unwrap(); let by_path = set_matches.value_of("by").unwrap(); adr_core::adr_repo::transition_to_completed_by(base_path, file_path, by_path) .unwrap(); } } Some(("superseded-by", set_matches)) => { if set_matches.is_present("path") && set_matches.is_present("by") { let cfg: AdrToolConfig = adr_config::config::get_config(); let base_path = Path::new(&cfg.adr_src_dir); let file_path = set_matches.value_of("path").unwrap(); let by_path = set_matches.value_of("by").unwrap(); adr_core::adr_repo::transition_to_superseded_by(base_path, file_path, by_path) .unwrap(); } } Some(("obsoleted", set_matches)) => { if set_matches.is_present("path") { let cfg: AdrToolConfig = adr_config::config::get_config(); let base_path = Path::new(&cfg.adr_src_dir); let file_path = set_matches.value_of("path").unwrap(); adr_core::adr_repo::transition_to_obsoleted(base_path, file_path).unwrap(); } } _ => unreachable!(), }, Some(("config", config_matches)) => match config_matches.subcommand() { Some(("list", _remote_matches)) => { list_all_config().unwrap(); } Some(("set", set_matches)) => { set_config( set_matches.value_of("name").unwrap(), set_matches.value_of("value").unwrap(), ) .unwrap(); } _ => unreachable!(), }, Some(("tags", tags_matches)) => match tags_matches.subcommand() { Some(("list", _remote_matches)) => { list_all_tags().unwrap(); } _ => unreachable!(), }, Some(("search", search_matches)) => { if search_matches.is_present("query") { let query = search_matches.value_of("query").unwrap().to_string(); search(query).unwrap(); } if search_matches.is_present("build-index") { build_index().unwrap(); } if search_matches.is_present("title") { let query = search_matches.value_of("title").unwrap().to_string(); search("title:".to_string() + &query).unwrap(); } } _ => println!("Please, try adr --help"), // If all subcommands are defined above, anything else is unreachabe!() } }
//! Error types used in sea-query. /// Result type for sea-query pub type Result<T> = anyhow::Result<T, Error>; #[derive(thiserror::Error, Debug, PartialEq, Eq)] pub enum Error { /// Column and value vector having different length #[error("Columns and values length mismatch: {col_len} != {val_len}")] ColValNumMismatch { col_len: usize, val_len: usize }, }
pub const LV2_MIDI_MidiEvent: *const u8 = b"http://lv2plug.in/ns/ext/midi#MidiEvent\0" as *const u8; type LV2_Midi_Message_Type = u8; pub const LV2_MIDI_MSG_INVALID: LV2_Midi_Message_Type = 0; // Invalid Message pub const LV2_MIDI_MSG_NOTE_OFF: LV2_Midi_Message_Type = 0x80; // Note Off pub const LV2_MIDI_MSG_NOTE_ON: LV2_Midi_Message_Type = 0x90; // Note On pub const LV2_MIDI_MSG_NOTE_PRESSURE: LV2_Midi_Message_Type = 0xA0; // Note Pressure pub const LV2_MIDI_MSG_CONTROLLER: LV2_Midi_Message_Type = 0xB0; // Controller pub const LV2_MIDI_MSG_PGM_CHANGE: LV2_Midi_Message_Type = 0xC0; // Program Change pub const LV2_MIDI_MSG_CHANNEL_PRESSURE: LV2_Midi_Message_Type = 0xD0; // Channel Pressure pub const LV2_MIDI_MSG_BENDER: LV2_Midi_Message_Type = 0xE0; // Pitch Bender pub const LV2_MIDI_MSG_SYSTEM_EXCLUSIVE: LV2_Midi_Message_Type = 0xF0; // System Exclusive Begin pub const LV2_MIDI_MSG_MTC_QUARTER: LV2_Midi_Message_Type = 0xF1; // MTC Quarter Frame pub const LV2_MIDI_MSG_SONG_POS: LV2_Midi_Message_Type = 0xF2; // Song Position pub const LV2_MIDI_MSG_SONG_SELECT: LV2_Midi_Message_Type = 0xF3; // Song Select pub const LV2_MIDI_MSG_TUNE_REQUEST: LV2_Midi_Message_Type = 0xF6; // Tune Request pub const LV2_MIDI_MSG_CLOCK: LV2_Midi_Message_Type = 0xF8; // Clock pub const LV2_MIDI_MSG_START: LV2_Midi_Message_Type = 0xFA; // Start pub const LV2_MIDI_MSG_CONTINUE: LV2_Midi_Message_Type = 0xFB; // Continue pub const LV2_MIDI_MSG_STOP: LV2_Midi_Message_Type = 0xFC; // Stop pub const LV2_MIDI_MSG_ACTIVE_SENSE: LV2_Midi_Message_Type = 0xFE; // Active Sensing pub const LV2_MIDI_MSG_RESET: LV2_Midi_Message_Type = 0xFF; // Reset type LV2_Midi_Controller = u8; pub const LV2_MIDI_CTL_MSB_BANK: LV2_Midi_Controller = 0x00; // Bank Selection pub const LV2_MIDI_CTL_MSB_MODWHEEL: LV2_Midi_Controller = 0x01; // Modulation pub const LV2_MIDI_CTL_MSB_BREATH: LV2_Midi_Controller = 0x02; // Breath pub const LV2_MIDI_CTL_MSB_FOOT: LV2_Midi_Controller = 0x04; // Foot pub const LV2_MIDI_CTL_MSB_PORTAMENTO_TIME: LV2_Midi_Controller = 0x05; // Portamento Time pub const LV2_MIDI_CTL_MSB_DATA_ENTRY: LV2_Midi_Controller = 0x06; // Data Entry pub const LV2_MIDI_CTL_MSB_MAIN_VOLUME: LV2_Midi_Controller = 0x07; // Main Volume pub const LV2_MIDI_CTL_MSB_BALANCE: LV2_Midi_Controller = 0x08; // Balance pub const LV2_MIDI_CTL_MSB_PAN: LV2_Midi_Controller = 0x0A; // Panpot pub const LV2_MIDI_CTL_MSB_EXPRESSION: LV2_Midi_Controller = 0x0B; // Expression pub const LV2_MIDI_CTL_MSB_EFFECT1: LV2_Midi_Controller = 0x0C; // Effect1 pub const LV2_MIDI_CTL_MSB_EFFECT2: LV2_Midi_Controller = 0x0D; // Effect2 pub const LV2_MIDI_CTL_MSB_GENERAL_PURPOSE1: LV2_Midi_Controller = 0x10; // General Purpose 1 pub const LV2_MIDI_CTL_MSB_GENERAL_PURPOSE2: LV2_Midi_Controller = 0x11; // General Purpose 2 pub const LV2_MIDI_CTL_MSB_GENERAL_PURPOSE3: LV2_Midi_Controller = 0x12; // General Purpose 3 pub const LV2_MIDI_CTL_MSB_GENERAL_PURPOSE4: LV2_Midi_Controller = 0x13; // General Purpose 4 pub const LV2_MIDI_CTL_LSB_BANK: LV2_Midi_Controller = 0x20; // Bank Selection pub const LV2_MIDI_CTL_LSB_MODWHEEL: LV2_Midi_Controller = 0x21; // Modulation pub const LV2_MIDI_CTL_LSB_BREATH: LV2_Midi_Controller = 0x22; // Breath pub const LV2_MIDI_CTL_LSB_FOOT: LV2_Midi_Controller = 0x24; // Foot pub const LV2_MIDI_CTL_LSB_PORTAMENTO_TIME: LV2_Midi_Controller = 0x25; // Portamento Time pub const LV2_MIDI_CTL_LSB_DATA_ENTRY: LV2_Midi_Controller = 0x26; // Data Entry pub const LV2_MIDI_CTL_LSB_MAIN_VOLUME: LV2_Midi_Controller = 0x27; // Main Volume pub const LV2_MIDI_CTL_LSB_BALANCE: LV2_Midi_Controller = 0x28; // Balance pub const LV2_MIDI_CTL_LSB_PAN: LV2_Midi_Controller = 0x2A; // Panpot pub const LV2_MIDI_CTL_LSB_EXPRESSION: LV2_Midi_Controller = 0x2B; // Expression pub const LV2_MIDI_CTL_LSB_EFFECT1: LV2_Midi_Controller = 0x2C; // Effect1 pub const LV2_MIDI_CTL_LSB_EFFECT2: LV2_Midi_Controller = 0x2D; // Effect2 pub const LV2_MIDI_CTL_LSB_GENERAL_PURPOSE1: LV2_Midi_Controller = 0x30; // General Purpose 1 pub const LV2_MIDI_CTL_LSB_GENERAL_PURPOSE2: LV2_Midi_Controller = 0x31; // General Purpose 2 pub const LV2_MIDI_CTL_LSB_GENERAL_PURPOSE3: LV2_Midi_Controller = 0x32; // General Purpose 3 pub const LV2_MIDI_CTL_LSB_GENERAL_PURPOSE4: LV2_Midi_Controller = 0x33; // General Purpose 4 pub const LV2_MIDI_CTL_SUSTAIN: LV2_Midi_Controller = 0x40; // Sustain Pedal pub const LV2_MIDI_CTL_PORTAMENTO: LV2_Midi_Controller = 0x41; // Portamento pub const LV2_MIDI_CTL_SOSTENUTO: LV2_Midi_Controller = 0x42; // Sostenuto pub const LV2_MIDI_CTL_SOFT_PEDAL: LV2_Midi_Controller = 0x43; // Soft Pedal pub const LV2_MIDI_CTL_LEGATO_FOOTSWITCH: LV2_Midi_Controller = 0x44; // Legato Foot Switch pub const LV2_MIDI_CTL_HOLD2: LV2_Midi_Controller = 0x45; // Hold2 pub const LV2_MIDI_CTL_SC1_SOUND_VARIATION: LV2_Midi_Controller = 0x46; // SC1 Sound Variation pub const LV2_MIDI_CTL_SC2_TIMBRE: LV2_Midi_Controller = 0x47; // SC2 Timbre pub const LV2_MIDI_CTL_SC3_RELEASE_TIME: LV2_Midi_Controller = 0x48; // SC3 Release Time pub const LV2_MIDI_CTL_SC4_ATTACK_TIME: LV2_Midi_Controller = 0x49; // SC4 Attack Time pub const LV2_MIDI_CTL_SC5_BRIGHTNESS: LV2_Midi_Controller = 0x4A; // SC5 Brightness pub const LV2_MIDI_CTL_SC6: LV2_Midi_Controller = 0x4B; // SC6 pub const LV2_MIDI_CTL_SC7: LV2_Midi_Controller = 0x4C; // SC7 pub const LV2_MIDI_CTL_SC8: LV2_Midi_Controller = 0x4D; // SC8 pub const LV2_MIDI_CTL_SC9: LV2_Midi_Controller = 0x4E; // SC9 pub const LV2_MIDI_CTL_SC10: LV2_Midi_Controller = 0x4F; // SC10 pub const LV2_MIDI_CTL_GENERAL_PURPOSE5: LV2_Midi_Controller = 0x50; // General Purpose 5 pub const LV2_MIDI_CTL_GENERAL_PURPOSE6: LV2_Midi_Controller = 0x51; // General Purpose 6 pub const LV2_MIDI_CTL_GENERAL_PURPOSE7: LV2_Midi_Controller = 0x52; // General Purpose 7 pub const LV2_MIDI_CTL_GENERAL_PURPOSE8: LV2_Midi_Controller = 0x53; // General Purpose 8 pub const LV2_MIDI_CTL_PORTAMENTO_CONTROL: LV2_Midi_Controller = 0x54; // Portamento Control pub const LV2_MIDI_CTL_E1_REVERB_DEPTH: LV2_Midi_Controller = 0x5B; // E1 Reverb Depth pub const LV2_MIDI_CTL_E2_TREMOLO_DEPTH: LV2_Midi_Controller = 0x5C; // E2 Tremolo Depth pub const LV2_MIDI_CTL_E3_CHORUS_DEPTH: LV2_Midi_Controller = 0x5D; // E3 Chorus Depth pub const LV2_MIDI_CTL_E4_DETUNE_DEPTH: LV2_Midi_Controller = 0x5E; // E4 Detune Depth pub const LV2_MIDI_CTL_E5_PHASER_DEPTH: LV2_Midi_Controller = 0x5F; // E5 Phaser Depth pub const LV2_MIDI_CTL_DATA_INCREMENT: LV2_Midi_Controller = 0x60; // Data Increment pub const LV2_MIDI_CTL_DATA_DECREMENT: LV2_Midi_Controller = 0x61; // Data Decrement pub const LV2_MIDI_CTL_NRPN_LSB: LV2_Midi_Controller = 0x62; // Non-registered Parameter Number pub const LV2_MIDI_CTL_NRPN_MSB: LV2_Midi_Controller = 0x63; // Non-registered Parameter Number pub const LV2_MIDI_CTL_RPN_LSB: LV2_Midi_Controller = 0x64; // Registered Parameter Number pub const LV2_MIDI_CTL_RPN_MSB: LV2_Midi_Controller = 0x65; // Registered Parameter Number pub const LV2_MIDI_CTL_ALL_SOUNDS_OFF: LV2_Midi_Controller = 0x78; // All Sounds Off pub const LV2_MIDI_CTL_RESET_CONTROLLERS: LV2_Midi_Controller = 0x79; // Reset Controllers pub const LV2_MIDI_CTL_LOCAL_CONTROL_SWITCH: LV2_Midi_Controller = 0x7A; // Local Control Switch pub const LV2_MIDI_CTL_ALL_NOTES_OFF: LV2_Midi_Controller = 0x7B; // All Notes Off pub const LV2_MIDI_CTL_OMNI_OFF: LV2_Midi_Controller = 0x7C; // Omni Off pub const LV2_MIDI_CTL_OMNI_ON: LV2_Midi_Controller = 0x7D; // Omni On pub const LV2_MIDI_CTL_MONO1: LV2_Midi_Controller = 0x7E; // Mono1 pub const LV2_MIDI_CTL_MONO2: LV2_Midi_Controller = 0x7F; // Mono2 pub fn midi_is_voice_message(msg: *const u8) -> bool { unsafe { *msg >= 0x80 && *msg < 0xF0 } } pub fn midi_is_system_message(msg: *const u8) -> bool { unsafe { match *msg { 0xF4 => false, 0xF5 => false, 0xF7 => false, 0xF9 => false, 0xFD => false, _ => (*msg & 0xF0) == 0xF0, } } } pub fn midi_message_type(msg: *const u8) -> LV2_Midi_Message_Type { unsafe { if midi_is_voice_message(msg) { (*msg & 0xF0) as LV2_Midi_Message_Type } else if midi_is_system_message(msg) { *msg as LV2_Midi_Message_Type } else { LV2_MIDI_MSG_INVALID } } }
use std; use std::mem::size_of; use std::slice; use std::path::Path; use failure::{Error, ResultExt}; use read_process_memory::{Pid, TryIntoProcessHandle, copy_address, ProcessHandle}; use proc_maps::{get_process_maps, MapRange}; use python_bindings::{v2_7_15, v3_3_7, v3_5_5, v3_6_6, v3_7_0}; use python_interpreters; use stack_trace::{StackTrace, get_stack_traces}; use binary_parser::{parse_binary, BinaryInfo}; use utils::{copy_struct, copy_pointer}; use python_interpreters::{InterpreterState, ThreadState}; #[derive(Debug)] pub struct PythonSpy { pub pid: Pid, pub process: ProcessHandle, pub version: Version, pub interpreter_address: usize, pub threadstate_address: usize, pub python_filename: String, pub python_install_path: String, pub version_string: String } impl PythonSpy { pub fn new(pid: Pid) -> Result<PythonSpy, Error> { let process = pid.try_into_process_handle().context("Failed to open target process")?; // get basic process information (memory maps/symbols etc) let python_info = PythonProcessInfo::new(pid)?; let version = get_python_version(&python_info, process)?; info!("python version {} detected", version); let interpreter_address = get_interpreter_address(&python_info, process, &version)?; info!("Found interpreter at 0x{:016x}", interpreter_address); // lets us figure out which thread has the GIL let threadstate_address = match python_info.get_symbol("_PyThreadState_Current") { Some(&addr) => { info!("Found _PyThreadState_Current @ 0x{:016x}", addr); addr as usize }, None => { warn!("Failed to find _PyThreadState_Current symbol - won't be able to detect GIL usage"); 0 } }; // Figure out the base path of the python install let python_install_path = { let mut python_path = Path::new(&python_info.python_filename); if let Some(parent) = python_path.parent() { python_path = parent; if python_path.to_str().unwrap().ends_with("/bin") { if let Some(parent) = python_path.parent() { python_path = parent; } } } python_path.to_str().unwrap().to_string() }; let version_string = format!("python{}.{}", version.major, version.minor); Ok(PythonSpy{pid, process, version, interpreter_address, threadstate_address, python_filename: python_info.python_filename, python_install_path, version_string}) } /// Creates a PythonSpy object, retrying up to max_retries times /// mainly useful for the case where the process is just started and /// symbols/python interpreter might not be loaded yet pub fn retry_new(pid: Pid, max_retries:u64) -> Result<PythonSpy, Error> { let mut retries = 0; loop { let err = match PythonSpy::new(pid) { Ok(process) => { // verify that we can load a stack trace before returning success match process.get_stack_traces() { Ok(_) => return Ok(process), Err(err) => err } }, Err(err) => err }; // If we failed, retry a couple times before returning the last error retries += 1; if retries >= max_retries { return Err(err); } info!("Failed to connect to process, retrying. Error: {}", err); std::thread::sleep(std::time::Duration::from_millis(20)); } } /// Gets a StackTrace for each thread in the current process pub fn get_stack_traces(&self) -> Result<Vec<StackTrace>, Error> { match self.version { // Currently 3.7.x and 3.8.0a0 have the same ABI, but this might change // as 3.8 evolvess Version{major: 3, minor: 8, ..} => self._get_stack_traces::<v3_7_0::_is>(), Version{major: 3, minor: 7, ..} => self._get_stack_traces::<v3_7_0::_is>(), Version{major: 3, minor: 6, ..} => self._get_stack_traces::<v3_6_6::_is>(), // ABI for 3.4 and 3.5 is the same for our purposes Version{major: 3, minor: 5, ..} => self._get_stack_traces::<v3_5_5::_is>(), Version{major: 3, minor: 4, ..} => self._get_stack_traces::<v3_5_5::_is>(), Version{major: 3, minor: 3, ..} => self._get_stack_traces::<v3_3_7::_is>(), // ABI for 2.3/2.4/2.5/2.6/2.7 is also compatible Version{major: 2, minor: 3...7, ..} => self._get_stack_traces::<v2_7_15::_is>(), _ => Err(format_err!("Unsupported version of Python: {}", self.version)), } } // implementation of get_stack_traces, where we have a type for the InterpreterState fn _get_stack_traces<I: InterpreterState>(&self) -> Result<Vec<StackTrace>, Error> { // figure out what thread has the GIL by inspecting _PyThreadState_Current let mut gil_thread_id = 0; if self.threadstate_address > 0 { let addr: usize = copy_struct(self.threadstate_address, &self.process)?; if addr != 0 { let threadstate: I::ThreadState = copy_struct(addr, &self.process)?; gil_thread_id = threadstate.thread_id(); } } // Get the stack traces for each thread let interp: I = copy_struct(self.interpreter_address, &self.process) .context("Failed to copy PyInterpreterState from process")?; let mut traces = get_stack_traces(&interp, &self.process)?; // annotate traces to indicate which thread is holding the gil (if any), // and to provide a shortened filename for trace in &mut traces { if trace.thread_id == gil_thread_id { trace.owns_gil = true; } for frame in &mut trace.frames { frame.short_filename = Some(self.shorten_filename(&frame.filename).to_owned()); } } Ok(traces) } /// We want to display filenames without the boilerplate of the python installation /// directory etc. This strips off common prefixes from python library code. pub fn shorten_filename<'a>(&self, filename: &'a str) -> &'a str { if filename.starts_with(&self.python_install_path) { let mut filename = &filename[self.python_install_path.len() + 1..]; if filename.starts_with("lib") { filename = &filename[4..]; if filename.starts_with(&self.version_string) { filename = &filename[self.version_string.len() + 1..]; } if filename.starts_with("site-packages") { filename = &filename[14..]; } } filename } else { filename } } } /// Returns the version of python running in the process. fn get_python_version(python_info: &PythonProcessInfo, process: ProcessHandle) -> Result<Version, Error> { // If possible, grab the sys.version string from the processes memory (mac osx). if let Some(&addr) = python_info.get_symbol("Py_GetVersion.version") { info!("Getting version from symbol address"); return Ok(Version::scan_bytes(&copy_address(addr as usize, 128, &process)?)?); } // otherwise get version info from scanning BSS section for sys.version string info!("Getting version from python binary BSS"); let bss = copy_address(python_info.python_binary.bss_addr as usize, python_info.python_binary.bss_size as usize, &process)?; match Version::scan_bytes(&bss) { Ok(version) => return Ok(version), Err(err) => { info!("Failed to get version from BSS section: {}", err); // try again if there is a libpython.so if let Some(ref libpython) = python_info.libpython_binary { info!("Getting version from libpython BSS"); let bss = copy_address(libpython.bss_addr as usize, libpython.bss_size as usize, &process)?; match Version::scan_bytes(&bss) { Ok(version) => return Ok(version), Err(err) => info!("Failed to get version from libpython BSS section: {}", err) } } } } // the python_filename might have the version encoded in it (/usr/bin/python3.5 etc). // try reading that in (will miss patch level on python, but that shouldn't matter) info!("Trying to get version from path: {}", python_info.python_filename); let path = std::path::Path::new(&python_info.python_filename); if let Some(python) = path.file_name() { if let Some(python) = python.to_str() { if python.starts_with("python") { let tokens: Vec<&str> = python[6..].split('.').collect(); if tokens.len() >= 2 { if let (Ok(major), Ok(minor)) = (tokens[0].parse::<u64>(), tokens[1].parse::<u64>()) { return Ok(Version{major, minor, patch:0, release_flags: "".to_owned()}) } } } } } Err(format_err!("Failed to find python version from target process")) } fn get_interpreter_address(python_info: &PythonProcessInfo, process: ProcessHandle, version: &Version) -> Result<usize, Error> { // get the address of the main PyInterpreterState object from loaded symbols if we can // (this tends to be faster than scanning through the bss section) match version { Version{major: 3, minor: 7, ..} => { if let Some(&addr) = python_info.get_symbol("_PyRuntime") { // TODO: we actually want _PyRuntime.interpeters.head, and probably should // generate bindings for the pyruntime object rather than hardcode the offset (24) here return Ok(copy_struct((addr + 24) as usize, &process)?); } }, _ => { if let Some(&addr) = python_info.get_symbol("interp_head") { return Ok(copy_struct(addr as usize, &process) .context("Failed to copy PyInterpreterState location from process")?); } } }; info!("Failed to get interp_head from symbols, scanning BSS section from main binary"); // try scanning the BSS section of the binary for things that might be the interpreterstate match get_interpreter_address_from_binary(&python_info.python_binary, &python_info.maps, process, version) { Ok(addr) => Ok(addr), // Before giving up, try again if there is a libpython.so Err(err) => { info!("Failed to get interpreter from binary BSS, scanning libpython BSS"); match python_info.libpython_binary { Some(ref libpython) => { Ok(get_interpreter_address_from_binary(libpython, &python_info.maps, process, version)?) }, None => Err(err) } } } } fn get_interpreter_address_from_binary(binary: &BinaryInfo, maps: &[MapRange], process: ProcessHandle, version: &Version) -> Result<usize, Error> { // different versions have different layouts, check as appropiate match version { Version{major: 3, minor: 8, ..} => check_addresses::<v3_7_0::_is>(binary, maps, process), Version{major: 3, minor: 7, ..} => check_addresses::<v3_7_0::_is>(binary, maps, process), Version{major: 3, minor: 6, ..} => check_addresses::<v3_6_6::_is>(binary, maps, process), Version{major: 3, minor: 5, ..} => check_addresses::<v3_5_5::_is>(binary, maps, process), Version{major: 3, minor: 4, ..} => check_addresses::<v3_5_5::_is>(binary, maps, process), Version{major: 3, minor: 3, ..} => check_addresses::<v3_3_7::_is>(binary, maps, process), Version{major: 2, minor: 3...7, ..} => check_addresses::<v2_7_15::_is>(binary, maps, process), _ => Err(format_err!("Unsupported version of Python: {}", version)) } } // Checks whether a block of memory (from BSS/.data etc) contains pointers that are pointing // to a valid PyInterpreterState fn check_addresses<I>(binary: &BinaryInfo, maps: &[MapRange], process: ProcessHandle) -> Result<usize, Error> where I: python_interpreters::InterpreterState { // On windows, we can't just check if a pointer is valid by looking to see if it points // to something in the virtual memory map. Brute-force it instead #[cfg(windows)] fn maps_contain_addr(addr: usize, maps: &[MapRange]) -> bool { true } #[cfg(not(windows))] use proc_maps::maps_contain_addr; // We're going to scan the BSS/data section for things, and try to narrowly scan things that // look like pointers to PyinterpreterState let bss = copy_address(binary.bss_addr as usize, binary.bss_size as usize, &process)?; #[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))] let addrs = unsafe { slice::from_raw_parts(bss.as_ptr() as *const usize, bss.len() / size_of::<usize>()) }; for &addr in addrs { if maps_contain_addr(addr, maps) { // this address points to valid memory. try loading it up as a PyInterpreterState // to further check let interp: I = match copy_struct(addr, &process) { Ok(interp) => interp, Err(_) => continue }; // get the pythreadstate pointer from the interpreter object, and if it is also // a valid pointer then load it up. let threads = interp.head(); if maps_contain_addr(threads as usize, maps) { // If the threadstate points back to the interpreter like we expect, then // this is almost certainly the address of the intrepreter let thread = match copy_pointer(threads, &process) { Ok(thread) => thread, Err(_) => continue }; // as a final sanity check, try getting the stack_traces, and only return if this works if thread.interp() as usize == addr && get_stack_traces(&interp, &process).is_ok() { return Ok(addr); } } } } Err(format_err!("Failed to find a python interpreter in the .data section")) } /// Holds information about the python process: memory map layout, parsed binary info /// for python /libpython etc. pub struct PythonProcessInfo { python_binary: BinaryInfo, // if python was compiled with './configure --enabled-shared', code/symbols will // be in a libpython.so file instead of the executable. support that. libpython_binary: Option<BinaryInfo>, maps: Vec<MapRange>, python_filename: String, } impl PythonProcessInfo { fn new(pid: Pid) -> Result<PythonProcessInfo, Error> { // get virtual memory layout let maps = get_process_maps(pid)?; info!("Got virtual memory maps from pid {}:", pid); for map in &maps { info!("map: {:016x}-{:016x} {}{}{} {}", map.start(), map.start() + map.size(), if map.is_read() {'r'} else {'-'}, if map.is_write() {'w'} else {'-'}, if map.is_exec() {'x'} else {'-'}, map.filename().as_ref().unwrap_or(&"".to_owned())); } // parse the main python binary let (python_binary, python_filename) = { #[cfg(unix)] let python_bin_pattern = "bin/python"; #[cfg(windows)] let python_bin_pattern = ".exe"; let map = maps.iter() .find(|m| if let Some(pathname) = &m.filename() { pathname.contains(python_bin_pattern) && m.is_exec() } else { false }).ok_or_else(|| format_err!("Couldn't find python binary"))?; let filename = map.filename().clone().unwrap(); info!("Found python binary @ {}", filename); // TODO: consistent types? u64 -> usize? for map.start etc let mut python_binary = parse_binary(&filename, map.start() as u64)?; // windows symbols are stored in separate files (.pdb), load #[cfg(windows)] python_binary.symbols.extend(get_windows_python_symbols(pid, &filename, map.start() as u64)?); // For OSX, need to adjust main binary symbols by substracting _mh_execute_header // (which we've added to by map.start already, so undo that here) #[cfg(target_os = "macos")] { let offset = python_binary.symbols["_mh_execute_header"] - map.start() as u64; for address in python_binary.symbols.values_mut() { *address -= offset; } if python_binary.bss_addr != 0 { python_binary.bss_addr -= offset; } } (python_binary, filename) }; // likewise handle libpython for python versions compiled with --enabled-shared let libpython_binary = { #[cfg(unix)] let is_python_lib = |pathname: &str| pathname.contains("lib/libpython"); #[cfg(windows)] let is_python_lib = |pathname: &str| { use regex::Regex; lazy_static! { static ref RE: Regex = Regex::new(r"\\python\d\d.dll$").unwrap(); } RE.is_match(pathname) }; let libmap = maps.iter() .find(|m| if let Some(ref pathname) = &m.filename() { is_python_lib(pathname) && m.is_exec() } else { false }); let mut libpython_binary: Option<BinaryInfo> = None; if let Some(libpython) = libmap { if let Some(filename) = &libpython.filename() { info!("Found libpython binary @ {}", filename); let mut parsed = parse_binary(filename, libpython.start() as u64)?; #[cfg(windows)] parsed.symbols.extend(get_windows_python_symbols(pid, filename, libpython.start() as u64)?); libpython_binary = Some(parsed); } } // On OSX, it's possible that the Python library is a dylib loaded up from the system // framework (like /System/Library/Frameworks/Python.framework/Versions/2.7/Python) // In this case read in the dyld_info information and figure out the filename from there #[cfg(target_os = "macos")] { if libpython_binary.is_none() { use proc_maps::mac_maps::get_dyld_info; let dyld_infos = get_dyld_info(pid)?; for dyld in &dyld_infos { let segname = unsafe { std::ffi::CStr::from_ptr(dyld.segment.segname.as_ptr()) }; info!("dyld: {:016x}-{:016x} {:10} {}", dyld.segment.vmaddr, dyld.segment.vmaddr + dyld.segment.vmsize, segname.to_string_lossy(), dyld.filename); } let python_dyld_data = dyld_infos.iter() .find(|m| m.filename.ends_with("/Python") && m.filename.starts_with("/System/Library/Frameworks/") && m.segment.segname[0..7] == [95, 95, 68, 65, 84, 65, 0]); if let Some(libpython) = python_dyld_data { info!("Found libpython binary from dyld @ {}", libpython.filename); let mut binary = parse_binary(&libpython.filename, libpython.segment.vmaddr)?; // TODO: bss addr offsets returned from parsing binary are wrong // (assumes data section isn't split from text section like done here). // BSS occurs somewhere in the data section, just scan that // (could later tighten this up to look at segment sections too) binary.bss_addr = libpython.segment.vmaddr; binary.bss_size = libpython.segment.vmsize; libpython_binary = Some(binary); } } } libpython_binary }; Ok(PythonProcessInfo{python_binary, libpython_binary, maps, python_filename}) } pub fn get_symbol(&self, symbol: &str) -> Option<&u64> { if let Some(addr) = self.python_binary.symbols.get(symbol) { return Some(addr); } match self.libpython_binary { Some(ref binary) => binary.symbols.get(symbol), None => None } } } // We can't use goblin to parse external symbol files (like in a separate .pdb file) on windows, // So use the win32 api to load up the couple of symbols we need on windows. Note: // we still can get export's from the PE file #[cfg(windows)] use std::collections::HashMap; #[cfg(windows)] pub fn get_windows_python_symbols(pid: Pid, filename: &str, offset: u64) -> std::io::Result<HashMap<String, u64>> { use proc_maps::win_maps::SymbolLoader; let handler = SymbolLoader::new(pid)?; let _module = handler.load_module(filename)?; // need to keep this module in scope let mut ret = HashMap::new(); // currently we only need a subset of symbols, and enumerating the symbols is // expensive (via SymEnumSymbolsW), so rather than load up all symbols like we // do for goblin, just load the the couple we need directly. for symbol in ["_PyThreadState_Current", "interp_head", "_PyRuntime"].iter() { if let Ok((base, addr)) = handler.address_from_name(symbol) { // If we have a module base (ie from PDB), need to adjust by the offset // otherwise seems like we can take address directly let addr = if base == 0 { addr } else { offset + addr - base }; ret.insert(String::from(*symbol), addr); } } Ok(ret) } #[derive(Debug, PartialEq, Eq)] pub struct Version { pub major: u64, pub minor: u64, pub patch: u64, pub release_flags: String } impl Version { pub fn scan_bytes(data: &[u8]) -> Result<Version, Error> { use regex::bytes::Regex; lazy_static! { static ref RE: Regex = Regex::new(r"((2|3)\.(3|4|5|6|7|8)\.(\d{1,2}))((a|b|c|rc)\d{1,2})? (.{1,64})").unwrap(); } if let Some(cap) = RE.captures_iter(data).next() { let release = match cap.get(5) { Some(x) => { std::str::from_utf8(x.as_bytes())? }, None => "" }; let major = std::str::from_utf8(&cap[2])?.parse::<u64>()?; let minor = std::str::from_utf8(&cap[3])?.parse::<u64>()?; let patch = std::str::from_utf8(&cap[4])?.parse::<u64>()?; info!("Found matching version string '{}'", std::str::from_utf8(&cap[0])?); return Ok(Version{major, minor, patch, release_flags:release.to_owned()}); } Err(format_err!("failed to find version string")) } } impl std::fmt::Display for Version { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}.{}.{}{}", self.major, self.minor, self.patch, self.release_flags) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_find_version() { let version = Version::scan_bytes(b"2.7.10 (default, Oct 6 2017, 22:29:07)").unwrap(); assert_eq!(version, Version{major: 2, minor: 7, patch: 10, release_flags: "".to_owned()}); let version = Version::scan_bytes(b"3.6.3 |Anaconda custom (64-bit)| (default, Oct 6 2017, 12:04:38)").unwrap(); assert_eq!(version, Version{major: 3, minor: 6, patch: 3, release_flags: "".to_owned()}); let version = Version::scan_bytes(b"Python 3.7.0rc1 (v3.7.0rc1:dfad352267, Jul 20 2018, 13:27:54)").unwrap(); assert_eq!(version, Version{major: 3, minor: 7, patch: 0, release_flags: "rc1".to_owned()}); let version = Version::scan_bytes(b"1.7.0rc1 (v1.7.0rc1:dfad352267, Jul 20 2018, 13:27:54)"); assert!(version.is_err(), "don't match unsupported "); let version = Version::scan_bytes(b"3.7 10 "); assert!(version.is_err(), "needs dotted version"); let version = Version::scan_bytes(b"3.7.10fooboo "); assert!(version.is_err(), "limit suffixes"); } }
use crate::string_collection::{StringCollection, Key as SCKey}; use crate::stoppable_thread::StoppableThread; use crate::memdb::{TimeData, MemDB}; use crate::common::{LiteZoneData, LitePlotData}; use std::time::{Instant, Duration}; use std::boxed::Box; use std::mem::MaybeUninit; use std::sync::atomic::{AtomicU64, Ordering}; use temporal_lens::shmem::{self, SharedMemory, FrameData, ZoneData, PlotData}; use log::{info, warn}; static POLLER: StoppableThread = StoppableThread::new("shmem_poller"); static LAST_QUERY: AtomicU64 = AtomicU64::new(0); pub fn start(mut shmem: SharedMemory, opt_start: Option<Instant>, mut str_collection: StringCollection, mut frame_db: MemDB<FrameData>, mut zone_db: MemDB<LiteZoneData>, mut plot_db: MemDB<LitePlotData>) { POLLER.start(move || { let mut frame_data: Box<MaybeUninit<[FrameData; shmem::NUM_ENTRIES]>> = Box::new_uninit(); let mut zone_data: Box<MaybeUninit<[ZoneData; shmem::NUM_ENTRIES]>> = Box::new_uninit(); let mut plot_data: Box<MaybeUninit<[PlotData; shmem::NUM_ENTRIES]>> = Box::new_uninit(); let mut last_time: shmem::Time = 0.0; let mut counter = 0; while POLLER.running() { let mut total_data_retrieved = 0; if let Some(start) = opt_start { if start.elapsed().as_secs() - LAST_QUERY.load(Ordering::Relaxed) >= 30 { info!("No keep-alive sent within the last 30 seconds. Shutting down server."); drop(shmem); std::process::exit(0); } } //================= FRAMES =================// let (fd, count, missed) = unsafe { let (count, missed) = shmem.frame_data.retrieve_unchecked(frame_data.get_mut().as_mut_ptr()); (frame_data.get_ref(), count, missed) }; if missed > 0 { warn!("Server is too slow! Missed {} FrameData entries!", missed); } for i in 0..count { let fdi = &fd[i]; frame_db.push(TimeData { time: fdi.end, data: *fdi }); } total_data_retrieved += count; //================= ZONES =================// let (zd, count, missed) = unsafe { let (count, missed) = shmem.zone_data.retrieve_unchecked(zone_data.get_mut().as_mut_ptr()); (zone_data.get_ref(), count, missed) }; if missed > 0 { warn!("Server is too slow! Missed {} ZoneData entries!", missed); } for i in 0..count { let zdi = &zd[i]; if let Some(s) = zdi.name.make_str() { str_collection.insert(SCKey::StaticString(zdi.name.get_key()), s); } if let Some(s) = zdi.thread.make_str() { str_collection.insert(SCKey::ThreadName(zdi.thread.get_key()), s); } let entry = TimeData { time: if zdi.end < last_time { last_time } else { zdi.end }, data: LiteZoneData { uid : zdi.uid, color : zdi.color, duration: zdi.duration, depth : zdi.depth, name : zdi.name.get_key(), thread : zdi.thread.get_key() } }; last_time = zdi.end; zone_db.push(entry); //Is that good or is it better to do it all at once? } total_data_retrieved += count; //================= PLOTS =================// let (pd, count, missed) = unsafe { let (count, missed) = shmem.plot_data.retrieve_unchecked(plot_data.get_mut().as_mut_ptr()); (plot_data.get_ref(), count, missed) }; if missed > 0 { warn!("Server is too slow! Missed {} PlotData entries!", missed); } for i in 0..count { let pdi = &pd[i]; if let Some(s) = pdi.name.make_str() { str_collection.insert(SCKey::StaticString(pdi.name.get_key()), s); } plot_db.push(TimeData { time: pdi.time, data: LitePlotData { color: pdi.color, value: pdi.value, name : pdi.name.get_key() } }); } total_data_retrieved += count; frame_db.unload_old_chunks(); zone_db.unload_old_chunks(); plot_db.unload_old_chunks(); if total_data_retrieved <= 0 { std::thread::sleep(Duration::from_millis(10)); counter = 0; } else { counter += 1; if counter >= 4 { counter = 0; std::thread::yield_now(); } } } }); } pub fn stop() -> bool { POLLER.stop() } pub fn update_keep_alive(t: u64) { LAST_QUERY.store(t, Ordering::Relaxed); }
use rustzx_core::host::Stopwatch; use std::time::{Duration, Instant}; pub struct InstantStopwatch { timestamp: Instant, } impl Default for InstantStopwatch { fn default() -> Self { Self { timestamp: Instant::now(), } } } impl Stopwatch for InstantStopwatch { fn new() -> Self { Self::default() } fn measure(&self) -> Duration { self.timestamp.elapsed() } }
use api_client::ApiClient; use serde_json; use serde_json::Value; use std::collections::HashMap; use std::io; use std::io::{Cursor, Read}; use std::io::ErrorKind as IoErrorKind; use utils::decode_list; use errors::*; chef_json_type!(DataBagItemJsonClass, "Chef::DataBagItem"); chef_json_type!(DataBagItemChefType, "data_bag_item"); #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct DataBagItem { id: Option<String>, #[serde(default)] data_bag: Option<String>, #[serde(default)] chef_type: DataBagItemChefType, #[serde(default)] json_class: DataBagItemJsonClass, #[serde(default)] pub raw_data: HashMap<String, Value>, } impl Read for DataBagItem { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if let Ok(data_bag_item) = serde_json::to_vec(self) { let mut data_bag_item = Cursor::new(data_bag_item.as_ref() as &[u8]); Read::read(&mut data_bag_item, buf) } else { Err(io::Error::new( IoErrorKind::InvalidData, "Failed to convert data bag item to JSON", )) } } } impl DataBagItem { pub fn new<N, D>(id: N, data_bag: D) -> Self where N: Into<String>, D: Into<String>, { DataBagItem { id: Some(id.into()), data_bag: Some(data_bag.into()), ..Default::default() } } pub fn fetch<N, D>(client: &ApiClient, data_bag: D, id: N) -> Result<DataBagItem> where N: Into<String>, D: Into<String>, { let org = &client.config.organization_path(); let path = format!("{}/data/{}/{}", org, data_bag.into(), id.into()); client.get::<DataBagItem>(path.as_ref()) } pub fn id(&self) -> Result<String> { if let Some(id) = self.raw_data.get("id") { serde_json::from_value(id.clone()).chain_err(|| "Failed to fetch field") } else { Err(ErrorKind::KeyMissingError("id".to_owned()).into()) } } pub fn save(&self, client: &ApiClient) -> Result<DataBagItem> { let id = try!(self.id()); let data_bag = &self.data_bag.clone().unwrap(); let org = &client.config.organization_path(); let path = format!("{}/data/{}/{}", org, data_bag, id); client.put::<&DataBagItem, DataBagItem>(path.as_ref(), &self) } pub fn delete(&self, client: &ApiClient) -> Result<DataBagItem> { let id = try!(self.id()); let data_bag = &self.data_bag.clone().unwrap(); let org = &client.config.organization_path(); let path = format!("{}/data/{}/{}", org, data_bag, id); client.delete::<DataBagItem>(path.as_ref()) } pub fn from_json<R>(r: R) -> Result<DataBagItem> where R: Read, { Ok(try!(serde_json::from_reader::<R, DataBagItem>(r))) } } pub fn delete_data_bag_item<D, N>(client: &ApiClient, data_bag: D, id: N) -> Result<DataBagItem> where D: Into<String>, N: Into<String>, { let org = &client.config.organization_path(); let path = format!("{}/data/{}/{}", org, data_bag.into(), id.into()); client.delete::<DataBagItem>(path.as_ref()) } #[derive(Debug)] pub struct DataBagItemList { count: usize, data_bag: String, data_bag_items: Vec<String>, client: ApiClient, } impl DataBagItemList { pub fn new<D: Into<String>>(client: &ApiClient, data_bag: D) -> Self { let org = &client.config.organization_path(); let db = data_bag.into(); let path = format!("{}/data/{}", org, &db); client .get(path.as_ref()) .and_then(decode_list) .and_then(|list| { Ok(DataBagItemList { data_bag: db, data_bag_items: list, count: 0, client: client.clone(), }) }) .unwrap() } } impl Iterator for DataBagItemList { type Item = Result<DataBagItem>; fn count(self) -> usize { self.data_bag_items.len() } fn next(&mut self) -> Option<Self::Item> { if self.data_bag_items.len() >= 1 { Some(DataBagItem::fetch( &self.client, self.data_bag.clone(), self.data_bag_items.remove(0), )) } else { None } } } #[cfg(test)] mod tests { // use super::DataBagItem; // use std::fs::File; // #[test] // fn test_data_bag_item_from_file() { // let fh = File::open("fixtures/data_bag_item.json").unwrap(); // let data_bag_item = DataBagItem::from_json(fh).unwrap(); // assert_eq!(data_bag_item.id(), "test") // } }
use amethyst::{assets::LoaderBundle, core::transform::TransformBundle, prelude::*, renderer::{ plugins::{RenderFlat2D, RenderToWindow}, rendy::hal::command::ClearColor, types::DefaultBackend, RenderingBundle, }, utils::{application_root_dir, ortho_camera::build_camera_normalize_system}}; mod particles; mod camera; use crate::particles::ParticleState; fn main() -> amethyst::Result<()> { amethyst::start_logger(Default::default()); let app_root = application_root_dir()?; let display_config_path = app_root.join("config").join("display.ron"); let mut dispatcher = DispatcherBuilder::default(); dispatcher .add_bundle(LoaderBundle) .add_bundle(TransformBundle) .add_bundle( RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config_path(display_config_path)?.with_clear(ClearColor { float32: [0.0, 0.0, 0.0, 1.0], }), ) .with_plugin(RenderFlat2D::default()), ) .add_system(|| { build_camera_normalize_system() }); let assets_dir = app_root.join("assets"); let game = Application::new(assets_dir, ParticleState, dispatcher)?; game.run(); Ok(()) }
#![allow(clippy::if_same_then_else)] #![allow(clippy::needless_bool)] use std::{ fmt, time::{Duration, Instant}, }; use futures::{try_ready, StartSend}; use resol_vbus::{ chrono::Utc, live_data_encoder::{bytes_from_data, length_from_data}, Data, Datagram, Header, LiveDataBuffer, }; use tokio::{prelude::*, timer::Delay}; use crate::error::Error; fn into_datagram<R, W>( args: (LiveDataStream<R, W>, Option<Data>), ) -> (LiveDataStream<R, W>, Option<Datagram>) where R: AsyncRead, W: AsyncWrite, { let (lds, opt_data) = args; let opt_dgram = match opt_data { Some(data) => Some(data.into_datagram()), None => None, }; (lds, opt_dgram) } /// A `Stream`/`Sink` wrapper for RESOL VBus `Data` items encoded in the /// live / wire representation. /// /// It also contains methods to communicate with a VBus device to get or set /// values etc. #[derive(Debug)] pub struct LiveDataStream<R: AsyncRead, W: AsyncWrite> { reader: R, writer: W, channel: u8, self_address: u16, buf: LiveDataBuffer, } impl<R: AsyncRead, W: AsyncWrite> LiveDataStream<R, W> { /// Create a new `LiveDataStream`. pub fn new(reader: R, writer: W, channel: u8, self_address: u16) -> LiveDataStream<R, W> { LiveDataStream { reader, writer, channel, self_address, buf: LiveDataBuffer::new(channel), } } /// Consume `self` and return the underlying I/O pair. pub fn into_inner(self) -> (R, W) { let LiveDataStream { reader, writer, .. } = self; (reader, writer) } fn create_datagram( &self, destination_address: u16, command: u16, param16: i16, param32: i32, ) -> Datagram { Datagram { header: Header { timestamp: Utc::now(), channel: self.channel, destination_address, source_address: self.self_address, protocol_version: 0x20, }, command, param16, param32, } } /// Receive data from the VBus. /// /// This methods waits for `timeout_ms` milliseconds for incoming /// VBus data. Every time a valid `Data` is received over the VBus /// the `filter` function is called with that `Data` as its argument. /// The function returns a `bool` whether the provided `Data` is the /// data it was waiting for. /// /// If the `filter` function returns `true`, the respective `Data` /// is used to resolve the `receive` method's `Future`. /// /// If the `filter` function did not find the matching data within /// `timeout_ms` milliseconds, the `receive` method's `Future` resolves /// with `(self, None)`. pub fn receive<F>( self, timeout_ms: u64, filter: F, ) -> impl Future<Item = (Self, Option<Data>), Error = Error> where F: Fn(&Data) -> bool + Send + 'static, { ActionFuture::new(self, None, 1, timeout_ms, 0, Box::new(filter)) } /// Send data to the VBus and wait for a reply. /// /// This method sends the `tx_data` to the VBus and waits for up to /// `initial_timeout_ms` milliseconds for a reply. /// /// Every time a valid `Data` is received over the VBus the `filter` /// function is called with that `Data` as its argument. The function /// returns a `bool` whether the provided `Data` is the reply it was /// waiting for. /// /// If the `filter` function returns `true`, the respective `Data` /// is used to resolve the `transceive` method's `Future`. /// /// If the `filter` function did not find the matching reply within /// `initial_timeout_ms` milliseconds, the `tx_data` is send again up /// `max_tries` times, increasing the timeout by `timeout_increment_ms` /// milliseconds every time. /// /// After `max_tries` without a matching reply the `transceive` method's /// `Future` resolves with `(self, None)`. pub fn transceive<F>( self, tx_data: Data, max_tries: usize, initial_timeout_ms: u64, timeout_increment_ms: u64, filter: F, ) -> impl Future<Item = (Self, Option<Data>), Error = Error> where F: Fn(&Data) -> bool + Send + 'static, { ActionFuture::new( self, Some(tx_data), max_tries, initial_timeout_ms, timeout_increment_ms, Box::new(filter), ) } /// Wait for any VBus data. pub fn receive_any_data( self, timeout_ms: u64, ) -> impl Future<Item = (Self, Option<Data>), Error = Error> { self.receive(timeout_ms, |_| true) } /// Wait for a datagram that offers VBus control. pub fn wait_for_free_bus(self) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { ActionFuture::new( self, None, 1, 20000, 0, Box::new(|data| { if let Data::Datagram(ref dgram) = *data { if dgram.command != 0x0500 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Give back bus control to the regular VBus master. pub fn release_bus( self, address: u16, ) -> impl Future<Item = (Self, Option<Data>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x0600, 0, 0); let tx_data = Some(Data::Datagram(tx_dgram)); ActionFuture::new( self, tx_data, 2, 2500, 2500, Box::new(|data| data.is_packet()), ) } /// Get a value by its index. pub fn get_value_by_index( self, address: u16, index: i16, subindex: u8, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x0300 | u16::from(subindex), index, 0); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != (0x0100 | u16::from(subindex)) { false } else if dgram.param16 != tx_dgram.param16 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Set a value by its index. pub fn set_value_by_index( self, address: u16, index: i16, subindex: u8, value: i32, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x0200 | u16::from(subindex), index, value); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != (0x0100 | u16::from(subindex)) { false } else if dgram.param16 != tx_dgram.param16 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Get a value's ID hash by its index. pub fn get_value_id_hash_by_index( self, address: u16, index: i16, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1000, index, 0); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x0100 { false } else if dgram.param16 != tx_dgram.param16 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Get a value's index by its ID hash. pub fn get_value_index_by_id_hash( self, address: u16, id_hash: i32, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1100, 0, id_hash); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x0100 { false } else if dgram.param32 != tx_dgram.param32 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Get the capabilities (part 1) from a VBus device. pub fn get_caps1( self, address: u16, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1300, 0, 0); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x1301 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Begin a bulk value transaction. pub fn begin_bulk_value_transaction( self, address: u16, tx_timeout: i32, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1400, 0, tx_timeout); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x1401 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Commit a bulk value transaction. pub fn commit_bulk_value_transaction( self, address: u16, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1402, 0, 0); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x1403 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Rollback a bulk value transaction. pub fn rollback_bulk_value_transaction( self, address: u16, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1404, 0, 0); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != 0x1405 { false } else { true } } else { false } }), ) .map(into_datagram) } /// Set a value by its index while inside a bulk value transaction. pub fn set_bulk_value_by_index( self, address: u16, index: i16, subindex: u8, value: i32, ) -> impl Future<Item = (Self, Option<Datagram>), Error = Error> { let tx_dgram = self.create_datagram(address, 0x1500 | u16::from(subindex), index, value); let tx_data = Some(Data::Datagram(tx_dgram.clone())); ActionFuture::new( self, tx_data, 3, 500, 500, Box::new(move |data| { if let Data::Datagram(ref dgram) = *data { if dgram.header.source_address != tx_dgram.header.destination_address { false } else if dgram.header.destination_address != tx_dgram.header.source_address { false } else if dgram.command != (0x1600 | u16::from(subindex)) { false } else if dgram.param16 != tx_dgram.param16 { false } else { true } } else { false } }), ) .map(into_datagram) } } impl<R: AsyncRead, W: AsyncWrite> Stream for LiveDataStream<R, W> { type Item = Data; type Error = Error; fn poll(&mut self) -> Poll<Option<Data>, Error> { // println!("LiveDataStream::poll called"); loop { // println!(" loop"); if self.buf.peek_length().is_some() { break; } // println!(" reader.poll()"); let mut buf = [0u8; 256]; let len = try_ready!(self.reader.poll_read(&mut buf)); // println!(" reader.poll() returned {} bytes @ {:?}", len, Utc::now()); if len == 0 { return Ok(Async::Ready(None)); } self.buf.extend_from_slice(&buf[0..len]); } let data = self.buf.read_data(); // println!(" data = {:?}", data); Ok(Async::Ready(data)) } } impl<R: AsyncRead, W: AsyncWrite> Sink for LiveDataStream<R, W> { type SinkItem = Data; type SinkError = Error; fn start_send(&mut self, data: Data) -> StartSend<Data, Error> { let len = length_from_data(&data); let mut buf = vec![0; len]; buf.resize(len, 0); bytes_from_data(&data, &mut buf); match self.writer.poll_write(&buf) { Ok(Async::Ready(written_len)) => { if written_len == len { Ok(AsyncSink::Ready) } else { Err(Error::new("Unable to write all bytes at once")) } } Ok(Async::NotReady) => Ok(AsyncSink::NotReady(data)), Err(err) => Err(Error::new(err)), } } fn poll_complete(&mut self) -> Poll<(), Error> { self.writer.poll_flush().map_err(Error::new) } } #[cfg(test)] impl<R: AsyncRead, W: AsyncWrite> LiveDataStream<R, W> { pub fn writer_ref(&self) -> &W { &self.writer } } #[derive(Debug)] enum ActionFuturePhase { Sending, Receiving, Done, } struct ActionFuture<R: AsyncRead, W: AsyncWrite> { stream: Option<LiveDataStream<R, W>>, tx_data: Option<Vec<u8>>, max_tries: usize, timeout: Duration, timeout_increment: Duration, filter: Box<dyn Fn(&Data) -> bool + Send + 'static>, phase: ActionFuturePhase, current_try: usize, delay: Option<Delay>, } impl<R: AsyncRead, W: AsyncWrite> ActionFuture<R, W> { fn new( stream: LiveDataStream<R, W>, tx_data: Option<Data>, max_tries: usize, initial_timeout_ms: u64, timeout_increment_ms: u64, filter: Box<dyn Fn(&Data) -> bool + Send + 'static>, ) -> ActionFuture<R, W> { let tx_data = tx_data.map(|ref data| { let len = length_from_data(data); let mut buf = vec![0; len]; buf.resize(len, 0); bytes_from_data(data, &mut buf); buf }); ActionFuture { stream: Some(stream), tx_data, max_tries, timeout: Duration::from_millis(initial_timeout_ms), timeout_increment: Duration::from_millis(timeout_increment_ms), filter, phase: ActionFuturePhase::Sending, current_try: 0, delay: None, } } } impl<R: AsyncRead + fmt::Debug, W: AsyncWrite + fmt::Debug> fmt::Debug for ActionFuture<R, W> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("ActionFuture") .field("stream", &self.stream) .field("tx_data", &self.tx_data) .field("max_tries", &self.max_tries) .field("timeout", &self.timeout) .field("timeout_increment", &self.timeout_increment) .field("filter", &"...") .field("phase", &self.phase) .field("current_try", &self.current_try) .field("delay", &self.delay) .finish() } } impl<R: AsyncRead, W: AsyncWrite> Future for ActionFuture<R, W> { type Item = (LiveDataStream<R, W>, Option<Data>); type Error = Error; fn poll(&mut self) -> Poll<(LiveDataStream<R, W>, Option<Data>), Error> { // println!("ActionFuture::poll called()"); loop { // println!(" {:?}", self.phase); match self.phase { ActionFuturePhase::Sending => { if let Some(ref data) = self.tx_data { let len = try_ready!(self.stream.as_mut().unwrap().writer.poll_write(data)); if len != data.len() { return Err(Error::new("Unable to write all bytes at once")); } } self.phase = ActionFuturePhase::Receiving; self.delay = Some(Delay::new(Instant::now() + self.timeout)); } ActionFuturePhase::Receiving => { // println!(" stream.poll()"); match self.stream.as_mut().unwrap().poll()? { Async::Ready(data) => { if let Some(data) = data { // println!(" {:?}", data); if (self.filter)(&data) { // println!(" ready!"); self.delay = None; self.phase = ActionFuturePhase::Done; return Ok(Async::Ready(( self.stream.take().unwrap(), Some(data), ))); } } else { return Err(Error::new("Reached EOF")); } } Async::NotReady => { // println!(" delay.poll()"); try_ready!(self.delay.as_mut().unwrap().poll()); self.timeout += self.timeout_increment; self.current_try += 1; self.delay = None; // println!(" try: {}/{}", self.current_try, self.max_tries); if self.current_try < self.max_tries { self.phase = ActionFuturePhase::Sending; } else { self.phase = ActionFuturePhase::Done; return Ok(Async::Ready((self.stream.take().unwrap(), None))); } } } } ActionFuturePhase::Done => { unreachable!(); } } } } } #[cfg(test)] mod tests { use std::io::Cursor; use resol_vbus::Packet; use super::*; fn extend_from_data(buf: &mut Vec<u8>, data: &Data) { let len = length_from_data(data); let idx = buf.len(); buf.resize(idx + len, 0); bytes_from_data(data, &mut buf[idx..]); } fn extend_with_empty_packet( buf: &mut Vec<u8>, destination_address: u16, source_address: u16, command: u16, ) { let data = Data::Packet(Packet { header: Header { timestamp: Utc::now(), channel: 0, destination_address, source_address, protocol_version: 0x20, }, command, frame_count: 0, frame_data: [0; 508], }); extend_from_data(buf, &data); } fn extend_from_datagram( buf: &mut Vec<u8>, destination_address: u16, source_address: u16, command: u16, param16: i16, param32: i32, ) { let data = Data::Datagram(Datagram { header: Header { timestamp: Utc::now(), channel: 0, destination_address, source_address, protocol_version: 0x20, }, command, param16, param32, }); extend_from_data(buf, &data); } fn simulate_run<T, E: fmt::Display + fmt::Debug, F: Future<Item = T, Error = E>>( mut f: F, ) -> T { match f.poll().expect("Unable to poll future") { Async::Ready(value) => value, Async::NotReady => panic!("Future returned NotReady"), } } trait ToBytes { fn to_bytes(&self) -> Vec<u8>; } fn hex_encode<T: ToBytes>(value: &T) -> String { let buf = value.to_bytes(); buf.iter() .map(|b| format!("{:02x}", b)) .collect::<Vec<String>>() .concat() } impl ToBytes for Cursor<Vec<u8>> { fn to_bytes(&self) -> Vec<u8> { self.get_ref().clone() } } impl ToBytes for Data { fn to_bytes(&self) -> Vec<u8> { let len = length_from_data(self); let mut buf = Vec::new(); buf.resize(len, 0); bytes_from_data(self, &mut buf); buf } } impl ToBytes for Datagram { fn to_bytes(&self) -> Vec<u8> { Data::Datagram(self.clone()).to_bytes() } } #[test] fn test_wait_for_free_bus() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0000, 0x7E11, 0x0500, 0, 0); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.wait_for_free_bus()); assert_eq!("", hex_encode(lds.writer_ref())); assert_eq!( "aa0000117e200005000000000000004b", hex_encode(&data.unwrap()) ); } #[test] fn test_release_bus() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0100, 0, 0); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.release_bus(0x7E11)); assert_eq!( "aa117e2000200006000000000000002a", hex_encode(lds.writer_ref()) ); assert_eq!("aa1000117e100001004f", hex_encode(&data.unwrap())); } #[test] fn test_get_value_by_index() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x0156, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x0156, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0157, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0157, 0x1235, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0156, 0x1234, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.get_value_by_index(0x7E11, 0x1234, 0x56)); assert_eq!( "aa117e20002056033412000000000011", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20560134125e3c1a781c4b", hex_encode(&data.unwrap()) ); } #[test] fn test_set_value_by_index() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x0156, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x0156, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0157, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0156, 0x1235, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0156, 0x1234, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.set_value_by_index(0x7E11, 0x1234, 0x56, 0x789abcde)); assert_eq!( "aa117e200020560234125e3c1a781c4a", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20560134125e3c1a781c4b", hex_encode(&data.unwrap()) ); } #[test] fn test_get_value_id_hash_by_index() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x0100, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x0100, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0101, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0100, 0x1235, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0100, 0x1234, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.get_value_id_hash_by_index(0x7E11, 0x1234)); assert_eq!( "aa117e2000200010341200000000005a", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20000134125e3c1a781c21", hex_encode(&data.unwrap()) ); } #[test] fn test_get_value_index_by_id_hash() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x0100, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x0100, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0101, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0100, 0x1234, 0x789abcdf); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x0100, 0x1234, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.get_value_index_by_id_hash(0x7E11, 0x789abcde)); assert_eq!( "aa117e200020001100005e3c1a781c57", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20000134125e3c1a781c21", hex_encode(&data.unwrap()) ); } #[test] fn test_get_caps1() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x1301, 0, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x1301, 0, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1300, 0, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1301, 0, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.get_caps1(0x7E11)); assert_eq!( "aa117e2000200013000000000000001d", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20011300005e3c1a781c54", hex_encode(&data.unwrap()) ); } #[test] fn test_begin_bulk_value_transaction() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x1401, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x1401, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1400, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1401, 0, 0); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.begin_bulk_value_transaction(0x7E11, 0x789abcde)); assert_eq!( "aa117e200020001400005e3c1a781c54", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e200114000000000000001b", hex_encode(&data.unwrap()) ); } #[test] fn test_commit_value_transaction() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x1403, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x1403, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1402, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1403, 0, 0); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.commit_bulk_value_transaction(0x7E11)); assert_eq!( "aa117e2000200214000000000000001a", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e2003140000000000000019", hex_encode(&data.unwrap()) ); } #[test] fn test_rollback_value_transaction() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x1405, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x1405, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1404, 0, 0); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1405, 0, 0); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.rollback_bulk_value_transaction(0x7E11)); assert_eq!( "aa117e20002004140000000000000018", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e2005140000000000000017", hex_encode(&data.unwrap()) ); } #[test] fn test_set_bulk_value_by_index() { let mut rx_buf = Vec::new(); let tx_buf = Cursor::new(Vec::new()); extend_with_empty_packet(&mut rx_buf, 0x0010, 0x7E11, 0x0100); extend_from_datagram(&mut rx_buf, 0x0021, 0x7E11, 0x1656, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E10, 0x1656, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1657, 0x1234, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1656, 0x1235, 0x789abcde); extend_from_datagram(&mut rx_buf, 0x0020, 0x7E11, 0x1656, 0x1234, 0x789abcde); let lds = LiveDataStream::new(&rx_buf[..], tx_buf, 0, 0x0020); let (lds, data) = simulate_run(lds.set_bulk_value_by_index(0x7E11, 0x1234, 0x56, 0x789abcde)); assert_eq!( "aa117e200020561534125e3c1a781c37", hex_encode(lds.writer_ref()) ); assert_eq!( "aa2000117e20561634125e3c1a781c36", hex_encode(&data.unwrap()) ); } }
use std::{fmt, future::Future, mem, sync::Arc}; use bitflags::bitflags; use twilight_model::{ application::interaction::{ ApplicationCommand, ApplicationCommandAutocomplete, MessageComponentInteraction, }, channel::message::MessageFlags, guild::Permissions, http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType}, }; use crate::{ commands::{fun, help, osu, owner, songs, tracking, twitch, utility}, core::buckets::BucketName, embeds::EmbedBuilder, util::{ constants::{ common_literals::{HELP, MAP, PROFILE}, OWNER_USER_ID, RED, }, Authored, InteractionExt, }, BotResult, Context, Error, }; use super::ProcessResult; #[derive(Copy, Clone, Default)] struct CommandArgs { bools: ArgBools, bucket: Option<BucketName>, } bitflags! { #[derive(Default)] pub struct ArgBools: u8 { const AUTHORITY = 1 << 0; const EPHEMERAL = 1 << 1; const ONLY_GUILDS = 1 << 2; const ONLY_OWNER = 1 << 3; // const DEFERRED_MSG = 1 << 4; // TODO } } pub async fn handle_component( ctx: Arc<Context>, component: Box<MessageComponentInteraction>, ) -> BotResult<()> { let name = component.data.custom_id.as_str(); log_interaction(&ctx, &*component, name); ctx.stats.increment_component(name); match name { "help_menu" | "help_back" => help::handle_menu_select(&ctx, *component).await, "bg_start_include" => fun::handle_bg_start_include(&ctx, *component).await, "bg_start_exclude" => fun::handle_bg_start_exclude(&ctx, *component).await, "bg_start_effects" => fun::handle_bg_start_effects(&ctx, *component).await, "bg_start_button" => fun::handle_bg_start_button(ctx, *component).await, "bg_start_cancel" => fun::handle_bg_start_cancel(&ctx, *component).await, "higher_button" => fun::handle_higher(ctx, *component).await, "lower_button" => fun::handle_lower(ctx, *component).await, "give_up_button" => fun::handle_give_up(ctx, *component).await, "try_again_button" => fun::handle_try_again(ctx, *component).await, _ => Err(Error::UnknownMessageComponent { component }), } } pub async fn handle_autocomplete( ctx: Arc<Context>, command: ApplicationCommandAutocomplete, ) -> BotResult<()> { let name = command.data.name.as_str(); ctx.stats.increment_autocomplete(name); match name { HELP => help::handle_autocomplete(ctx, command).await, "badges" => osu::handle_badge_autocomplete(ctx, command).await, "medal" => osu::handle_medal_autocomplete(ctx, command).await, _ => Err(Error::UnknownSlashAutocomplete(command.data.name)), } } pub async fn handle_command(ctx: Arc<Context>, mut command: ApplicationCommand) -> BotResult<()> { let name = mem::take(&mut command.data.name); log_interaction(&ctx, &command, &name); ctx.stats.increment_slash_command(&name); let mut args = CommandArgs::default(); let command_result = match name.as_str() { "avatar" => process_command(ctx, command, args, osu::slash_avatar).await, "badges" => process_command(ctx, command, args, osu::slash_badges).await, "bg" => process_command(ctx, command, args, fun::slash_bg).await, "bws" => process_command(ctx, command, args, osu::slash_bws).await, "commands" => process_command(ctx, command, args, utility::slash_commands).await, "compare" => process_command(ctx, command, args, osu::slash_compare).await, "config" => { args.bools |= ArgBools::EPHEMERAL; process_command(ctx, command, args, utility::slash_config).await } "countrytop" => process_command(ctx, command, args, osu::slash_countrytop).await, "cs" => process_command(ctx, command, args, osu::slash_cs).await, "fix" => process_command(ctx, command, args, osu::slash_fix).await, "graph" => process_command(ctx, command, args, osu::slash_graph).await, HELP => { // Necessary to be able to use data.create_message later on start_thinking(&ctx, &command, true).await?; help::slash_help(ctx, command) .await .map(|_| ProcessResult::Success) } //TODO: bucket baby "higherlower" => process_command(ctx, command, args, fun::slash_higherlower).await, "hl" => process_command(ctx, command, args, fun::slash_higherlower).await, "invite" => process_command(ctx, command, args, utility::slash_invite).await, "leaderboard" => process_command(ctx, command, args, osu::slash_leaderboard).await, "link" => { args.bools |= ArgBools::EPHEMERAL; process_command(ctx, command, args, osu::slash_link).await } MAP => process_command(ctx, command, args, osu::slash_map).await, "mapper" => process_command(ctx, command, args, osu::slash_mapper).await, "matchcompare" => { args.bucket = Some(BucketName::MatchCompare); process_command(ctx, command, args, osu::slash_matchcompare).await } "matchcost" => process_command(ctx, command, args, osu::slash_matchcost).await, "matchlive" => { args.bools |= ArgBools::AUTHORITY; process_command(ctx, command, args, osu::slash_matchlive).await } "medal" => process_command(ctx, command, args, osu::slash_medal).await, "minesweeper" => process_command(ctx, command, args, fun::slash_minesweeper).await, "mostplayed" => process_command(ctx, command, args, osu::slash_mostplayed).await, "nochoke" => process_command(ctx, command, args, osu::slash_nochoke).await, "osc" => process_command(ctx, command, args, osu::slash_osc).await, "osekai" => process_command(ctx, command, args, osu::slash_osekai).await, "osustats" => process_command(ctx, command, args, osu::slash_osustats).await, "owner" => { args.bools |= ArgBools::ONLY_OWNER; args.bools |= ArgBools::EPHEMERAL; process_command(ctx, command, args, owner::slash_owner).await } "ping" => process_command(ctx, command, args, utility::slash_ping).await, "pinned" => process_command(ctx, command, args, osu::slash_pinned).await, "popular" => process_command(ctx, command, args, osu::slash_popular).await, "pp" => process_command(ctx, command, args, osu::slash_pp).await, PROFILE => process_command(ctx, command, args, osu::slash_profile).await, "prune" => { args.bools |= ArgBools::AUTHORITY; args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, utility::slash_prune).await } "rank" => process_command(ctx, command, args, osu::slash_rank).await, "ranking" => process_command(ctx, command, args, osu::slash_ranking).await, "ratios" => process_command(ctx, command, args, osu::slash_ratio).await, "recent" => process_command(ctx, command, args, osu::slash_recent).await, "roleassign" => { args.bools |= ArgBools::AUTHORITY; args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, utility::slash_roleassign).await } "roll" => process_command(ctx, command, args, utility::slash_roll).await, "rb" => process_command(ctx, command, args, osu::slash_rb).await, "rs" => process_command(ctx, command, args, osu::slash_rs).await, "search" => process_command(ctx, command, args, osu::slash_mapsearch).await, "serverconfig" => { args.bools |= ArgBools::AUTHORITY; args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, utility::slash_serverconfig).await } "serverleaderboard" => { args.bucket = Some(BucketName::Leaderboard); args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, osu::slash_serverleaderboard).await } "simulate" => process_command(ctx, command, args, osu::slash_simulate).await, "snipe" => { args.bucket = Some(BucketName::Snipe); process_command(ctx, command, args, osu::slash_snipe).await } "song" => { args.bucket = Some(BucketName::Songs); process_command(ctx, command, args, songs::slash_song).await } "top" => process_command(ctx, command, args, osu::slash_top).await, "topif" => process_command(ctx, command, args, osu::slash_topif).await, "topold" => process_command(ctx, command, args, osu::slash_topold).await, "track" => { args.bools |= ArgBools::AUTHORITY; args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, tracking::slash_track).await } "trackstream" => { args.bools |= ArgBools::AUTHORITY; args.bools |= ArgBools::ONLY_GUILDS; process_command(ctx, command, args, twitch::slash_trackstream).await } "whatif" => process_command(ctx, command, args, osu::slash_whatif).await, _ => { return Err(Error::UnknownSlashCommand { name, command: Box::new(command), }); } }; match command_result { Ok(ProcessResult::Success) => info!("Processed slash command `{name}`"), Ok(result) => info!("Command `/{name}` was not processed: {result:?}"), Err(why) => return Err(Error::Command(Box::new(why), name)), } Ok(()) } async fn process_command<R>( ctx: Arc<Context>, command: ApplicationCommand, args: CommandArgs, fun: fn(Arc<Context>, ApplicationCommand) -> R, ) -> BotResult<ProcessResult> where R: Future<Output = BotResult<()>>, { let ephemeral = args.bools.contains(ArgBools::EPHEMERAL); match pre_process_command(&ctx, &command, args).await? { Some(result) => Ok(result), None => { // Let discord know the command is now being processed start_thinking(&ctx, &command, ephemeral).await?; // Call command function (fun)(ctx, command).await?; Ok(ProcessResult::Success) } } } async fn start_thinking( ctx: &Context, command: &ApplicationCommand, ephemeral: bool, ) -> BotResult<()> { let data = InteractionResponseData { flags: ephemeral.then(|| MessageFlags::EPHEMERAL), ..Default::default() }; let response = InteractionResponse { kind: InteractionResponseType::DeferredChannelMessageWithSource, data: Some(data), }; ctx.interaction() .create_response(command.id, &command.token, &response) .exec() .await?; Ok(()) } async fn premature_error( ctx: &Context, command: &ApplicationCommand, content: impl Into<String>, ephemeral: bool, ) -> BotResult<()> { let embed = EmbedBuilder::new().color(RED).description(content).build(); let flags = ephemeral.then(|| MessageFlags::EPHEMERAL); let data = InteractionResponseData { embeds: Some(vec![embed]), flags, ..Default::default() }; let response = InteractionResponse { kind: InteractionResponseType::ChannelMessageWithSource, data: Some(data), }; ctx.interaction() .create_response(command.id, &command.token, &response) .exec() .await?; Ok(()) } #[inline(never)] async fn pre_process_command( ctx: &Context, command: &ApplicationCommand, args: CommandArgs, ) -> BotResult<Option<ProcessResult>> { let guild_id = command.guild_id; // Only in guilds? if args.bools.contains(ArgBools::ONLY_GUILDS) && guild_id.is_none() { let content = "That command is only available in servers"; premature_error(ctx, command, content, false).await?; return Ok(Some(ProcessResult::NoDM)); } let author_id = command.author().ok_or(Error::MissingInteractionAuthor)?.id; // Only for owner? if args.bools.contains(ArgBools::ONLY_OWNER) && author_id.get() != OWNER_USER_ID { let content = "That command can only be used by the bot owner"; premature_error(ctx, command, content, true).await?; return Ok(Some(ProcessResult::NoOwner)); } // Does bot have sufficient permissions to send response in a guild? // Technically not necessary but there is currently no other way for // users to disable slash commands in certain channels. if let Some(guild) = command.guild_id { let user = ctx.cache.current_user()?.id; let channel = command.channel_id; let permissions = ctx.cache.get_channel_permissions(user, channel, guild); if !permissions.contains(Permissions::SEND_MESSAGES) { let content = "I have no send permission in this channel so I won't process commands"; premature_error(ctx, command, content, true).await?; return Ok(Some(ProcessResult::NoSendPermission)); } } // Ratelimited? { let mutex = ctx.buckets.get(BucketName::All); let mut bucket = mutex.lock(); let ratelimit = bucket.take(author_id.get()); if ratelimit > 0 { trace!("Ratelimiting user {author_id} for {ratelimit} seconds"); return Ok(Some(ProcessResult::Ratelimited(BucketName::All))); } } if let Some(bucket) = args.bucket { if let Some((cooldown, bucket)) = super::_check_ratelimit(ctx, author_id, guild_id, bucket).await { if !matches!(bucket, BucketName::BgHint) { let content = format!("Command on cooldown, try again in {cooldown} seconds"); premature_error(ctx, command, content, true).await?; } return Ok(Some(ProcessResult::Ratelimited(bucket))); } } // Only for authorities? if args.bools.contains(ArgBools::AUTHORITY) { match super::check_authority(ctx, author_id, command.guild_id).await { Ok(None) => {} Ok(Some(content)) => { premature_error(ctx, command, content, true).await?; return Ok(Some(ProcessResult::NoAuthority)); } Err(why) => { let content = "Error while checking authority status"; let _ = premature_error(ctx, command, content, true).await; return Err(Error::Authority(Box::new(why))); } } } Ok(None) } fn log_interaction(ctx: &Context, interaction: &dyn InteractionExt, name: &str) { let username = interaction.username().unwrap_or("<unknown user>"); let location = InteractionLocationLog { ctx, interaction }; info!("[{location}] {username} used `{name}` interaction"); } struct InteractionLocationLog<'l> { ctx: &'l Context, interaction: &'l dyn InteractionExt, } impl fmt::Display for InteractionLocationLog<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let guild = match self.interaction.guild_id() { Some(id) => id, None => return f.write_str("Private"), }; match self.ctx.cache.guild(guild, |g| write!(f, "{}:", g.name())) { Ok(Ok(_)) => { let channel_result = self.ctx.cache.channel(self.interaction.channel_id(), |c| { f.write_str(c.name.as_deref().unwrap_or("<uncached channel>")) }); match channel_result { Ok(Ok(_)) => Ok(()), Ok(err) => err, Err(_) => f.write_str("<uncached channel>"), } } Ok(err) => err, Err(_) => f.write_str("<uncached guild>"), } } }
use primitives::*; use glium; use glium::glutin; use std::collections::LinkedList; pub struct Renderer<'a> { surface: &'a mut glium::Frame, rendering_context: &'a RenderingContext, size: Size, viewport_stack: Vec<Rect>, } #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); pub struct RenderingContext { vertex_buffer: glium::VertexBuffer<Vertex>, index_buffer: glium::IndexBuffer<u16>, program: glium::Program, } impl<'a> Renderer<'a> { pub fn new(surface: &'a mut glium::Frame, rendering_context: &'a RenderingContext, size: Size, viewport: Rect) -> Renderer<'a> { Renderer { surface: surface, size: size, viewport_stack: vec![viewport], rendering_context: rendering_context, } } fn to_relative(&self, rect: Rect) ->((f32, f32), (f32, f32)) { let ((x, y), (w, h)) = self.viewport().transform_to_outer(rect).to_pos_size_tuple(); ((x / self.size.w * 2.0 - 1.0, 1.0 - y / self.size.h * 2.0), (w / self.size.w * 2.0, h / self.size.h * 2.0)) } fn viewport(&self) -> Rect { self.viewport_stack.last().unwrap().clone() } /*pub fn sub_renderer(&'a mut self, rect: Rect) -> Renderer<'a> { Renderer::new(self.surface, self.rendering_context, self.size, self.viewport.transform_to_outer(rect)) }*/ pub fn push_rect(&mut self, rect: Rect) { let transformed = self.viewport().transform_to_outer(rect); self.viewport_stack.push(transformed); } pub fn pop_rect(&mut self) { self.viewport_stack.pop(); } pub fn clear(&mut self, color: Color) { let size = self.viewport().size.clone(); self.rect(Rect::from_size(size), color); } pub fn rect(&mut self, rect: Rect, color: Color) { let (pos, size) = self.to_relative(rect); self.rendering_context.draw_rect(self.surface, pos, size, color); } pub fn execute(&mut self, commands: RenderCommandList) { for cmd in commands.to_list() { match cmd { RenderCommand::Clear(color) => self.clear(color), RenderCommand::Rect(rect, color) => self.rect(rect, color), } } } } impl RenderingContext { pub fn new(display: &glium::Display) -> RenderingContext { let vertex_buffer = { glium::VertexBuffer::new(display, &[ Vertex { position: [ 0.0, 0.0] }, Vertex { position: [ 1.0, 0.0] }, Vertex { position: [ 1.0, -1.0] }, Vertex { position: [ 0.0, -1.0] }, ] ).unwrap() }; let index_buffer = glium::IndexBuffer::new(display, glium::index::PrimitiveType::TrianglesList, &[0u16, 1, 2, 0, 2, 3]).unwrap(); let program = program!(display, 140 => { vertex: " #version 140 uniform vec2 pos; uniform vec2 size; uniform vec3 color; in vec2 position; out vec3 vColor; void main() { gl_Position = vec4(position.x * size.x + pos.x, position.y * size.y + pos.y, 0.0, 1.0); vColor = color; } ", fragment: " #version 140 in vec3 vColor; out vec4 f_color; void main() { f_color = vec4(vColor, 1.0); } " }/*, 110 => { vertex: " #version 110 uniform mat4 matrix; attribute vec2 position; attribute vec3 color; varying vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 110 varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", }, 100 => { vertex: " #version 100 uniform lowp mat4 matrix; attribute lowp vec2 position; attribute lowp vec3 color; varying lowp vec3 vColor; void main() { gl_Position = vec4(position, 0.0, 1.0) * matrix; vColor = color; } ", fragment: " #version 100 varying lowp vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0); } ", },*/ ).unwrap(); RenderingContext { vertex_buffer: vertex_buffer, index_buffer: index_buffer, program: program, } } pub fn draw_rect(&self, surface: &mut glium::Frame, pos: (f32, f32), size: (f32, f32), color: Color) { use glium::Surface; info!("[Renderer] Drawing rect with pos: {:?} size: {:?}", &pos, &size); let uniforms = uniform! { pos: pos, size: size, color: color.to_tuple_rgb() }; surface.draw(&self.vertex_buffer, &self.index_buffer, &self.program, &uniforms, &Default::default()).unwrap(); } } pub enum RenderCommand { Clear(Color), Rect(Rect, Color), } pub struct RenderCommandList { list: LinkedList<RenderCommand>, } impl RenderCommandList { pub fn new() -> RenderCommandList { RenderCommandList { list: LinkedList::new(), } } pub fn add(&mut self, command: RenderCommand) { self.list.push_back(command); } pub fn add_many(&mut self, commands: RenderCommandList) { self.list.append(&mut commands.to_list()); } pub fn to_list(self) -> LinkedList<RenderCommand> { self.list } }
use crate::{ backend::QueryBuilder, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, QueryStatementBuilder, }; /// Delete existing rows from the table /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let query = Query::delete() /// .from_table(Glyph::Table) /// .or_where(Expr::col(Glyph::Id).lt(1)) /// .or_where(Expr::col(Glyph::Id).gt(10)) /// .to_owned(); /// /// assert_eq!( /// query.to_string(MysqlQueryBuilder), /// r#"DELETE FROM `glyph` WHERE `id` < 1 OR `id` > 10"# /// ); /// assert_eq!( /// query.to_string(PostgresQueryBuilder), /// r#"DELETE FROM "glyph" WHERE "id" < 1 OR "id" > 10"# /// ); /// assert_eq!( /// query.to_string(SqliteQueryBuilder), /// r#"DELETE FROM `glyph` WHERE `id` < 1 OR `id` > 10"# /// ); /// ``` #[derive(Debug, Clone)] pub struct DeleteStatement { pub(crate) table: Option<Box<TableRef>>, pub(crate) wherei: ConditionHolder, pub(crate) orders: Vec<OrderExpr>, pub(crate) limit: Option<Value>, } impl Default for DeleteStatement { fn default() -> Self { Self::new() } } impl DeleteStatement { /// Construct a new [`DeleteStatement`] pub fn new() -> Self { Self { table: None, wherei: ConditionHolder::new(), orders: Vec::new(), limit: None, } } /// Specify which table to delete from. /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let query = Query::delete() /// .from_table(Glyph::Table) /// .and_where(Expr::col(Glyph::Id).eq(1)) /// .to_owned(); /// /// assert_eq!( /// query.to_string(MysqlQueryBuilder), /// r#"DELETE FROM `glyph` WHERE `id` = 1"# /// ); /// assert_eq!( /// query.to_string(PostgresQueryBuilder), /// r#"DELETE FROM "glyph" WHERE "id" = 1"# /// ); /// assert_eq!( /// query.to_string(SqliteQueryBuilder), /// r#"DELETE FROM `glyph` WHERE `id` = 1"# /// ); /// ``` #[allow(clippy::wrong_self_convention)] pub fn from_table<T>(&mut self, tbl_ref: T) -> &mut Self where T: IntoTableRef, { self.table = Some(Box::new(tbl_ref.into_table_ref())); self } /// Limit number of updated rows. pub fn limit(&mut self, limit: u64) -> &mut Self { self.limit = Some(Value::BigUnsigned(limit)); self } } impl QueryStatementBuilder for DeleteStatement { /// Build corresponding SQL statement for certain database backend and collect query parameters /// /// # Examples /// /// ``` /// use sea_query::{*, tests_cfg::*}; /// /// let query = Query::delete() /// .from_table(Glyph::Table) /// .and_where(Expr::col(Glyph::Id).eq(1)) /// .to_owned(); /// /// assert_eq!( /// query.to_string(MysqlQueryBuilder), /// r#"DELETE FROM `glyph` WHERE `id` = 1"# /// ); /// /// let mut params = Vec::new(); /// let mut collector = |v| params.push(v); /// /// assert_eq!( /// query.build_collect(MysqlQueryBuilder, &mut collector), /// r#"DELETE FROM `glyph` WHERE `id` = ?"# /// ); /// assert_eq!( /// params, /// vec![ /// Value::Int(1), /// ] /// ); /// ``` fn build_collect<T: QueryBuilder>( &self, query_builder: T, collector: &mut dyn FnMut(Value), ) -> String { let mut sql = SqlWriter::new(); query_builder.prepare_delete_statement(self, &mut sql, collector); sql.result() } fn build_collect_any( &self, query_builder: &dyn QueryBuilder, collector: &mut dyn FnMut(Value), ) -> String { let mut sql = SqlWriter::new(); query_builder.prepare_delete_statement(self, &mut sql, collector); sql.result() } } impl OrderedStatement for DeleteStatement { fn add_order_by(&mut self, order: OrderExpr) -> &mut Self { self.orders.push(order); self } } impl ConditionalStatement for DeleteStatement { fn and_or_where(&mut self, condition: LogicalChainOper) -> &mut Self { self.wherei.add_and_or(condition); self } fn cond_where<C>(&mut self, condition: C) -> &mut Self where C: IntoCondition, { self.wherei.add_condition(condition.into_condition()); self } }
//! The goal of this module is to see when to fetch data from the SEC //! //! -> could be based on time //! -> could be based on when the rss feed updates use crate::errors::*; use reqwest::header::ETAG; /// In a perfect World, this would only request when given a valid etag, /// but no one likes to give etags. pub fn get_rss(website: &str, _cached_etag: Option<&str>) -> Result<(String, String)> { let client = reqwest::Client::new(); let mut res = client .get(website) .header(ETAG, "Blah") .send() .chain_err(|| "Website not reached")?; println!("{:#?}", &res); // Todo figure how etags work let etag = "NO TAG".to_string(); let a = res.text().chain_err(|| "Unable to extract text")?; Ok((a, etag)) } #[cfg(test)] mod timing_test { use super::*; #[test] fn get_rss_1() { let res = get_rss("askduhalskjfgnawuehflnk", None); assert!(res.is_err()); match res { Err(x) => assert!(x.kind().description() == "Website not reached"), _ => assert!(false), }; } #[test] fn check_etag() { // Etags allow clients to make conditional requests. In our case, we wish to // continue with the request iff the page has changed. // let res = get_rss("http://www.wsj.com", None); if let Err(e) = res { println!("{}", e); assert!(false); } assert!(true); } }
//! Handle selection of entities. use crate::component; use bevy::prelude::*; use bevy_mod_picking::PickingEvent; use bevy_mod_picking::SelectionEvent; /// Handle selection of entities. pub fn selection_handler(mut pick_events: EventReader<PickingEvent>, mut commands: Commands) { for pick_event in pick_events.iter() { match &pick_event { &PickingEvent::Selection(SelectionEvent::JustSelected(entity)) => { let mut entity = commands.entity(*entity); entity.insert(component::Selected); } &PickingEvent::Selection(SelectionEvent::JustDeselected(entity)) => { let mut entity = commands.entity(*entity); entity.remove::<component::Selected>(); } _ => (), } } }
use na::{DMatrix, DVector}; use num::Zero; pub trait Diagonal<T> { fn diag(&self, k: isize) -> DVector<T>; } pub trait Rotate<T> { // rotate pi/2 in the clockwise direction // return rotated matrix fn rotated(&self) -> DMatrix<T>; // rotate in place fn rotate(&mut self); } impl<T: Clone> Diagonal<T> for DMatrix<T> { fn diag(&self, k: isize) -> DVector<T> { let m = self.nrows(); let n = self.ncols(); let mut i: usize = 0; let mut j: usize = 0; if k >= 0 { j = k as usize; } else { i = -k as usize; } let mut diag: Vec<T> = vec![]; while i < m && j < n { diag.push(self[(i, j)].clone()); i += 1; j += 1; } DVector::from_slice(diag.len(), &diag) } } impl<T: Copy + Clone + Zero> Rotate<T> for DMatrix<T> { fn rotated(&self) -> DMatrix<T> { let m = self.nrows(); let n = self.ncols(); let mut rotated_mat = DMatrix::new_zeros(n, m); for i in 0..n { for j in 0..m { rotated_mat[(i, j)] = self[(m - j - 1, i)] } } rotated_mat } fn rotate(&mut self) { let m = self.nrows(); let n = self.ncols(); let mut rotated_mat = DMatrix::new_zeros(n, m); for i in 0..n { for j in 0..m { rotated_mat[(i, j)] = self[(m - j - 1, i)] } } *self = rotated_mat } } #[cfg(test)] mod test { use super::*; use na::{DMatrix, Column, Row}; #[test] fn test_rotated() { let elems = vec![1, 2, 3, 4, 5, 6]; let mat = DMatrix::from_row_vector(3, 2, &elems[..]); let rot_mat = mat.rotated(); assert_eq!(rot_mat.column(0).at, vec![5, 6]); assert_eq!(rot_mat.column(1).at, vec![3, 4]); assert_eq!(rot_mat.column(2).at, vec![1, 2]); assert_eq!(rot_mat.row(0).at, vec![5, 3, 1]); assert_eq!(rot_mat.row(1).at, vec![6, 4, 2]); } #[test] fn test_rotate() { let elems = vec![1, 2, 3, 4, 5, 6]; let mut mat = DMatrix::from_row_vector(3, 2, &elems[..]); mat.rotate(); assert_eq!(mat.column(0).at, vec![5, 6]); assert_eq!(mat.column(1).at, vec![3, 4]); assert_eq!(mat.column(2).at, vec![1, 2]); assert_eq!(mat.row(0).at, vec![5, 3, 1]); assert_eq!(mat.row(1).at, vec![6, 4, 2]); } #[test] fn test_diagonal() { let elems = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let mat = DMatrix::from_row_vector(3, 3, &elems[..]); assert_eq!(mat.diag(2).at, vec![3]); assert_eq!(mat.diag(1).at, vec![2, 6]); assert_eq!(mat.diag(0).at, vec![1, 5, 9]); assert_eq!(mat.diag(-1).at, vec![4, 8]); assert_eq!(mat.diag(-2).at, vec![7]); } }
// https://projecteuler.net/problem=23 /* A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. */ fn main() { let start_time = std::time::Instant::now(); let sol = solve(); let elapsed = start_time.elapsed().as_micros(); println!("\nSolution: {}", sol); //println!("Elasped time: {} us", elapsed); let mut remain = elapsed; let mut s = String::new(); if remain == 0 { s.insert_str(0,"0"); } while remain > 0 { let temp = remain%1000; remain /= 1000; if remain > 0 { s = format!(",{:03}",temp) + &s; } else { s = format!("{}",temp) + &s; } } println!("Elasped time: {} us", s); } fn solve() -> u64 { let mut rv = 0_u64; // create a vector for abundant numbers let mut v = std::vec::Vec::<u64>::with_capacity(20000); for n in 1..=28123 { let sum : u64 = sb::math::proper_divisors(n).iter().sum(); // store the number if it's abundant if sum > n { v.push(n); } if test_number(n,&v) { rv += n; } } return rv; } fn test_number(n : u64, v : &std::vec::Vec::<u64>) -> bool { let half = n/2; for i in v.iter() { if half < *i as u64 { return true; } let target = n - *i as u64; for j in v.iter().rev() { if target > *j as u64 { break; } if target == *j { return false; } } } true }
use block; use chain; pub struct Node { blockchain: chain::Blockchain, } impl Node { pub fn new() -> Node { Node { blockchain: chain::Blockchain::new() } } pub fn mine(&mut self) { println!("Start mining"); for _ in 0..5 { self.mine_block(); } self.blockchain.print(); } fn mine_block(&mut self) { let payload = vec![1, 2, 3, 4]; let mut new_block = block::Block::new(payload); new_block.parent = self.blockchain.get_parent_hash(); new_block.proof_of_work(); self.blockchain.add_block(new_block); } }
use nu_engine::get_full_help; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, IntoPipelineData, PipelineData, Signature, Value, }; #[derive(Clone)] pub struct Overlay; impl Command for Overlay { fn name(&self) -> &str { "overlay" } fn signature(&self) -> Signature { Signature::build("overlay").category(Category::Core) } fn usage(&self) -> &str { "Commands for manipulating overlays." } fn extra_usage(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn is_parser_keyword(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { Ok(Value::String { val: get_full_help(&Overlay.signature(), &[], engine_state, stack), span: call.head, } .into_pipeline_data()) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Overlay {}) } }
pub mod area; pub mod area_edge; pub mod edge; pub mod multi; pub mod renderer; pub mod square; pub mod tile;
pub type Index = usize; // TODO make this a type parameter use ::vec::IdVec; /// Used as a key to access an instance inside a IdVec<T>. /// Internally, this is only an integer index (but with greater type safety). // manually implementing hash, clone, copy, pub struct Id<T> { index: Index, _marker: ::std::marker::PhantomData<T>, } impl<T> Id<T> { pub fn from_index(index: Index) -> Self { Id { index, _marker: ::std::marker::PhantomData, } } /// Convenience function which allows writing the index first, and the IdVec afterwards. /// Example: `the_selected_entity.of(entities)` /// Panics when calling on an invalid id pub fn of<'s>(self, vec: &'s IdVec<T>) -> &'s T { &vec[self] } /// Convenience function which allows writing the index first, and the IdVec afterwards. /// Example: `the_selected_entity.of_mut(entities)` /// Panics when calling on an invalid id pub fn of_mut<'s>(self, vec: &'s mut IdVec<T>) -> &'s mut T { &mut vec[self] } /// Convenience function which allows writing the index first, and the IdVec afterwards. /// Example: `the_selected_entity.try_of(entities)` pub fn try_of<'s>(self, vec: &'s IdVec<T>) -> Option<&'s T> { vec.get(self) } /// Convenience function which allows writing the index first, and the IdVec afterwards. /// Example: `the_selected_entity.try_of_mut(entities)` pub fn try_of_mut<'s>(self, vec: &'s mut IdVec<T>) -> Option<&'s mut T> { vec.get_mut(self) } /// The actual integer value for this Id. pub fn index_value(self) -> Index { self.index } } impl<T> Eq for Id<T> {} impl<T> PartialEq for Id<T> { fn eq(&self, other: &Id<T>) -> bool { self.index == other.index } } impl<T> Copy for Id<T> {} impl<T> Clone for Id<T> { fn clone(&self) -> Self { *self } } impl<T> ::std::hash::Hash for Id<T> { fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { state.write_usize(self.index); } } impl<T> ::std::fmt::Debug for Id<T> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "Id#{:?}", self.index) } } #[cfg(test)] mod test { use super::*; #[test] pub fn internal_index(){ for index in 0..32 { let id : Id<f32> = Id::from_index(index); let eq_id : Id<f32> = Id::from_index(index); let non_eq_id : Id<f32> = Id::from_index(index + 1); assert_eq!(id, eq_id); assert_ne!(id, non_eq_id); assert_eq!(id.index_value(), index); } } }
fn main(){ let mut b:(i32,bool,f64) = (110,true,10.9); print01(b); print02(&mut b); print01(b) } //pass the tuple as a parameter fn print01(x:(i32,bool,f64)) { println!("Inside print01 method"); println!("{:?}",x); } fn print02(x:&mut (i32,bool,f64)) { println!("Inside print02 method"); x.0 = 1; x.1 = false; x.2 = 0.0; println!("{:?}", x); }
//! platform-independent traits. Submodules with backends will be selectable //! via cargo features in future mod events_sdl; use rustzx_core::{ zx::{ joy::{ kempston::KempstonKey, sinclair::{SinclairJoyNum, SinclairKey}, }, keys::{CompoundKey, ZXKey}, mouse::kempston::{KempstonMouseButton, KempstonMouseWheelDirection}, }, EmulationMode, }; use std::path::PathBuf; pub use events_sdl::EventsSdl; // Event type pub enum Event { ZXKey(ZXKey, bool), CompoundKey(CompoundKey, bool), Kempston(KempstonKey, bool), Sinclair(SinclairJoyNum, SinclairKey, bool), MouseMove { x: i8, y: i8 }, MouseButton(KempstonMouseButton, bool), MouseWheel(KempstonMouseWheelDirection), SwitchFrameTrace, ChangeJoyKeyboardLayer(bool), ChangeSpeed(EmulationMode), InsertTape, StopTape, QuickSave, QuickLoad, OpenFile(PathBuf), Exit, } /// provides event response interface pub trait EventDevice { // get last event fn pop_event(&mut self) -> Option<Event>; }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 0x08], #[doc = "0x08 - LTDC Synchronization Size Configuration Register"] pub sscr: SSCR, #[doc = "0x0c - LTDC Back Porch Configuration Register"] pub bpcr: BPCR, #[doc = "0x10 - LTDC Active Width Configuration Register"] pub awcr: AWCR, #[doc = "0x14 - LTDC Total Width Configuration Register"] pub twcr: TWCR, #[doc = "0x18 - LTDC Global Control Register"] pub gcr: GCR, _reserved5: [u8; 0x08], #[doc = "0x24 - LTDC Shadow Reload Configuration Register"] pub srcr: SRCR, _reserved6: [u8; 0x04], #[doc = "0x2c - LTDC Background Color Configuration Register"] pub bccr: BCCR, _reserved7: [u8; 0x04], #[doc = "0x34 - LTDC Interrupt Enable Register"] pub ier: IER, #[doc = "0x38 - LTDC Interrupt Status Register"] pub isr: ISR, #[doc = "0x3c - LTDC Interrupt Clear Register"] pub icr: ICR, #[doc = "0x40 - LTDC Line Interrupt Position Configuration Register"] pub lipcr: LIPCR, #[doc = "0x44 - LTDC Current Position Status Register"] pub cpsr: CPSR, #[doc = "0x48 - LTDC Current Display Status Register"] pub cdsr: CDSR, _reserved13: [u8; 0x38], #[doc = "0x84 - LTDC Layer Control Register"] pub l1cr: L1CR, #[doc = "0x88 - LTDC Layer Window Horizontal Position Configuration Register"] pub l1whpcr: L1WHPCR, #[doc = "0x8c - LTDC Layer Window Vertical Position Configuration Register"] pub l1wvpcr: L1WVPCR, #[doc = "0x90 - LTDC Layer Color Keying Configuration Register"] pub l1ckcr: L1CKCR, #[doc = "0x94 - LTDC Layer Pixel Format Configuration Register"] pub l1pfcr: L1PFCR, #[doc = "0x98 - LTDC Layer Constant Alpha Configuration Register"] pub l1cacr: L1CACR, #[doc = "0x9c - LTDC Layer Default Color Configuration Register"] pub l1dccr: L1DCCR, #[doc = "0xa0 - LTDC Layer Blending Factors Configuration Register"] pub l1bfcr: L1BFCR, _reserved21: [u8; 0x08], #[doc = "0xac - LTDC Layer Color Frame Buffer Address Register"] pub l1cfbar: L1CFBAR, #[doc = "0xb0 - LTDC Layer Color Frame Buffer Length Register"] pub l1cfblr: L1CFBLR, #[doc = "0xb4 - LTDC Layer ColorFrame Buffer Line Number Register"] pub l1cfblnr: L1CFBLNR, _reserved24: [u8; 0x0c], #[doc = "0xc4 - LTDC Layerx CLUT Write Register"] pub l1clutwr: L1CLUTWR, _reserved25: [u8; 0x3c], #[doc = "0x104 - LTDC Layer Control Register"] pub l2cr: L2CR, #[doc = "0x108 - LTDC Layerx Window Horizontal Position Configuration Register"] pub l2whpcr: L2WHPCR, #[doc = "0x10c - LTDC Layer Window Vertical Position Configuration Register"] pub l2wvpcr: L2WVPCR, #[doc = "0x110 - LTDC Layer Color Keying Configuration Register"] pub l2ckcr: L2CKCR, #[doc = "0x114 - LTDC Layer Pixel Format Configuration Register"] pub l2pfcr: L2PFCR, #[doc = "0x118 - LTDC Layer Constant Alpha Configuration Register"] pub l2cacr: L2CACR, #[doc = "0x11c - LTDC Layer Default Color Configuration Register"] pub l2dccr: L2DCCR, _reserved32: [u8; 0x04], #[doc = "0x124 - LTDC Layer Blending Factors Configuration Register"] pub l2bfcr: L2BFCR, _reserved33: [u8; 0x04], #[doc = "0x12c - LTDC Layer Color Frame Buffer Address Register"] pub l2cfbar: L2CFBAR, #[doc = "0x130 - LTDC Layer Color Frame Buffer Length Register"] pub l2cfblr: L2CFBLR, #[doc = "0x134 - LTDC Layer ColorFrame Buffer Line Number Register"] pub l2cfblnr: L2CFBLNR, _reserved36: [u8; 0x0c], #[doc = "0x144 - LTDC Layerx CLUT Write Register"] pub l2clutwr: L2CLUTWR, } #[doc = "SSCR (rw) register accessor: LTDC Synchronization Size Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sscr::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 [`sscr::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 [`sscr`] module"] pub type SSCR = crate::Reg<sscr::SSCR_SPEC>; #[doc = "LTDC Synchronization Size Configuration Register"] pub mod sscr; #[doc = "BPCR (rw) register accessor: LTDC Back Porch Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bpcr::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 [`bpcr::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 [`bpcr`] module"] pub type BPCR = crate::Reg<bpcr::BPCR_SPEC>; #[doc = "LTDC Back Porch Configuration Register"] pub mod bpcr; #[doc = "AWCR (rw) register accessor: LTDC Active Width Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`awcr::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 [`awcr::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 [`awcr`] module"] pub type AWCR = crate::Reg<awcr::AWCR_SPEC>; #[doc = "LTDC Active Width Configuration Register"] pub mod awcr; #[doc = "TWCR (rw) register accessor: LTDC Total Width Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`twcr::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 [`twcr::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 [`twcr`] module"] pub type TWCR = crate::Reg<twcr::TWCR_SPEC>; #[doc = "LTDC Total Width Configuration Register"] pub mod twcr; #[doc = "GCR (rw) register accessor: LTDC Global Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gcr::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 [`gcr::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 [`gcr`] module"] pub type GCR = crate::Reg<gcr::GCR_SPEC>; #[doc = "LTDC Global Control Register"] pub mod gcr; #[doc = "SRCR (rw) register accessor: LTDC Shadow Reload Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`srcr::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 [`srcr::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 [`srcr`] module"] pub type SRCR = crate::Reg<srcr::SRCR_SPEC>; #[doc = "LTDC Shadow Reload Configuration Register"] pub mod srcr; #[doc = "BCCR (rw) register accessor: LTDC Background Color Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bccr::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 [`bccr::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 [`bccr`] module"] pub type BCCR = crate::Reg<bccr::BCCR_SPEC>; #[doc = "LTDC Background Color Configuration Register"] pub mod bccr; #[doc = "IER (rw) register accessor: LTDC Interrupt Enable Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::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 [`ier::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 [`ier`] module"] pub type IER = crate::Reg<ier::IER_SPEC>; #[doc = "LTDC Interrupt Enable Register"] pub mod ier; #[doc = "ISR (r) register accessor: LTDC Interrupt Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`isr`] module"] pub type ISR = crate::Reg<isr::ISR_SPEC>; #[doc = "LTDC Interrupt Status Register"] pub mod isr; #[doc = "ICR (w) register accessor: LTDC Interrupt Clear 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 [`icr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`icr`] module"] pub type ICR = crate::Reg<icr::ICR_SPEC>; #[doc = "LTDC Interrupt Clear Register"] pub mod icr; #[doc = "LIPCR (rw) register accessor: LTDC Line Interrupt Position Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`lipcr::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 [`lipcr::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 [`lipcr`] module"] pub type LIPCR = crate::Reg<lipcr::LIPCR_SPEC>; #[doc = "LTDC Line Interrupt Position Configuration Register"] pub mod lipcr; #[doc = "CPSR (r) register accessor: LTDC Current Position Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpsr`] module"] pub type CPSR = crate::Reg<cpsr::CPSR_SPEC>; #[doc = "LTDC Current Position Status Register"] pub mod cpsr; #[doc = "CDSR (r) register accessor: LTDC Current Display Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cdsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cdsr`] module"] pub type CDSR = crate::Reg<cdsr::CDSR_SPEC>; #[doc = "LTDC Current Display Status Register"] pub mod cdsr; #[doc = "L1CR (rw) register accessor: LTDC Layer Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1cr::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 [`l1cr::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 [`l1cr`] module"] pub type L1CR = crate::Reg<l1cr::L1CR_SPEC>; #[doc = "LTDC Layer Control Register"] pub mod l1cr; #[doc = "L2CR (rw) register accessor: LTDC Layer Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2cr::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 [`l2cr::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 [`l2cr`] module"] pub type L2CR = crate::Reg<l2cr::L2CR_SPEC>; #[doc = "LTDC Layer Control Register"] pub mod l2cr; #[doc = "L1WHPCR (rw) register accessor: LTDC Layer Window Horizontal Position Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1whpcr::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 [`l1whpcr::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 [`l1whpcr`] module"] pub type L1WHPCR = crate::Reg<l1whpcr::L1WHPCR_SPEC>; #[doc = "LTDC Layer Window Horizontal Position Configuration Register"] pub mod l1whpcr; #[doc = "L2WHPCR (rw) register accessor: LTDC Layerx Window Horizontal Position Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2whpcr::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 [`l2whpcr::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 [`l2whpcr`] module"] pub type L2WHPCR = crate::Reg<l2whpcr::L2WHPCR_SPEC>; #[doc = "LTDC Layerx Window Horizontal Position Configuration Register"] pub mod l2whpcr; #[doc = "L1WVPCR (rw) register accessor: LTDC Layer Window Vertical Position Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1wvpcr::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 [`l1wvpcr::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 [`l1wvpcr`] module"] pub type L1WVPCR = crate::Reg<l1wvpcr::L1WVPCR_SPEC>; #[doc = "LTDC Layer Window Vertical Position Configuration Register"] pub mod l1wvpcr; #[doc = "L2WVPCR (rw) register accessor: LTDC Layer Window Vertical Position Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2wvpcr::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 [`l2wvpcr::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 [`l2wvpcr`] module"] pub type L2WVPCR = crate::Reg<l2wvpcr::L2WVPCR_SPEC>; #[doc = "LTDC Layer Window Vertical Position Configuration Register"] pub mod l2wvpcr; #[doc = "L1CKCR (rw) register accessor: LTDC Layer Color Keying Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1ckcr::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 [`l1ckcr::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 [`l1ckcr`] module"] pub type L1CKCR = crate::Reg<l1ckcr::L1CKCR_SPEC>; #[doc = "LTDC Layer Color Keying Configuration Register"] pub mod l1ckcr; #[doc = "L2CKCR (rw) register accessor: LTDC Layer Color Keying Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2ckcr::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 [`l2ckcr::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 [`l2ckcr`] module"] pub type L2CKCR = crate::Reg<l2ckcr::L2CKCR_SPEC>; #[doc = "LTDC Layer Color Keying Configuration Register"] pub mod l2ckcr; #[doc = "L1PFCR (rw) register accessor: LTDC Layer Pixel Format Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1pfcr::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 [`l1pfcr::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 [`l1pfcr`] module"] pub type L1PFCR = crate::Reg<l1pfcr::L1PFCR_SPEC>; #[doc = "LTDC Layer Pixel Format Configuration Register"] pub mod l1pfcr; #[doc = "L2PFCR (rw) register accessor: LTDC Layer Pixel Format Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2pfcr::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 [`l2pfcr::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 [`l2pfcr`] module"] pub type L2PFCR = crate::Reg<l2pfcr::L2PFCR_SPEC>; #[doc = "LTDC Layer Pixel Format Configuration Register"] pub mod l2pfcr; #[doc = "L1CACR (rw) register accessor: LTDC Layer Constant Alpha Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1cacr::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 [`l1cacr::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 [`l1cacr`] module"] pub type L1CACR = crate::Reg<l1cacr::L1CACR_SPEC>; #[doc = "LTDC Layer Constant Alpha Configuration Register"] pub mod l1cacr; #[doc = "L2CACR (rw) register accessor: LTDC Layer Constant Alpha Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2cacr::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 [`l2cacr::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 [`l2cacr`] module"] pub type L2CACR = crate::Reg<l2cacr::L2CACR_SPEC>; #[doc = "LTDC Layer Constant Alpha Configuration Register"] pub mod l2cacr; #[doc = "L1DCCR (rw) register accessor: LTDC Layer Default Color Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1dccr::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 [`l1dccr::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 [`l1dccr`] module"] pub type L1DCCR = crate::Reg<l1dccr::L1DCCR_SPEC>; #[doc = "LTDC Layer Default Color Configuration Register"] pub mod l1dccr; #[doc = "L2DCCR (rw) register accessor: LTDC Layer Default Color Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2dccr::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 [`l2dccr::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 [`l2dccr`] module"] pub type L2DCCR = crate::Reg<l2dccr::L2DCCR_SPEC>; #[doc = "LTDC Layer Default Color Configuration Register"] pub mod l2dccr; #[doc = "L1BFCR (rw) register accessor: LTDC Layer Blending Factors Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1bfcr::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 [`l1bfcr::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 [`l1bfcr`] module"] pub type L1BFCR = crate::Reg<l1bfcr::L1BFCR_SPEC>; #[doc = "LTDC Layer Blending Factors Configuration Register"] pub mod l1bfcr; #[doc = "L2BFCR (rw) register accessor: LTDC Layer Blending Factors Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2bfcr::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 [`l2bfcr::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 [`l2bfcr`] module"] pub type L2BFCR = crate::Reg<l2bfcr::L2BFCR_SPEC>; #[doc = "LTDC Layer Blending Factors Configuration Register"] pub mod l2bfcr; #[doc = "L1CFBAR (rw) register accessor: LTDC Layer Color Frame Buffer Address Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1cfbar::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 [`l1cfbar::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 [`l1cfbar`] module"] pub type L1CFBAR = crate::Reg<l1cfbar::L1CFBAR_SPEC>; #[doc = "LTDC Layer Color Frame Buffer Address Register"] pub mod l1cfbar; #[doc = "L2CFBAR (rw) register accessor: LTDC Layer Color Frame Buffer Address Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2cfbar::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 [`l2cfbar::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 [`l2cfbar`] module"] pub type L2CFBAR = crate::Reg<l2cfbar::L2CFBAR_SPEC>; #[doc = "LTDC Layer Color Frame Buffer Address Register"] pub mod l2cfbar; #[doc = "L1CFBLR (rw) register accessor: LTDC Layer Color Frame Buffer Length Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1cfblr::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 [`l1cfblr::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 [`l1cfblr`] module"] pub type L1CFBLR = crate::Reg<l1cfblr::L1CFBLR_SPEC>; #[doc = "LTDC Layer Color Frame Buffer Length Register"] pub mod l1cfblr; #[doc = "L2CFBLR (rw) register accessor: LTDC Layer Color Frame Buffer Length Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2cfblr::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 [`l2cfblr::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 [`l2cfblr`] module"] pub type L2CFBLR = crate::Reg<l2cfblr::L2CFBLR_SPEC>; #[doc = "LTDC Layer Color Frame Buffer Length Register"] pub mod l2cfblr; #[doc = "L1CFBLNR (rw) register accessor: LTDC Layer ColorFrame Buffer Line Number Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l1cfblnr::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 [`l1cfblnr::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 [`l1cfblnr`] module"] pub type L1CFBLNR = crate::Reg<l1cfblnr::L1CFBLNR_SPEC>; #[doc = "LTDC Layer ColorFrame Buffer Line Number Register"] pub mod l1cfblnr; #[doc = "L2CFBLNR (rw) register accessor: LTDC Layer ColorFrame Buffer Line Number Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`l2cfblnr::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 [`l2cfblnr::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 [`l2cfblnr`] module"] pub type L2CFBLNR = crate::Reg<l2cfblnr::L2CFBLNR_SPEC>; #[doc = "LTDC Layer ColorFrame Buffer Line Number Register"] pub mod l2cfblnr; #[doc = "L1CLUTWR (w) register accessor: LTDC Layerx CLUT Write 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 [`l1clutwr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`l1clutwr`] module"] pub type L1CLUTWR = crate::Reg<l1clutwr::L1CLUTWR_SPEC>; #[doc = "LTDC Layerx CLUT Write Register"] pub mod l1clutwr; #[doc = "L2CLUTWR (w) register accessor: LTDC Layerx CLUT Write 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 [`l2clutwr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`l2clutwr`] module"] pub type L2CLUTWR = crate::Reg<l2clutwr::L2CLUTWR_SPEC>; #[doc = "LTDC Layerx CLUT Write Register"] pub mod l2clutwr;
use std::env; fn main() { let target = env::var("TARGET"); println!("cargo:info=Building for {:?} target!", target); println!("cargo:rustc-link-lib=m"); // the "-l" flag println!("cargo:rustc-link-lib=c"); // the "-l" flag }
//! Test vectors from Appendix G: //! https://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf use aes::Aes128; use eax::Eax; aead::new_test!(aes128eax, "aes128eax", Eax<Aes128>);
use crate::dataset::show_result; use crate::layer::Layer; use crate::matrix::{Matrix, MatrixOps}; #[derive(Debug)] pub struct NeuralNetwork { lr: f64, layers: Vec<Layer>, } impl NeuralNetwork { pub fn new(shape: Vec<usize>) -> NeuralNetwork { let mut layers = Vec::new(); let len = shape.len(); for i in 1..len { layers.push(Layer::new_by_rand(shape[i - 1], shape[i])) } NeuralNetwork { lr: 0.3, layers } } pub fn inference(&self, input: Matrix) -> Matrix { let mut res = input; for layer in self.layers.iter() { // layer.show(); res = layer.call(&res); // res.show(); } res } pub fn train(&mut self, input: &Matrix, label: &Matrix) -> Matrix { // inference and save output let mut layer_outputs = Vec::new(); let mut res = input.clone(); layer_outputs.push(input.clone()); for layer in self.layers.iter() { res = layer.call(&res); // res.show(); layer_outputs.push(res.clone()); } // calculate err -> update weights let mut layer_errs = Vec::new(); let length = layer_outputs.len(); let mut err = Matrix::zeros(1, 1); for i in 0..length { let index = length - i - 1; if i == 0 { err = label.sub(&layer_outputs[index]); } else { err = self.layers[index].weights_matrix.transpose().product(&err); } layer_errs.push(err.clone()); } // update weight let length = layer_errs.len(); for i in 0..length - 1 { let index = length - i - 1; let mut gradient = layer_errs[i].mul(&layer_outputs[index]); let mut tmp = Matrix::ones(layer_outputs[index].rows, layer_outputs[index].cols); tmp = tmp.sub(&layer_outputs[index]); gradient = tmp.mul(&gradient); gradient = gradient.product(&layer_outputs[index - 1].transpose()); gradient = gradient.mul_const(self.lr); self.layers[index - 1].weights_matrix = self.layers[index - 1].weights_matrix.add(&gradient); } res.transpose() } pub fn eval(&self, input: &Matrix, label: &Matrix) { let pred = self.inference(input.clone()); show_result(pred.transpose(), label.clone()); } pub fn show(&self) { println!("[Neural Network] learning rate: {}", self.lr); println!("[Neural Network] layers: "); for layer in self.layers.iter() { layer.show(); } } } #[cfg(test)] mod nn_tests { use crate::matrix::{Matrix, MatrixOps}; use crate::nn::NeuralNetwork; #[test] fn test_inference() { let nn = NeuralNetwork::new(vec![3, 4, 1]); let inputs = Matrix::new(vec![vec![0.9, 0.1, 0.8]]); let inputs = inputs.transpose(); nn.inference(inputs); } #[test] fn test_train() { let mut nn = NeuralNetwork::new(vec![3, 4, 1]); let inputs = Matrix::new(vec![vec![0.9, 0.1, 0.8]]); let label = Matrix::new(vec![vec![1.0]]); let inputs = inputs.transpose(); for _i in 0..10 { nn.show(); nn.train(&inputs, &label); nn.show(); } } }
use specs::prelude::*; use crate::components::Frame; pub struct FrameCounter; impl<'a> System<'a> for FrameCounter { type SystemData = WriteStorage<'a, Frame>; fn run(&mut self, mut frames: Self::SystemData) { println!("rendering next frame"); for frame in (&mut frames).join() { frame.number += 1; } } }
use amethyst::{prelude::*, utils::application_root_dir}; use crate::entities::{camera::init_camera, fps::init_fps_display, player::init_player}; use crate::utils::textures::{load_spritesheet, load_texture}; pub struct Stage1; pub const ARENA_WIDTH: f32 = 384.0; pub const ARENA_HEIGHT: f32 = 256.0; const PLAYER_INIT_X: f32 = ARENA_WIDTH / 2.0; const PLAYER_INIT_Y: f32 = ARENA_HEIGHT / 2.0; impl SimpleState for Stage1 { fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let world = data.world; let player_texture_path = format!( "{}/resources/textures/0x72_16x16DungeonTileset.v4.png", application_root_dir() ); let spritesheet_path = format!( "{}/resources/textures/0x72_16*16DungeonTileset.ron", application_root_dir() ); let texture_handle = load_texture(player_texture_path, &world); let sprite_sheet_handle = load_spritesheet(spritesheet_path, texture_handle, &world); init_player(world, PLAYER_INIT_X, PLAYER_INIT_Y, sprite_sheet_handle); init_camera(world, ARENA_WIDTH, ARENA_HEIGHT); init_fps_display(world); } }
/// # Geodesy library for all that extra fun post data gathering analysis. /// /// One to work out the distance between two points. /// Make a structure of a series of points and implement. /// At any point you are doing stuff to a series of points. //todo - size of error for a long lat: 51.0, 1.0 is x m^2 area. // todo - expected distance error for a given pdop. pub mod kinematics; pub mod position; /// This is the basic coordinate data for a single point in space. /// /// - UTC is used when calculating speed (relative UTC is needed) /// - altitude is used when measuring distance and actually calculates euclidian distance between /// points. If not required just put altitude to 0 and it will not affect calculations. #[derive(Default, PartialEq, Debug)] pub struct Coordinate { pub utc: f64, pub latitude: Option<f32>, pub longitude: Option<f32>, pub altitude: Option<f32>, }
mod physics; mod motor; use physics::{ElevatorSpecification, ElevatorState, MotorInput, simulate_elevator, DataRecorder, MotorController, MotorVoltage}; use motor::{SmoothMotorController, SimpleMotorController}; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; extern crate floating_duration; use std::time::Instant; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::io::prelude::*; extern crate termion; use termion::{clear, cursor, style}; use termion::raw; use termion::raw::IntoRawMode; use termion::input::TermRead; use termion::event::Key; use std::cmp; fn variable_summary<W: Write>(stdout: &mut raw::RawTerminal<W>, vname: String, data: &Vec<f64>) { let (avg, dev) = variable_summary_stats(data); variable_summary_print(stdout, vname, avg, dev); } fn variable_summary_stats(data: &Vec<f64>) -> (f64, f64) { //calculate statistics let N = data.len(); let sum = data.clone().into_iter() .fold(0.0, |a, b| a+b); let avg = sum / (N as f64); let dev = ( data.clone().into_iter() .map(|v| (v - avg).powi(2)) .fold(0.0, |a, b| a+b) / (N as f64) ).sqrt(); (avg, dev) } fn variable_summary_print<W: Write>(stdout: &mut raw::RawTerminal<W>, vname: String, avg: f64, dev: f64) { //print formatted output write!(stdout, "Average of {:25}{:.6}\r\n", vname, avg); write!(stdout, "Standard deviation of {:14}{:.6}\r\n", vname, dev); write!(stdout, "\r\n"); } struct SimpleDataRecorder<'a, W: 'a + Write> { esp: ElevatorSpecification, termwidth: u64, termheight: u64, stdout: &'a mut raw::RawTerminal<W>, log: File, record_location: Vec<f64>, record_velocity: Vec<f64>, record_acceleration: Vec<f64>, record_voltage: Vec<f64>, } impl<'a, W: Write> DataRecorder for SimpleDataRecorder<'a, W> { fn init(&mut self, esp: ElevatorSpecification, est: ElevatorState) { self.esp = esp.clone(); self.log.write_all(serde_json::to_string(&esp).unwrap().as_bytes()).expect("write spec to log"); self.log.write_all(b"\r\n").expect("write spec to log"); } fn poll(&mut self, est: ElevatorState, dst: u64) { let datum = (est.clone(), dst); self.log.write_all(serde_json::to_string(&datum).unwrap().as_bytes()).expect("write state to log"); self.log.write_all(b"\r\n").expect("write state to log"); self.record_location.push(est.location); self.record_velocity.push(est.velocity); self.record_acceleration.push(est.acceleration); self.record_voltage.push(est.motor_input.voltage()); //5.4. Print realtime statistics print!("{}{}{}", clear::All, cursor::Goto(1, 1), cursor::Hide); let carriage_floor = (est.location / self.esp.floor_height).floor(); let carriage_floor = if carriage_floor < 1.0 { 0 } else { carriage_floor as u64 }; let carriage_floor = cmp::min(carriage_floor, self.esp.floor_count-1); let mut terminal_buffer = vec![' ' as u8; (self.termwidth*self.termheight) as usize]; for ty in 0..self.esp.floor_count { terminal_buffer[ (ty*self.termwidth + 0) as usize ] = '[' as u8; terminal_buffer[ (ty*self.termwidth + 1) as usize ] = if (ty as u64)==((self.esp.floor_count-1)-carriage_floor) { 'X' as u8 } else { ' ' as u8 }; terminal_buffer[ (ty*self.termwidth + 2) as usize ] = ']' as u8; terminal_buffer[ (ty*self.termwidth + self.termwidth-2) as usize ] = '\r' as u8; terminal_buffer[ (ty*self.termwidth + self.termwidth-1) as usize ] = '\n' as u8; } let stats = vec![ format!("Carriage at floor {}", carriage_floor+1), format!("Location {:.06}", est.location), format!("Velocity {:.06}", est.velocity), format!("Acceleration {:.06}", est.acceleration), format!("Voltage [up-down] {:.06}", est.motor_input.voltage()), ]; for sy in 0..stats.len() { for (sx,sc) in stats[sy].chars().enumerate() { terminal_buffer[ sy*(self.termwidth as usize) + 6 + sx ] = sc as u8; } } write!(self.stdout, "{}", String::from_utf8(terminal_buffer).ok().unwrap()); self.stdout.flush().unwrap(); } fn summary(&mut self) { //6 Calculate and print summary statistics write!(self.stdout, "{}{}{}", clear::All, cursor::Goto(1, 1), cursor::Show).unwrap(); variable_summary(&mut self.stdout, "location".to_string(), &self.record_location); variable_summary(&mut self.stdout, "velocity".to_string(), &self.record_velocity); variable_summary(&mut self.stdout, "acceleration".to_string(), &self.record_acceleration); variable_summary(&mut self.stdout, "voltage".to_string(), &self.record_voltage); self.stdout.flush().unwrap(); } } pub fn run_simulation() { //1. Store location, velocity, and acceleration state //2. Store motor input voltage let mut est = ElevatorState { timestamp: 0.0, location: 0.0, velocity: 0.0, acceleration: 0.0, motor_input: MotorInput::Up { //zero is positive force to counter gravity voltage: 9.8 * (120000.0 / 8.0) } }; //3. Store input building description and floor requests let mut esp = ElevatorSpecification { floor_count: 0, floor_height: 0.0, carriage_weight: 120000.0 }; let mut floor_requests = Vec::new(); //4. Parse input and store as building description and floor requests let buffer = match env::args().nth(1) { Some(ref fp) if *fp == "-".to_string() => { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer) .expect("read_to_string failed"); buffer }, None => { let fp = "test1.txt"; let mut buffer = String::new(); File::open(fp) .expect("File::open failed") .read_to_string(&mut buffer) .expect("read_to_string failed"); buffer }, Some(fp) => { let mut buffer = String::new(); File::open(fp) .expect("File::open failed") .read_to_string(&mut buffer) .expect("read_to_string failed"); buffer } }; for (li,l) in buffer.lines().enumerate() { if li==0 { esp.floor_count = l.parse::<u64>().unwrap(); } else if li==1 { esp.floor_height = l.parse::<f64>().unwrap(); } else { floor_requests.push(l.parse::<u64>().unwrap()); } } let termsize = termion::terminal_size().ok(); let mut dr = SimpleDataRecorder { esp: esp.clone(), termwidth: termsize.map(|(w,_)| w-2).expect("termwidth") as u64, termheight: termsize.map(|(_,h)| h-2).expect("termheight") as u64, stdout: &mut io::stdout().into_raw_mode().unwrap(), log: File::create("simulation.log").expect("log file"), record_location: Vec::new(), record_velocity: Vec::new(), record_acceleration: Vec::new(), record_voltage: Vec::new() }; /* let mut mc = SimpleMotorController { esp: esp.clone() }; */ let mut mc = SmoothMotorController { timestamp: 0.0, esp: esp.clone() }; simulate_elevator(esp, est, floor_requests, &mut mc, &mut dr); dr.summary(); } #[cfg(test)] mod tests { use super::*; #[test] fn variable_stats() { let test_data = vec![ (vec![1.0, 2.0, 3.0, 4.0, 5.0], 3.0, 1.41), (vec![1.0, 3.0, 5.0, 7.0, 9.0], 5.0, 2.83), (vec![1.0, 9.0, 1.0, 9.0, 1.0], 4.2, 3.92), (vec![1.0, 0.5, 0.7, 0.9, 0.6], 0.74, 0.19), (vec![200.0, 3.0, 24.0, 92.0, 111.0], 86.0, 69.84), ]; for (data, avg, dev) in test_data { let (ravg, rdev) = variable_summary_stats(data); assert!( (avg-ravg).abs() < 0.1 ); assert!( (dev-rdev).abs() < 0.1 ); } } }
use druid::shell::keyboard::{KeyCode, KeyEvent, KeyModifiers}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use strum; use strum_macros::{Display, EnumProperty, EnumString}; #[derive(EnumString, Display, Clone, PartialEq)] pub enum InputState { #[strum(serialize = "normal", serialize = "n")] Normal, #[strum(serialize = "insert", serialize = "i")] Insert, #[strum(serialize = "visual", serialize = "v")] Visual, #[strum(serialize = "palette", serialize = "p")] Palette, #[strum(serialize = "completion", serialize = "c")] Completion, } #[derive(Clone)] pub struct KeyInput { pub key_code: KeyCode, pub mods: KeyModifiers, pub text: String, } impl FromStr for KeyInput { type Err = fmt::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let v: Vec<&str> = s.split('-').collect(); let mut mods = KeyModifiers::default(); let mut key_code = KeyCode::Key0; let mut text = "".to_string(); for e in &v[..v.len() - 1] { match e.to_lowercase().as_ref() { "a" => mods.alt = true, "c" => mods.ctrl = true, "m" => mods.meta = true, _ => (), }; } match v[v.len() - 1].to_lowercase().as_ref() { "tab" => key_code = KeyCode::Tab, "esc" => key_code = KeyCode::Escape, "bs" => key_code = KeyCode::Backspace, "cr" => key_code = KeyCode::Return, "up" => key_code = KeyCode::ArrowUp, "down" => key_code = KeyCode::ArrowDown, "left" => key_code = KeyCode::ArrowLeft, "right" => key_code = KeyCode::ArrowRight, _ => text = v[v.len() - 1].to_string(), } Ok(KeyInput { key_code, mods, text, }) } } impl Display for KeyInput { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut special = false; let mut r = "".to_string(); if self.mods.alt { r.push_str("a-"); } if self.mods.ctrl { r.push_str("c-"); } if self.mods.meta { r.push_str("m-"); } r.push_str(match self.key_code { KeyCode::Escape => "esc", KeyCode::Tab => "tab", KeyCode::Backspace => "bs", KeyCode::Return => "cr", KeyCode::ArrowUp => "up", KeyCode::ArrowDown => "down", KeyCode::ArrowLeft => "left", KeyCode::ArrowRight => "right", _ => &self.text, }); if r.len() > 1 { r = format!("<{}>", r) } write!(f, "{}", r) } } impl KeyInput { pub fn from_keyevent(event: &KeyEvent) -> KeyInput { KeyInput { key_code: event.key_code.clone(), mods: event.mods.clone(), text: event.unmod_text().unwrap_or("").to_string(), } } pub fn from_strings(s: String) -> Vec<KeyInput> { let mut keys = Vec::new(); let mut special = false; let mut special_key = "".to_string(); for c in s.chars() { if c == '<' { special = true; } else if c == '>' { if special { keys.push(special_key.to_string()); special = false; } else { keys.push(c.to_string()); } } else { if special { special_key.push(c); } else { keys.push(c.to_string()); } } } keys.iter() .map(|s| KeyInput::from_str(s).unwrap()) .collect() } } pub struct KeyMap { map: HashMap<String, Cmd>, } impl KeyMap { pub fn new() -> KeyMap { let mut keymap = KeyMap { map: HashMap::new(), }; keymap.add("n", "u", Command::Undo); keymap.add("n", "<C-r>", Command::Redo); keymap.add("n", "i", Command::Insert); keymap.add("n", "I", Command::InsertStartOfLine); keymap.add("n", "a", Command::AppendRight); keymap.add("n", "A", Command::AppendEndOfLine); keymap.add("n", "o", Command::NewLineBelow); keymap.add("n", "O", Command::NewLineAbove); keymap.add("n", "<M-;>", Command::SplitVertical); keymap.add("n", "<M-w>", Command::SplitClose); keymap.add("n", "<C-n>", Command::Hover); keymap.add("n", "<C-w>v", Command::SplitVertical); keymap.add("n", "<m-h>", Command::MoveCursorToWindowLeft); keymap.add("n", "<m-l>", Command::MoveCursorToWindowRight); keymap.add("n", "<m-x>", Command::ExchangeWindow); keymap.add("n", "<m-k>", Command::CommandPalette); keymap.add("nv", "v", Command::Visual); keymap.add("nv", "V", Command::VisualLine); keymap.add("nv", "x", Command::DeleteForward); keymap.add("nv", "s", Command::DeleteForwardInsert); keymap.add("invp", "<down>", Command::MoveDown); keymap.add("invp", "<up>", Command::MoveUp); keymap.add("inv", "<left>", Command::MoveLeft); keymap.add("inv", "<right>", Command::MoveRight); keymap.add("nv", "gg", Command::MoveToTop); keymap.add("nv", "G", Command::MoveToBottom); keymap.add("nv", "k", Command::MoveUp); keymap.add("nv", "j", Command::MoveDown); keymap.add("nv", "h", Command::MoveLeft); keymap.add("nv", "l", Command::MoveRight); keymap.add("nv", "b", Command::MoveWordLeft); keymap.add("nv", "e", Command::MoveWordRight); keymap.add("nv", "0", Command::MoveStartOfLine); keymap.add("nv", "$", Command::MoveEndOfLine); keymap.add("nv", "<C-u>", Command::ScrollPageUp); keymap.add("nv", "<C-d>", Command::ScrollPageDown); keymap.add("v", "<Esc>", Command::Escape); keymap.add("p", "<C-m>", Command::Execute); keymap.add("p", "<cr>", Command::Execute); keymap.add("p", "<C-n>", Command::MoveDown); keymap.add("p", "<C-p>", Command::MoveUp); keymap.add("c", "<C-n>", Command::MoveDown); keymap.add("c", "<C-p>", Command::MoveUp); keymap.add("c", "<C-m>", Command::Execute); keymap.add("c", "<cr>", Command::Execute); keymap.add("ip", "<Esc>", Command::Escape); keymap.add("ip", "<bs>", Command::DeleteBackward); keymap.add("ip", "<C-h>", Command::DeleteBackward); keymap.add("ip", "<C-u>", Command::DeleteToBeginningOfLine); keymap.add("i", "<C-w>", Command::DeleteWordBackward); keymap.add("i", "<cr>", Command::InsertNewLine); keymap.add("i", "<C-m>", Command::InsertNewLine); keymap.add("i", "<Tab>", Command::InsertTab); println!("keys is {:?}", &keymap.map.keys()); keymap } pub fn get(&self, state: InputState, inputs: Vec<KeyInput>) -> Cmd { let key = inputs .iter() .map(|i| format!("{} {}", state, i)) .collect::<Vec<String>>() .join(" "); self.map .get(&key) .unwrap_or(&Cmd { cmd: Some(Command::Unknown), more_input: false, }) .clone() } fn add(&mut self, state_strings: &str, input_strings: &str, command: Command) { let inputs = KeyInput::from_strings(input_strings.to_string()); let len = inputs.len(); for i in 0..len { for state_char in state_strings.chars() { if let Ok(state) = InputState::from_str(&state_char.to_string()) { let input = inputs[..i + 1] .iter() .map(|i| format!("{} {}", state, i)) .collect::<Vec<String>>() .join(" "); println!("input is {}", input); if i == len - 1 { if let Some(cmd) = self.map.get_mut(&input) { cmd.cmd = Some(command.clone()); } else { let cmd = Cmd { cmd: Some(command.clone()), more_input: false, }; self.map.insert(input, cmd); } } else { if let Some(cmd) = self.map.get_mut(&input) { cmd.more_input = true; } else { let cmd = Cmd { cmd: None, more_input: true, }; self.map.insert(input, cmd); } } } } } } } #[derive(Clone)] pub struct Cmd { pub cmd: Option<Command>, pub more_input: bool, } #[derive(EnumProperty, EnumString, Debug, Clone, PartialEq)] pub enum Command { #[strum(serialize = "insert", props(description = ""))] Insert, #[strum(serialize = "visual", props(description = ""))] Visual, #[strum(serialize = "visual_line", props(description = ""))] VisualLine, #[strum(serialize = "escape", props(description = ""))] Escape, #[strum(serialize = "undo", props(description = ""))] Undo, #[strum(serialize = "redo", props(description = ""))] Redo, #[strum(serialize = "delete_forward_insert", props(description = ""))] DeleteForwardInsert, #[strum(serialize = "delete_forward", props(description = ""))] DeleteForward, #[strum(serialize = "delete_backward", props(description = ""))] DeleteBackward, #[strum(serialize = "delete_word_backward", props(description = ""))] DeleteWordBackward, #[strum(serialize = "delete_to_beginning_of_line", props(description = ""))] DeleteToBeginningOfLine, #[strum(serialize = "move_cursor_to_window_below", props(description = ""))] MoveCursorToWindowBelow, #[strum(serialize = "move_cursor_to_window_above", props(description = ""))] MoveCursorToWindowAbove, #[strum(serialize = "move_cursor_to_window_left", props(description = ""))] MoveCursorToWindowLeft, #[strum(serialize = "move_cursor_to_window_right", props(description = ""))] MoveCursorToWindowRight, #[strum(serialize = "exchange_window", props(description = ""))] ExchangeWindow, #[strum(serialize = "split_close", props(description = ""))] SplitClose, #[strum(serialize = "split_vertical", props(description = ""))] SplitVertical, #[strum(serialize = "split_horizontal", props(description = ""))] SplitHorizontal, #[strum(serialize = "scroll_page_up", props(description = ""))] ScrollPageUp, #[strum(serialize = "scroll_page_down", props(description = ""))] ScrollPageDown, #[strum(serialize = "move_to_top", props(description = ""))] MoveToTop, #[strum(serialize = "move_to_bottom", props(description = ""))] MoveToBottom, #[strum(serialize = "move_up", props(description = ""))] MoveUp, #[strum(serialize = "move_down", props(description = ""))] MoveDown, #[strum(serialize = "move_left", props(description = ""))] MoveLeft, #[strum(serialize = "move_right", props(description = ""))] MoveRight, #[strum(serialize = "move_word_left", props(description = ""))] MoveWordLeft, #[strum(serialize = "move_word_right", props(description = ""))] MoveWordRight, #[strum(serialize = "move_start_of_line", props(description = ""))] MoveStartOfLine, #[strum(serialize = "move_end_of_line", props(description = ""))] MoveEndOfLine, #[strum(serialize = "insert_start_of_line", props(description = ""))] InsertStartOfLine, #[strum(serialize = "append_right", props(description = ""))] AppendRight, #[strum(serialize = "append_end_of_line", props(description = ""))] AppendEndOfLine, #[strum(serialize = "new_line_below", props(description = ""))] NewLineBelow, #[strum(serialize = "new_line_above", props(description = ""))] NewLineAbove, #[strum(serialize = "insert_new_line", props(description = ""))] InsertNewLine, #[strum(serialize = "insert_tab", props(description = ""))] InsertTab, #[strum(serialize = "command_palette", props(description = ""))] CommandPalette, #[strum(serialize = "execute", props(description = ""))] Execute, #[strum(serialize = "hover", props(description = ""))] Hover, #[strum(serialize = "unknown", props(description = ""))] Unknown, } #[derive(Clone)] pub struct Input { pub state: InputState, pub visual_line: bool, pub count: u64, } impl Input { pub fn new() -> Input { Input { state: InputState::Normal, visual_line: false, count: 0, } } }
use thiserror::Error; #[macro_export] macro_rules! generation { ($t:ty => $f:ident) => { impl $crate::models::gen::Generation for $t { #[inline] fn generation(&self) -> u64 { self.$f } fn set_generation( &mut self, generation: u64, ) -> Result<u64, $crate::models::gen::GenerationError> { let current = self.generation(); if current < generation { self.$f = generation; Ok(generation) } else { Err($crate::models::gen::GenerationError::NotIncrementing { current, desired: generation, }) } } } }; } #[derive(Debug, Error)] pub enum GenerationError { #[error("Generation not incrementing (was: {current}, desired: {desired})")] NotIncrementing { current: u64, desired: u64 }, } pub trait Generation { /// Get the generation from the provided resource, increment it by one, and set it to this resource. fn set_incremented_generation( &mut self, current: &dyn Generation, ) -> Result<u64, GenerationError> { self.set_generation(current.generation() + 1) } /// Increment the generation of this resource by one fn increment_generation(&mut self) -> Result<u64, GenerationError> { self.set_generation(self.generation() + 1) } /// Get the current generation fn generation(&self) -> u64; /// Set the generation fn set_generation(&mut self, generation: u64) -> Result<u64, GenerationError>; }
use std::sync::Arc; use ntex::web::types::{Json, Path, State}; use crate::{ article, errors::CustomError, models::{comment::{Comment, self}, user::GithubUserInfo}, AppState, }; pub async fn get_comments_for_article( article_id: Path<(u32,)>, state: State<Arc<AppState>>, ) -> Result<Json<Vec<Comment>>, CustomError> { let db_pool = &state.db_pool; let article_id = article_id.0; // 从文章id中查找所有评论,拿到 user_id content date,并从 users 表里拿到相同的 user_id(对应 users 表里的 id) 记录的 name, avatar_url let comments = sqlx::query!( "SELECT comments.id, comments.user_id, comments.content, comments.date, users.name, users.avatar_url FROM comments JOIN users ON comments.user_id = users.id WHERE comments.article = $1", article_id as i32 ).fetch_all(db_pool).await?.iter().map(|i| Comment { id: Some(i.id), user: Some(GithubUserInfo { id: i.user_id, login: i.name.clone(), avatar_url: i.avatar_url.clone(), }), content: i.content.clone(), date: Some(i.date), article: None, }) .collect::<Vec<Comment>>(); Ok(Json(comments)) }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - SAI global configuration register"] pub gcr: GCR, #[doc = "0x04 - SAI configuration register 1"] pub acr1: ACR1, #[doc = "0x08 - SAI configuration register 2"] pub acr2: ACR2, #[doc = "0x0c - SAI frame configuration register"] pub afrcr: AFRCR, #[doc = "0x10 - SAI slot register"] pub aslotr: ASLOTR, #[doc = "0x14 - SAI interrupt mask register"] pub aim: AIM, #[doc = "0x18 - SAI status register"] pub asr: ASR, #[doc = "0x1c - SAI clear flag register"] pub aclrfr: ACLRFR, #[doc = "0x20 - SAI data register"] pub adr: ADR, #[doc = "0x24 - SAI configuration register 1"] pub bcr1: BCR1, #[doc = "0x28 - SAI configuration register 2"] pub bcr2: BCR2, #[doc = "0x2c - SAI frame configuration register"] pub bfrcr: BFRCR, #[doc = "0x30 - SAI slot register"] pub bslotr: BSLOTR, #[doc = "0x34 - SAI interrupt mask register"] pub bim: BIM, #[doc = "0x38 - SAI status register"] pub bsr: BSR, #[doc = "0x3c - SAI clear flag register"] pub bclrfr: BCLRFR, #[doc = "0x40 - SAI data register"] pub bdr: BDR, #[doc = "0x44 - SAI PDM control register"] pub pdmcr: PDMCR, #[doc = "0x48 - SAI PDM delay register"] pub pdmdly: PDMDLY, } #[doc = "GCR (rw) register accessor: SAI global configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gcr::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 [`gcr::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 [`gcr`] module"] pub type GCR = crate::Reg<gcr::GCR_SPEC>; #[doc = "SAI global configuration register"] pub mod gcr; #[doc = "ACR1 (rw) register accessor: SAI configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`acr1::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 [`acr1::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 [`acr1`] module"] pub type ACR1 = crate::Reg<acr1::ACR1_SPEC>; #[doc = "SAI configuration register 1"] pub mod acr1; #[doc = "ACR2 (rw) register accessor: SAI configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`acr2::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 [`acr2::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 [`acr2`] module"] pub type ACR2 = crate::Reg<acr2::ACR2_SPEC>; #[doc = "SAI configuration register 2"] pub mod acr2; #[doc = "AFRCR (rw) register accessor: SAI frame configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`afrcr::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 [`afrcr::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 [`afrcr`] module"] pub type AFRCR = crate::Reg<afrcr::AFRCR_SPEC>; #[doc = "SAI frame configuration register"] pub mod afrcr; #[doc = "ASLOTR (rw) register accessor: SAI slot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`aslotr::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 [`aslotr::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 [`aslotr`] module"] pub type ASLOTR = crate::Reg<aslotr::ASLOTR_SPEC>; #[doc = "SAI slot register"] pub mod aslotr; #[doc = "AIM (rw) register accessor: SAI interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`aim::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 [`aim::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 [`aim`] module"] pub type AIM = crate::Reg<aim::AIM_SPEC>; #[doc = "SAI interrupt mask register"] pub mod aim; #[doc = "ASR (r) register accessor: SAI status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`asr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`asr`] module"] pub type ASR = crate::Reg<asr::ASR_SPEC>; #[doc = "SAI status register"] pub mod asr; #[doc = "ACLRFR (w) register accessor: SAI clear flag 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 [`aclrfr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`aclrfr`] module"] pub type ACLRFR = crate::Reg<aclrfr::ACLRFR_SPEC>; #[doc = "SAI clear flag register"] pub mod aclrfr; #[doc = "ADR (rw) register accessor: SAI data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`adr::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 [`adr::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 [`adr`] module"] pub type ADR = crate::Reg<adr::ADR_SPEC>; #[doc = "SAI data register"] pub mod adr; #[doc = "BCR1 (rw) register accessor: SAI configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bcr1::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 [`bcr1::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 [`bcr1`] module"] pub type BCR1 = crate::Reg<bcr1::BCR1_SPEC>; #[doc = "SAI configuration register 1"] pub mod bcr1; #[doc = "BCR2 (rw) register accessor: SAI configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bcr2::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 [`bcr2::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 [`bcr2`] module"] pub type BCR2 = crate::Reg<bcr2::BCR2_SPEC>; #[doc = "SAI configuration register 2"] pub mod bcr2; #[doc = "BFRCR (rw) register accessor: SAI frame configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bfrcr::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 [`bfrcr::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 [`bfrcr`] module"] pub type BFRCR = crate::Reg<bfrcr::BFRCR_SPEC>; #[doc = "SAI frame configuration register"] pub mod bfrcr; #[doc = "BSLOTR (rw) register accessor: SAI slot register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bslotr::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 [`bslotr::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 [`bslotr`] module"] pub type BSLOTR = crate::Reg<bslotr::BSLOTR_SPEC>; #[doc = "SAI slot register"] pub mod bslotr; #[doc = "BIM (rw) register accessor: SAI interrupt mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bim::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 [`bim::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 [`bim`] module"] pub type BIM = crate::Reg<bim::BIM_SPEC>; #[doc = "SAI interrupt mask register"] pub mod bim; #[doc = "BSR (r) register accessor: SAI status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bsr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bsr`] module"] pub type BSR = crate::Reg<bsr::BSR_SPEC>; #[doc = "SAI status register"] pub mod bsr; #[doc = "BCLRFR (w) register accessor: SAI clear flag 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 [`bclrfr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bclrfr`] module"] pub type BCLRFR = crate::Reg<bclrfr::BCLRFR_SPEC>; #[doc = "SAI clear flag register"] pub mod bclrfr; #[doc = "BDR (rw) register accessor: SAI data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bdr::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 [`bdr::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 [`bdr`] module"] pub type BDR = crate::Reg<bdr::BDR_SPEC>; #[doc = "SAI data register"] pub mod bdr; #[doc = "PDMCR (rw) register accessor: SAI PDM control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pdmcr::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 [`pdmcr::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 [`pdmcr`] module"] pub type PDMCR = crate::Reg<pdmcr::PDMCR_SPEC>; #[doc = "SAI PDM control register"] pub mod pdmcr; #[doc = "PDMDLY (rw) register accessor: SAI PDM delay register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pdmdly::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 [`pdmdly::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 [`pdmdly`] module"] pub type PDMDLY = crate::Reg<pdmdly::PDMDLY_SPEC>; #[doc = "SAI PDM delay register"] pub mod pdmdly;
use token::{Token, TokenType, bad_token}; use {Ctype, Type, Scope}; use util::roundup; use std::sync::Mutex; use std::collections::HashMap; // Quoted from 9cc // > This is a recursive-descendent parser which constructs abstract // > syntax tree from input tokens. // // > This parser knows only about BNF of the C grammer and doesn't care // > about its semantics. Therefore, some invalid expressions, such as // > `1+2=3`, are accepted by this parser, but that's intentional. // > Semantic errors are detected in a later pass. lazy_static!{ static ref ENV: Mutex<Env> = Mutex::new(Env::new(None)); } #[derive(Debug, Clone)] pub enum NodeType { Num(i32), // Number literal Str(String, usize), // String literal, (data, len) Ident(String), // Identifier Decl(String), // declaration Vardef(String, Option<Box<Node>>, Scope), // Variable definition, name = init Lvar(Scope), // Variable reference Gvar(String, String, usize), // Variable reference, (name, data, len) BinOp(TokenType, Box<Node>, Box<Node>), // left-hand, right-hand If(Box<Node>, Box<Node>, Option<Box<Node>>), // "if" ( cond ) then "else" els Ternary(Box<Node>, Box<Node>, Box<Node>), // cond ? then : els For(Box<Node>, Box<Node>, Box<Node>, Box<Node>), // "for" ( init; cond; inc ) body Break, DoWhile(Box<Node>, Box<Node>), // do { body } while(cond) Addr(Box<Node>), // address-of operator("&"), expr Deref(Box<Node>), // pointer dereference ("*"), expr Dot(Box<Node>, String, usize), // Struct member accessm, (expr, name, offset) Exclamation(Box<Node>), // !, expr Neg(Box<Node>), // - PostInc(Box<Node>), // post ++ PostDec(Box<Node>), // post -- Return(Box<Node>), // "return", stmt Sizeof(Box<Node>), // "sizeof", expr Alignof(Box<Node>), // "_Alignof", expr Call(String, Vec<Node>), // Function call(name, args) Func(String, Vec<Node>, Box<Node>, usize), // Function definition(name, args, body, stacksize) CompStmt(Vec<Node>), // Compound statement VecStmt(Vec<Node>), // For the purpose of assign a value when initializing an array. ExprStmt(Box<Node>), // Expression statement StmtExpr(Box<Node>), // Statement expression (GNU extn.) Null, } #[derive(Debug, Clone)] pub struct Node { pub op: NodeType, // Node type pub ty: Box<Type>, // C type } impl Node { pub fn new(op: NodeType) -> Self { Self { op, ty: Box::new(Type::default()), } } pub fn new_int(val: i32) -> Self { Node::new(NodeType::Num(val)) } pub fn scale_ptr(node: Box<Node>, ty: &Type) -> Self { match ty.ty { Ctype::Ptr(ref ptr_to) => { Node::new_binop(TokenType::Mul, *node, Node::new_int(ptr_to.size as i32)) } _ => panic!("expect ptr type"), } } pub fn new_binop(ty: TokenType, lhs: Node, rhs: Node) -> Self { Node::new(NodeType::BinOp(ty, Box::new(lhs), Box::new(rhs))) } pub fn new_num(val: i32) -> Self { Node::new(NodeType::Num(val)) } pub fn is_null(&self) -> bool { match self.op { NodeType::Null => true, _ => false, } } } macro_rules! new_expr( ($i:path, $expr:expr) => ( Node::new($i(Box::new($expr))) ) ); impl Type { pub fn new(ty: Ctype, size: usize) -> Self { Type { ty, size, align: size, } } pub fn void_ty() -> Self { Type::new(Ctype::Void, 0) } pub fn char_ty() -> Self { Type::new(Ctype::Char, 1) } pub fn int_ty() -> Self { Type::new(Ctype::Int, 4) } pub fn ptr_to(base: Box<Type>) -> Self { Type::new(Ctype::Ptr(base), 8) } pub fn ary_of(base: Box<Type>, len: usize) -> Self { let align = base.align; let size = base.size * len; let mut ty = Type::new(Ctype::Ary(base, len), size); ty.align = align; ty } } #[derive(Debug, Clone)] struct Env { tags: HashMap<String, Type>, typedefs: HashMap<String, Type>, next: Option<Box<Env>>, } impl Env { pub fn new(next: Option<Box<Env>>) -> Self { Env { next, tags: HashMap::new(), typedefs: HashMap::new(), } } } fn find_typedef(name: &String) -> Option<Type> { let env = ENV.lock().unwrap().clone(); let mut next: &Option<Box<Env>> = &Some(Box::new(env)); loop { if let Some(ref e) = next { let ty = e.typedefs.get(name); if ty.is_some() { return ty.cloned(); } next = &e.next; } else { return None; } } } fn find_tag(name: &String) -> Option<Type> { let env = ENV.lock().unwrap().clone(); let mut next: &Option<Box<Env>> = &Some(Box::new(env)); loop { if let Some(ref e) = next { let ty = e.tags.get(name); if ty.is_some() { return ty.cloned(); } next = &e.next; } else { return None; } } } fn expect(ty: TokenType, tokens: &Vec<Token>, pos: &mut usize) { let t = &tokens[*pos]; if t.ty != ty { bad_token(t, &format!("{:?} expected", ty)); } *pos += 1; } fn consume(ty: TokenType, tokens: &Vec<Token>, pos: &mut usize) -> bool { let t = &tokens[*pos]; if t.ty != ty { return false; } *pos += 1; return true; } fn is_typename(t: &Token) -> bool { use self::TokenType::*; if let TokenType::Ident(ref name) = t.ty { return find_typedef(name).is_some(); } t.ty == Int || t.ty == Char || t.ty == Void || t.ty == Struct } fn set_offset(members: &mut Vec<Node>) -> (usize, usize) { let mut off = 0; let mut align = 0; for node in members { if let NodeType::Vardef(_, _, Scope::Local(offset)) = &mut node.op { let t = &node.ty; off = roundup(off, t.align); *offset = off; off += t.size; if align < t.align { align = t.align; } } else { panic!(); } } return (off, align); } fn add_member(ty: &mut Type, mut members: Vec<Node>) { let (off, align) = set_offset(&mut members); if let Ctype::Struct(ref mut members2) = ty.ty { *members2 = members; } ty.size = roundup(off, align); } fn decl_specifiers(tokens: &Vec<Token>, pos: &mut usize) -> Option<Type> { let t = &tokens[*pos]; *pos += 1; match t.ty { TokenType::Ident(ref name) => { if let Some(ty) = find_typedef(name) { return Some(ty.clone()); } else { *pos -= 1; return None; } } TokenType::Int => Some(Type::int_ty()), TokenType::Char => Some(Type::char_ty()), TokenType::Void => Some(Type::void_ty()), TokenType::Struct => { let mut tag_may: Option<String> = None; let t = &tokens[*pos]; if let TokenType::Ident(ref name) = t.ty { *pos += 1; tag_may = Some(name.clone()) } let mut members = vec![]; if consume(TokenType::LeftBrace, tokens, pos) { while !consume(TokenType::RightBrace, tokens, pos) { members.push(declaration(tokens, pos)) } } let mut ty_may: Option<Type> = None; if let Some(ref tag) = tag_may { if members.is_empty() { ty_may = find_tag(&tag); } } let mut ty = ty_may.unwrap_or(Type::new(Ctype::Struct(vec![]), 10)); if !members.is_empty() { add_member(&mut ty, members); if let Some(tag) = tag_may { ENV.lock().unwrap().tags.insert(tag, ty.clone()); } } return Some(ty.clone()); } _ => bad_token(&t, "typename expected"), } } fn ident(tokens: &Vec<Token>, pos: &mut usize) -> String { let t = &tokens[*pos]; if let TokenType::Ident(ref name) = t.ty { *pos += 1; name.clone() } else { bad_token(t, "variable name expected"); } } fn primary(tokens: &Vec<Token>, pos: &mut usize) -> Node { let t = &tokens[*pos]; *pos += 1; match t.ty { TokenType::Num(val) => Node::new_num(val), TokenType::Str(ref str, len) => { let mut node = Node::new(NodeType::Str(str.clone(), len)); node.ty = Box::new(Type::ary_of(Box::new(Type::char_ty()), len)); node } TokenType::Ident(ref name) => { if !consume(TokenType::LeftParen, tokens, pos) { return Node::new(NodeType::Ident(name.clone())); } let mut args = vec![]; if consume(TokenType::RightParen, tokens, pos) { return Node::new(NodeType::Call(name.clone(), args)); } args.push(assign(tokens, pos)); while consume(TokenType::Comma, tokens, pos) { args.push(assign(tokens, pos)); } expect(TokenType::RightParen, tokens, pos); return Node::new(NodeType::Call(name.clone(), args)); } TokenType::LeftParen => { if consume(TokenType::LeftBrace, tokens, pos) { let stmt = Box::new(compound_stmt(tokens, pos)); expect(TokenType::RightParen, tokens, pos); return Node::new(NodeType::StmtExpr(stmt)); } let node = expr(tokens, pos); expect(TokenType::RightParen, tokens, pos); node } _ => bad_token(t, "number expected"), } } fn postfix(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = primary(tokens, pos); loop { if consume(TokenType::Inc, tokens, pos) { lhs = new_expr!(NodeType::PostInc, lhs); continue; } if consume(TokenType::Dec, tokens, pos) { lhs = new_expr!(NodeType::PostDec, lhs); continue; } if consume(TokenType::Dot, tokens, pos) { // TODO: Use new_expr! lhs = Node::new(NodeType::Dot(Box::new(lhs), ident(tokens, pos), 0)); continue; } if consume(TokenType::Arrow, tokens, pos) { lhs = Node::new(NodeType::Dot( Box::new(new_expr!(NodeType::Deref, lhs)), ident(tokens, pos), 0, )); continue; } if consume(TokenType::LeftBracket, tokens, pos) { lhs = new_expr!( NodeType::Deref, Node::new_binop(TokenType::Plus, lhs, assign(tokens, pos)) ); expect(TokenType::RightBracket, tokens, pos); continue; } return lhs; } } fn unary(tokens: &Vec<Token>, pos: &mut usize) -> Node { if consume(TokenType::Minus, tokens, pos) { return new_expr!(NodeType::Neg, unary(tokens, pos)); } if consume(TokenType::Mul, tokens, pos) { return new_expr!(NodeType::Deref, unary(tokens, pos)); } if consume(TokenType::And, tokens, pos) { return new_expr!(NodeType::Addr, unary(tokens, pos)); } if consume(TokenType::Exclamation, tokens, pos) { return new_expr!(NodeType::Exclamation, unary(tokens, pos)); } if consume(TokenType::Sizeof, tokens, pos) { return new_expr!(NodeType::Sizeof, unary(tokens, pos)); } if consume(TokenType::Alignof, tokens, pos) { return new_expr!(NodeType::Alignof, unary(tokens, pos)); } if consume(TokenType::Inc, tokens, pos) { return Node::new_binop(TokenType::AddEQ, unary(tokens, pos), Node::new_num(1)); } if consume(TokenType::Dec, tokens, pos) { return Node::new_binop(TokenType::SubEQ, unary(tokens, pos), Node::new_num(1)); } postfix(tokens, pos) } fn mul(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = unary(&tokens, pos); loop { if consume(TokenType::Mul, tokens, pos) { lhs = Node::new_binop(TokenType::Mul, lhs, unary(&tokens, pos)); } else if consume(TokenType::Div, tokens, pos) { lhs = Node::new_binop(TokenType::Div, lhs, unary(&tokens, pos)); } else if consume(TokenType::Mod, tokens, pos) { lhs = Node::new_binop(TokenType::Mod, lhs, unary(&tokens, pos)); } else { return lhs; } } } fn add(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = mul(&tokens, pos); loop { if consume(TokenType::Plus, tokens, pos) { lhs = Node::new_binop(TokenType::Plus, lhs, mul(&tokens, pos)); } else if consume(TokenType::Minus, tokens, pos) { lhs = Node::new_binop(TokenType::Minus, lhs, mul(&tokens, pos)); } else { return lhs; } } } fn shift(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = add(tokens, pos); loop { if consume(TokenType::SHL, tokens, pos) { lhs = Node::new_binop(TokenType::SHL, lhs, add(tokens, pos)); } else if consume(TokenType::SHR, tokens, pos) { lhs = Node::new_binop(TokenType::SHR, lhs, add(tokens, pos)); } else { return lhs; } } } fn relational(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = shift(tokens, pos); loop { if consume(TokenType::LeftAngleBracket, tokens, pos) { lhs = Node::new_binop(TokenType::LeftAngleBracket, lhs, shift(tokens, pos)); } else if consume(TokenType::RightAngleBracket, tokens, pos) { lhs = Node::new_binop(TokenType::LeftAngleBracket, shift(tokens, pos), lhs); } else if consume(TokenType::LE, tokens, pos) { lhs = Node::new_binop(TokenType::LE, lhs, shift(tokens, pos)) } else if consume(TokenType::GE, tokens, pos) { lhs = Node::new_binop(TokenType::LE, shift(tokens, pos), lhs); } else { return lhs; } } } fn equality(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = relational(tokens, pos); loop { if consume(TokenType::EQ, tokens, pos) { lhs = Node::new_binop(TokenType::EQ, lhs, relational(tokens, pos)); } else if consume(TokenType::NE, tokens, pos) { lhs = Node::new_binop(TokenType::NE, lhs, relational(tokens, pos)); } else { return lhs; } } } fn bit_and(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = equality(tokens, pos); while consume(TokenType::And, tokens, pos) { lhs = Node::new_binop(TokenType::And, lhs, equality(tokens, pos)); } return lhs; } fn bit_xor(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = bit_and(tokens, pos); while consume(TokenType::Hat, tokens, pos) { lhs = Node::new_binop(TokenType::Hat, lhs, bit_and(tokens, pos)); } return lhs; } fn bit_or(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = bit_xor(tokens, pos); while consume(TokenType::VerticalBar, tokens, pos) { lhs = Node::new_binop(TokenType::VerticalBar, lhs, bit_xor(tokens, pos)); } return lhs; } fn logand(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = bit_or(tokens, pos); while consume(TokenType::Logand, tokens, pos) { lhs = Node::new_binop(TokenType::Logand, lhs, logand(tokens, pos)); } return lhs; } fn logor(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut lhs = logand(tokens, pos); while consume(TokenType::Logor, tokens, pos) { lhs = Node::new_binop(TokenType::Logor, lhs, logand(tokens, pos)); } return lhs; } fn conditional(tokens: &Vec<Token>, pos: &mut usize) -> Node { let cond = logor(tokens, pos); if !consume(TokenType::Question, tokens, pos) { return cond; } let then = expr(tokens, pos); expect(TokenType::Colon, tokens, pos); let els = conditional(tokens, pos); Node::new(NodeType::Ternary( Box::new(cond), Box::new(then), Box::new(els), )) } fn assign_op(ty: &TokenType) -> Option<&TokenType> { use self::TokenType::*; match ty { Equal | MulEQ | DivEQ | ModEQ | AddEQ | SubEQ | ShlEQ | ShrEQ | BitandEQ | XorEQ | BitorEQ => Some(ty), _ => None, } } fn assign(tokens: &Vec<Token>, pos: &mut usize) -> Node { let lhs = conditional(tokens, pos); if let Some(op) = assign_op(&tokens[*pos].ty) { *pos += 1; Node::new_binop(op.clone(), lhs, assign(tokens, pos)) } else { lhs } } fn expr(tokens: &Vec<Token>, pos: &mut usize) -> Node { let lhs = assign(tokens, pos); if !consume(TokenType::Comma, tokens, pos) { return lhs; } return Node::new_binop(TokenType::Comma, lhs, expr(tokens, pos)); } fn ctype(tokens: &Vec<Token>, pos: &mut usize) -> Type { let t = &tokens[*pos]; if let Some(mut ty) = decl_specifiers(tokens, pos) { while consume(TokenType::Mul, tokens, pos) { ty = Type::ptr_to(Box::new(ty)); } ty } else { bad_token(t, "typename expected"); } } fn read_array(mut ty: Box<Type>, tokens: &Vec<Token>, pos: &mut usize) -> Type { let mut v: Vec<usize> = vec![]; while consume(TokenType::LeftBracket, tokens, pos) { if consume(TokenType::RightBracket, tokens, pos) { v.push(0); // temporary value continue; } let len = expr(tokens, pos); if let NodeType::Num(n) = len.op { v.push(n as usize); expect(TokenType::RightBracket, tokens, pos); } else { panic!("number expected"); } } v.reverse(); for val in v { ty = Box::new(Type::ary_of(ty, val)); } *ty } fn array_init_rval(tokens: &Vec<Token>, pos: &mut usize, ident: Node) -> Node { let mut init = vec![]; let mut i = 0; loop { let val = primary(tokens, pos); let node = new_expr!( NodeType::Deref, Node::new_binop(TokenType::Plus, ident.clone(), Node::new(NodeType::Num(i))) ); init.push(Node::new(NodeType::ExprStmt( Box::new(Node::new_binop(TokenType::Equal, node, val)), ))); if !consume(TokenType::Comma, tokens, pos) { break; } i += 1; } expect(TokenType::RightBrace, tokens, pos); return Node::new(NodeType::VecStmt(init)); } fn update_ptr_to(src: &mut Box<Type>, dst: Box<Type>, tokens: &Vec<Token>, pos: &mut usize) { match src.ty { Ctype::Ptr(ref mut ptr_to) => update_ptr_to(ptr_to, dst, tokens, pos), _ => *src = dst, } } fn direct_decl(ty: Box<Type>, tokens: &Vec<Token>, pos: &mut usize) -> Node { let t = &tokens[*pos]; let mut placeholder = Box::new(Type::default()); let mut node; if let TokenType::Ident(_) = t.ty { node = Node::new(NodeType::Vardef(ident(tokens, pos), None, Scope::Local(0))); } else if consume(TokenType::LeftParen, tokens, pos) { node = declarator(&mut placeholder, tokens, pos); expect(TokenType::RightParen, tokens, pos); } else { bad_token(t, "bad direct-declarator"); } // Read the second half of type name (e.g. `[3][5]`). update_ptr_to( &mut node.ty, Box::new(read_array(ty, tokens, pos)), tokens, pos, ); // Read an initializer. let init: Option<Box<Node>>; if consume(TokenType::Equal, tokens, pos) { // Assign a value when initializing an array. if let TokenType::Ident(ref name) = t.ty { if consume(TokenType::LeftBrace, tokens, pos) { let mut stmts = vec![]; let mut ary_declaration = Node::new(NodeType::Vardef(name.clone(), None, Scope::Local(0))); ary_declaration.ty = node.ty; stmts.push(ary_declaration); let init_ary = array_init_rval(tokens, pos, Node::new(NodeType::Ident(name.clone()))); stmts.push(init_ary); return Node::new(NodeType::VecStmt(stmts)); } } init = Some(Box::new(assign(tokens, pos))); match node.op { NodeType::Vardef(_, ref mut init2, _) => *init2 = init, _ => unreachable!(), } } return node; } fn declarator(ty: &mut Type, tokens: &Vec<Token>, pos: &mut usize) -> Node { while consume(TokenType::Mul, tokens, pos) { *ty = Type::ptr_to(Box::new(ty.clone())); } direct_decl(Box::new(ty.clone()), tokens, pos) } fn declaration(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut ty = decl_specifiers(tokens, pos).unwrap(); let node = declarator(&mut ty, tokens, pos); expect(TokenType::Semicolon, tokens, pos); return node; } fn param_declaration(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut ty = decl_specifiers(tokens, pos).unwrap(); let mut node = declarator(&mut ty, tokens, pos); if let Ctype::Ary(ary_of, _) = node.ty.ty { node.ty = Box::new(Type::ptr_to(ary_of)); } node } fn expr_stmt(tokens: &Vec<Token>, pos: &mut usize) -> Node { let expr = expr(tokens, pos); let node = new_expr!(NodeType::ExprStmt, expr); expect(TokenType::Semicolon, tokens, pos); node } fn stmt(tokens: &Vec<Token>, pos: &mut usize) -> Node { let t = &tokens[*pos]; *pos += 1; match t.ty { TokenType::Typedef => { let node = declaration(tokens, pos); if let NodeType::Vardef(name, _, _) = node.op { ENV.lock().unwrap().typedefs.insert(name, *node.ty); return Node::new(NodeType::Null); } else { unreachable!(); } } TokenType::If => { let mut els = None; expect(TokenType::LeftParen, tokens, pos); let cond = expr(&tokens, pos); expect(TokenType::RightParen, tokens, pos); let then = stmt(&tokens, pos); if consume(TokenType::Else, tokens, pos) { els = Some(Box::new(stmt(&tokens, pos))); } Node::new(NodeType::If(Box::new(cond), Box::new(then), els)) } TokenType::For => { expect(TokenType::LeftParen, tokens, pos); let init: Box<Node> = if is_typename(&tokens[*pos]) { Box::new(declaration(tokens, pos)) } else if consume(TokenType::Semicolon, tokens, pos) { Box::new(Node::new(NodeType::Null)) } else { Box::new(expr_stmt(tokens, pos)) }; let cond; if !consume(TokenType::Semicolon, tokens, pos) { cond = Box::new(expr(&tokens, pos)); expect(TokenType::Semicolon, tokens, pos); } else { cond = Box::new(Node::new(NodeType::Null)) } let inc; if !consume(TokenType::RightParen, tokens, pos) { inc = Box::new(new_expr!(NodeType::ExprStmt, expr(&tokens, pos))); expect(TokenType::RightParen, tokens, pos); } else { inc = Box::new(Node::new(NodeType::Null)) } let body = Box::new(stmt(&tokens, pos)); Node::new(NodeType::For(init, cond, inc, body)) } TokenType::While => { expect(TokenType::LeftParen, tokens, pos); let init = Box::new(Node::new(NodeType::Null)); let inc = Box::new(Node::new(NodeType::Null)); let cond = Box::new(expr(&tokens, pos)); expect(TokenType::RightParen, tokens, pos); let body = Box::new(stmt(&tokens, pos)); Node::new(NodeType::For(init, cond, inc, body)) } TokenType::Do => { let body = Box::new(stmt(tokens, pos)); expect(TokenType::While, tokens, pos); expect(TokenType::LeftParen, tokens, pos); let cond = Box::new(expr(tokens, pos)); expect(TokenType::RightParen, tokens, pos); expect(TokenType::Semicolon, tokens, pos); Node::new(NodeType::DoWhile(body, cond)) } TokenType::Break => Node::new(NodeType::Break), TokenType::Return => { let expr = expr(&tokens, pos); expect(TokenType::Semicolon, tokens, pos); Node::new(NodeType::Return(Box::new(expr))) } TokenType::LeftBrace => { let mut stmts = vec![]; while !consume(TokenType::RightBrace, tokens, pos) { stmts.push(stmt(&tokens, pos)); } Node::new(NodeType::CompStmt(stmts)) } TokenType::Semicolon => Node::new(NodeType::Null), _ => { *pos -= 1; if is_typename(&tokens[*pos]) { return declaration(tokens, pos); } return expr_stmt(tokens, pos); } } } fn compound_stmt(tokens: &Vec<Token>, pos: &mut usize) -> Node { let mut stmts = vec![]; let new_env = Env::new(Some(Box::new(ENV.lock().unwrap().clone()))); *ENV.lock().unwrap() = new_env; while !consume(TokenType::RightBrace, tokens, pos) { stmts.push(stmt(tokens, pos)); } let next = ENV.lock().unwrap().next.clone(); *ENV.lock().unwrap() = *next.unwrap(); Node::new(NodeType::CompStmt(stmts)) } fn toplevel(tokens: &Vec<Token>, pos: &mut usize) -> Option<Node> { let is_typedef = consume(TokenType::Typedef, &tokens, pos); let is_extern = consume(TokenType::Extern, &tokens, pos); let mut ty = ctype(tokens, pos); let t = &tokens[*pos]; let name: String; if let TokenType::Ident(ref name2) = t.ty { name = name2.clone(); } else { bad_token(t, "function or variable name expected"); } *pos += 1; // Function if consume(TokenType::LeftParen, tokens, pos) { let mut args = vec![]; if !consume(TokenType::RightParen, tokens, pos) { args.push(param_declaration(tokens, pos)); while consume(TokenType::Comma, tokens, pos) { args.push(param_declaration(tokens, pos)); } expect(TokenType::RightParen, tokens, pos); } if consume(TokenType::Semicolon, tokens, pos) { let mut node = Node::new(NodeType::Decl(name)); node.ty = Box::new(Type::new(Ctype::Func(Box::new(ty)), 0)); return Some(node); } let t = &tokens[*pos]; expect(TokenType::LeftBrace, tokens, pos); if is_typedef { bad_token(t, "typedef {} has function definition"); } let body = compound_stmt(tokens, pos); let mut node = Node::new(NodeType::Func(name, args, Box::new(body), 0)); node.ty = Box::new(Type::new(Ctype::Func(Box::new(ty)), 0)); return Some(node); } ty = read_array(Box::new(ty), tokens, pos); expect(TokenType::Semicolon, tokens, pos); if is_typedef { ENV.lock().unwrap().typedefs.insert( name.clone(), ty.clone(), ); return None; } // Global variable let mut node; if is_extern { node = Node::new(NodeType::Vardef( name, None, Scope::Global(String::new(), 0, true), )); } else { node = Node::new(NodeType::Vardef( name, None, Scope::Global(String::new(), ty.size, false), )); } node.ty = Box::new(ty); Some(node) } /* e.g. function -> param +---------+ int main() { ; +-+ int [] 2 int ary[2]; ; | +->stmt->declaration->read_array->primary ary[0]=1; ; | compound_stmt-+->stmt->... ary return ary[0]; ; | +->stmt->assign->postfix-+->primary } ; +-+ return [] +->primary 0 */ pub fn parse(tokens: &Vec<Token>) -> Vec<Node> { let mut pos = 0; let mut v = vec![]; while tokens.len() != pos { if let Some(node) = toplevel(tokens, &mut pos) { v.push(node); } } v }
// Copyright (C) 2017 1aim GmbH // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt; use std::ops::Deref; /// A phone number carrier. #[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Hash, Debug)] pub struct Carrier(pub(crate) String); impl<T: Into<String>> From<T> for Carrier { fn from(value: T) -> Carrier { Carrier(value.into()) } } impl Deref for Carrier { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for Carrier { fn as_ref(&self) -> &str { &self.0 } } impl fmt::Display for Carrier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } }
use nu_protocol::ast::Call; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::{ Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Value, }; #[derive(Clone)] pub struct ToUrl; impl Command for ToUrl { fn name(&self) -> &str { "to url" } fn signature(&self) -> Signature { Signature::build("to url").category(Category::Formats) } fn usage(&self) -> &str { "Convert table into url-encoded text" } fn examples(&self) -> Vec<Example> { vec![Example { description: "Outputs an URL string representing the contents of this table", example: r#"[[foo bar]; ["1" "2"]] | to url"#, result: Some(Value::test_string("foo=1&bar=2")), }] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<nu_protocol::PipelineData, ShellError> { let head = call.head; to_url(input, head) } } fn to_url(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> { let output: Result<String, ShellError> = input .into_iter() .map(move |value| match value { Value::Record { ref cols, ref vals, .. } => { let mut row_vec = vec![]; for (k, v) in cols.iter().zip(vals.iter()) { match v.as_string() { Ok(s) => { row_vec.push((k.clone(), s.to_string())); } _ => { return Err(ShellError::UnsupportedInput( "Expected table with string values".to_string(), head, )); } } } match serde_urlencoded::to_string(row_vec) { Ok(s) => Ok(s), _ => Err(ShellError::CantConvert( "URL".into(), value.get_type().to_string(), head, None, )), } } other => Err(ShellError::UnsupportedInput( "Expected a table from pipeline".to_string(), other.span().unwrap_or(head), )), }) .collect(); Ok(Value::string(output?, head).into_pipeline_data()) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ToUrl {}) } }
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> { (0..len).map(|_| self.input()).collect() } fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> { (0..row).map(|_| self.vec(col)).collect() } } struct Graph { n: usize, adj_list: Vec<Vec<usize>>, } impl Graph { fn new(n: usize) -> Self { let adj_list = vec![vec![]; n]; Graph { n: n, adj_list: adj_list } } fn add_edge(&mut self, u: usize, v: usize) { self.adj_list[u].push(v); } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let (n, q): (i64, i64) = (sc.input(), sc.input()); let mut graph = Graph::new(n as usize); for _ in 0..n - 1 { let (a, b): (i64, i64) = (sc.input(), sc.input()); graph.add_edge((a - 1) as usize, (b - 1) as usize); } let mut counter = vec![0; n as usize]; for _ in 0..q { let (p, x): (i64, i64) = (sc.input(), sc.input()); counter[(p - 1) as usize] += x; } let mut ans = vec![0; n as usize]; dfs(0, -1, counter[0], &mut ans, &graph, &counter); for i in ans { print!("{} ", i); } println!(); } fn dfs(cur: i64, par: i64, x: i64, ans: &mut Vec<i64>, g: &Graph, counter: &Vec<i64>) { ans[cur as usize] += x; for &next in g.adj_list[cur as usize].iter() { if next != (par as usize) { dfs(next as i64, cur, x + counter[next as usize], ans, g, counter); } } }
#[derive(Debug, PartialEq, Clone)] pub enum Token{ Illegal, EOF, // Literals UIdent(String), LIdent(String), Integer(String), // Symbols Backslash, Dot, LParen, RParen, Colon, Assign }
use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)] /// A cat clone written in rust /// /// Concatenate FILES(s) to standard output. /// /// With not FILE, or when FILE is -, read standard input. pub struct Opt { /// equivalent to -vET #[structopt(short = "A", long = "show-all")] pub show_all: bool, /// number nonempty output lines, overrides -n #[structopt(short = "b", long = "number-nonblank")] pub number_nonblank: bool, /// equivalent to -vE #[structopt(short = "e")] pub show_ends_and_nonprinting: bool, /// display $ at end of each line #[structopt(short = "E", long = "show-ends")] pub show_ends: bool, /// number all output lines #[structopt(short, long)] pub number: bool, /// suppress repeated empty output lines #[structopt(short, long = "squeeze-blank")] pub squeeze_blank: bool, /// display TAB characters as ^I #[structopt(short = "T", long = "show-tabs")] pub show_tabs: bool, /// (ignored) #[structopt(short = "u")] pub ignored: bool, /// use ^ and M- notation, except for LFD and TAB #[structopt(short = "v", long = "show-nonprinting")] pub show_nonprinting: bool, #[structopt(name = "FILE")] #[structopt(parse(from_os_str))] pub files: Vec<PathBuf>, } impl Opt { pub fn new_with_equivalent_options() -> Self { let mut opt = Opt::from_args(); opt.show_all_equivalent(); opt.show_ends_and_nonprinting_equivalent(); opt } pub fn should_use_fast_print(&self) -> bool { !(self.number || self.show_ends || self.show_tabs || self.show_nonprinting || self.show_ends_and_nonprinting || self.number_nonblank || self.show_all || self.squeeze_blank) } pub fn is_number_option(&self) -> bool { self.number || self.number_nonblank } fn show_all_equivalent(&mut self) { if self.show_all { self.show_nonprinting = true; self.show_ends = true; self.show_tabs = true; } } fn show_ends_and_nonprinting_equivalent(&mut self) { if self.show_ends_and_nonprinting { self.show_nonprinting = true; self.show_ends = true; } } }
// Copyright (C) 2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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 super::*; use crate as collator_selection; use sp_core::H256; use frame_support::{ parameter_types, ord_parameter_types, traits::{FindAuthor, GenesisBuild}, PalletId }; use sp_runtime::{ RuntimeAppPublic, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, testing::{Header, UintAuthorityId}, }; use frame_system::{EnsureSignedBy}; use frame_system as system; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aura: pallet_aura::{Pallet, Call, Storage, Config<T>}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>}, Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub const SS58Prefix: u8 = 42; } impl system::Config for Test { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type DbWeight = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData<u64>; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; type OnSetCode = (); } parameter_types! { pub const ExistentialDeposit: u64 = 5; } impl pallet_balances::Config for Test { type Balance = u64; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); type MaxLocks = (); } pub struct Author4; impl FindAuthor<u64> for Author4 { fn find_author<'a, I>(_digests: I) -> Option<u64> where I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>, { Some(4) } } impl pallet_authorship::Config for Test { type FindAuthor = Author4; type UncleGenerations = (); type FilterUncle = (); type EventHandler = CollatorSelection; } parameter_types! { pub const MinimumPeriod: u64 = 1; } impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = Aura; type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } impl pallet_aura::Config for Test { type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; } sp_runtime::impl_opaque_keys! { pub struct MockSessionKeys { // a key for aura authoring pub aura: UintAuthorityId, } } impl From<UintAuthorityId> for MockSessionKeys { fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { Self { aura } } } parameter_types! { pub static SessionHandlerCollators: Vec<u64> = vec![]; pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler<u64> for TestSessionHandler { const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) { SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: usize) {} } parameter_types! { pub const Offset: u64 = 0; pub const Period: u64 = 10; } impl pallet_session::Config for Test { type Event = Event; type ValidatorId = <Self as frame_system::Config>::AccountId; // we don't have stash and controller, thus we don't need the convert as well. type ValidatorIdOf = IdentityCollator; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>; type SessionManager = CollatorSelection; type SessionHandler = TestSessionHandler; type Keys = MockSessionKeys; type DisabledValidatorsThreshold = (); type WeightInfo = (); } ord_parameter_types! { pub const RootAccount: u64 = 777; } parameter_types! { pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxCandidates: u32 = 20; pub const MaxInvulnerables: u32 = 20; } impl Config for Test { type Event = Event; type Currency = Balances; type UpdateOrigin = EnsureSignedBy<RootAccount, u64>; type PotId = PotId; type MaxCandidates = MaxCandidates; type MaxInvulnerables = MaxInvulnerables; type KickThreshold = Period; type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { sp_tracing::try_init_simple(); let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); let invulnerables = vec![1, 2]; let keys = invulnerables.iter().map(|i| ( *i, *i, MockSessionKeys { aura: UintAuthorityId(*i) }, ) ).collect::<Vec<_>>(); let balances = pallet_balances::GenesisConfig::<Test> { balances: vec![ (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), ], }; let collator_selection = collator_selection::GenesisConfig::<Test> { desired_candidates: 2, candidacy_bond: 10, invulnerables, }; let session = pallet_session::GenesisConfig::<Test> { keys }; balances.assimilate_storage(&mut t).unwrap(); // collator selection must be initialized before session. collator_selection.assimilate_storage(&mut t).unwrap(); session.assimilate_storage(&mut t).unwrap(); t.into() } pub fn initialize_to_block(n: u64) { for i in System::block_number()+1..=n { System::set_block_number(i); <AllPallets as frame_support::traits::OnInitialize<u64>>::on_initialize(i); } }
use core::str::from_utf8_unchecked; use alloc::borrow::Cow; use alloc::string::String; use alloc::vec::Vec; #[cfg(feature = "std")] use std::io::{self, Write}; macro_rules! parse_script { ($e:expr, $step:ident, $b:block, $bq:block $(, $($addi:expr),+)?) => { match $step { 0 => { match $e { b'<' => $step = 1, $(b'\\' => $step = 10, $(| $addi)+ => $bq,)? _ => (), } } 1 => { match $e { b'/' => $step = 2, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 2 => { match $e { b's' | b'S' => $step = 3, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 3 => { match $e { b'c' | b'C' => $step = 4, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 4 => { match $e { b'r' | b'R' => $step = 5, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 5 => { match $e { b'i' | b'I' => $step = 6, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 6 => { match $e { b'p' | b'P' => $step = 7, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 7 => { match $e { b't' | b'T' => $step = 8, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 8 => { match $e { b'>' | 9..=13 | 28..=32 => { $step = 0; $b }, $(b'\\' => $step = 10, $(| $addi)+ => { $step = 0; $bq },)? _ => $step = 0, } } 10 => { match $e { b'<' => $step = 1, _ => $step = 0, } } _ => unreachable!(), } }; } macro_rules! parse_script_single_quoted_text { ($e:expr, $step:ident, $b:block, $bq:block) => { parse_script!($e, $step, $b, $bq, b'\''); }; } macro_rules! parse_script_double_quoted_text { ($e:expr, $step:ident, $b:block, $bq:block) => { parse_script!($e, $step, $b, $bq, b'"'); }; } macro_rules! parse_script_quoted_text { ($e:expr, $step:ident, $b:block, $bq:block) => { parse_script!($e, $step, $b, $bq, b'\'', b'"'); }; } encode_impl! { 7; /// The following substring is escaped: /// /// * `</script>` => `<\/script>` parse_script; /// Encode text used in the `<script>` element. encode_script; /// Write text used in the `<script>` element to a mutable `String` reference and return the encoded string slice. encode_script_to_string; /// Write text used in the `<script>` element to a mutable `Vec<u8>` reference and return the encoded data slice. encode_script_to_vec; /// Write text used in the `<script>` element to a writer. encode_script_to_writer; } encode_impl! { 7; /// The following substring and character are escaped: /// /// * `</script>` => `<\/script>` /// * `'` => `\'` parse_script_single_quoted_text; /// Encode text used in a single quoted text in the `<script>` element. encode_script_single_quoted_text; /// Write text used in a single quoted text in the `<script>` element to a mutable `String` reference and return the encoded string slice. encode_script_single_quoted_text_to_string; /// Write text used in a single quoted text in the `<script>` element to a mutable `Vec<u8>` reference and return the encoded data slice. encode_script_single_quoted_text_to_vec; /// Write text used in a single quoted text in the `<script>` element to a writer. encode_script_single_quoted_text_to_writer; } encode_impl! { 7; /// The following substring and character are escaped: /// /// * `</script>` => `<\/script>` /// * `"` => `\"` parse_script_double_quoted_text; /// Encode text used in a double quoted text in the `<script>` element. encode_script_double_quoted_text; /// Write text used in a double quoted text in the `<script>` element to a mutable `String` reference and return the encoded string slice. encode_script_double_quoted_text_to_string; /// Write text used in a double quoted text in the `<script>` element to a mutable `Vec<u8>` reference and return the encoded data slice. encode_script_double_quoted_text_to_vec; /// Write text used in a double quoted text in the `<script>` element to a writer. encode_script_double_quoted_text_to_writer; } encode_impl! { 7; /// The following substring and characters are escaped: /// /// * `</script>` => `<\/script>` /// * `"` => `\"` /// * `'` => `\'` parse_script_quoted_text; /// Encode text used in a quoted text in the `<script>` element. encode_script_quoted_text; /// Write text used in a quoted text in the `<script>` element to a mutable `String` reference and return the encoded string slice. encode_script_quoted_text_to_string; /// Write text used in a quoted text in the `<script>` element to a mutable `Vec<u8>` reference and return the encoded data slice. encode_script_quoted_text_to_vec; /// Write text used in a quoted text in the `<script>` element to a writer. encode_script_quoted_text_to_writer; }
// macro (generate struct or method for each number??) // plain normal way // enum (create custom enum type with fizz, buzz, and fizzbuzz variants, then write from/into, etc) // also pull out basic number -> String code into separate function to discuss on its own // lifetimes version where number is passed in as reference and &str is passed back // build.rs version // what is this? // "a tour of rust via fizz buzz" // "six(?) ways to fizz buzz with rust" // "learn rust via fizz buzz" extern crate core; mod func; mod flexible; mod display; mod intro; mod enumeration; mod iterator; fn main() { }
use abstract_integers::*; abstract_unsigned_secret_integer!(BigBounded, 256); abstract_secret_modular_integer!( Felem, BigBounded, BigBounded::pow2(255) - BigBounded::from_literal(19) ); #[test] fn arith() { let x1 = Felem::from_literal(24875808327634644); let x2 = Felem::from_literal(91987276365379830); let _x3 = x1 + x2; // TODO: natmods don't implement eq // assert_eq!(Felem::from_literal(116863084693014474u128), x3.into()) } abstract_secret_modular_integer!(SmallModular, BigBounded, BigBounded::from_literal(255)); #[test] fn wrapping() { let x1 = SmallModular::from_literal(254); let x2 = SmallModular::from_literal(3); let _x3 = x1 + x2; // TODO: natmods don't implement eq // assert_eq!(SmallModular::from_literal(2), x3.into()); let x4 = SmallModular::from_literal(5); let _x5 = _x3 - x4; // TODO: natmods don't implement eq // assert_eq!(SmallModular::from_literal(252), x5.into()); } abstract_nat_mod!( FieldElement, Scalar, 256, "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff" ); #[test] fn conversion() { let x = FieldElement::from_hex("6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"); let y = FieldElement::from_hex("4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); let _z = x * y; () }
use amethyst::{ core::timing::Time, ecs::prelude::{Read, System}, input::InputHandler, renderer::VirtualKeyCode, }; #[derive(Default)] pub struct DummySystem { pub counter: u64, } impl<'a,> System<'a,> for DummySystem { type SystemData = (Read<'a, Time,>, Read<'a, InputHandler<String, String,>,>,); fn run(&mut self, (time, input,): Self::SystemData,) { if self.counter > 100 { info!("Main update {}", time.absolute_real_time_seconds()); self.counter = 0; } self.counter = self.counter + 1; if input.key_is_down(VirtualKeyCode::Space,) { trace!("Space is down. Main update"); } if let Some(down,) = input.action_is_down("shoot",) { if down { trace!("Shooting."); } } } }
// return Ok(x) where x is the number of steps required to reach 1 // pub fn collatz(n: u64) -> Result<u64, &'static str> { if n <= 0 { return Err("Must be greater than 0") } let mut count = 0; let mut value = n; let is_even = |x: u64| x & 1 == 0; while value != 1 { match is_even(value) { true => { value = value / 2 } false => { value = (value * 3) + 1 } } count = count +1; } Ok(count) }
//! Tests auto-converted from "sass-spec/spec/non_conformant/sass/import" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/sass/import/unquoted.hrx" mod unquoted { #[allow(unused)] use super::rsass; }
use crate::common; use crate::matrix2::Matrix2; use crate::vector2::Vector2; use crate::vector3::Vector3; use std::cmp; use std::fmt; use std::fmt::{Display, Formatter}; use std::ops::{ Neg, Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, }; #[repr(C, packed)] #[derive(Copy, Clone, Debug)] pub struct Matrix3 { pub m: [f32; 9], } impl Matrix3 { /// Creates a matrix set to its identity /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::new(); /// assert_eq!(actual, Matrix3 { /// m: [ /// 1.0, 0.0, 0.0, /// 0.0, 1.0, 0.0, /// 0.0, 0.0, 1.0, /// ], /// }); /// ``` #[inline] pub fn new() -> Matrix3 { Matrix3 { m: [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ], } } /// Creates a matrix from the provided values /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let expected = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn make( m11: f32, m21: f32, m31: f32, m12: f32, m22: f32, m32: f32, m13: f32, m23: f32, m33: f32, ) -> Matrix3 { Matrix3 { m: [m11, m21, m31, m12, m22, m32, m13, m23, m33], } } /// Gets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m11(), 1.0); /// ``` #[inline] pub fn m11(&self) -> f32 { self.m[0] } /// Gets the value for the m21 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m21(), 2.0); /// ``` #[inline] pub fn m21(&self) -> f32 { self.m[1] } /// Gets the value for the m31 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m31(), 3.0); /// ``` #[inline] pub fn m31(&self) -> f32 { self.m[2] } /// Gets the value for the m12 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m12(), 4.0); /// ``` #[inline] pub fn m12(&self) -> f32 { self.m[3] } /// Gets the value for the m22 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m22(), 5.0); /// ``` #[inline] pub fn m22(&self) -> f32 { self.m[4] } /// Gets the value for the m32 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m32(), 6.0); /// ``` #[inline] pub fn m32(&self) -> f32 { self.m[5] } /// Gets the value for the m13 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m13(), 7.0); /// ``` #[inline] pub fn m13(&self) -> f32 { self.m[6] } /// Gets the value for the m23 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m23(), 8.0); /// ``` #[inline] pub fn m23(&self) -> f32 { self.m[7] } /// Gets the value for the m33 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual.m33(), 9.0); /// ``` #[inline] pub fn m33(&self) -> f32 { self.m[8] } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m11(1.0); /// let expected = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m11(&mut self, v: f32) { self.m[0] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m21(1.0); /// let expected = [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m21(&mut self, v: f32) { self.m[1] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m31(1.0); /// let expected = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m31(&mut self, v: f32) { self.m[2] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m12(1.0); /// let expected = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m12(&mut self, v: f32) { self.m[3] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m22(1.0); /// let expected = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m22(&mut self, v: f32) { self.m[4] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m32(1.0); /// let expected = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m32(&mut self, v: f32) { self.m[5] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m13(1.0); /// let expected = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m13(&mut self, v: f32) { self.m[6] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m23(1.0); /// let expected = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m23(&mut self, v: f32) { self.m[7] = v; } /// Sets the value for the m11 element /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /// actual.set_m33(1.0); /// let expected = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]; /// assert_eq!(actual.m, expected); /// ``` #[inline] pub fn set_m33(&mut self, v: f32) { self.m[8] = v; } /// Sets the internal contents of the matrix /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::new(); /// actual.set(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let expected = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn set( &mut self, m11: f32, m21: f32, m31: f32, m12: f32, m22: f32, m32: f32, m13: f32, m23: f32, m33: f32, ) { self.set_m11(m11); self.set_m21(m21); self.set_m31(m31); self.set_m12(m12); self.set_m22(m22); self.set_m32(m32); self.set_m13(m13); self.set_m23(m23); self.set_m33(m33); } /// Transposes the matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual.transpose(); /// let expected = Matrix3::make(1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn transpose(&mut self) { let mut m = self.m; let temp = m[1]; m[1] = m[3]; m[3] = temp; let temp = m[5]; m[5] = m[7]; m[7] = temp; let temp = m[2]; m[2] = m[6]; m[6] = temp; self.m = m; } /// Find the matrix's determinant /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0).determinant(); /// assert_eq!(actual, 0.0); /// ``` #[inline] pub fn determinant(&self) -> f32 { self.m11() * (self.m22() * self.m33() - self.m23() * self.m32()) - (self.m12() * (self.m21() * self.m33() - self.m23() * self.m31())) + (self.m13() * (self.m21() * self.m32() - self.m22() * self.m31())) } /// Inverses the matrix /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 0.0, 5.0, 2.0, 1.0, 6.0, 3.0, 4.0, 0.0); /// actual.inverse(); /// let expected = Matrix3::make(-24.0, 20.0, -5.0, 18.0, -15.0, 4.0, 5.0, -4.0, 1.0); /// assert_eq!(actual, expected); /// ``` #[inline] pub fn inverse(&mut self) -> bool { let det = self.determinant(); if det == 0.0 { return false; } let inv_det = 1.0 / det; let m11 = Matrix2::make(self.m22(), self.m23(), self.m32(), self.m33()).determinant() * inv_det; let m21 = Matrix2::make(self.m23(), self.m21(), self.m33(), self.m31()).determinant() * inv_det; let m31 = Matrix2::make(self.m21(), self.m22(), self.m31(), self.m32()).determinant() * inv_det; let m12 = Matrix2::make(self.m13(), self.m12(), self.m33(), self.m32()).determinant() * inv_det; let m22 = Matrix2::make(self.m11(), self.m13(), self.m31(), self.m33()).determinant() * inv_det; let m32 = Matrix2::make(self.m12(), self.m11(), self.m32(), self.m31()).determinant() * inv_det; let m13 = Matrix2::make(self.m12(), self.m13(), self.m22(), self.m23()).determinant() * inv_det; let m23 = Matrix2::make(self.m13(), self.m11(), self.m23(), self.m21()).determinant() * inv_det; let m33 = Matrix2::make(self.m11(), self.m12(), self.m21(), self.m22()).determinant() * inv_det; self.set_m11(m11); self.set_m21(m21); self.set_m31(m31); self.set_m12(m12); self.set_m22(m22); self.set_m32(m32); self.set_m13(m13); self.set_m23(m23); self.set_m33(m33); true } /// Determine whether or not all elements of the matrix are valid /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// assert!(actual.is_valid()); /// ``` #[inline] pub fn is_valid(&self) -> bool { for i in 0..9 { if !common::is_valid(self.m[i]) { return false; } } true } } impl Neg for Matrix3 { type Output = Matrix3; /// Negates the matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = -Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let expected = Matrix3::make(-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn neg(self) -> Matrix3 { let mut m = [0.0; 9]; unsafe { for (i, elem) in self.m.iter().enumerate() { m[i] = -*elem; } } Matrix3 { m } } } impl Add<f32> for Matrix3 { type Output = Matrix3; /// Find the resulting matrix by adding a scalar to a matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) + 1.0; /// let expected = Matrix3::make(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add(self, _rhs: f32) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem + _rhs; } } mat } } impl Add<Matrix3> for Matrix3 { type Output = Matrix3; /// Add two matrices /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let a = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let b = Matrix3::make(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0); /// let actual = a + b; /// let expected = Matrix3::make(10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add(self, _rhs: Matrix3) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem + _rhs.m[i]; } } mat } } impl AddAssign<f32> for Matrix3 { /// Increment a matrix by a scalar /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual += 10.0; /// let expected = Matrix3::make(11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add_assign(&mut self, _rhs: f32) { unsafe { for elem in self.m.iter_mut() { *elem += _rhs; } } } } impl AddAssign<Matrix3> for Matrix3 { /// Increment a matrix by another matrix /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual += Matrix3::make(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0); /// let expected = Matrix3::make(10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn add_assign(&mut self, _rhs: Matrix3) { unsafe { for (i, elem) in self.m.iter_mut().enumerate() { *elem += _rhs.m[i]; } } } } impl Sub<f32> for Matrix3 { type Output = Matrix3; /// Find the resulting matrix by subtracting a scalar from a matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) - 10.0; /// let expected = Matrix3::make(-9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub(self, _rhs: f32) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem - _rhs; } } mat } } impl Sub<Matrix3> for Matrix3 { type Output = Matrix3; /// Subtract two matrices /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let a = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let b = Matrix3::make(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0); /// let actual = a - b; /// let expected = Matrix3::make(-8.0, -6.0, -4.0, -2.0, 0.0, 2.0, 4.0, 6.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub(self, _rhs: Matrix3) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem - _rhs.m[i]; } } mat } } impl SubAssign<f32> for Matrix3 { /// Decrement a matrix by a scalar /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual -= 1.0; /// let expected = Matrix3::make(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn sub_assign(&mut self, _rhs: f32) { unsafe { for elem in self.m.iter_mut() { *elem -= _rhs; } } } } impl SubAssign<Matrix3> for Matrix3 { /// Decrement a matrix by another matrix /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0); /// actual -= Matrix3::make(1.0, 3.0, 4.0, 5.0, 5.0, 7.0, 8.0, 9.0, 9.0); /// assert_eq!(actual, Matrix3::new()); /// ``` #[inline] fn sub_assign(&mut self, _rhs: Matrix3) { unsafe { for (i, elem) in self.m.iter_mut().enumerate() { *elem -= _rhs.m[i]; } } } } impl Mul<f32> for Matrix3 { type Output = Matrix3; /// Find the resulting matrix by multiplying a scalar to a matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) * 2.0; /// let expected = Matrix3::make(2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul(self, _rhs: f32) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem * _rhs; } } mat } } impl Mul<Matrix3> for Matrix3 { type Output = Matrix3; /// Multiply two matrices /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let a = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let b = Matrix3::make(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0); /// let actual = a * b; /// let expected = Matrix3::make(90.0, 114.0, 138.0, 54.0, 69.0, 84.0, 18.0, 24.0, 30.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul(self, _rhs: Matrix3) -> Matrix3 { let m11 = self.m11() * _rhs.m11() + self.m12() * _rhs.m21() + self.m13() * _rhs.m31(); let m21 = self.m21() * _rhs.m11() + self.m22() * _rhs.m21() + self.m23() * _rhs.m31(); let m31 = self.m31() * _rhs.m11() + self.m32() * _rhs.m21() + self.m33() * _rhs.m31(); let m12 = self.m11() * _rhs.m12() + self.m12() * _rhs.m22() + self.m13() * _rhs.m32(); let m22 = self.m21() * _rhs.m12() + self.m22() * _rhs.m22() + self.m23() * _rhs.m32(); let m32 = self.m31() * _rhs.m12() + self.m32() * _rhs.m22() + self.m33() * _rhs.m32(); let m13 = self.m11() * _rhs.m13() + self.m12() * _rhs.m23() + self.m13() * _rhs.m33(); let m23 = self.m21() * _rhs.m13() + self.m22() * _rhs.m23() + self.m23() * _rhs.m33(); let m33 = self.m31() * _rhs.m13() + self.m32() * _rhs.m23() + self.m33() * _rhs.m33(); Matrix3::make(m11, m21, m31, m12, m22, m32, m13, m23, m33) } } impl MulAssign<f32> for Matrix3 { /// Multiply a matrix by a scalar /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual *= 2.0; /// let expected = Matrix3::make(2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul_assign(&mut self, _rhs: f32) { unsafe { for elem in self.m.iter_mut() { *elem *= _rhs; } } } } impl MulAssign<Matrix3> for Matrix3 { /// Multiply a matrix by another matrix /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual *= Matrix3::make(9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0); /// let expected = Matrix3::make(90.0, 114.0, 138.0, 54.0, 69.0, 84.0, 18.0, 24.0, 30.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn mul_assign(&mut self, _rhs: Matrix3) { let res = *self * _rhs; self.m = res.m; } } impl Div<f32> for Matrix3 { type Output = Matrix3; /// Find the resulting matrix by dividing a scalar to a matrix's elements /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0) / 2.0; /// let expected = Matrix3::make(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5); /// assert_eq!(actual, expected); /// ``` #[inline] fn div(self, _rhs: f32) -> Matrix3 { let mut mat = Matrix3::new(); unsafe { for (i, elem) in self.m.iter().enumerate() { mat.m[i] = *elem / _rhs; } } mat } } impl DivAssign<f32> for Matrix3 { /// Divide a matrix by a scalar /// /// # Examples /// ``` /// use vex::Matrix3; /// /// let mut actual = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// actual /= 2.0; /// let expected = Matrix3::make(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5); /// assert_eq!(actual, expected); /// ``` #[inline] fn div_assign(&mut self, _rhs: f32) { unsafe { for elem in self.m.iter_mut() { *elem /= _rhs; } } } } impl cmp::PartialEq for Matrix3 { /// Determines if two matrices' elements are equivalent /// /// # Examples /// ``` /// use vex::Matrix3; /// /// assert!(Matrix3::new() == Matrix3::new()); /// ``` #[inline] fn eq(&self, _rhs: &Matrix3) -> bool { unsafe { for (i, elem) in self.m.iter().enumerate() { if *elem != _rhs.m[i] { return false; } } } true } } impl Display for Matrix3 { #[inline] fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!( f, "[\n {}, {}, {}\n {}, {}, {}\n {}, {}, {}\n]", self.m11(), self.m12(), self.m13(), self.m21(), self.m22(), self.m23(), self.m31(), self.m32(), self.m33(), ) } } impl common::Matrix<Vector2> for Matrix3 { /// Find the resulting vector given a vector and matrix /// /// # Examples /// ``` /// use vex::Matrix; /// use vex::Matrix3; /// use vex::Vector2; /// /// let m = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let v = Vector2::make(1.0, 2.0); /// let actual = m.transform_point(&v); /// let expected = Vector2::make(16.0, 20.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn transform_point(&self, point: &Vector2) -> Vector2 { Vector2::make( self.m11() * point.x + self.m12() * point.y + self.m13(), self.m21() * point.x + self.m22() * point.y + self.m23(), ) } } impl common::Matrix<Vector3> for Matrix3 { /// Find the resulting vector given a vector and matrix /// /// # Examples /// ``` /// use vex::Matrix; /// use vex::Matrix3; /// use vex::Vector3; /// /// let m = Matrix3::make(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); /// let v = Vector3::make(1.0, 2.0, 3.0); /// let actual = m.transform_point(&v); /// let expected = Vector3::make(30.0, 36.0, 42.0); /// assert_eq!(actual, expected); /// ``` #[inline] fn transform_point(&self, point: &Vector3) -> Vector3 { Vector3::make( self.m11() * point.x + self.m12() * point.y + self.m13() * point.z, self.m21() * point.x + self.m22() * point.y + self.m23() * point.z, self.m31() * point.x + self.m32() * point.y + self.m33() * point.z, ) } }
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/fn-varargs" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/errors/fn-varargs/at-start.hrx" // Ignoring "at_start", error tests are not supported yet. // From "sass-spec/spec/non_conformant/errors/fn-varargs/multiple.hrx" // Ignoring "multiple", error tests are not supported yet. // From "sass-spec/spec/non_conformant/errors/fn-varargs/with-default.hrx" // Ignoring "with_default", error tests are not supported yet. // From "sass-spec/spec/non_conformant/errors/fn-varargs/with-optional.hrx" #[test] fn with_optional() { assert_eq!( rsass("@function test($param:\"default\",$rest...) {}").unwrap(), "" ); }
use std::fs::File; use std::io::{BufReader,BufRead}; fn diff_of_line(line: String) -> u32 { let v: Vec<u32> = line.split("\t").flat_map(|s| s.parse::<u32>()).collect(); let min = v.iter().min().unwrap(); let max = v.iter().max().unwrap(); max - min } fn quotient_of_two_evenly_divisible_numbers(line: String) -> u32 { let mut numbers: Vec<u32> = line.split("\t").flat_map(|s| s.parse::<u32>()).collect(); numbers.sort_by(|a, b| a.cmp(b)); let mut quotient = 0; while let Some(top) = numbers.pop() { for num in numbers.iter() { if top % num == 0 { quotient = top / num; break; } } } quotient } fn part_one() { let file = File::open("input.txt").unwrap(); let checksum: u32 = BufReader::new(&file).lines() .filter_map(Result::ok) .map(diff_of_line) .fold(0, |sum, d| sum + d); assert_eq!(46402, checksum); } fn part_two() { let file = File::open("input.txt").unwrap(); let checksum: u32 = BufReader::new(&file).lines() .filter_map(Result::ok) .map(quotient_of_two_evenly_divisible_numbers) .fold(0, |sum, d| sum + d); assert_eq!(265, checksum); } fn main() { part_one(); part_two(); }
pub mod parserInfo; pub mod parserHeader; pub mod parserMotionData; pub mod parserSessionData; pub mod parserLapData; pub mod parserEventData; pub mod parserParticipantsData; pub mod parserCarSetupData; pub mod parserCarTelemetryData; pub mod parserCarStatusData; use serde_derive::{Serialize}; #[derive(Debug, Serialize)] pub struct PacketResult { packetType: String, packetData: PacketData } pub struct Packet; impl Packet { fn parse(input: &[u8], packet_id: &u8) -> PacketResult { match packet_id { 0 => { let result = parserMotionData::parse_motion_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "MotionData".to_string(), packetData: PacketData::MotionData(packet) } } 1 => { let result = parserSessionData::parse_session_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "SessionData".to_string(), packetData: PacketData::SessionData(packet) } } 2 => { let result = parserLapData::parse_lap_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "LapData".to_string(), packetData: PacketData::LapData(packet) } } 3 => { let result = parserEventData::parse_event_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "EventData".to_string(), packetData: PacketData::EventData(packet) } } 4 => { let result = parserParticipantsData::parse_participants_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "ParticipantsData".to_string(), packetData: PacketData::ParticipantsData(packet) } } 5 => { let result = parserCarSetupData::parse_car_setup_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "CarSetupData".to_string(), packetData: PacketData::CarSetupData(packet) } } 6 => { let result = parserCarTelemetryData::parse_car_telemetry_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "CarTelemetryData".to_string(), packetData: PacketData::CarTelemetryData(packet) } } 7 => { let result = parserCarStatusData::parse_car_status_data_packet(&input); let (_, packet) = result.unwrap(); PacketResult { packetType: "CarStatusData".to_string(), packetData: PacketData::CarStatusData(packet) } } _ => panic!("Unknown packet type") } } } #[derive(Debug, Serialize)] pub enum PacketData { MotionData(parserMotionData::PacketMotionData), SessionData(parserSessionData::PacketSessionData), LapData(parserLapData::PacketLapData), EventData(parserEventData::PacketEventData), ParticipantsData(parserParticipantsData::PacketParticipantsData), CarSetupData(parserCarSetupData::PacketCarSetupData), CarTelemetryData(parserCarTelemetryData::PacketCarTelemetryData), CarStatusData(parserCarStatusData::PacketCarStatusData), } pub fn parse_packet(input: &[u8]) -> PacketResult { let (_, packet_info) = parserInfo::get_packet_info(&input).unwrap(); Packet::parse(&input, &packet_info.m_packetId) }