text
stringlengths
8
4.13M
use super::super::{ program::MaskProgram, webgl::{WebGlF32Vbo, WebGlI16Ibo, WebGlRenderingContext}, ModelMatrix, }; use super::{Camera, TableBlock}; use crate::{ block::{self, BlockId}, Color, }; use ndarray::Array2; use std::collections::HashMap; #[derive(PartialEq, PartialOrd)] pub struct Total<T>(pub T); impl<T: PartialEq> Eq for Total<T> {} impl<T: PartialOrd> Ord for Total<T> { fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() } } pub struct CharacterCollectionRenderer { vertexis_buffer_xy: WebGlF32Vbo, vertexis_buffer_xz: WebGlF32Vbo, texture_coord_buffer: WebGlF32Vbo, index_buffer: WebGlI16Ibo, } impl CharacterCollectionRenderer { pub fn new(gl: &WebGlRenderingContext) -> Self { let vertexis_buffer_xy = gl.create_vbo_with_f32array( &[ [0.5, 0.5, 1.0 / 128.0], [-0.5, 0.5, 1.0 / 128.0], [0.5, -0.5, 1.0 / 128.0], [-0.5, -0.5, 1.0 / 128.0], ] .concat(), ); let vertexis_buffer_xz = gl.create_vbo_with_f32array( &[ [0.5, 0.0, 1.0], [-0.5, 0.0, 1.0], [0.5, 0.0, 0.0], [-0.5, 0.0, 0.0], ] .concat(), ); let texture_coord_buffer = gl.create_vbo_with_f32array(&[[1.0, 1.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]].concat()); let index_buffer = gl.create_ibo_with_i16array(&[0, 1, 2, 3, 2, 1]); Self { vertexis_buffer_xy, vertexis_buffer_xz, texture_coord_buffer, index_buffer, } } pub fn render<'a>( &self, gl: &WebGlRenderingContext, program: &MaskProgram, camera: &Camera, vp_matrix: &Array2<f32>, block_field: &block::Field, characters: impl Iterator<Item = &'a BlockId>, id_map: &mut HashMap<u32, TableBlock>, floating_object: &Option<&BlockId>, client_id: &String, ) { gl.set_attribute(&self.vertexis_buffer_xy, &program.a_vertex_location, 3, 0); gl.set_attribute( &self.texture_coord_buffer, &program.a_texture_coord_location, 2, 0, ); gl.bind_buffer( web_sys::WebGlRenderingContext::ELEMENT_ARRAY_BUFFER, Some(&self.index_buffer), ); let mut mvp_matrixies: Vec<(Array2<f32>, [f32; 4])> = vec![]; for (character_id, character) in block_field.listed::<block::Character>(characters.collect()) { if floating_object .map(|object_id| character_id != *object_id) .unwrap_or(true) && character.is_showable(client_id) { let s = character.size(); let p = character.position(); let model_matrix: Array2<f32> = ModelMatrix::new() .with_scale(&[s[0], s[1], 1.0]) .with_movement(p) .into(); let mvp_matrix = vp_matrix.dot(&model_matrix); let mvp_matrix = mvp_matrix.t(); let color = Color::from(id_map.len() as u32 | 0xFF000000); gl.uniform_matrix4fv_with_f32_array( Some(&program.u_translate_location), false, &[ mvp_matrix.row(0).to_vec(), mvp_matrix.row(1).to_vec(), mvp_matrix.row(2).to_vec(), mvp_matrix.row(3).to_vec(), ] .concat() .into_iter() .map(|a| a as f32) .collect::<Vec<f32>>(), ); gl.uniform1i(Some(&program.u_flag_round_location), 1); gl.uniform4fv_with_f32_array( Some(&program.u_mask_color_location), &color.to_f32array(), ); gl.draw_elements_with_i32( web_sys::WebGlRenderingContext::TRIANGLES, 6, web_sys::WebGlRenderingContext::UNSIGNED_SHORT, 0, ); let model_matrix: Array2<f32> = ModelMatrix::new() .with_scale(s) .with_x_axis_rotation(camera.x_axis_rotation() - std::f32::consts::FRAC_PI_2) .with_z_axis_rotation(camera.z_axis_rotation()) .with_movement(p) .into(); let mvp_matrix = vp_matrix.dot(&model_matrix); mvp_matrixies.push((mvp_matrix, color.to_f32array())); id_map.insert(color.to_u32(), TableBlock::new(character_id.clone(), 0)); } } gl.set_attribute(&self.vertexis_buffer_xz, &program.a_vertex_location, 3, 0); for (mvp_matrix, color) in mvp_matrixies { let mvp_matrix = mvp_matrix.t(); gl.uniform_matrix4fv_with_f32_array( Some(&program.u_translate_location), false, &[ mvp_matrix.row(0).to_vec(), mvp_matrix.row(1).to_vec(), mvp_matrix.row(2).to_vec(), mvp_matrix.row(3).to_vec(), ] .concat() .into_iter() .map(|a| a as f32) .collect::<Vec<f32>>(), ); gl.uniform1i(Some(&program.u_flag_round_location), 0); gl.uniform4fv_with_f32_array(Some(&program.u_mask_color_location), &color); gl.draw_elements_with_i32( web_sys::WebGlRenderingContext::TRIANGLES, 6, web_sys::WebGlRenderingContext::UNSIGNED_SHORT, 0, ); } } }
use lambda_runtime::{error::HandlerError, lambda, Context}; use serde_derive::Deserialize; use serde_json::{json, Value}; #[derive(Deserialize)] struct AuthorizationEvent { #[serde(rename = "methodArn")] method_arn: String, } fn main() { lambda!(handler) } fn handler(event: AuthorizationEvent, _: Context) -> Result<Value, HandlerError> { Ok(json!({ "principalId": "anonymous", // TODO "policyDocument": { "Version": "2012-10-17", "Statement": { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource": event.method_arn } }, "context": {} })) }
use hey_listen::{ sync::{ParallelDispatcherRequest, ParallelDispatcher, ParallelListener}, RwLock, }; use std::sync::Arc; #[derive(Clone, Eq, Hash, PartialEq)] enum Event { VariantA, VariantB, } #[test] fn dispatch_parallel_to_dyn_traits() { #[derive(Default)] struct CountingEventListener { dispatch_counter: usize, } impl ParallelListener<Event> for CountingEventListener { fn on_event(&mut self, _event: &Event) -> Option<ParallelDispatcherRequest> { self.dispatch_counter += 1; None } } let mut dispatcher = ParallelDispatcher::<Event>::default(); let listener_a = Arc::new(RwLock::new(CountingEventListener::default())); let listener_b = Arc::new(RwLock::new(CountingEventListener::default())); dispatcher.add_listener(Event::VariantA, &listener_a); dispatcher.add_listener(Event::VariantB, &listener_b); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 0); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 1); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 2); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 3); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 1); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 3); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 2); } #[test] fn dispatch_parallel_to_functions() { let mut dispatcher = ParallelDispatcher::<Event>::default(); #[derive(Default)] struct DispatchCounter { counter: usize, }; let counter_a = Arc::new(RwLock::new(DispatchCounter::default())); let counter_b = Arc::new(RwLock::new(DispatchCounter::default())); let weak_counter_ref = Arc::downgrade(&Arc::clone(&counter_a)); let closure_a = Box::new(move |_event: &Event| { let listener = &weak_counter_ref.upgrade().unwrap(); listener.try_write().unwrap().counter += 1; None }); let weak_counter_ref = Arc::downgrade(&Arc::clone(&counter_b)); let closure_b = Box::new(move |_event: &Event| { let listener = &weak_counter_ref.upgrade().unwrap(); listener.try_write().unwrap().counter += 1; None }); dispatcher.add_fn(Event::VariantA, closure_a); dispatcher.add_fn(Event::VariantB, closure_b); assert_eq!(counter_a.try_write().unwrap().counter, 0); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(counter_a.try_write().unwrap().counter, 1); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(counter_a.try_write().unwrap().counter, 2); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(counter_a.try_write().unwrap().counter, 3); assert_eq!(counter_b.try_write().unwrap().counter, 1); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(counter_a.try_write().unwrap().counter, 3); assert_eq!(counter_b.try_write().unwrap().counter, 2); } #[test] fn stop_listening_parallel_for_dyn_traits() { #[derive(Default)] struct CountingEventListener { dispatch_counter: usize, } impl ParallelListener<Event> for CountingEventListener { fn on_event(&mut self, _event: &Event) -> Option<ParallelDispatcherRequest> { self.dispatch_counter += 1; Some(ParallelDispatcherRequest::StopListening) } } let mut dispatcher = ParallelDispatcher::<Event>::default(); let listener_a = Arc::new(RwLock::new(CountingEventListener::default())); let listener_b = Arc::new(RwLock::new(CountingEventListener::default())); dispatcher.add_listener(Event::VariantA, &listener_a); dispatcher.add_listener(Event::VariantB, &listener_b); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 0); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 1); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 1); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 0); dispatcher.dispatch_event(&Event::VariantA); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 1); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 1); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(listener_a.try_write().unwrap().dispatch_counter, 1); assert_eq!(listener_b.try_write().unwrap().dispatch_counter, 1); } #[test] fn stop_listening_parallel_for_fns() { let mut dispatcher = ParallelDispatcher::<Event>::default(); #[derive(Default)] struct DispatchCounter { counter: usize, }; let counter_a = Arc::new(RwLock::new(DispatchCounter::default())); let counter_b = Arc::new(RwLock::new(DispatchCounter::default())); let weak_counter_ref = Arc::downgrade(&Arc::clone(&counter_a)); let closure_a = Box::new(move |_event: &Event| { let listener = &weak_counter_ref.upgrade().unwrap(); listener.try_write().unwrap().counter += 1; None }); let weak_counter_ref = Arc::downgrade(&Arc::clone(&counter_b)); let closure_b = Box::new(move |_event: &Event| { let listener = &weak_counter_ref.upgrade().unwrap(); listener.try_write().unwrap().counter += 1; None }); dispatcher.add_fn(Event::VariantA, closure_a); dispatcher.add_fn(Event::VariantB, closure_b); assert_eq!(counter_a.try_write().unwrap().counter, 0); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(counter_a.try_write().unwrap().counter, 1); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); assert_eq!(counter_a.try_write().unwrap().counter, 2); assert_eq!(counter_b.try_write().unwrap().counter, 0); dispatcher.dispatch_event(&Event::VariantA); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(counter_a.try_write().unwrap().counter, 3); assert_eq!(counter_b.try_write().unwrap().counter, 1); dispatcher.dispatch_event(&Event::VariantB); assert_eq!(counter_a.try_write().unwrap().counter, 3); assert_eq!(counter_b.try_write().unwrap().counter, 2); } #[test] fn is_send_and_sync() { fn assert_send<T: Send + Sync>(_: &T) {}; assert_send(&ParallelDispatcher::<Event>::default()); }
use std::io; extern crate fancy_regex; use fancy_regex::Regex as Regex; fn check(i: u32, re1: &Regex, re2: &Regex) -> bool{ let as_string = i.to_string(); let matches = re1.is_match(&as_string).unwrap(); let rc = matches && re2.is_match(&as_string).unwrap(); return rc; } fn main() -> io::Result<()> { let min = 264793; let max = 803935; let mut count = 0; let re1 : Regex = Regex::new(r"(\d)\1").unwrap(); let re2 : Regex = Regex::new(r"^1*2*3*4*5*6*7*8*9*$").unwrap(); for i in min..max{ if check(i, &re1, &re2){ println!("Matches: {}",i); count += 1; } } println!("Matches: {}", count); Ok(()) }
mod maps; mod strs; mod vect; fn main() { vect::vectors(); println!(""); strs::strings(); println!(""); maps::maps(); }
use prelude::*; use draw::prelude::*; use widgets::text::StaticTextStyle; pub struct ListItemSelected { pub widget: Option<Widget>, } #[derive(Debug, Copy, Clone)] pub struct ItemSelected; #[derive(Default)] pub struct ListHandler { selected: Option<Widget>, } impl EventHandler<ListItemSelected> for ListHandler { fn handle(&mut self, event: &ListItemSelected, _: EventArgs) { let selected = event.widget.clone(); if selected != self.selected { if let Some(ref mut old_selected) = self.selected { old_selected.remove_prop(Property::Selected); } } self.selected = selected; } } pub struct ListItemHandler { list_widget: Widget, } impl ListItemHandler { pub fn new(list_widget: Widget) -> Self { ListItemHandler { list_widget: list_widget } } } impl EventHandler<ClickEvent> for ListItemHandler { fn handle(&mut self, _: &ClickEvent, mut args: EventArgs) { if !args.widget.props().contains(&Property::Selected) { args.widget.add_prop(Property::Selected); let event = ListItemSelected { widget: Some(args.widget.clone()) }; self.list_widget.event(event); args.widget.event(ItemSelected); *args.handled = true; } } } component_style!{pub struct List<name="list", style=ListStyle> { layout_settings: LinearLayoutSettings = { let mut layout_settings = LinearLayoutSettings::new(Orientation::Vertical); layout_settings.item_align = ItemAlignment::Fill; layout_settings }, }} impl WidgetModifier for List { fn apply(&self, widget: &mut Widget) { widget .add_handler(ListHandler::default()) .add_handler(|_: &ClickEvent, args: EventArgs| { args.widget.event(ListItemSelected { widget: None }); }) .linear_layout(self.layout_settings); } } pub fn add_contents_to_list<C, I, F>(list: &mut Widget, contents: C, build: F) where C: Iterator<Item=I>, F: Fn(I, &mut Widget) -> Widget, { for item in contents { let mut widget = build(item, list); widget .set_name("list_item") .add_handler(ListItemHandler::new(list.clone())); list.add_child(widget); } } pub fn default_text_adapter(text: String, list: &mut Widget) -> Widget { let mut text_widget = Widget::new("list_item_text"); text_widget.set_draw_style(DrawStyle::from_class::<TextStyle>("list_item_text")); StaticTextStyle::from_text(&text).component().apply(&mut text_widget); let mut item_widget = Widget::new("list_item_rect"); item_widget.set_draw_style(DrawStyle::from_class::<RectStyle>("list_item_rect")) .enable_hover(); text_widget.layout().add(align_left(&item_widget)); item_widget.layout().add(match_width(list)); item_widget.add_child(text_widget); item_widget }
use std::fmt::Debug; use thiserror::Error; #[derive(Debug, Error)] pub enum MetadataError { #[error("empty response")] Empty, #[error("audio item is non-playable when it should be")] NonPlayable, #[error("audio item duration can not be: {0}")] InvalidDuration(i32), #[error("track is marked as explicit, which client setting forbids")] ExplicitContentFiltered, }
struct Person { name: &'static str, age: u8, } impl Person { fn print_details(&self) { println!("\nName: {}\nAge: {}\nCan speak: {}", self.name, self.age, self.can_speak()); } } trait VoiceBox { fn speak(&self); fn can_speak(&self) -> bool; } impl VoiceBox for Person { fn speak(&self) { println!("Hello my name is {}", self.name); } fn can_speak(&self) -> bool { return self.age > 4; } } fn main() { let adam = Person { name: "Adam", age: 19, }; adam.print_details(); adam.speak(); }
/* * 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. */ //! Routines for tracing and decoding instructions to a particular architecture use iced_x86::Decoder; use iced_x86::DecoderOptions; use iced_x86::Formatter; use iced_x86::IntelFormatter; use reverie::syscalls::MemoryAccess; use crate::regs::RegAccess; /// Decodes an instruction on top of the rip pub fn decode_instruction(task: &safeptrace::Stopped) -> Result<String, safeptrace::Error> { let mut code = [0u8; 16]; let regs = task.getregs()?; task.read_exact(regs.ip() as usize, &mut code)?; let mut decoder = Decoder::with_ip(64, &code, regs.ip(), DecoderOptions::NONE); let instruction = decoder.decode(); let mut formatter = IntelFormatter::new(); let mut output = String::new(); formatter.format(&instruction, &mut output); Ok(output) }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_config::constants::CORE_CODE_ADDRESS, identifier::Identifier, language_storage::{ModuleId, StructTag, TypeTag}, }; use once_cell::sync::Lazy; pub const STC_NAME: &str = "STC"; pub static STC_IDENTIFIER: Lazy<Identifier> = Lazy::new(|| Identifier::new(STC_NAME).unwrap()); pub static STC_MODULE: Lazy<ModuleId> = Lazy::new(|| ModuleId::new(CORE_CODE_ADDRESS, STC_IDENTIFIER.to_owned())); pub static STC_STRUCT_NAME: Lazy<Identifier> = Lazy::new(|| Identifier::new("STC").unwrap()); pub fn stc_type_tag() -> TypeTag { TypeTag::Struct(StructTag { address: CORE_CODE_ADDRESS, module: STC_IDENTIFIER.clone(), name: STC_STRUCT_NAME.clone(), type_params: vec![], }) }
use super::{shared::mask_32, shared::vector_256, *}; use crate::{ input::{error::InputError, Input, InputBlockIterator}, query::JsonString, result::InputRecorder, FallibleIterator, }; const SIZE: usize = 32; pub(crate) struct Avx2MemmemClassifier32<'i, 'b, 'r, I, R> where I: Input, R: InputRecorder<I::Block<'i, SIZE>> + 'r, { input: &'i I, iter: &'b mut I::BlockIterator<'i, 'r, SIZE, R>, } impl<'i, 'b, 'r, I, R> Avx2MemmemClassifier32<'i, 'b, 'r, I, R> where I: Input, R: InputRecorder<I::Block<'i, SIZE>>, 'i: 'r, { #[inline] #[allow(dead_code)] pub(crate) fn new(input: &'i I, iter: &'b mut I::BlockIterator<'i, 'r, SIZE, R>) -> Self { Self { input, iter } } // Here we want to detect the pattern `"c"` // For interblock communication we need to bit of information that requires extra work to get obtained. // one for the block cut being `"` and `c"` and one for `"c` and `"`. We only deal with one of them. #[target_feature(enable = "avx2")] unsafe fn find_letter( &mut self, label: &JsonString, mut offset: usize, ) -> Result<Option<(usize, I::Block<'i, SIZE>)>, InputError> { let classifier = vector_256::BlockClassifier256::new(label.bytes()[0], b'"'); let mut previous_block: u32 = 0; while let Some(block) = self.iter.next()? { let mut classified = classifier.classify_block(&block); classified.first &= classified.second << 1 | 1; // we AND `"` bitmask with `c` bitmask to filter c's position in the stream following a `"` // We should need the last bit of previous block. Instead of memoizing, we simply assume it is one. // It could gives only add more potential match. if let Some(res) = mask_32::find_in_mask( self.input, label, previous_block, classified.first, classified.second, offset, ) { return Ok(Some((res, block))); } offset += SIZE; previous_block = classified.first >> (SIZE - 1); } Ok(None) } #[target_feature(enable = "avx2")] #[inline] unsafe fn find_label_avx2( &mut self, label: &JsonString, mut offset: usize, ) -> Result<Option<(usize, I::Block<'i, SIZE>)>, InputError> { if label.bytes().len() == 1 { return self.find_letter(label, offset); } let classifier = vector_256::BlockClassifier256::new(label.bytes()[0], label.bytes()[1]); let mut previous_block: u32 = 0; while let Some(block) = self.iter.next()? { let classified = classifier.classify_block(&block); if let Some(res) = mask_32::find_in_mask( self.input, label, previous_block, classified.first, classified.second, offset, ) { return Ok(Some((res, block))); } offset += SIZE; previous_block = classified.first >> (SIZE - 1); } Ok(None) } } impl<'i, 'b, 'r, I, R> Memmem<'i, 'b, 'r, I, SIZE> for Avx2MemmemClassifier32<'i, 'b, 'r, I, R> where I: Input, R: InputRecorder<I::Block<'i, SIZE>>, 'i: 'r, { // Output the relative offsets fn find_label( &mut self, first_block: Option<I::Block<'i, SIZE>>, start_idx: usize, label: &JsonString, ) -> Result<Option<(usize, I::Block<'i, SIZE>)>, InputError> { if let Some(b) = first_block { if let Some(res) = shared::find_label_in_first_block(self.input, b, start_idx, label)? { return Ok(Some(res)); } } let next_block_offset = self.iter.get_offset(); // SAFETY: target feature invariant unsafe { self.find_label_avx2(label, next_block_offset) } } }
//! This module defines the `Proc`, which represents a compiled function in memory. //! The `Proc` struct contains enough informations for the `Builder` to inline calls to procedures, //! and to call them efficiently. use arch::Operand; use assembler::AssemblyStyle; use parser::Syntax; use typesystem::{Fun, Ty, TyParameters}; use std::fmt::Write; use std::hash::{Hash, Hasher}; use std::slice; /// A procedure compiled by an `Assembler` into machine code. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Proc<'cx> { /// Reference to the start of the procedure. pub ptr: &'cx (), /// Length of the procedure's body. pub size: u32, /// Parameters accepted by the proc. pub parameters: Vec<Operand>, /// Location of the return value. pub return_value: Operand } impl<'cx> Proc<'cx> { /// Returns a new compiled procedure, given a pointer to the /// function it points to, the length of its body, its parameters and /// return value. pub fn new(ptr: &'cx (), size: u32, parameters: Vec<Operand>, return_value: Operand) -> Self { Proc { ptr, size, parameters, return_value } } /// Returns a slice that represents the body of the compiled function. pub fn as_slice(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.ptr as *const () as *const u8, self.size as usize) } } /// Writes the content of the compiled function as a string. pub fn write_buffer(&self, w: &mut Write) { for b in self.as_slice() { write!(w, "\\x{:02X}", b).expect("Could not write byte to buffer.") } } } /// A group of procedures related to a same function. /// /// This type stores both the direct- and continuation-passing-style versions of the [`Proc`] /// of a single [`Fun`]. #[derive(Debug)] pub struct Procs<'cx> { pub(crate) fun: &'cx Fun<'cx>, pub(crate) gh: u64, cps_proc: Option<Proc<'cx>>, ds_proc: Option<Proc<'cx>> } impl<'cx> Eq for Procs<'cx> {} impl<'cx> PartialEq for Procs<'cx> { fn eq(&self, other: &Procs<'cx>) -> bool { self.fun == other.fun && self.gh == other.gh } } impl<'cx> Hash for Procs<'cx> { fn hash<H: Hasher>(&self, state: &mut H) { self.fun.hash(state) } } impl<'cx> Procs<'cx> { /// Returns a new procedures group associated with the specified function, /// and for the specified type parameters. #[allow(unnecessary_mut_passed)] pub fn new(fun: &'cx Fun<'cx>, args: &TyParameters<'static, 'cx>) -> Self { Procs { fun, gh: hash!(args), cps_proc: None, ds_proc: None } } /// Returns the Continuation-Passing Style version of the procedure. pub fn cps_proc(&self) -> Option<&Proc<'cx>> { self.cps_proc.as_ref() } /// Returns the Direct Style version of the procedure. pub fn ds_proc(&self) -> Option<&Proc<'cx>> { self.ds_proc.as_ref() } /// Returns the specified version of the procedure. pub fn get_proc(&self, style: AssemblyStyle) -> Option<&Proc<'cx>> { match style { AssemblyStyle::CPS => self.cps_proc.as_ref(), AssemblyStyle::DS => self.ds_proc.as_ref() } } /// Sets the Continuation-Passing Style version of the procedure. pub fn set_cps_proc(&mut self, procedure: Proc<'cx>) { self.cps_proc = Some(procedure) } /// Sets the Direct Style version of the procedure. pub fn set_ds_proc(&mut self, procedure: Proc<'cx>) { self.ds_proc = Some(procedure) } /// Sets the specified version of the procedure. pub fn set_proc(&mut self, procedure: Proc<'cx>, style: AssemblyStyle) { match style { AssemblyStyle::CPS => self.cps_proc = Some(procedure), AssemblyStyle::DS => self.ds_proc = Some(procedure) } } /// If the CPS procedure already exists, returns it. /// Else, creates it using the specified function, inserts it, /// and returns it. pub fn get_cps_proc_or_insert<F>(&mut self, insertion: F) -> &Proc<'cx> where F: FnOnce() -> Proc<'cx> { if let &Some(ref procd) = &dup!(self => Self).cps_proc { return procd } let procd = insertion(); self.cps_proc = Some(procd); self.cps_proc.as_ref().unwrap() } /// If the DS procedure already exists, returns it. /// Else, creates it using the specified function, inserts it, /// and returns it. pub fn get_ds_proc_or_insert<F>(&mut self, insertion: F) -> &Proc<'cx> where F: FnOnce() -> Proc<'cx> { if let &Some(ref procd) = &dup!(self => Self).ds_proc { return procd } let procd = insertion(); self.ds_proc = Some(procd); self.ds_proc.as_ref().unwrap() } /// Returns a boolean indicating whether the Continuation-Passing Style version of this /// procedure has been compiled. pub fn has_cps(&self) -> bool { self.cps_proc.is_some() } /// Returns a boolean indicating whether the Direct Style version of this procedure has been /// compiled. pub fn has_ds(&self) -> bool { self.ds_proc.is_some() } /// Returns the function to which this procedure corresponds. pub fn function(&self) -> &'cx Fun<'cx> { self.fun } /// Returns a `Syntax` that represents the current procedure. /// /// # Errors /// The procedure cannot be made into a syntax parser. pub fn as_syntax(&self, ty: &'cx Ty<'cx>) -> Option<Syntax<'cx>> { if let Some(ref procd) = self.ds_proc { Some(Syntax::new::<()>(ty, unsafe { *(procd.ptr as *const () as *const _) })) } else { None } } }
error_chain! { foreign_links { //IO(std::io::Error); PG(postgres::Error); } } pub type ResT<T> = Result<T>;
pub mod ast; pub mod parser; #[cfg(test)] mod tests;
pub mod bus; pub mod decoder; pub mod encoder; pub mod messages; pub mod types;
mod parser; use parser::*; fn main() -> Result<(), parser::ParsingError> { let packet = "POST /cgi-bin/process.cgi HTTP/1.1\r User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\r Host: www.tutorialspoint.com\r Content-Type: application/x-www-form-urlencoded\r Content-Length: length\r Accept-Language: en-us\r Accept-Encoding: gzip, deflate\r Connection: Keep-Alive\r \r licenseID=string&content=string&/paramsXML=string"; let parser = HttpRequestParser::<RequestLine<Method>>::start(packet); println!("{:#?}", parser); let parser = parser.parse()?; println!("{:#?}", parser); let parser = parser.parse()?; println!("{:#?}", parser); let parser = parser.parse()?; println!("{:#?}", parser); let parser = parser.parse()?; println!("{:#?}", parser); let request = parser.parse(); println!("{:#?}", request); Ok(()) }
use serenity::client::Context; use serenity::model::channel::GuildChannel; use serenity::model::guild::PartialMember; use serenity::model::id::{GuildId, RoleId, UserId}; use serenity::model::prelude::{Channel, User}; use std::collections::HashMap; use std::fmt::Display; use std::sync::Mutex; lazy_static! { static ref PERMISSION_CACHE: Mutex<HashMap<GuildId, HashMap<RoleId, PermissionLevel>>> = Mutex::new(HashMap::new()); } #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Display, FromPrimitive)] #[repr(i8)] pub enum PermissionLevel { Banned = -10, Bot = -5, Everyone = 0, Helper = 20, Moderator = 40, Admin = 60, ServerOwner = 80, BotCreator = 100, } async fn get_db_user_permission_level_for_role( ctx: &Context, guild: GuildId, role: &RoleId, ) -> PermissionLevel { { let mut guard = PERMISSION_CACHE.lock().unwrap(); match guard.get(&guild) { Some(g) => { if let Some(p) = g.get(&role) { return *p; }; } None => { guard.insert(guild, HashMap::new()); } }; } let permission = crate::database::role_permissions::get_role_permission(ctx, guild, role).await; let final_permission = match permission { None => PermissionLevel::Everyone, Some(v) => v, }; { let mut guard = PERMISSION_CACHE.lock().unwrap(); guard .get_mut(&guild) .unwrap() .insert(*role, final_permission); } final_permission } async fn get_guild_owner(guild_channel: &GuildChannel, ctx: &Context) -> UserId { match guild_channel.guild(ctx).await { None => { guild_channel .guild_id .to_partial_guild(ctx) .await .unwrap() .owner_id } Some(g) => g.owner_id, } } pub async fn get_user_permission_level( ctx: &Context, channel: Channel, user: &User, member: &PartialMember, ) -> PermissionLevel { if user.id == crate::global::owner_id() { return PermissionLevel::BotCreator; } if user.bot { return PermissionLevel::Bot; } return match channel { Channel::Guild(guild_channel) => { if get_guild_owner(&guild_channel, ctx).await == user.id { PermissionLevel::ServerOwner } else { let mut highest_permission = PermissionLevel::Banned; for role in &member.roles { let perm = get_db_user_permission_level_for_role(&ctx, guild_channel.guild_id, role) .await; if perm > highest_permission { highest_permission = perm; } } highest_permission } } _ => PermissionLevel::Everyone, }; }
//! Common transaction components. mod fees; mod intermediary; pub mod permissions; pub use currency::transactions::components::fees::{FeeStrategy, FeesCalculator, ThirdPartyFees}; pub use currency::transactions::components::intermediary::Intermediary; // pub use currency::transactions::components::permissions::{mask_for, has_permission, is_authorized}; // pub use currency::transactions::components::permissions::{ // TRANSFER_MASK, TRANSFER_WITH_FEES_PAYER_MASK, ADD_ASSETS_MASK, DELETE_ASSETS_MASK, TRADE_MASK, // TRADE_INTERMEDIARY_MASK, EXCHANGE_MASK, EXCHANGE_INTERMEDIARY_MASK, BID_MASK, ASK_MASK, ALL_ALLOWED_MASK // };
mod common; #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_mov() { let (cpu, _mem) = common::execute_arm("mov-imm", "mov r0, #5"); assert_eq!(cpu.registers.read(0), 5); // If the shift amount is specified in the instruction, the PC will be 8 bytes ahead. let (cpu, _mem) = common::execute_arm("mov-r15", "mov r0, r15"); assert_eq!(cpu.registers.read(0), 8); // If a register is used to specify the shift amount the PC will be 12 bytes ahead. let (cpu, _mem) = common::execute_arm("mov-r15-shift-reg", "mov r0, r15, lsl r3"); assert_eq!(cpu.registers.read(0), 12); // Check that flags and Rd are correctly set on mov with lsr #32. let (cpu, _mem) = common::execute_arm( "mov-lsr-32", " ldr r1, =0x80000001 movs r0, r1, lsr #32 ", ); assert!(cpu.registers.getf_c()); assert!(!cpu.registers.getf_n()); assert!(cpu.registers.getf_z()); assert_eq!(cpu.registers.read(0), 0); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_asr() { // ASR by register with a value of 0. let (cpu, _mem) = common::execute_arm( "mov-asr-reg-0", " mov r3, #3 movs r4, r3, lsr #1 @ set carry mov r2, #0 movs r3, r4, asr r2 ", ); assert!(cpu.registers.getf_c()); assert_eq!(cpu.registers.read(3), 1); // ASR by register with a value of 33 let (cpu, _mem) = common::execute_arm( "mov-asr-reg-33", " ldr r2, =0x80000000 mov r3, #33 movs r2, r2, asr r3 ", ); assert!(cpu.registers.getf_c()); assert_eq!(cpu.registers.read(2), 0xFFFFFFFF); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_mvn() { let (cpu, _mem) = common::execute_arm( "mvn", " mov r2, #label mvn r3, #0 eor r2, r2, r3 mvn r3, r15 nop label: ", ); assert_eq!(cpu.registers.read(3), cpu.registers.read(2)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_orr() { let (cpu, _mem) = common::execute_arm( "orr", " mov r2, #2 mov r3, #3 movs r4, r3, lsr #1 @ set carry orrs r3, r3, r2, rrx ", ); assert!(!cpu.registers.getf_c()); assert!(cpu.registers.getf_n()); assert!(!cpu.registers.getf_z()); assert_eq!(cpu.registers.read(3), 0x80000003); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_rsc() { let (cpu, _mem) = common::execute_arm( "rsc", " mov r2, #2 mov r3, #3 adds r9, r9, r9 @ clear carry rscs r3, r2, r3 ", ); assert!(cpu.registers.getf_c()); assert!(!cpu.registers.getf_n()); assert!(cpu.registers.getf_z()); assert_eq!(cpu.registers.read(2), 2); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_sbc() { let mut exec = common::Executor::new("sbc", arm::Isa::Arm); exec.push( " ldr r2,=0xFFFFFFFF adds r3, r2, r2 @ set carry sbcs r2, r2, r2 ", ); assert!(exec.cpu.registers.getf_c()); assert!(!exec.cpu.registers.getf_n()); assert!(exec.cpu.registers.getf_z()); exec.push( " adds r9, r9 @ clear carry sbcs r2, r2, #0 ", ); assert!(!exec.cpu.registers.getf_z()); assert!(!exec.cpu.registers.getf_c()); assert!(exec.cpu.registers.getf_n()); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_adc() { let mut exec = common::Executor::new("adc", arm::Isa::Arm); exec.push( " mov r2, #0x80000000 mov r3, #0xF adds r9, r9, r9 @ clear carry adcs r2, r2, r3 ", ); assert!(!exec.cpu.registers.getf_c()); assert!(exec.cpu.registers.getf_n()); assert!(!exec.cpu.registers.getf_v()); assert!(!exec.cpu.registers.getf_z()); exec.push( " adcs r2, r2, r2 ", ); assert!(exec.cpu.registers.getf_c()); assert!(!exec.cpu.registers.getf_n()); exec.push( " adc r3, r3, r3 ", ); assert_eq!(exec.cpu.registers.read(3), 0x1F); exec.push( " mov r0, #0xFFFFFFFF adds r0, r0, #1 @ set carry mov r0, #0 mov r2, #1 adc r0, r0, r2, lsr #1 ", ); assert_eq!(exec.cpu.registers.read(0), 1); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_add() { let mut exec = common::Executor::new("add", arm::Isa::Arm); exec.push( " ldr r2, =0xFFFFFFFE mov r3, #1 adds r2, r2, r3 ", ); assert!(!exec.cpu.registers.getf_c()); assert!(exec.cpu.registers.getf_n()); assert!(!exec.cpu.registers.getf_v()); assert!(!exec.cpu.registers.getf_z()); exec.push( " adds r2, r2, r3 ", ); assert!(exec.cpu.registers.getf_c()); assert!(!exec.cpu.registers.getf_n()); assert!(!exec.cpu.registers.getf_v()); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_and() { let mut exec = common::Executor::new("and", arm::Isa::Arm); exec.push( " mov r2, #2 mov r3, #5 ands r2, r2, r3, lsr #1 ", ); assert!(exec.cpu.registers.getf_c()); assert!(!exec.cpu.registers.getf_z()); assert_eq!(exec.cpu.registers.read(2), 2); exec.push( " mov r2, #0xC00 mov r3, r2 mov r4, #0x80000000 ands r2, r2, r4, asr #32 ", ); assert!(exec.cpu.registers.getf_c()); assert!(!exec.cpu.registers.getf_n()); assert!(!exec.cpu.registers.getf_z()); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_bic() { let (cpu, _mem) = common::execute_arm( "bic", " adds r9, r9, r9 @ clear carry ldr r2, =0xFFFFFFFF ldr r3, =0xC000000D bics r2, r2, r3, asr #1 ", ); assert!(cpu.registers.getf_c()); assert!(!cpu.registers.getf_n()); assert!(!cpu.registers.getf_z()); assert_eq!(cpu.registers.read(2), 0x1FFFFFF9); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_eor() { let (cpu, _mem) = common::execute_arm( "eor", " mov r2, #1 mov r3, #3 eors r2, r2, r3, lsl #31 eors r2, r2, r3, lsl #0 ", ); assert!(cpu.registers.getf_c()); assert!(cpu.registers.getf_n()); assert!(!cpu.registers.getf_z()); assert_eq!(cpu.registers.read(2), 0x80000002); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_cmn() { let (cpu, _mem) = common::execute_arm( "cmn", " adds r9, r9, r9 @ clear carry ldr r2, =0x7FFFFFFF ldr r3, =0x70000000 cmn r2, r3 ", ); assert!(!cpu.registers.getf_c()); assert!(cpu.registers.getf_n()); assert!(cpu.registers.getf_v()); assert!(!cpu.registers.getf_z()); assert_eq!(cpu.registers.read(2), 0x7FFFFFFF); }
use super::{common_invest_args, parse_common_invest_args}; use clap::{App, Arg, ArgMatches, SubCommand}; use investment::Investment; use prettytable::row::Row; pub const SUB_INVEST_TABLE: &str = "table"; const ARG_EVERY_PERIOD: &str = "every-period"; const ARG_TO: &str = "to"; /// Returns the loan info-at sub command pub fn invest_table_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name(SUB_INVEST_TABLE) .about("print the amotization table for a loan") .arg( Arg::with_name(ARG_EVERY_PERIOD) .takes_value(true) .required(true) .index(1), ).arg( Arg::with_name(ARG_TO) .takes_value(true) .required(true) .index(2), ).args(common_invest_args().as_slice()) } /// Execute the work and print results for the info-at sub command /// /// # Arguments /// * `matches` - The command matches to retrieve the paramters pub fn execute_invest_table<'a>(matches: &ArgMatches<'a>) { let invest = parse_common_invest_args(matches); let every = matches .value_of(ARG_EVERY_PERIOD) .unwrap() .parse::<u32>() .unwrap(); let to = matches.value_of(ARG_TO).unwrap().parse::<u32>().unwrap(); println!("*** For an investment of {} and regular additions of {} per period at a interest rate of {}% per year\n", invest.capital, invest.regular_addition, invest.yield_rate * 100_f32); let mut invest_table = table!([ "At (periods)", "At (~years)", "Total additions", "Total invest", "Capital", "interest earned", ]); invest_table.add_row(get_row(&invest, 0)); for at in (every..to).step_by(every as usize) { invest_table.add_row(get_row(&invest, at)); } invest_table.add_row(get_row(&invest, to)); invest_table.printstd(); } fn get_row(invest: &Investment, at: u32) -> Row { let years_round = format!("{:.1}", at as f32 / invest.periodicity as f32); let capital_at = invest.capital_at(at); let total_invest = invest.capital + invest.additions_total(at); row![ at, years_round, format!("{:.2}", invest.additions_total(at)), format!("{:.2}", total_invest), format!("{:.2}", capital_at), format!("{:.2}", capital_at - total_invest as f64), ] }
fn main() { let v = vec![1, 2, 3, 4]; let third: &i32 = &v[2]; let fourth: Option<&i32> = v.get(3); let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Float(10.11), SpreadsheetCell::Text(String::from("blue")), ]; } // <- vec & v go out of scope here #[derive(Debug)] enum SpreadsheetCell { Int(i32), Float(f64), Text(String), }
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. No part of rdma-core, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of rdma-core. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/rdma-core/master/COPYRIGHT. extern "C" { pub fn mxm_config_free_context_opts(opts: *mut mxm_context_opts_t); pub fn mxm_config_free_ep_opts(opts: *mut mxm_ep_opts_t); pub fn mxm_config_print(stream: *mut FILE, ctx_opts: *mut mxm_context_opts_t, ep_opts: *mut mxm_ep_opts_t, flags: c_uint); pub fn mxm_config_read_context_opts(optsp: *mut *mut mxm_context_opts_t) -> mxm_error_t; pub fn mxm_config_read_ep_opts(optsp: *mut *mut mxm_ep_opts_t) -> mxm_error_t; pub fn mxm_config_read_opts(ctx_optsp: *mut *mut mxm_context_opts_t, ep_optsp: *mut *mut mxm_ep_opts_t, prefix: *const c_char, config_file: *const c_char, flags: c_uint) -> mxm_error_t; }
use tantivy::{ Index, IndexWriter, schema::*, directory::MmapDirectory, }; use env_logger; use log::{info, debug}; use std::sync::Mutex; use std::path::Path; use rayon::prelude::*; use storage::tantivy::{index_anchors, create_schema}; use wikitools::loaders::build_or_load_page_indices; use wikitools::settings::Settings; use storage::page::{PageIterator, TantivyPageIterator}; use wikitools::utils::{open_seek_bzip}; fn main() -> Result<(), Box<std::error::Error>> { env_logger::init(); let settings = Settings::new("config.toml")?; info!("wikitools dump 0.0.0"); debug!("settings: {:#?}", settings); let indices = build_or_load_page_indices(&settings)?; let schema = create_schema(); if !settings.search_index.index_dir.exists() { info!("Creating search index dir: {}", settings.search_index.index_dir.to_str().unwrap()); std::fs::create_dir(&settings.search_index.index_dir)?; } let index = { info!("Loading search index dir: {}", settings.search_index.index_dir.to_str().unwrap()); let index_dir = &settings.search_index.index_dir; match MmapDirectory::open(index_dir) { Ok(mmap_dir) => { if Index::exists(&mmap_dir) { Index::open(mmap_dir).unwrap() } else { Index::create_in_dir(index_dir, schema.clone()).unwrap() } } _ => Index::create_in_dir(index_dir, schema.clone()).unwrap() } }; let index_buf_sz = 1024 * 1024 * 1024; let chunk_len = 10_000; let index_writer = index.writer(index_buf_sz).unwrap(); let index_writer = Mutex::new(index_writer); let chunk_count = indices.len() / chunk_len; info!("Processing {} document chunks in blocks of {}", indices.len(), chunk_len); info!("Using index buffer size: {}", index_buf_sz); for (index, chunk) in indices.keys().collect::<Vec<_>>().chunks(chunk_len).enumerate() { info!("Processing chunk {}/{}", index, chunk_count); index_anchors(chunk.to_vec(), &settings.data.dump, &index_writer, &schema)?; let mut writer = index_writer.lock().expect("Failed to unlock indexer"); info!("Committing pending documents..."); writer.commit().unwrap(); } Ok(()) }
mod geo; mod model; mod obj; mod render; use std::vec::{Vec}; extern crate image; fn main() { let imgx = 800; let imgy = 800; let mut imgbuf = image::RgbImage::new(imgx, imgy); let mut scene = render::Scene::new(Vec::<obj::Obj>::new(), &mut imgbuf); scene.add_object(obj::Obj::from_file("obj/diablo3_pose.obj").unwrap() .load_texture("obj/textures/diablo3_pose_diffuse.tga")); scene.light_direction(0., 0., -1.); scene.draw(); scene.save("test.png").expect("Failed to save image"); }
use iron::request::Request; use iron::response::Response; use iron::IronResult; use iron::status; use router::Router; use ijr::JsonResponse; use middleware::mysql::PoolProvider; use model::rush::Rush; use repository; pub fn create(request: &mut Request) -> IronResult<Response> { let mysql_pool = request.extensions.get::<PoolProvider>().unwrap().clone(); let repo = repository::rush::Rush::new(mysql_pool); let rush = Rush::new(); repo.create(&rush); info!("created {}.", rush); Ok(Response::with((status::Ok, JsonResponse::json(rush)))) } pub fn fetch(request: &mut Request) -> IronResult<Response> { let mysql_pool = request.extensions.get::<PoolProvider>().unwrap().clone(); let repo = repository::rush::Rush::new(mysql_pool); let uuid = request.extensions.get::<Router>().unwrap().find("uuid"); if uuid.is_none() { return Ok(Response::with((status::BadRequest))); } match repo.find(uuid.unwrap().to_string()) { Some(rush) => Ok(Response::with((status::Ok, JsonResponse::json(rush)))), None => Ok(Response::with((status::NotFound))), } }
/*! This crate creates a perfect hash function for an enum, providing a single method: `T::lookup(&str) -> Option<T>` This method will return either the exact match of the variant, or None `std::fmt::Display` is also implemented for convenient printing of the string representation of the variant # Examples: ## derive Derive a perfect hash on a enum, uses the variant names, as lowercase in the PHF: ``` use phf::PerfectHash; #[derive(PerfectHash, Debug, PartialEq)] enum Keyword { Fn, When, If, Then, Else, Where, Select, Return } assert_eq!(Keyword::lookup("when"), Some(Keyword::When)); assert_eq!(Keyword::lookup("asdf"), None); ``` ## mapping Use a macro to create an enum for things that can't be trivially converted via their name: ```ignore use phf::{PerfectHash, phf_mapping}; // This takes in an enum name to generate, then the variants and what they should map to: phf_mapping! { Sigil => Pipe = "<|", FDiv = "/.", IDIv = "//", }; assert_eq!(Sigil::lookup("<|"), Some(Sigil::Pipe)); ``` */ pub use derive::*; pub use internal::*;
use inkwell::types::FloatType; use super::*; impl<'ctx> Compiler<'ctx> { pub fn void_ptr_type(&self) -> BasicTypeEnum<'ctx> { self.llvm.i8_type().ptr_type(AddressSpace::Generic).into() } pub fn value_type(&self, vars: &mut Vars<'ctx>, ty: &Type) -> BasicTypeEnum<'ctx> { match ty { Type::Fn(func) => self.closure_type(vars, func).into(), Type::Struct(id) => self.struct_type(vars, *id).into(), Type::Enum(id) => self.enum_type(vars, *id).into(), Type::Tuple(tys) => self.tuple_type(vars, tys).into(), Type::Primitive(PrimitiveType::Bool) => self.bool_type().into(), Type::Primitive(PrimitiveType::Int) => self.int_type().into(), Type::Primitive(PrimitiveType::Char) => self.char_type().into(), Type::Primitive(PrimitiveType::String) => self.string_type(vars).into(), Type::Primitive(PrimitiveType::Float) => self.float_type().into(), Type::Primitive(PrimitiveType::Never) | Type::Infer(_) | Type::Unknown => { unreachable!("This type should not exist at codegen: {:?}", ty) } } } pub fn bool_type(&self) -> IntType<'ctx> { self.llvm.bool_type() } pub fn int_type(&self) -> IntType<'ctx> { self.llvm.i32_type() } pub fn char_type(&self) -> IntType<'ctx> { self.llvm.i32_type() } pub fn float_type(&self) -> FloatType<'ctx> { self.llvm.f32_type() } pub fn string_type(&self, vars: &mut Vars<'ctx>) -> StructType<'ctx> { match vars.string_type { Some(ty) => ty, None => { let ty = self.llvm.opaque_struct_type("String"); ty.set_body( &[ self.llvm.i32_type().into(), self.llvm.i8_type().ptr_type(AddressSpace::Generic).into(), ], false, ); vars.string_type = Some(ty); ty } } } // type of toplevel or builtin functions - ie no env ptr needed pub fn known_fn_type(&self, vars: &mut Vars<'ctx>, ty: &FnType) -> FunctionType<'ctx> { let FnType { params, ret } = ty; let params = params .iter() .map(|ty| self.value_type(vars, ty)) .collect::<Vec<_>>(); if ret.as_ref() == &Type::NEVER { self.llvm.void_type().fn_type(&params, false) } else { self.value_type(vars, ret).fn_type(&params, false) } } pub fn fn_type(&self, vars: &mut Vars<'ctx>, ty: &FnType) -> FunctionType<'ctx> { let FnType { params, ret } = ty; let params = &std::iter::once(self.void_ptr_type()) .chain(params.iter().map(|ty| self.value_type(vars, ty))) .collect::<Vec<_>>(); if ret.as_ref() == &Type::NEVER { self.llvm.void_type().fn_type(params, false) } else { self.value_type(vars, ret).fn_type(params, false) } } pub fn closure_type(&self, vars: &mut Vars<'ctx>, ty: &FnType) -> StructType<'ctx> { self.llvm.struct_type( &[ self.fn_type(vars, ty) .ptr_type(AddressSpace::Generic) .into(), self.void_ptr_type(), ], false, ) } pub fn tuple_type(&self, vars: &mut Vars<'ctx>, tys: &[Type]) -> StructType<'ctx> { self.llvm.struct_type( &tys.iter() .map(|ty| self.value_type(vars, ty)) .collect::<Vec<_>>(), false, ) } pub fn unit_type(&self) -> StructType<'ctx> { self.llvm.struct_type(&[], false) } pub fn aggregate_type(&self, vars: &mut Vars<'ctx>, types: &[StructField]) -> StructType<'ctx> { self.llvm .struct_type(&self.aggregate_types(vars, types), false) } fn aggregate_types( &self, vars: &mut Vars<'ctx>, types: &[StructField], ) -> Vec<BasicTypeEnum<'ctx>> { types .iter() .map(|field| { let ty = &self.types[field.ty]; if ty.is_stack() { self.value_type(vars, ty) } else { self.value_type(vars, ty) .ptr_type(AddressSpace::Generic) .into() } }) .collect::<Vec<_>>() } pub fn struct_type(&self, vars: &mut Vars<'ctx>, id: StructDefId) -> StructType<'ctx> { match vars.types.get(&Left(id)) { Some(ty) => *ty, None => { let struct_def = &self.hir[id]; let struct_name = &self.hir[struct_def.name]; let ty = self.llvm.opaque_struct_type(struct_name.as_str()); vars.types.insert(Left(id), ty); ty.set_body(&self.aggregate_types(vars, &struct_def.fields), false); ty } } } pub fn enum_type(&self, vars: &mut Vars<'ctx>, enum_id: EnumDefId) -> StructType<'ctx> { match vars.types.get(&Right(enum_id)) { Some(ty) => *ty, None => { let enum_def = &self.hir[enum_id]; let enum_name = &self.hir[enum_def.name]; let ty = self.llvm.opaque_struct_type(enum_name.as_str()); vars.types.insert(Right(enum_id), ty); let discriminant = self .enum_discriminant_type(enum_id) .map_or_else(|| self.unit_type().into(), Into::into); let target_triple = self.module.get_triple(); let target_str = target_triple.as_str().to_str().unwrap(); let layout = TargetData::create(target_str); let largest_payload = enum_def .variants .iter() .map(|variant| self.aggregate_type(vars, &variant.fields)) .max_by_key(|ty| layout.get_bit_size(&ty.as_any_type_enum())) .unwrap_or_else(|| self.unit_type()); ty.set_body(&[discriminant, largest_payload.into()], false); ty } } } }
// Copyright 2018-2021 Google LLC // // 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. //! Screensavers for XSecurelock using SFML or Bevy. Enable one of the features, either `simple` for //! SFML or `engine` for Bevy, and see the corresponding module for usage. #[cfg(any(feature = "engine", doc))] pub mod engine; #[cfg(any(feature = "simple", doc))] pub mod simple;
use std::ops::{Index, IndexMut}; use std::fmt::{self, Debug}; use std::iter; use smallvec::SmallVec; #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, Hash)] pub struct Vec3<T> { height: usize, depth: usize, width: usize, data: SmallVec<[T; 2048]>, // 20 characters * 8 x 8 board } impl<T> Vec3<T> { fn idx(&self, (x, y, z): (usize, usize, usize)) -> Option<usize> { if z >= self.depth || x >= self.width || y >= self.height { None } else { Some(self.height * self.width * z + self.width * y + x) } } pub fn fill(width: usize, height: usize, depth: usize, value: T) -> Vec3<T> where T: Clone { let data = iter::repeat(value).take(width * height * depth).collect(); Vec3 { width, height, depth, data, } } } impl<T> Index<(usize, usize, usize)> for Vec3<T> { type Output = T; fn index(&self, idx: (usize, usize, usize)) -> &T { &self.data[self.idx(idx).expect("index out of bounds")] } } impl<T> IndexMut<(usize, usize, usize)> for Vec3<T> { fn index_mut(&mut self, idx: (usize, usize, usize)) -> &mut T { let idx = self.idx(idx).expect("index out of bounds"); &mut self.data[idx] } } impl<T: Debug> Debug for Vec3<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Vec3:\t")?; for i in 0..self.width { write!(f, "{:?}:\t", i)?; for j in 0..self.height { for k in 0..self.depth { write!(f, "{:?}, ", self[(i,j,k)])?; } write!(f, "\n\t\t")?; } write!(f, "\n\t")?; } Ok(()) } } #[derive(Clone, Eq, Ord, PartialOrd, PartialEq, Hash)] pub struct Vec2<T> { height: usize, width: usize, data: SmallVec<[T; 64]>, // 8 x 8 board } impl<T> Vec2<T> { fn idx(&self, (x, y): (usize, usize)) -> Option<usize> { if x >= self.width || y >= self.height { None } else { Some(x + y * self.width) } } pub fn fill(width: usize, height: usize, value: T) -> Vec2<T> where T: Clone { let data = iter::repeat(value).take(width * height).collect(); Vec2 { width, height, data, } } } impl<T> Index<(usize, usize)> for Vec2<T> { type Output = T; fn index(&self, idx: (usize, usize)) -> &T { &self.data[self.idx(idx).expect("index out of bounds")] } } impl<T> IndexMut<(usize, usize)> for Vec2<T> { fn index_mut(&mut self, idx: (usize, usize)) -> &mut T { let idx = self.idx(idx).expect("index out of bounds"); &mut self.data[idx] } } impl<T: Debug> Debug for Vec2<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Vec3:\t")?; for i in 0..self.width { write!(f, "{:?}:\t", i)?; for j in 0..self.height { write!(f, "{:?}, ", self[(i,j)])?; } write!(f, "\n\t")?; } Ok(()) } } #[test] fn smoke() { let mut v = Vec3::fill(3, 4, 4, false); { v[(1, 2, 0)] = true; } println!("{:?}", v); assert!(v[(1, 2, 0)]); }
#[doc = "Reader of register CTRL"] pub type R = crate::R<u32, super::CTRL>; #[doc = "Writer for register CTRL"] pub type W = crate::W<u32, super::CTRL>; #[doc = "Register CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `COUNTER_ENABLED`"] pub type COUNTER_ENABLED_R = crate::R<u32, u32>; #[doc = "Write proxy for field `COUNTER_ENABLED`"] pub struct COUNTER_ENABLED_W<'a> { w: &'a mut W, } impl<'a> COUNTER_ENABLED_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Counter enables for counters 0 up to CNT_NR-1. '0': counter disabled. '1': counter enabled. Counter static configuration information (e.g. CTRL.MODE, all TR_CTRL0, TR_CTRL1, and TR_CTRL2 register fields) should only be modified when the counter is disabled. When a counter is disabled, command and status information associated to the counter is cleared by HW, this includes: - the associated counter triggers in the CMD register are set to '0'. - the counter's interrupt cause fields in counter's INTR register. - the counter's status fields in counter's STATUS register.. - the counter's trigger outputs ('tr_overflow', 'tr_underflow' and 'tr_compare_match'). - the counter's line outputs ('line_out' and 'line_compl_out'). In multi-core environments, use the CTRL_SET/CTRL_CLR registers to avoid race-conditions on read-modify-write attempts to this register."] #[inline(always)] pub fn counter_enabled(&self) -> COUNTER_ENABLED_R { COUNTER_ENABLED_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Counter enables for counters 0 up to CNT_NR-1. '0': counter disabled. '1': counter enabled. Counter static configuration information (e.g. CTRL.MODE, all TR_CTRL0, TR_CTRL1, and TR_CTRL2 register fields) should only be modified when the counter is disabled. When a counter is disabled, command and status information associated to the counter is cleared by HW, this includes: - the associated counter triggers in the CMD register are set to '0'. - the counter's interrupt cause fields in counter's INTR register. - the counter's status fields in counter's STATUS register.. - the counter's trigger outputs ('tr_overflow', 'tr_underflow' and 'tr_compare_match'). - the counter's line outputs ('line_out' and 'line_compl_out'). In multi-core environments, use the CTRL_SET/CTRL_CLR registers to avoid race-conditions on read-modify-write attempts to this register."] #[inline(always)] pub fn counter_enabled(&mut self) -> COUNTER_ENABLED_W { COUNTER_ENABLED_W { w: self } } }
pub mod process; pub mod fork; pub mod signal; pub mod pipe; pub mod redirect;
pub mod prototypes; mod util;
use std::fmt::Display; use super::{AddressingMode, Status, CPU}; #[derive(Clone, Copy)] pub struct Opcode<'a> { pub code: u8, pub mnemonic: &'a str, pub length: u8, pub cycles: u8, pub mode: AddressingMode, } impl<'a> Opcode<'a> { fn new(code: u8, mnemonic: &'a str, length: u8, cycles: u8, mode: AddressingMode) -> Self { Opcode { code, mnemonic, length, cycles, mode, } } fn basic() -> Self { Opcode { code: 0x02, mnemonic: "NUL", length: 0, cycles: 0, mode: AddressingMode::Immediate, } } } impl<'a> Display for Opcode<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.mnemonic) } } impl<'a> CPU<'a> { pub fn interpret(&mut self, opcode: &Opcode) -> bool { match opcode.code { 0x00 => { self.increment_program_counter(opcode.length); return false; } 0x69 | 0x65 | 0x75 | 0x6D | 0x7D | 0x79 | 0x61 | 0x71 => self.adc(opcode), 0x29 | 0x25 | 0x35 | 0x2D | 0x3D | 0x39 | 0x21 | 0x31 => self.and(opcode), 0x0A | 0x06 | 0x16 | 0x0E | 0x1E => self.asl(opcode), 0x90 => self.bcc(), 0xB0 => self.bcs(), 0xF0 => self.beq(), 0x24 | 0x2C => self.bit(opcode), 0x30 => self.bmi(), 0xD0 => self.bne(), 0x10 => self.bpl(), 0x50 => self.bvc(), 0x70 => self.bvs(), 0xC9 | 0xC5 | 0xD5 | 0xCD | 0xDD | 0xD9 | 0xC1 | 0xD1 => self.cmp(opcode), 0xE0 | 0xE4 | 0xEC => self.cpx(opcode), 0xC0 | 0xC4 | 0xCC => self.cpy(opcode), 0x18 => self.clc(), 0xD8 => self.cld(), 0x58 => self.cli(), 0xB8 => self.clv(), 0xC6 | 0xD6 | 0xCE | 0xDE => self.dec(opcode), 0xCA => self.dex(), 0x88 => self.dey(), 0x49 | 0x45 | 0x55 | 0x4D | 0x5D | 0x59 | 0x41 | 0x51 => self.eor(opcode), 0xE6 | 0xF6 | 0xEE | 0xFE => self.inc(opcode), 0xE8 => self.inx(opcode), 0xC8 => self.iny(opcode), 0x4C => self.jmp_absolute(), 0x6C => self.jmp_indirect(), 0x20 => self.jsr(), 0xA9 | 0xA5 | 0xB5 | 0xAD | 0xBD | 0xB9 | 0xA1 | 0xB1 => self.lda(opcode), 0xA2 | 0xA6 | 0xB6 | 0xAE | 0xBE => self.ldx(opcode), 0xA0 | 0xA4 | 0xB4 | 0xAC | 0xBC => self.ldy(opcode), 0x4A | 0x46 | 0x56 | 0x4E | 0x5E => self.lsr(opcode), 0xEA => self.nop(), 0x09 | 0x05 | 0x15 | 0x0D | 0x1D | 0x19 | 0x01 | 0x11 => self.ora(opcode), 0x48 => self.pha(), 0x08 => self.php(), 0x68 => self.pla(), 0x28 => self.plp(), 0x2A | 0x26 | 0x36 | 0x2E | 0x3E => self.rol(opcode), 0x6A | 0x66 | 0x76 | 0x6E | 0x7E => self.ror(opcode), 0x40 => self.rti(), 0x60 => self.rts(), 0xE9 | 0xE5 | 0xF5 | 0xED | 0xFD | 0xF9 | 0xE1 | 0xF1 => self.sbc(opcode), 0x38 => self.sec(), 0xF8 => self.sed(), 0x78 => self.sei(), 0x85 | 0x95 | 0x8D | 0x9D | 0x99 | 0x81 | 0x91 => self.sta(opcode), 0x86 | 0x96 | 0x8E => self.stx(opcode), 0x84 | 0x94 | 0x8C => self.sty(opcode), 0xAA => self.tax(), 0xA8 => self.tay(), 0xBA => self.tsx(), 0x8A => self.txa(), 0x9A => self.txs(), 0x98 => self.tya(), _ => panic!("Unknown opcode: {:#x}", opcode.code), } true } fn adc(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.add_to_accumulator(value); self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn and(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.accumulator &= value; self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn asl(&mut self, opcode: &Opcode) { let value; if opcode.mode == AddressingMode::None { value = self.accumulator; } else { let address = self.get_operand_address(opcode.mode); value = self.mem_read(address); } let result = (value as u16) << 1; if result > 0xff { self.status.set(Status::CARRY) } self.accumulator = result as u8; self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn bcc(&mut self) { self.branch(!self.status.contains(Status::CARRY)); } fn bcs(&mut self) { self.branch(self.status.contains(Status::CARRY)); } fn beq(&mut self) { self.branch(self.status.contains(Status::ZERO)); } fn bit(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); let result = self.accumulator & value; if result == 0 { self.status.set(Status::ZERO); } else { self.status.reset(Status::ZERO); } if value & 0x80 != 0 { self.status.set(Status::NEGATIV); } else { self.status.reset(Status::NEGATIV); } if value & 0x40 != 0 { self.status.set(Status::OVERFLOW); } else { self.status.reset(Status::OVERFLOW); } self.increment_program_counter(opcode.length); } fn bmi(&mut self) { self.branch(self.status.contains(Status::NEGATIV)); } fn bne(&mut self) { self.branch(!self.status.contains(Status::ZERO)); } fn bpl(&mut self) { self.branch(!self.status.contains(Status::NEGATIV)); } fn bvc(&mut self) { self.branch(!self.status.contains(Status::OVERFLOW)); } fn bvs(&mut self) { self.branch(self.status.contains(Status::OVERFLOW)); } fn cmp(&mut self, opcode: &Opcode) { self.compare(opcode, self.accumulator); } fn cpx(&mut self, opcode: &Opcode) { self.compare(opcode, self.register_x); } fn cpy(&mut self, opcode: &Opcode) { self.compare(opcode, self.register_y); } fn clc(&mut self) { self.status.reset(Status::CARRY); } fn sec(&mut self) { self.status.set(Status::CARRY); } fn cld(&mut self) { self.status.reset(Status::DECIMAL_MODE); } fn sed(&mut self) { self.status.set(Status::DECIMAL_MODE); } fn cli(&mut self) { self.status.reset(Status::INTERRUPT_DISABLE); } fn sei(&mut self) { self.status.set(Status::INTERRUPT_DISABLE); } fn clv(&mut self) { self.status.reset(Status::OVERFLOW); } fn dec(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); let result = value.wrapping_sub(1); self.mem_write(address, result); self.update_zero_and_negative_flags(result); self.increment_program_counter(opcode.length); } fn dex(&mut self) { self.register_x = self.register_x.wrapping_sub(1); self.update_zero_and_negative_flags(self.register_x); } fn dey(&mut self) { self.register_y = self.register_y.wrapping_sub(1); self.update_zero_and_negative_flags(self.register_y); } fn eor(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); let result = self.accumulator ^ value; self.accumulator = result; self.update_zero_and_negative_flags(result); self.increment_program_counter(opcode.length); } fn inc(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); let result = value.wrapping_add(1); self.mem_write(address, result); self.update_zero_and_negative_flags(result); self.increment_program_counter(opcode.length); } fn inx(&mut self, opcode: &Opcode) { self.register_x = self.register_x.wrapping_add(1); self.update_zero_and_negative_flags(self.register_x); self.increment_program_counter(opcode.length); } fn iny(&mut self, opcode: &Opcode) { self.register_y = self.register_y.wrapping_add(1); self.update_zero_and_negative_flags(self.register_y); self.increment_program_counter(opcode.length); } fn jmp_absolute(&mut self) { let mem_address = self.mem_read_u16(self.program_counter); self.program_counter = mem_address; } fn jmp_indirect(&mut self) { let mem_address = self.mem_read_u16(self.program_counter); //6502 bug mode with with page boundary: // if address $3000 contains $40, $30FF contains $80, and $3100 contains $50, // the result of JMP ($30FF) will be a transfer of control to $4080 rather than $5080 as you intended // i.e. the 6502 took the low byte of the address from $30FF and the high byte from $3000 let indirect_ref = if mem_address & 0x00FF == 0x00FF { let lo = self.mem_read(mem_address); let hi = self.mem_read(mem_address & 0xFF00); (hi as u16) << 8 | (lo as u16) } else { self.mem_read_u16(mem_address) }; self.program_counter = indirect_ref; } fn jsr(&mut self) { self.push_u16(self.program_counter + 2 - 1); let address = self.mem_read_u16(self.program_counter); self.program_counter = address; } fn lda(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.accumulator = value; self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn ldx(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.register_x = value; self.update_zero_and_negative_flags(self.register_x); self.increment_program_counter(opcode.length); } fn ldy(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.register_y = value; self.update_zero_and_negative_flags(self.register_y); self.increment_program_counter(opcode.length); } fn lsr(&mut self, opcode: &Opcode) { let before; if opcode.mode == AddressingMode::None { before = self.accumulator; self.accumulator = self.accumulator >> 1; } else { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); before = value; self.mem_write(address, value >> 1); } let carry = before & 0x01; if carry == 1 { self.status.set(Status::CARRY); } else { self.status.reset(Status::CARRY); } self.update_zero_and_negative_flags(before >> 1); self.increment_program_counter(opcode.length); } fn nop(&self) {} fn ora(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); self.accumulator |= value; self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn pha(&mut self) { self.push(self.accumulator); } fn php(&mut self) { self.push(self.status.get()); } fn pla(&mut self) { self.accumulator = self.pop(); self.update_zero_and_negative_flags(self.accumulator); } fn plp(&mut self) { let data = self.pop(); self.status.insert(data); } fn rol(&mut self, opcode: &Opcode) { let carry; let result; if opcode.mode == AddressingMode::None { carry = self.accumulator & 0x80; self.accumulator = self.accumulator << 1; self.accumulator |= self.status.get() & Status::CARRY; result = self.accumulator; } else { let address = self.get_operand_address(opcode.mode); let mut value = self.mem_read(address); carry = value & 0x80; value = value << 1; value |= self.status.get() & Status::CARRY; self.mem_write(address, value); result = value; } if carry == 0x80 { self.status.set(Status::CARRY); } else { self.status.reset(Status::CARRY); } if result & 0x80 == 0x80 { self.status.set(Status::NEGATIV); } else { self.status.reset(Status::NEGATIV); } if self.accumulator == 0 { self.status.set(Status::ZERO); } else { self.status.reset(Status::ZERO); } self.increment_program_counter(opcode.length); } fn ror(&mut self, opcode: &Opcode) { let carry; let result; if opcode.mode == AddressingMode::None { carry = self.accumulator & 0x01; self.accumulator = self.accumulator >> 1; let old_carry = self.status.get() & Status::CARRY; if old_carry == 1 { self.accumulator |= 0x80; } result = self.accumulator; } else { let address = self.get_operand_address(opcode.mode); let mut value = self.mem_read(address); carry = value & 0x01; value = value >> 1; let old_carry = self.status.get() & Status::CARRY; if old_carry == 1 { value |= 0x80; } self.mem_write(address, value); result = value; } if carry == 1 { self.status.set(Status::CARRY); } else { self.status.reset(Status::CARRY); } if result & 0x80 == 0x80 { self.status.set(Status::NEGATIV); } else { self.status.reset(Status::NEGATIV); } if self.accumulator == 0 { self.status.set(Status::ZERO); } else { self.status.reset(Status::ZERO); } self.increment_program_counter(opcode.length); } fn rti(&mut self) { let flags = self.pop(); self.status.insert(flags); self.status.reset(Status::BREAK); self.status.insert(Status::BREAK2); self.program_counter = self.pop_u16(); } fn rts(&mut self) { self.program_counter = self.pop_u16() + 1; } fn sbc(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); let mut value = self.mem_read(address); value = !value + 1; self.add_to_accumulator(value); self.update_zero_and_negative_flags(self.accumulator); self.increment_program_counter(opcode.length); } fn sta(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); self.mem_write(address, self.accumulator); self.increment_program_counter(opcode.length); } fn stx(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); self.mem_write(address, self.register_x); self.increment_program_counter(opcode.length); } fn sty(&mut self, opcode: &Opcode) { let address = self.get_operand_address(opcode.mode); self.mem_write(address, self.register_y); self.increment_program_counter(opcode.length); } fn tax(&mut self) { self.register_x = self.accumulator; self.update_zero_and_negative_flags(self.register_x); } fn tay(&mut self) { self.register_y = self.accumulator; self.update_zero_and_negative_flags(self.register_y); } fn tsx(&mut self) { self.register_x = self.stack_pointer as u8; self.update_zero_and_negative_flags(self.register_x); } fn txa(&mut self) { self.accumulator = self.register_x; self.update_zero_and_negative_flags(self.accumulator); } fn txs(&mut self) { self.stack_pointer = (self.register_x as u16) | 0x100; } fn tya(&mut self) { self.accumulator = self.register_y; self.update_zero_and_negative_flags(self.accumulator); } fn update_zero_and_negative_flags(&mut self, result: u8) { if result == 0 { self.status.set(Status::ZERO); } else { self.status.reset(Status::ZERO); } if result & 0b1000_0000 != 0 { self.status.set(Status::NEGATIV); } else { self.status.reset(Status::NEGATIV); } } fn add_to_accumulator(&mut self, data: u8) { let carry = if self.status.get() & 0x01 == 1 { 1 } else { 0 }; let sum = self.accumulator as u16 + data as u16 + carry; if sum > 0xff { self.status.set(Status::CARRY); } else { self.status.reset(Status::CARRY); } let result = sum as u8; if (data ^ result) & (result ^ self.accumulator) & 0x80 != 0 { self.status.set(Status::OVERFLOW); } else { self.status.reset(Status::OVERFLOW); } self.accumulator = result; } fn compare(&mut self, opcode: &Opcode, data: u8) { let address = self.get_operand_address(opcode.mode); let value = self.mem_read(address); if value <= data { self.status.set(Status::CARRY); } else { self.status.reset(Status::CARRY); } self.update_zero_and_negative_flags(data.wrapping_sub(value)); self.increment_program_counter(opcode.length); } fn branch(&mut self, condition: bool) { let mut jump: i8 = 0; if condition { jump = self.mem_read(self.program_counter) as i8; } self.program_counter = self .program_counter .wrapping_add(1) .wrapping_add(jump as u16); } pub fn create_opcode_table() -> [Opcode<'a>; 0xFF] { let mut opcode_table: [Opcode; 0xFF] = [Opcode::basic(); 0xFF]; opcode_table[0x69] = Opcode::new(0x69, "ADC", 2, 2, AddressingMode::Immediate); opcode_table[0x65] = Opcode::new(0x65, "ADC", 2, 3, AddressingMode::ZeroPage); opcode_table[0x75] = Opcode::new(0x75, "ADC", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x6D] = Opcode::new(0x6D, "ADC", 3, 4, AddressingMode::Absolute); opcode_table[0x7D] = Opcode::new(0x7D, "ADC", 3, 4, AddressingMode::Absolute_X); opcode_table[0x79] = Opcode::new(0x79, "ADC", 3, 4, AddressingMode::Absolute_Y); opcode_table[0x61] = Opcode::new(0x61, "ADC", 2, 6, AddressingMode::Indirect_X); opcode_table[0x71] = Opcode::new(0x71, "ADC", 2, 5, AddressingMode::Indirect_Y); opcode_table[0x29] = Opcode::new(0x29, "AND", 2, 2, AddressingMode::Immediate); opcode_table[0x25] = Opcode::new(0x25, "AND", 2, 3, AddressingMode::ZeroPage); opcode_table[0x35] = Opcode::new(0x35, "AND", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x2D] = Opcode::new(0x2D, "AND", 3, 4, AddressingMode::Absolute); opcode_table[0x3D] = Opcode::new(0x3D, "AND", 3, 4, AddressingMode::Absolute_X); opcode_table[0x39] = Opcode::new(0x39, "AND", 3, 4, AddressingMode::Absolute_Y); opcode_table[0x21] = Opcode::new(0x21, "AND", 2, 6, AddressingMode::Indirect_X); opcode_table[0x31] = Opcode::new(0x31, "AND", 2, 5, AddressingMode::Indirect_Y); opcode_table[0x0A] = Opcode::new(0x0A, "ASL", 1, 2, AddressingMode::None); opcode_table[0x06] = Opcode::new(0x06, "ASL", 2, 5, AddressingMode::ZeroPage); opcode_table[0x16] = Opcode::new(0x16, "ASL", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0x0E] = Opcode::new(0x0E, "ASL", 1, 6, AddressingMode::Absolute); opcode_table[0x1E] = Opcode::new(0x1E, "ASL", 1, 7, AddressingMode::Absolute_X); opcode_table[0x90] = Opcode::new(0x90, "BCC", 2, 2, AddressingMode::None); opcode_table[0xB0] = Opcode::new(0xB0, "BCS", 2, 2, AddressingMode::None); opcode_table[0xF0] = Opcode::new(0xF0, "BEQ", 2, 2, AddressingMode::None); opcode_table[0x24] = Opcode::new(0x24, "BIT", 2, 3, AddressingMode::ZeroPage); opcode_table[0x2C] = Opcode::new(0x2C, "BIT", 3, 4, AddressingMode::Absolute); opcode_table[0x30] = Opcode::new(0x30, "BMI", 2, 2, AddressingMode::None); opcode_table[0xD0] = Opcode::new(0xD0, "BNE", 2, 2, AddressingMode::None); opcode_table[0x10] = Opcode::new(0x10, "BPL", 2, 2, AddressingMode::None); opcode_table[0x00] = Opcode::new(0x00, "BRK", 1, 7, AddressingMode::None); opcode_table[0x50] = Opcode::new(0x50, "BVC", 2, 2, AddressingMode::None); opcode_table[0x70] = Opcode::new(0x70, "BVS", 2, 2, AddressingMode::None); opcode_table[0x18] = Opcode::new(0x18, "CLC", 1, 2, AddressingMode::None); opcode_table[0xD8] = Opcode::new(0xD8, "CLD", 1, 2, AddressingMode::None); opcode_table[0x58] = Opcode::new(0x58, "CLI", 1, 2, AddressingMode::None); opcode_table[0xB8] = Opcode::new(0xB8, "CLV", 1, 2, AddressingMode::None); opcode_table[0xC9] = Opcode::new(0xC9, "CMP", 2, 2, AddressingMode::Immediate); opcode_table[0xC5] = Opcode::new(0xC5, "CMP", 2, 3, AddressingMode::ZeroPage); opcode_table[0xD5] = Opcode::new(0xD5, "CMP", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0xCD] = Opcode::new(0xCD, "CMP", 3, 4, AddressingMode::Absolute); opcode_table[0xDD] = Opcode::new(0xDD, "CMP", 3, 4, AddressingMode::Absolute_X); opcode_table[0xD9] = Opcode::new(0xD9, "CMP", 3, 4, AddressingMode::Absolute_Y); opcode_table[0xC1] = Opcode::new(0xC1, "CMP", 2, 6, AddressingMode::Indirect_X); opcode_table[0xD1] = Opcode::new(0xD1, "CMP", 2, 5, AddressingMode::Indirect_Y); opcode_table[0xE0] = Opcode::new(0xE0, "CPX", 2, 2, AddressingMode::Immediate); opcode_table[0xE4] = Opcode::new(0xE4, "CPX", 2, 3, AddressingMode::ZeroPage); opcode_table[0xEC] = Opcode::new(0xEC, "CPX", 3, 4, AddressingMode::Absolute); opcode_table[0xC0] = Opcode::new(0xC0, "CPY", 2, 2, AddressingMode::Immediate); opcode_table[0xC4] = Opcode::new(0xC4, "CPY", 2, 3, AddressingMode::ZeroPage); opcode_table[0xCC] = Opcode::new(0xCC, "CPY", 3, 4, AddressingMode::Absolute); opcode_table[0xC6] = Opcode::new(0xC6, "DEC", 2, 5, AddressingMode::ZeroPage); opcode_table[0xD6] = Opcode::new(0xD6, "DEC", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0xCE] = Opcode::new(0xCE, "DEC", 3, 6, AddressingMode::Absolute); opcode_table[0xDE] = Opcode::new(0xDE, "DEC", 3, 7, AddressingMode::Absolute_X); opcode_table[0xCA] = Opcode::new(0xCA, "DEX", 1, 2, AddressingMode::None); opcode_table[0x88] = Opcode::new(0x88, "DEY", 1, 2, AddressingMode::None); opcode_table[0x49] = Opcode::new(0x49, "EOR", 2, 2, AddressingMode::Immediate); opcode_table[0x45] = Opcode::new(0x45, "EOR", 2, 3, AddressingMode::ZeroPage); opcode_table[0x55] = Opcode::new(0x55, "EOR", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x4D] = Opcode::new(0x4D, "EOR", 3, 4, AddressingMode::Absolute); opcode_table[0x5D] = Opcode::new(0x5D, "EOR", 3, 4, AddressingMode::Absolute_X); opcode_table[0x59] = Opcode::new(0x59, "EOR", 3, 4, AddressingMode::Absolute_Y); opcode_table[0x41] = Opcode::new(0x41, "EOR", 2, 6, AddressingMode::Indirect_X); opcode_table[0x51] = Opcode::new(0x51, "EOR", 2, 5, AddressingMode::Indirect_Y); opcode_table[0xE6] = Opcode::new(0xE6, "INC", 2, 5, AddressingMode::ZeroPage); opcode_table[0xF6] = Opcode::new(0xF6, "INC", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0xEE] = Opcode::new(0xEE, "INC", 3, 6, AddressingMode::Absolute); opcode_table[0xFE] = Opcode::new(0xFE, "INC", 3, 7, AddressingMode::Absolute_X); opcode_table[0xE8] = Opcode::new(0xE8, "INX", 1, 2, AddressingMode::None); opcode_table[0xC8] = Opcode::new(0xC8, "INY", 1, 2, AddressingMode::None); opcode_table[0x4C] = Opcode::new(0x4C, "JMP", 1, 2, AddressingMode::None); opcode_table[0x6C] = Opcode::new(0x6C, "JMP", 1, 2, AddressingMode::None); opcode_table[0x20] = Opcode::new(0x20, "JSR", 1, 2, AddressingMode::None); opcode_table[0xA9] = Opcode::new(0xA9, "LDA", 2, 2, AddressingMode::Immediate); opcode_table[0xA5] = Opcode::new(0xA5, "LDA", 2, 3, AddressingMode::ZeroPage); opcode_table[0xB5] = Opcode::new(0xB5, "LDA", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0xAD] = Opcode::new(0xAD, "LDA", 3, 4, AddressingMode::Absolute); opcode_table[0xBD] = Opcode::new(0xBD, "LDA", 3, 4, AddressingMode::Absolute_X); opcode_table[0xB9] = Opcode::new(0xB9, "LDA", 3, 4, AddressingMode::Absolute_Y); opcode_table[0xA1] = Opcode::new(0xA1, "LDA", 2, 6, AddressingMode::Indirect_X); opcode_table[0xB1] = Opcode::new(0xB1, "LDA", 2, 5, AddressingMode::Indirect_Y); opcode_table[0xA2] = Opcode::new(0xA2, "LDX", 2, 2, AddressingMode::Immediate); opcode_table[0xA6] = Opcode::new(0xA6, "LDX", 2, 3, AddressingMode::ZeroPage); opcode_table[0xB6] = Opcode::new(0xB6, "LDX", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0xAE] = Opcode::new(0xAE, "LDX", 3, 4, AddressingMode::Absolute); opcode_table[0xBE] = Opcode::new(0xBE, "LDX", 3, 4, AddressingMode::Absolute_Y); opcode_table[0xA0] = Opcode::new(0xA0, "LDY", 2, 2, AddressingMode::Immediate); opcode_table[0xA4] = Opcode::new(0xA4, "LDY", 2, 3, AddressingMode::ZeroPage); opcode_table[0xB4] = Opcode::new(0xB4, "LDY", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0xAC] = Opcode::new(0xAC, "LDY", 3, 4, AddressingMode::Absolute); opcode_table[0xBC] = Opcode::new(0xBC, "LDY", 3, 4, AddressingMode::Absolute_Y); opcode_table[0x4A] = Opcode::new(0x4A, "LSR", 1, 2, AddressingMode::None); opcode_table[0x46] = Opcode::new(0x46, "LSR", 2, 5, AddressingMode::ZeroPage); opcode_table[0x56] = Opcode::new(0x56, "LSR", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0x4E] = Opcode::new(0x4E, "LSR", 3, 6, AddressingMode::Absolute); opcode_table[0x5E] = Opcode::new(0x5E, "LSR", 3, 7, AddressingMode::Absolute_X); opcode_table[0xEA] = Opcode::new(0xEA, "NOP", 1, 2, AddressingMode::None); opcode_table[0x09] = Opcode::new(0x09, "ORA", 2, 2, AddressingMode::Immediate); opcode_table[0x05] = Opcode::new(0x05, "ORA", 2, 3, AddressingMode::ZeroPage); opcode_table[0x15] = Opcode::new(0x15, "ORA", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x0D] = Opcode::new(0x0D, "ORA", 3, 4, AddressingMode::Absolute); opcode_table[0x1D] = Opcode::new(0x1D, "ORA", 3, 4, AddressingMode::Absolute_X); opcode_table[0x19] = Opcode::new(0x19, "ORA", 3, 4, AddressingMode::Absolute_Y); opcode_table[0x01] = Opcode::new(0x01, "ORA", 2, 6, AddressingMode::Indirect_X); opcode_table[0x11] = Opcode::new(0x11, "ORA", 2, 5, AddressingMode::Indirect_Y); opcode_table[0x48] = Opcode::new(0x48, "PHA", 1, 3, AddressingMode::None); opcode_table[0x08] = Opcode::new(0x08, "PHP", 1, 3, AddressingMode::None); opcode_table[0x68] = Opcode::new(0x68, "PLA", 1, 4, AddressingMode::None); opcode_table[0x28] = Opcode::new(0x28, "PLP", 1, 4, AddressingMode::None); opcode_table[0x2A] = Opcode::new(0x2A, "ROL", 1, 2, AddressingMode::None); opcode_table[0x26] = Opcode::new(0x26, "ROL", 2, 5, AddressingMode::ZeroPage); opcode_table[0x36] = Opcode::new(0x36, "ROL", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0x2E] = Opcode::new(0x2E, "ROL", 3, 6, AddressingMode::Absolute); opcode_table[0x3E] = Opcode::new(0x3E, "ROL", 3, 7, AddressingMode::Absolute_X); opcode_table[0x6A] = Opcode::new(0x6A, "ROR", 1, 2, AddressingMode::None); opcode_table[0x66] = Opcode::new(0x66, "ROR", 2, 5, AddressingMode::ZeroPage); opcode_table[0x76] = Opcode::new(0x76, "ROR", 2, 6, AddressingMode::ZeroPage_X); opcode_table[0x6E] = Opcode::new(0x6E, "ROR", 3, 6, AddressingMode::Absolute); opcode_table[0x7E] = Opcode::new(0x7E, "ROR", 3, 7, AddressingMode::Absolute_X); opcode_table[0x40] = Opcode::new(0x40, "RTI", 1, 6, AddressingMode::None); opcode_table[0x60] = Opcode::new(0x60, "RTS", 1, 6, AddressingMode::None); opcode_table[0xE9] = Opcode::new(0xE9, "SBC", 2, 2, AddressingMode::Immediate); opcode_table[0xE5] = Opcode::new(0xE5, "SBC", 2, 3, AddressingMode::ZeroPage); opcode_table[0xF5] = Opcode::new(0xF5, "SBC", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0xED] = Opcode::new(0xED, "SBC", 3, 4, AddressingMode::Absolute); opcode_table[0xFD] = Opcode::new(0xFD, "SBC", 3, 4, AddressingMode::Absolute_X); opcode_table[0xF9] = Opcode::new(0xF9, "SBC", 3, 4, AddressingMode::Absolute_Y); opcode_table[0xE1] = Opcode::new(0xE1, "SBC", 2, 6, AddressingMode::Indirect_X); opcode_table[0xF1] = Opcode::new(0xF1, "SBC", 2, 5, AddressingMode::Indirect_Y); opcode_table[0x38] = Opcode::new(0x38, "SEC", 1, 2, AddressingMode::None); opcode_table[0xF8] = Opcode::new(0xF8, "SED", 1, 2, AddressingMode::None); opcode_table[0x78] = Opcode::new(0x78, "SEI", 1, 2, AddressingMode::None); opcode_table[0x85] = Opcode::new(0x85, "STA", 2, 3, AddressingMode::ZeroPage); opcode_table[0x95] = Opcode::new(0x95, "STA", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x8D] = Opcode::new(0x8D, "STA", 3, 4, AddressingMode::Absolute); opcode_table[0x9D] = Opcode::new(0x9D, "STA", 3, 5, AddressingMode::Absolute_X); opcode_table[0x99] = Opcode::new(0x99, "STA", 3, 5, AddressingMode::Absolute_Y); opcode_table[0x81] = Opcode::new(0x81, "STA", 2, 6, AddressingMode::Indirect_X); opcode_table[0x91] = Opcode::new(0x91, "STA", 2, 6, AddressingMode::Indirect_Y); opcode_table[0x86] = Opcode::new(0x86, "STX", 2, 3, AddressingMode::ZeroPage); opcode_table[0x96] = Opcode::new(0x96, "STX", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x8E] = Opcode::new(0x8E, "STX", 3, 4, AddressingMode::Absolute); opcode_table[0x84] = Opcode::new(0x84, "STY", 2, 3, AddressingMode::ZeroPage); opcode_table[0x94] = Opcode::new(0x94, "STY", 2, 4, AddressingMode::ZeroPage_X); opcode_table[0x8C] = Opcode::new(0x8C, "STY", 3, 4, AddressingMode::Absolute); opcode_table[0xAA] = Opcode::new(0xAA, "TAX", 1, 2, AddressingMode::None); opcode_table[0xA8] = Opcode::new(0xA8, "TAY", 1, 2, AddressingMode::None); opcode_table[0xBA] = Opcode::new(0xBA, "TSX", 1, 2, AddressingMode::None); opcode_table[0x8A] = Opcode::new(0x8A, "TXA", 1, 2, AddressingMode::None); opcode_table[0x9A] = Opcode::new(0x9A, "TXS", 1, 2, AddressingMode::None); opcode_table[0x98] = Opcode::new(0x98, "TYA", 1, 2, AddressingMode::None); opcode_table } }
pub mod create_database; pub mod create_document; pub mod delete_document; pub mod execute_view; pub mod read_document; pub mod update_document; pub use self::create_database::CreateDatabase; pub use self::create_document::CreateDocument; pub use self::delete_document::DeleteDocument; pub use self::execute_view::ExecuteView; pub use self::read_document::ReadDocument; pub use self::update_document::UpdateDocument; pub mod query_keys { use {Error, Revision, serde, transport}; macro_rules! define_query_key { ($key_name:ident, $key_str:expr) => { pub struct $key_name; impl transport::AsQueryKey for $key_name { type Key = &'static str; fn as_query_key(&self) -> Self::Key { $key_str } } } } macro_rules! define_query_value_bool { ($key_name:ident) => { impl transport::AsQueryValue<$key_name> for bool { type Value = &'static str; fn as_query_value(&self) -> Self::Value { if *self { "true" } else { "false" } } } } } macro_rules! define_query_value_simple { ($key_name:ident, $value_type:ty) => { impl transport::AsQueryValue<$key_name> for $value_type { type Value = String; fn as_query_value(&self) -> Self::Value { self.to_string() } } } } define_query_key!(AttachmentsQueryKey, "attachments"); define_query_value_bool!(AttachmentsQueryKey); define_query_key!(DescendingQueryKey, "descending"); define_query_value_bool!(DescendingQueryKey); define_query_key!(EndKeyQueryKey, "endkey"); impl<T> transport::AsQueryValueFallible<EndKeyQueryKey> for T where T: serde::Serialize, { type Value = String; fn as_query_value_fallible(&self) -> Result<Self::Value, Error> { use serde_json; serde_json::to_string(self).map_err(|e| Error::JsonEncode { cause: e }) } } define_query_key!(GroupLevelQueryKey, "group_level"); define_query_value_simple!(GroupLevelQueryKey, u32); define_query_key!(GroupQueryKey, "group"); define_query_value_bool!(GroupQueryKey); define_query_key!(IncludeDocsQueryKey, "include_docs"); define_query_value_bool!(IncludeDocsQueryKey); define_query_key!(InclusiveEndQueryKey, "inclusive_end"); define_query_value_bool!(InclusiveEndQueryKey); define_query_key!(LimitQueryKey, "limit"); define_query_value_simple!(LimitQueryKey, u64); define_query_key!(ReduceQueryKey, "reduce"); define_query_value_bool!(ReduceQueryKey); define_query_key!(RevisionQueryKey, "rev"); impl transport::AsQueryValue<RevisionQueryKey> for Revision { type Value = String; fn as_query_value(&self) -> Self::Value { self.to_string() } } define_query_key!(StartKeyQueryKey, "startkey"); impl<T> transport::AsQueryValueFallible<StartKeyQueryKey> for T where T: serde::Serialize, { type Value = String; fn as_query_value_fallible(&self) -> Result<Self::Value, Error> { use serde_json; serde_json::to_string(self).map_err(|e| Error::JsonEncode { cause: e }) } } }
//! Deployment Recipes use ckb_tool::ckb_types::H256; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CellRecipe { pub name: String, pub tx_hash: H256, pub index: u32, pub occupied_capacity: u64, pub data_hash: H256, pub type_id: Option<H256>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct DepGroupRecipe { pub name: String, pub tx_hash: H256, pub index: u32, pub occupied_capacity: u64, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct DeploymentRecipe { pub cell_recipes: Vec<CellRecipe>, pub dep_group_recipes: Vec<DepGroupRecipe>, }
#![doc = "generated by AutoRust 0.1.0"] #[cfg(feature = "package-2019-12")] mod package_2019_12; #[cfg(feature = "package-2019-12")] pub use package_2019_12::{models, operations, API_VERSION}; #[cfg(feature = "package-2018-10")] mod package_2018_10; #[cfg(feature = "package-2018-10")] pub use package_2018_10::{models, operations, API_VERSION}; #[cfg(feature = "package-2018-09")] mod package_2018_09; #[cfg(feature = "package-2018-09")] pub use package_2018_09::{models, operations, API_VERSION}; #[cfg(feature = "package-2018-06")] mod package_2018_06; #[cfg(feature = "package-2018-06")] pub use package_2018_06::{models, operations, API_VERSION}; #[cfg(feature = "package-2018-04")] mod package_2018_04; #[cfg(feature = "package-2018-04")] pub use package_2018_04::{models, operations, API_VERSION}; #[cfg(feature = "package-2018-02-preview")] mod package_2018_02_preview; #[cfg(feature = "package-2018-02-preview")] pub use package_2018_02_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2017-12-preview")] mod package_2017_12_preview; #[cfg(feature = "package-2017-12-preview")] pub use package_2017_12_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2017-10-preview")] mod package_2017_10_preview; #[cfg(feature = "package-2017-10-preview")] pub use package_2017_10_preview::{models, operations, API_VERSION}; #[cfg(feature = "package-2017-08-preview")] mod package_2017_08_preview; #[cfg(feature = "package-2017-08-preview")] pub use package_2017_08_preview::{models, operations, API_VERSION}; pub struct OperationConfig { pub api_version: String, pub client: reqwest::Client, pub base_path: String, pub token_credential: Option<Box<dyn azure_core::TokenCredential>>, pub token_credential_resource: String, } impl OperationConfig { pub fn new(token_credential: Box<dyn azure_core::TokenCredential>) -> Self { Self { token_credential: Some(token_credential), ..Default::default() } } } impl Default for OperationConfig { fn default() -> Self { Self { api_version: API_VERSION.to_owned(), client: reqwest::Client::new(), base_path: "https://management.azure.com".to_owned(), token_credential: None, token_credential_resource: "https://management.azure.com/".to_owned(), } } }
use rust::solve; fn main() { solve(); }
use simple_error::bail; use std::error; use std::io; use std::io::BufRead; use crate::day; pub type BoxResult<T> = Result<T, Box<dyn error::Error>>; pub struct Day05 {} impl day::Day for Day05 { fn tag(&self) -> &str { "05" } fn part1(&self, input: &dyn Fn() -> Box<dyn io::Read>) { println!("{:?}", self.part1_impl(&mut *input(), 1)); } fn part2(&self, input: &dyn Fn() -> Box<dyn io::Read>) { println!("{:?}", self.part2_impl(&mut *input(), 5)); } } impl Day05 { fn op(&self, c: i32) -> i32 { c % 100 } fn val(&self, p: &Vec<i32>, ip: usize, i: usize) -> i32 { let a = p[ip + i]; let v = if p[ip] / vec![100, 1000][i - 1] % 10 == 0 { p[a as usize] } else { a }; v } fn part1_impl(self: &Self, input: &mut dyn io::Read, i: i32) -> BoxResult<i32> { let reader = io::BufReader::new(input); let mut p = reader.split(b',') .map(|v| String::from_utf8(v.unwrap()).unwrap()) .map(|s| s.trim_end().parse::<i32>().unwrap()) .collect::<Vec<_>>(); let mut ip = 0; let mut o = None; while self.op(p[ip]) != 99 { match self.op(p[ip]) { 1 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = a + b; ip += 4; }, 2 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = a * b; ip += 4; }, 3 => { let a = p[ip + 1]; p[a as usize] = i; ip += 2; }, 4 => { let a = self.val(&p, ip, 1); o = Some(a); ip += 2; } _ => bail!("unknown opcode {}: {}", ip, self.op(p[ip])), }; } if o.is_none() { bail!("no output"); } Ok(o.unwrap()) } fn part2_impl(self: &Self, input: &mut dyn io::Read, i: i32) -> BoxResult<i32> { let reader = io::BufReader::new(input); let mut p = reader.split(b',') .map(|v| String::from_utf8(v.unwrap()).unwrap()) .map(|s| s.trim_end().parse::<i32>().unwrap()) .collect::<Vec<_>>(); let mut ip = 0; let mut o = None; while self.op(p[ip]) != 99 { match self.op(p[ip]) { 1 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = a + b; ip += 4; }, 2 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = a * b; ip += 4; }, 3 => { let a = p[ip + 1]; p[a as usize] = i; ip += 2; }, 4 => { let a = self.val(&p, ip, 1); o = Some(a); ip += 2; }, 5 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2) as usize; ip = if a != 0 { b } else { ip + 3 }; }, 6 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2) as usize; ip = if a == 0 { b } else { ip + 3 }; }, 7 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = if a < b { 1 } else { 0 }; ip += 4; }, 8 => { let a = self.val(&p, ip, 1); let b = self.val(&p, ip, 2); let c = p[ip + 3 as usize] as usize; p[c] = if a == b { 1 } else { 0 }; ip += 4; }, _ => bail!("unknown opcode {}: {}", ip, self.op(p[ip])), }; } if o.is_none() { bail!("no output"); } Ok(o.unwrap()) } } #[cfg(test)] mod tests { use super::*; fn test1(s: &str, i: i32, o: Option<i32>) { let r = Day05 {}.part1_impl(&mut s.as_bytes(), i); if o == None { assert!(r.is_err()); } else { assert_eq!(r.unwrap(), o.unwrap()); } } #[test] fn part1() { test1("3,0,4,0,99", 1, Some(1)); test1("1002,4,3,4,33", 1, None); test1("1101,100,-1,4,0", 1, None); } fn test2(s: &str, i: i32, o: i32) { assert_eq!( Day05 {}.part2_impl(&mut s.as_bytes(), i).unwrap(), o); } #[test] fn part2() { test2("3,9,8,9,10,9,4,9,99,-1,8", 1, 0); test2("3,9,8,9,10,9,4,9,99,-1,8", 8, 1); test2("3,9,7,9,10,9,4,9,99,-1,8", 1, 1); test2("3,9,7,9,10,9,4,9,99,-1,8", 8, 0); test2("3,3,1108,-1,8,3,4,3,99", 1, 0); test2("3,3,1108,-1,8,3,4,3,99", 8, 1); test2("3,3,1107,-1,8,3,4,3,99", 1, 1); test2("3,3,1107,-1,8,3,4,3,99", 8, 0); test2("3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9", 0, 0); test2("3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9", 2, 1); test2("3,3,1105,-1,9,1101,0,0,12,4,12,99,1", 0, 0); test2("3,3,1105,-1,9,1101,0,0,12,4,12,99,1", 2, 1); test2("3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99", 0, 999); test2("3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99", 8, 1000); test2("3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99", 80, 1001); } }
use std::ops::{Deref, DerefMut}; #[derive(Debug, Copy, Clone, Default)] pub struct RV32Registers { inner: [u32; 32], pc: u32, // x0: u32, // x1: u32, // x2: u32, // x3: u32, // x4: u32, // x5: u32, // x6: u32, // x7: u32, // x8: u32, // x9: u32, // x10: u32, // x11: u32, // x12: u32, // x13: u32, // x14: u32, // x15: u32, // x16: u32, // x17: u32, // x18: u32, // x19: u32, // x20: u32, // x21: u32, // x22: u32, // x23: u32, // x24: u32, // x25: u32, // x26: u32, // x27: u32, // x28: u32, // x29: u32, // x30: u32, // x31: u32, // pc: u32, } impl Deref for RV32Registers { type Target = [u32; 32]; fn deref(&self) -> &[u32; 32] { &self.inner } } impl DerefMut for RV32Registers { fn deref_mut(&mut self) -> &mut [u32; 32] { &mut self.inner } } impl RV32Registers { pub fn new() -> Self { Default::default() } pub fn get_pc(&self) -> u32 { self.pc } // This might have a signedness issue when we are adding pub fn add_to_pc(&mut self, val: u32) { let (value, overflow) = self.pc.overflowing_add(val); self.pc = value; } pub fn set_pc(&mut self, val: u32) { self.pc = val; } pub fn increment_pc(&mut self) { self.pc += 4; } } #[cfg(test)] mod tests { use super::*; #[test] fn new() { let regs = RV32Registers::new(); assert_eq!(*regs, [0; 32]) // assert_eq!(regs.x0, 0); // assert_eq!(regs.x1, 0); // assert_eq!(regs.x2, 0); // assert_eq!(regs.x3, 0); // assert_eq!(regs.x4, 0); // assert_eq!(regs.x5, 0); // assert_eq!(regs.x6, 0); // assert_eq!(regs.x7, 0); // assert_eq!(regs.x8, 0); // assert_eq!(regs.x9, 0); // assert_eq!(regs.x10, 0); // assert_eq!(regs.x11, 0); // assert_eq!(regs.x12, 0); // assert_eq!(regs.x13, 0); // assert_eq!(regs.x14, 0); // assert_eq!(regs.x15, 0); // assert_eq!(regs.x16, 0); // assert_eq!(regs.x17, 0); // assert_eq!(regs.x18, 0); // assert_eq!(regs.x19, 0); // assert_eq!(regs.x20, 0); // assert_eq!(regs.x21, 0); // assert_eq!(regs.x22, 0); // assert_eq!(regs.x23, 0); // assert_eq!(regs.x24, 0); // assert_eq!(regs.x25, 0); // assert_eq!(regs.x26, 0); // assert_eq!(regs.x27, 0); // assert_eq!(regs.x28, 0); // assert_eq!(regs.x29, 0); // assert_eq!(regs.x30, 0); // assert_eq!(regs.x31, 0); // assert_eq!(regs.pc, 0); } #[test] fn inc_pc() { let mut regs = RV32Registers::new(); assert_eq!(regs.pc, 0); regs.increment_pc(); assert_eq!(regs.pc, 4); } #[test] fn get_pc() { let mut regs = RV32Registers::new(); assert_eq!(regs.get_pc(), 0); regs.increment_pc(); assert_eq!(regs.get_pc(), 4); } }
#[doc = "Register `CR1` reader"] pub type R = crate::R<CR1_SPEC>; #[doc = "Register `CR1` writer"] pub type W = crate::W<CR1_SPEC>; #[doc = "Field `TAMP1E` reader - TAMP1E"] pub type TAMP1E_R = crate::BitReader; #[doc = "Field `TAMP1E` writer - TAMP1E"] pub type TAMP1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2E` reader - TAMP2E"] pub type TAMP2E_R = crate::BitReader; #[doc = "Field `TAMP2E` writer - TAMP2E"] pub type TAMP2E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3E` reader - TAMP3E"] pub type TAMP3E_R = crate::BitReader; #[doc = "Field `TAMP3E` writer - TAMP3E"] pub type TAMP3E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP4E` reader - TAMP4E"] pub type TAMP4E_R = crate::BitReader; #[doc = "Field `TAMP4E` writer - TAMP4E"] pub type TAMP4E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP5E` reader - TAMP5E"] pub type TAMP5E_R = crate::BitReader; #[doc = "Field `TAMP5E` writer - TAMP5E"] pub type TAMP5E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP6E` reader - TAMP6E"] pub type TAMP6E_R = crate::BitReader; #[doc = "Field `TAMP6E` writer - TAMP6E"] pub type TAMP6E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP7E` reader - TAMP7E"] pub type TAMP7E_R = crate::BitReader; #[doc = "Field `TAMP7E` writer - TAMP7E"] pub type TAMP7E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP8E` reader - TAMP8E"] pub type TAMP8E_R = crate::BitReader; #[doc = "Field `TAMP8E` writer - TAMP8E"] pub type TAMP8E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP1E` reader - ITAMP1E"] pub type ITAMP1E_R = crate::BitReader; #[doc = "Field `ITAMP1E` writer - ITAMP1E"] pub type ITAMP1E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP2E` reader - ITAMP2E"] pub type ITAMP2E_R = crate::BitReader; #[doc = "Field `ITAMP2E` writer - ITAMP2E"] pub type ITAMP2E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP3E` reader - ITAMP3E"] pub type ITAMP3E_R = crate::BitReader; #[doc = "Field `ITAMP3E` writer - ITAMP3E"] pub type ITAMP3E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP5E` reader - ITAMP5E"] pub type ITAMP5E_R = crate::BitReader; #[doc = "Field `ITAMP5E` writer - ITAMP5E"] pub type ITAMP5E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP8E` reader - ITAMP5E"] pub type ITAMP8E_R = crate::BitReader; #[doc = "Field `ITAMP8E` writer - ITAMP5E"] pub type ITAMP8E_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - TAMP1E"] #[inline(always)] pub fn tamp1e(&self) -> TAMP1E_R { TAMP1E_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TAMP2E"] #[inline(always)] pub fn tamp2e(&self) -> TAMP2E_R { TAMP2E_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - TAMP3E"] #[inline(always)] pub fn tamp3e(&self) -> TAMP3E_R { TAMP3E_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - TAMP4E"] #[inline(always)] pub fn tamp4e(&self) -> TAMP4E_R { TAMP4E_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - TAMP5E"] #[inline(always)] pub fn tamp5e(&self) -> TAMP5E_R { TAMP5E_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TAMP6E"] #[inline(always)] pub fn tamp6e(&self) -> TAMP6E_R { TAMP6E_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - TAMP7E"] #[inline(always)] pub fn tamp7e(&self) -> TAMP7E_R { TAMP7E_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - TAMP8E"] #[inline(always)] pub fn tamp8e(&self) -> TAMP8E_R { TAMP8E_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 16 - ITAMP1E"] #[inline(always)] pub fn itamp1e(&self) -> ITAMP1E_R { ITAMP1E_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - ITAMP2E"] #[inline(always)] pub fn itamp2e(&self) -> ITAMP2E_R { ITAMP2E_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - ITAMP3E"] #[inline(always)] pub fn itamp3e(&self) -> ITAMP3E_R { ITAMP3E_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 20 - ITAMP5E"] #[inline(always)] pub fn itamp5e(&self) -> ITAMP5E_R { ITAMP5E_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 23 - ITAMP5E"] #[inline(always)] pub fn itamp8e(&self) -> ITAMP8E_R { ITAMP8E_R::new(((self.bits >> 23) & 1) != 0) } } impl W { #[doc = "Bit 0 - TAMP1E"] #[inline(always)] #[must_use] pub fn tamp1e(&mut self) -> TAMP1E_W<CR1_SPEC, 0> { TAMP1E_W::new(self) } #[doc = "Bit 1 - TAMP2E"] #[inline(always)] #[must_use] pub fn tamp2e(&mut self) -> TAMP2E_W<CR1_SPEC, 1> { TAMP2E_W::new(self) } #[doc = "Bit 2 - TAMP3E"] #[inline(always)] #[must_use] pub fn tamp3e(&mut self) -> TAMP3E_W<CR1_SPEC, 2> { TAMP3E_W::new(self) } #[doc = "Bit 3 - TAMP4E"] #[inline(always)] #[must_use] pub fn tamp4e(&mut self) -> TAMP4E_W<CR1_SPEC, 3> { TAMP4E_W::new(self) } #[doc = "Bit 4 - TAMP5E"] #[inline(always)] #[must_use] pub fn tamp5e(&mut self) -> TAMP5E_W<CR1_SPEC, 4> { TAMP5E_W::new(self) } #[doc = "Bit 5 - TAMP6E"] #[inline(always)] #[must_use] pub fn tamp6e(&mut self) -> TAMP6E_W<CR1_SPEC, 5> { TAMP6E_W::new(self) } #[doc = "Bit 6 - TAMP7E"] #[inline(always)] #[must_use] pub fn tamp7e(&mut self) -> TAMP7E_W<CR1_SPEC, 6> { TAMP7E_W::new(self) } #[doc = "Bit 7 - TAMP8E"] #[inline(always)] #[must_use] pub fn tamp8e(&mut self) -> TAMP8E_W<CR1_SPEC, 7> { TAMP8E_W::new(self) } #[doc = "Bit 16 - ITAMP1E"] #[inline(always)] #[must_use] pub fn itamp1e(&mut self) -> ITAMP1E_W<CR1_SPEC, 16> { ITAMP1E_W::new(self) } #[doc = "Bit 17 - ITAMP2E"] #[inline(always)] #[must_use] pub fn itamp2e(&mut self) -> ITAMP2E_W<CR1_SPEC, 17> { ITAMP2E_W::new(self) } #[doc = "Bit 18 - ITAMP3E"] #[inline(always)] #[must_use] pub fn itamp3e(&mut self) -> ITAMP3E_W<CR1_SPEC, 18> { ITAMP3E_W::new(self) } #[doc = "Bit 20 - ITAMP5E"] #[inline(always)] #[must_use] pub fn itamp5e(&mut self) -> ITAMP5E_W<CR1_SPEC, 20> { ITAMP5E_W::new(self) } #[doc = "Bit 23 - ITAMP5E"] #[inline(always)] #[must_use] pub fn itamp8e(&mut self) -> ITAMP8E_W<CR1_SPEC, 23> { ITAMP8E_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 = "control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::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 [`cr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR1_SPEC; impl crate::RegisterSpec for CR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr1::R`](R) reader structure"] impl crate::Readable for CR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr1::W`](W) writer structure"] impl crate::Writable for CR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR1 to value 0xffff_0000"] impl crate::Resettable for CR1_SPEC { const RESET_VALUE: Self::Ux = 0xffff_0000; }
use proconio::{fastout, input}; #[fastout] fn main() { input! { s: String, }; println!( "{}", match s.as_str() { "RRR" => 3, "RRS" | "SRR" => 2, "SSS" => 0, _ => 1, } ); }
#![recursion_limit = "128"] #[macro_use] extern crate combine; extern crate clap; mod error; mod eval; mod parser; mod syntax; mod tc; use clap::{App, Arg}; use error::*; use std::fs::File; use std::io::prelude::*; use std::process; fn parse_and_eval( code: &str, mem_limit: usize, reg_limit: usize, ) -> Result<i32, Error> { let blocks = try!(parser::parse(code)); let blocks = try!(tc::tc(blocks)); return eval::eval(mem_limit, reg_limit, blocks); } fn main_result() -> Result<i32, Error> { let args = App::new("ILVM") .version(env!("CARGO_PKG_VERSION")) .arg( Arg::with_name("memlimit") .short("m") .long("memory-limit") .value_name("MEM_LIMIT") .default_value("1024") .help("Sets a memory limit in words") .takes_value(true), ).arg( Arg::with_name("INPUT") .value_name("FILENAME") .help("Sets the input file to use") .required(true) .index(1), ).arg( Arg::with_name("reglimit") .short("r") .value_name("REG_LIMIT") .default_value("32") .long("num-registers") .help("Set the number of registers"), ).get_matches(); let path = args.value_of("INPUT").unwrap(); let mut file = try!(File::open(&path)); let mut buf = String::new(); try!(file.read_to_string(&mut buf)); parse_and_eval( &buf[..], args.value_of("memlimit").unwrap().parse::<usize>().unwrap(), args.value_of("reglimit").unwrap().parse::<usize>().unwrap(), ) } fn main() { match main_result() { Ok(r) => println!("Normal termination. Result = {}", r), Err(err) => { println!("An error occurred.\n{}", err); process::exit(1) } } } #[cfg(test)] mod tests { use super::syntax::{Val, Printable, Instr}; fn parse_and_eval(code: &str) -> Result<i32, super::error::Error> { super::parse_and_eval(code, 500, 10) } fn assert_code_eq_block(code : &str, expected_block : Instr) { match super::parser::parse(code) { Result::Ok(blocks) => { match super::tc::tc(blocks) { Result::Ok(blocks) => match blocks.get(&0) { Option::Some(block) => assert_eq!(*block, expected_block), _ => assert!(false, "no zero block found in") } _ => assert!(false, "tc returned Error") } } Result::Err(super::Error::Parse(s)) => assert!(false, format!("parse error, {}", s)), _ => assert!(false, format!("parse returned Error on input, {}", code)) }; } #[test] fn test_trailing_whitespace() { let r = parse_and_eval( r#" block 0 { exit(200); } "#, ).unwrap(); assert!(r == 200); } #[test] fn test_trailing_garbage() { let r = super::parser::parse( r#" block 0 { exit(200); } xxx"#, ); assert!(r.is_err()); } #[test] fn test_print_parsing() { let code = r#" block 0 { print(r0); exit(200); }"#; let expected_block = Instr::Print(Printable::Val(Val::Reg(0)), Box::new(Instr::Exit(Val::Imm(200)) )); assert_code_eq_block(code, expected_block); } #[test] fn test_print_array_parsing() { let code = r#" block 0 { print(array(r0, 6)); exit(200); }"#; let expected_block = Instr::Print(Printable::Array(Val::Reg(0), Val::Imm(6)), Box::new(Instr::Exit(Val::Imm(200)) )); assert_code_eq_block(code, expected_block); } #[test] fn test_exit() { let r = parse_and_eval( r#" block 0 { exit(200); }"#, ).unwrap(); assert!(r == 200); } #[test] fn test_reg_copy() { let r = parse_and_eval( r#" block 0 { r0 = 200; r2 = r0; exit(r2); }"#, ).unwrap(); assert!(r == 200); } #[test] fn test_reg_add() { let r = parse_and_eval( r#" block 0 { r0 = 200; r1 = 11; r3 = r0 + r1; exit(r3); }"#, ).unwrap(); assert!(r == 211); } #[test] fn test_load_store() { let r = parse_and_eval( r#" block 0 { r0 = 200; *r0 = 42; r1 = *r0; exit(r1); }"#, ).unwrap(); assert!(r == 42); } #[test] fn test_goto() { let r = parse_and_eval( r#" block 0 { r2 = 200; goto(10); } block 10 { r2 = r2 + 1; exit(r2); }"#, ).unwrap(); assert!(r == 201); } #[test] fn test_indirect_goto() { let r = parse_and_eval( r#" block 0 { r2 = 200; r3 = 10; goto(r3); } block 10 { r2 = r2 + r3; exit(r2); }"#, ).unwrap(); assert!(r == 210); } #[test] fn test_ifz() { let r = parse_and_eval( r#" block 0 { r2 = 1; ifz r2 { exit(20); } else { exit(30); } }"#, ).unwrap(); assert!(r == 30); } #[test] fn test_fac() { let r = parse_and_eval( r#" block 0 { r2 = 1; r1 = 5; goto(1); } block 1 { ifz r1 { exit(r2); } else { r2 = r2 * r1; r1 = r1 - 1; goto(1); } }"#, ).unwrap(); assert!(r == 120); } #[test] fn test_malloc() { let r = parse_and_eval( r#" block 0 { r0 = malloc(10); exit(r0); }"#, ).unwrap(); assert!(r == 1); } }
use crate::impl_typesystem; use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ArrowTypeSystem { Int32(bool), Int64(bool), UInt32(bool), UInt64(bool), Float32(bool), Float64(bool), Boolean(bool), LargeUtf8(bool), LargeBinary(bool), Date32(bool), Date64(bool), Time64(bool), DateTimeTz(bool), } impl_typesystem! { system = ArrowTypeSystem, mappings = { { Int32 => i32 } { Int64 => i64 } { UInt32 => u32 } { UInt64 => u64 } { Float64 => f64 } { Float32 => f32 } { Boolean => bool } { LargeUtf8 => String } { LargeBinary => Vec<u8> } { Date32 => NaiveDate } { Date64 => NaiveDateTime } { Time64 => NaiveTime } { DateTimeTz => DateTime<Utc> } } }
use crate::player::*; use crate::human::*; pub struct ComputerPlayer { pub name: String, hidden_card: u8, visible_cards_sum: u8, passed: bool, } impl ComputerPlayer { pub fn new(n: &str) -> Self { ComputerPlayer { name: String::from(n), hidden_card: 0, visible_cards_sum: 0, passed: false, } } fn pick_or_pass(&self, p1: u8, p2: u8, p3: u8) -> bool { let score = self.get_score(); if score < 15 { return true } else if score >= 18 { return false } if score >= 15 && score < 19 { if p1 + self.get_hidden_card() >= score || p2 + self.get_hidden_card() >= score || p3 + self.get_hidden_card() >= score { return true } } false } } impl Player for ComputerPlayer { fn take_hidden_card(&mut self, card: u8) { self.hidden_card = card; println!("{}: takes the hidden card ({})", self.name, card); } fn take_visible_card(&mut self, card: u8) { self.visible_cards_sum = card; println!("{}: takes a card {}", self.name, card); } fn get_hidden_card(&self) -> u8 { self.hidden_card } fn get_sum_of_visible_cards(&self) -> u8 { self.visible_cards_sum } fn offer_card(&mut self, human: &HumanPlayer, cp1: &ComputerPlayer, cp2: &ComputerPlayer, _: &ComputerPlayer) -> bool { let resp = self.pick_or_pass(human.get_score(), cp1.get_score(), cp2.get_score()); if !resp { self.passed = resp } resp } }
use std::result::Result; use bytes::{BufMut, BytesMut}; use futures::stream::SplitSink; use futures::{Sink, SinkExt, StreamExt}; use rsocket_rust::{ error::RSocketError, frame::Frame, transport::{Connection, FrameSink, FrameStream}, utils::Writeable, }; use tokio::net::TcpStream; use tokio_tungstenite::MaybeTlsStream; use tokio_tungstenite::{ tungstenite::{Error as WsError, Message}, WebSocketStream, }; #[derive(Debug)] pub struct WebsocketConnection { stream: WebSocketStream<MaybeTlsStream<TcpStream>>, } impl WebsocketConnection { pub(crate) fn new(stream: WebSocketStream<MaybeTlsStream<TcpStream>>) -> WebsocketConnection { WebsocketConnection { stream } } } struct InnerSink(SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>); impl Sink<Frame> for InnerSink { type Error = WsError; fn poll_ready( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), Self::Error>> { self.as_mut().0.poll_ready_unpin(cx) } fn start_send(mut self: std::pin::Pin<&mut Self>, item: Frame) -> Result<(), Self::Error> { let mut b = BytesMut::new(); item.write_to(&mut b); let msg = Message::binary(b.to_vec()); self.as_mut().0.start_send_unpin(msg) } fn poll_flush( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), Self::Error>> { self.as_mut().0.poll_flush_unpin(cx) } fn poll_close( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), Self::Error>> { self.as_mut().0.poll_close_unpin(cx) } } impl Connection for WebsocketConnection { fn split(self) -> (Box<FrameSink>, Box<FrameStream>) { let (sink, stream) = self.stream.split(); ( Box::new(InnerSink(sink).sink_map_err(|e| RSocketError::Other(e.into()))), Box::new(stream.map(|it| match it { Ok(msg) => { let raw = msg.into_data(); let mut bf = BytesMut::new(); bf.put_slice(&raw[..]); match Frame::decode(&mut bf) { Ok(frame) => Ok(frame), Err(e) => Err(RSocketError::Other(e)), } } Err(e) => Err(RSocketError::Other(e.into())), })), ) } }
// This file is part of Substrate. // Copyright (C) 2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use crate::CliConfiguration; use crate::Result; use crate::SubstrateCli; use chrono::prelude::*; use futures::pin_mut; use futures::select; use futures::{future, future::FutureExt, Future}; use log::info; use sc_service::{Configuration, TaskManager, TaskType}; use sp_utils::metrics::{TOKIO_THREADS_ALIVE, TOKIO_THREADS_TOTAL}; use std::marker::PhantomData; #[cfg(target_family = "unix")] async fn main<F, E>(func: F) -> std::result::Result<(), Box<dyn std::error::Error>> where F: Future<Output = std::result::Result<(), E>> + future::FusedFuture, E: 'static + std::error::Error, { use tokio::signal::unix::{signal, SignalKind}; let mut stream_int = signal(SignalKind::interrupt())?; let mut stream_term = signal(SignalKind::terminate())?; let t1 = stream_int.recv().fuse(); let t2 = stream_term.recv().fuse(); let t3 = func; pin_mut!(t1, t2, t3); select! { _ = t1 => {}, _ = t2 => {}, res = t3 => res?, } Ok(()) } #[cfg(not(unix))] async fn main<F, E>(func: F) -> std::result::Result<(), Box<dyn std::error::Error>> where F: Future<Output = std::result::Result<(), E>> + future::FusedFuture, E: 'static + std::error::Error, { use tokio::signal::ctrl_c; let t1 = ctrl_c().fuse(); let t2 = func; pin_mut!(t1, t2); select! { _ = t1 => {}, res = t2 => res?, } Ok(()) } /// Build a tokio runtime with all features pub fn build_runtime() -> std::result::Result<tokio::runtime::Runtime, std::io::Error> { tokio::runtime::Builder::new() .threaded_scheduler() .on_thread_start(|| { TOKIO_THREADS_ALIVE.inc(); TOKIO_THREADS_TOTAL.inc(); }) .on_thread_stop(|| { TOKIO_THREADS_ALIVE.dec(); }) .enable_all() .build() } fn run_until_exit<FUT, ERR>( mut tokio_runtime: tokio::runtime::Runtime, future: FUT, task_manager: TaskManager, ) -> Result<()> where FUT: Future<Output = std::result::Result<(), ERR>> + future::Future, ERR: 'static + std::error::Error, { let f = future.fuse(); pin_mut!(f); tokio_runtime.block_on(main(f)).map_err(|e| e.to_string())?; tokio_runtime.block_on(task_manager.clean_shutdown()); Ok(()) } /// A Substrate CLI runtime that can be used to run a node or a command pub struct Runner<C: SubstrateCli> { config: Configuration, tokio_runtime: tokio::runtime::Runtime, phantom: PhantomData<C>, } impl<C: SubstrateCli> Runner<C> { /// Create a new runtime with the command provided in argument pub fn new<T: CliConfiguration>(cli: &C, command: &T) -> Result<Runner<C>> { let tokio_runtime = build_runtime()?; let runtime_handle = tokio_runtime.handle().clone(); let task_executor = move |fut, task_type| match task_type { TaskType::Async => runtime_handle.spawn(fut).map(drop), TaskType::Blocking => runtime_handle.spawn_blocking(move || futures::executor::block_on(fut)).map(drop), }; Ok(Runner { config: command.create_configuration(cli, task_executor.into())?, tokio_runtime, phantom: PhantomData, }) } /// Log information about the node itself. /// /// # Example: /// /// ```text /// 2020-06-03 16:14:21 Substrate Node /// 2020-06-03 16:14:21 ✌️ version 2.0.0-rc3-f4940588c-x86_64-linux-gnu /// 2020-06-03 16:14:21 ❤️ by Parity Technologies <admin@parity.io>, 2017-2020 /// 2020-06-03 16:14:21 📋 Chain specification: Flaming Fir /// 2020-06-03 16:14:21 🏷 Node name: jolly-rod-7462 /// 2020-06-03 16:14:21 👤 Role: FULL /// 2020-06-03 16:14:21 💾 Database: RocksDb at /tmp/c/chains/flamingfir7/db /// 2020-06-03 16:14:21 ⛓ Native runtime: node-251 (substrate-node-1.tx1.au10) /// ``` fn print_node_infos(&self) { info!("{}", C::impl_name()); info!("✌️ version {}", C::impl_version()); info!("❤️ by {}, {}-{}", C::author(), C::copyright_start_year(), Local::today().year(),); info!("📋 Chain specification: {}", self.config.chain_spec.name()); info!("🏷 Node name: {}", self.config.network.node_name); info!("👤 Role: {}", self.config.display_role()); info!( "💾 Database: {} at {}", self.config.database, self.config .database .path() .map_or_else(|| "<unknown>".to_owned(), |p| p.display().to_string()) ); info!("⛓ Native runtime: {}", C::native_runtime_version(&self.config.chain_spec)); } /// A helper function that runs a node with tokio and stops if the process receives the signal /// `SIGTERM` or `SIGINT`. pub fn run_node_until_exit( mut self, initialise: impl FnOnce(Configuration) -> sc_service::error::Result<TaskManager>, ) -> Result<()> { self.print_node_infos(); let mut task_manager = initialise(self.config)?; let res = self.tokio_runtime.block_on(main(task_manager.future().fuse())); self.tokio_runtime.block_on(task_manager.clean_shutdown()); res.map_err(|e| e.to_string().into()) } /// A helper function that runs a command with the configuration of this node pub fn sync_run(self, runner: impl FnOnce(Configuration) -> Result<()>) -> Result<()> { runner(self.config) } /// A helper function that runs a future with tokio and stops if the process receives /// the signal SIGTERM or SIGINT pub fn async_run<FUT>( self, runner: impl FnOnce(Configuration) -> Result<(FUT, TaskManager)>, ) -> Result<()> where FUT: Future<Output = Result<()>>, { let (future, task_manager) = runner(self.config)?; run_until_exit(self.tokio_runtime, future, task_manager) } /// Get an immutable reference to the node Configuration pub fn config(&self) -> &Configuration { &self.config } /// Get a mutable reference to the node Configuration pub fn config_mut(&mut self) -> &mut Configuration { &mut self.config } }
extern crate iron; extern crate time; extern crate alpaca_client; use iron::prelude::*; use iron::{typemap, AfterMiddleware, BeforeMiddleware}; use time::{OffsetDateTime}; mod trading_strategy; mod momentum; mod index_funding_balancing; struct ResponseTime; struct Health { status: String } impl typemap::Key for ResponseTime { type Value = u64; } impl BeforeMiddleware for ResponseTime { fn before(&self, req: &mut Request) -> IronResult<()> { let t = OffsetDateTime::now_utc() - OffsetDateTime::unix_epoch(); req.extensions.insert::<ResponseTime>(t.whole_milliseconds() as u64); Ok(()) } } impl AfterMiddleware for ResponseTime { fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> { let t = OffsetDateTime::now_utc() - OffsetDateTime::unix_epoch(); let delta = t.whole_milliseconds() as u64 - *req.extensions.get::<ResponseTime>().unwrap(); println!("Request took: {} ms", (delta as f64)); Ok(res) } } fn health(_: &mut Request) -> IronResult<Response> { let health = Health { status: String::from("up") }; Ok(Response::with((iron::status::Ok, "status: ".to_owned() + &*health.status))) } fn main() { let mut chain = Chain::new(health); chain.link_before(ResponseTime); chain.link_after(ResponseTime); Iron::new(chain).http("127.0.0.1:3000").unwrap(); }
/// https://www.bilibili.com/video/BV1rK4y1p79j/?spm_id_from=333.788.b_7265636f5f6c697374.2 mod facts; use datafrog::{Iteration, Relation, RelationLeaper}; use facts::{ Point, Variable_or_field}; fn main() { let mut iteration = Iteration::new(); // line 1: b= new C(); // line 3: c= new C(); let new: Relation<(Variable_or_field, Point)> = vec![ (Variable_or_field::variable('b' ), Point::from(1)), (Variable_or_field::variable('c' ), Point::from(3)), ] .iter() .collect(); // line 2: a=b; // line 5: d=c; let assign: Relation<(Variable_or_field, Variable_or_field)> = vec![ (Variable_or_field::variable('b' ), Variable_or_field::variable('a' )), (Variable_or_field::variable('c' ), Variable_or_field::variable('d' )), ] .iter() .collect(); // line 4: c.f=a; // line 6: c.f=d; let store: Relation<(Variable_or_field,(char,Variable_or_field))> = vec![ (Variable_or_field::variable('c'),('f',Variable_or_field::variable('a'))), (Variable_or_field::variable('c'),('f',Variable_or_field::variable('d'))), ] .iter() .collect(); // line 7: e=d.f; let load: Relation<( Variable_or_field,(char,Variable_or_field))> = vec![ (Variable_or_field::variable('d'),('f',Variable_or_field::variable('e'))) ] .iter() .collect(); let pt = iteration.variable::<(Variable_or_field, Point)>("pt"); pt.extend(new.iter()); let edge = iteration.variable::<(Variable_or_field, Variable_or_field)>("edge"); edge.extend(assign.iter()); // temp1 let t1=iteration.variable::<(Variable_or_field,(Point,char))>("t1"); // temp2 let t2=iteration.variable::<(Variable_or_field,Variable_or_field)>("t2"); while iteration.changed() { // pt(x,oi):- pt(y,oi), edge(y,x)). pt.from_join(&pt,&edge,|&_y,&o,&x|(x,o)); // t1(p1,f,y) :- pt(pi,x) , x=f.y. t1.from_leapjoin(&pt,store.extend_with(|&(x,p)| x),|&(x,p),&(c,y)|(y,(p,c)) ); // pt(oi.f,oj) :- t1(y,(oi,f)), pt(y,oj). pt.from_join(&t1,&pt,|&_y,&(oi,f),&oj| (Variable_or_field::field(oi,f),oj)); edge.from_join(&pt,&store,|&_x,&o,&(f,y)| (y,Variable_or_field::field(o,f))); // t2((oi,f),y) :- pt(oi,x),y=x.f. t2.from_leapjoin(&pt,load.extend_with(|&(x,_p)|x),|&(_x,p),&(f,y)| (Variable_or_field::field(p,f),y)); // pt(y,oj):- t2((oi,f),y),pt((oi,f),oj). pt.from_join(&t2,&pt,|&_z,&y,&oj|(y,oj)); edge.from_join(&pt,&load,|&_x,&o,&(f,y)|(Variable_or_field::field(o,f),y)); } let x = pt.complete(); println!("{}", x.elements.len()); println!("{:?}", x.elements); let e=edge.complete(); println!("{}", e.elements.len()); println!("{:?}", e.elements); } // b=new C(); // a=b; // c=new C(); // c.f=a; // d=c; // c.f=d; // e=d.f // // {o1} {o1} // |-----a <------b // {o1,o3} {o1,o3} | // e <----- o3.f <----| // | // |-----d <------c // {o3} {o3} //
use libc::{c_char, c_int, c_void}; use munge_sys::{munge_decode, munge_encode, munge_free, munge_strerror, MungeErr}; use std::{ borrow::{Cow, ToOwned}, convert::TryInto, ffi::{CStr, CString}, ops::Not, *, }; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Credential { uid: u32, gid: u32, payload: Option<Vec<u8>>, } impl Credential { #[inline] pub fn uid(self: &'_ Self) -> u32 { self.uid } #[inline] pub fn gid(self: &'_ Self) -> u32 { self.gid } #[inline] pub fn payload(self: &'_ Self) -> Option<&'_ [u8]> { self.payload.as_ref().map(Vec::as_slice) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MungeError { Snafu, BadArg, BadLength, Overflow, NoMemory, Socket, Timeout, BadCred, BadVersion, BadCipher, BadMac, BadZip, BadRealm, CredInvalid, CredExpired, CredRewound, CredReplayed, CredUnauthorized, } impl fmt::Display for MungeError { fn fmt(self: &'_ Self, stream: &'_ mut fmt::Formatter<'_>) -> fmt::Result { self.with_str(|s| write!(stream, "{}", s)) } } impl error::Error for MungeError {} impl MungeError { pub fn with_str<R, F>(self: &'_ Self, f: F) -> R where F: FnOnce(Cow<str>) -> R, { let errno = self.to_number(); let slice = unsafe { CStr::from_ptr(munge_strerror(errno)) }; f(slice.to_string_lossy()) } #[inline] pub fn to_string(self: &'_ Self) -> String { self.with_str(|s| s.into_owned()) } pub fn to_number(self: &'_ Self) -> MungeErr::Type { match *self { MungeError::Snafu => MungeErr::SNAFU, MungeError::BadArg => MungeErr::BAD_ARG, MungeError::BadLength => MungeErr::BAD_LENGTH, MungeError::Overflow => MungeErr::OVERFLOW, MungeError::NoMemory => MungeErr::NO_MEMORY, MungeError::Socket => MungeErr::SOCKET, MungeError::Timeout => MungeErr::TIMEOUT, MungeError::BadCred => MungeErr::BAD_CRED, MungeError::BadVersion => MungeErr::BAD_VERSION, MungeError::BadCipher => MungeErr::BAD_CIPHER, MungeError::BadMac => MungeErr::BAD_MAC, MungeError::BadZip => MungeErr::BAD_ZIP, MungeError::BadRealm => MungeErr::BAD_REALM, MungeError::CredInvalid => MungeErr::CRED_INVALID, MungeError::CredExpired => MungeErr::CRED_EXPIRED, MungeError::CredRewound => MungeErr::CRED_REWOUND, MungeError::CredReplayed => MungeErr::CRED_REPLAYED, MungeError::CredUnauthorized => MungeErr::CRED_UNAUTHORIZED, } } pub fn try_from_number(number: MungeErr::Type) -> Option<Self> { Some(match number { MungeErr::SNAFU => MungeError::Snafu, MungeErr::BAD_ARG => MungeError::BadArg, MungeErr::BAD_LENGTH => MungeError::BadLength, MungeErr::OVERFLOW => MungeError::Overflow, MungeErr::NO_MEMORY => MungeError::NoMemory, MungeErr::SOCKET => MungeError::Socket, MungeErr::TIMEOUT => MungeError::Timeout, MungeErr::BAD_CRED => MungeError::BadCred, MungeErr::BAD_VERSION => MungeError::BadVersion, MungeErr::BAD_CIPHER => MungeError::BadCipher, MungeErr::BAD_MAC => MungeError::BadMac, MungeErr::BAD_ZIP => MungeError::BadZip, MungeErr::BAD_REALM => MungeError::BadRealm, MungeErr::CRED_INVALID => MungeError::CredInvalid, MungeErr::CRED_EXPIRED => MungeError::CredExpired, MungeErr::CRED_REWOUND => MungeError::CredRewound, MungeErr::CRED_REPLAYED => MungeError::CredReplayed, MungeErr::CRED_UNAUTHORIZED => MungeError::CredUnauthorized, _ => return None, }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Error { MungeError(MungeError), InvalidUtf8, InnerNull, } impl From<MungeError> for Error { #[inline] fn from(munge_error: MungeError) -> Error { Error::MungeError(munge_error) } } impl fmt::Display for Error { fn fmt(self: &'_ Self, stream: &'_ mut fmt::Formatter<'_>) -> fmt::Result { match *self { Error::MungeError(ref munge_err) => write!(stream, "munge errored: {}", munge_err,), Error::InvalidUtf8 => write!( stream, "C string to Rust string lift failed: got non UTF8 output", ), Error::InnerNull => write!( stream, "Rust string to C string lift failed: input had inner null", ), } } } impl error::Error for Error { fn source(self: &'_ Self) -> Option<&'_ (dyn error::Error + 'static)> { if let &Error::MungeError(ref munge_error) = self { Some(munge_error as _) } else { None } } } pub fn encode(payload: Option<&'_ [u8]>) -> Result<String, Error> { let mut cred: *const c_char = std::ptr::null(); let (payload_ptr, payload_len) = if let Some(payload) = payload { ( payload.as_ptr() as *const c_void, payload.len().try_into().expect("payload length overflow"), ) } else { (ptr::null(), 0) }; let result = unsafe { munge_encode(&mut cred, std::ptr::null_mut(), payload_ptr, payload_len) }; ::scopeguard::defer!(unsafe { munge_free(cred as *mut c_void); }); if result != MungeErr::SUCCESS { return Err(MungeError::try_from_number(result).unwrap().into()); } else { assert!(cred.is_null().not()); } let owned_cred = String::from_utf8( // convert to an owned `String`, but including the final nul byte unsafe { CStr::from_ptr(cred) } .to_bytes_with_nul() .to_owned(), ) .map_err(|_| Error::InvalidUtf8)?; Ok(owned_cred) } pub fn decode(cred: impl Into<String> + AsRef<str>) -> Result<Credential, Error> { let mut ret = Credential::default(); let mut payload_ptr: *mut c_void = std::ptr::null_mut(); let mut payload_length: c_int = 0; let buffer: CString; let cred: &CStr = match cred.as_ref().bytes().position(|x| x == b'\0') { None => { let mut bytes = <Vec<u8> as From<String>>::from(cred.into()); bytes.reserve_exact(1); bytes.push(b'\0'); buffer = unsafe { CString::from_vec_unchecked(bytes) }; &*buffer } Some(len) if len + 1 >= cred.as_ref().len() => unsafe { CStr::from_bytes_with_nul_unchecked(cred.as_ref().as_bytes()) }, _ => { return Err(Error::InnerNull); } }; let result = unsafe { munge_decode( cred.as_ptr() as *const c_char, std::ptr::null_mut(), &mut payload_ptr, &mut payload_length, &mut ret.uid, &mut ret.gid, ) }; ::scopeguard::defer!(unsafe { munge_free(payload_ptr); }); if result != MungeErr::SUCCESS { return Err(MungeError::try_from_number(result).unwrap().into()); } if payload_ptr.is_null().not() { ret.payload = Some( unsafe { slice::from_raw_parts( payload_ptr as *const u8, payload_length.try_into().expect("Got payload_length < 0"), ) } .to_owned(), ); } Ok(ret) } #[cfg(test)] mod tests { use super::{decode, encode, MungeError}; #[test] fn test_that_mungeerror_works() { assert_eq!(MungeError::Snafu.to_string(), "Internal error"); assert_eq!(MungeError::BadArg.to_string(), "Invalid argument"); } #[test] fn test_that_encode_decode_round_trip_without_payload_works() { let message = decode(&encode(None).unwrap()).unwrap(); assert_eq!(message.payload, None); assert!(message.uid > 0); assert!(message.gid > 0); } #[test] fn test_that_encode_decode_round_trip_with_payload_works() { let orig_payload = &b"abc"[..]; let message = decode(&encode(Some(orig_payload)).unwrap()).unwrap(); let payload = message.payload(); assert_eq!(payload, Some(orig_payload)); assert!(message.uid() > 0); assert!(message.gid() > 0); } }
use crate::util; use regex::Regex; use std::collections::HashMap; use std::collections::VecDeque; pub fn solve() { let input_file = "input-day-9.txt"; println!("Day 9 answers"); print!(" first puzzle: "); let answer1 = solve_file(input_file, 1); println!("{}", answer1); print!(" second puzzle: "); let answer2 = solve_file(input_file, 100); println!("{}", answer2); } fn solve_file(input: &str, marbles_factor: usize) -> usize { let v = util::aoc2018_row_file_to_vector(input); solve_puzzle(&v, marbles_factor) } fn solve_puzzle(str_vector: &[String], marble_factor: usize) -> usize { let (players, mut marbles) = shared_puzzle_start(str_vector); marbles *= marble_factor; let mut player_score: HashMap<usize, usize> = HashMap::new(); let mut circle: VecDeque<usize> = VecDeque::with_capacity(marbles); let mut marble_val = 0; circle.push_front(marble_val); marble_val += 1; 'outer: loop { for p in 0..players { if marble_val % 23 != 0 { for _rot_step in 0..2 { let rot_marble = circle.pop_front().expect("Ain't popping"); circle.push_back(rot_marble); } circle.push_front(marble_val); } else { for _rot_step in 0..6 { // Other way now let rot_marble = circle.pop_back().expect("Ain't popping right..."); circle.push_front(rot_marble); } let removed_marble_val = circle.pop_back().unwrap(); let round_points = removed_marble_val + marble_val; player_score .entry(p) .and_modify(|e| *e += round_points) .or_insert(round_points); } marble_val += 1; if marble_val > marbles { break 'outer; } } } let mut max_score = 0; for (_k, v) in player_score { if v > max_score { max_score = v; }; } max_score } fn shared_puzzle_start(str_vector: &[String]) -> (usize, usize) { if str_vector.len() != 1 { panic!("One-liners, if you please"); } let line = &str_vector[0]; let re = Regex::new(r"^(\d+) players; last marble is worth (\d+) points$").unwrap(); let caps = re.captures(&line).unwrap(); let a: usize = caps[1].parse().expect("Not an integer"); let b: usize = caps[2].parse().expect("Not an integer"); (a, b) } #[cfg(test)] mod tests { use super::*; #[test] fn test_day_9_first() { let deps = vec![String::from("9 players; last marble is worth 25 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 32); let deps = vec![String::from("10 players; last marble is worth 1618 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 8317); let deps = vec![String::from("13 players; last marble is worth 7999 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 146373); let deps = vec![String::from("17 players; last marble is worth 1104 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 2764); let deps = vec![String::from("21 players; last marble is worth 6111 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 54718); let deps = vec![String::from("30 players; last marble is worth 5807 points")]; let a1 = solve_puzzle(&deps, 1); assert_eq!(a1, 37305); } }
use syn::parse_quote_spanned; use super::{ FlowProperties, FlowPropertyVal, OperatorCategory, OperatorConstraints, WriteContextArgs, RANGE_0, RANGE_1, }; use crate::graph::OperatorInstance; /// > 0 input streams, 1 output stream /// /// > Arguments: None. /// /// Emits a single unit `()` at the start of the first tick. /// /// ```hydroflow /// initialize() /// -> assert_eq([()]); /// ``` pub const INITIALIZE: OperatorConstraints = OperatorConstraints { name: "initialize", categories: &[OperatorCategory::Source], hard_range_inn: RANGE_0, soft_range_inn: RANGE_0, hard_range_out: RANGE_1, soft_range_out: RANGE_1, num_args: 0, persistence_args: RANGE_0, type_args: RANGE_0, is_external_input: false, ports_inn: None, ports_out: None, properties: FlowProperties { deterministic: FlowPropertyVal::Yes, monotonic: FlowPropertyVal::Yes, inconsistency_tainted: false, }, input_delaytype_fn: |_| None, write_fn: |wc @ &WriteContextArgs { op_span, .. }, diagnostics| { let wc = WriteContextArgs { op_inst: &OperatorInstance { arguments: parse_quote_spanned!(op_span=> [()]), ..wc.op_inst.clone() }, ..wc.clone() }; (super::source_iter::SOURCE_ITER.write_fn)(&wc, diagnostics) }, };
fn run() -> std::io::Result<()> { let cmd = std::env::var("OCAML").unwrap_or("ocaml".to_string()); let output = std::process::Command::new(cmd) .arg("version.ml") .arg(std::env::var("OUT_DIR").unwrap()) .output()?; let output = String::from_utf8(output.stdout).unwrap(); let split: Vec<&str> = output.split('.').collect(); let major = split[0].parse::<usize>().unwrap(); let minor = split[1].parse::<usize>().unwrap(); if major >= 4 && minor >= 10 { println!("cargo:rustc-cfg=caml_state"); } Ok(()) } fn main() { let _ = run(); }
// q0070_runclimbing_stairs struct Solution; // impl Solution { // pub fn climb_stairs(n: i32) -> i32 { // if n == 1 { // return 1; // } else if n == 2 { // return 2; // } else { // return Solution::climb_stairs(n - 1) + Solution::climb_stairs(n - 2); // } // } // } impl Solution { pub fn climb_stairs(n: i32) -> i32 { let mut buf = vec![0; n as usize]; Solution::climb(n as usize, &mut buf) } fn climb(n: usize, buf: &mut Vec<i32>) -> i32 { if n == 1 { return 1; } else if n == 2 { return 2; } else { if buf[n - 1] == 0 { buf[n - 1] = Solution::climb(n - 1, buf) + Solution::climb(n - 2, buf); } return buf[n - 1]; } } } #[cfg(test)] mod tests { use super::Solution; #[test] fn it_works() { let ret = [ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, ]; for (i, o) in (1..=20).into_iter().zip(ret.into_iter().cloned()) { assert_eq!(o, Solution::climb_stairs(i)); } } }
mod q01dair1q; fn main () { q01dair1q::hello(); }
mod print; //mod to call the script fn main() { print::run(); //script::function }
use ast::Ast; use ast::lang_result::LangError; use nom::IResult; use parser::program; use std::io::prelude::*; use std::io::BufReader; use std::fs::OpenOptions; use std::error::Error; pub fn read_file_into_ast(filename: String) -> Result<Ast, LangError> { match OpenOptions::new().read(true).open(&filename) { Ok(file) => { let mut file_contents: String = String::new(); let mut buf_reader = BufReader::new(&file); match buf_reader.read_to_string(&mut file_contents) { Ok(_) => {} Err(e) => { return Err(LangError::CouldNotReadFile { filename: filename, reason: e.description().to_string(), }) } } match program(file_contents.as_bytes()) { IResult::Done(_, ast) => return Ok(ast), IResult::Error(e) => Err(LangError::CouldNotParseFile { filename: filename, reason: e.description().to_string(), }), IResult::Incomplete(_) => Err(LangError::CouldNotParseFile { filename: filename, reason: "Incomplete parse".to_string(), }), } } Err(e) => { return Err(LangError::CouldNotReadFile { filename: filename, reason: e.description().to_string(), }) } } }
// Copyright 2018-2020 argmin developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Utility functions use ndarray_rand::RandomExt; use rand::distributions::Uniform; use rand::prelude::*; use std::iter::FromIterator; /// Computes the Eigenvalues of a 2x2 matrix pub fn eigenvalues_2x2(mat: &ndarray::ArrayView2<f64>) -> (f64, f64) { let a = mat[(0, 0)]; let b = mat[(0, 1)]; let c = mat[(1, 0)]; let d = mat[(1, 1)]; let tmp = ((-(a + d) / 2.0).powi(2) - a * d + b * c).sqrt(); let l1 = (a + d) / 2.0 + tmp; let l2 = (a + d) / 2.0 - tmp; // if l1.abs() > l2.abs() { if l1 > l2 { (l1, l2) } else { (l2, l1) } } /// Swaps columns `idx1` and `idx2` of matrix `mat` pub fn swap_columns<T>(mat: &mut ndarray::Array2<T>, idx1: usize, idx2: usize) where ndarray::OwnedRepr<T>: ndarray::Data, { let s = mat.raw_dim(); for i in 0..s[0] { mat.swap((i, idx1), (i, idx2)); } } /// Swaps rows `idx1` and `idx2` of matrix `mat` pub fn swap_rows<T>(mat: &mut ndarray::Array2<T>, idx1: usize, idx2: usize) where ndarray::OwnedRepr<T>: ndarray::Data, { let s = mat.raw_dim(); for i in 0..s[1] { mat.swap((idx1, i), (idx2, i)); } } /// Returns the index of the largest element in a 1D array pub fn index_of_largest<'a, T>(c: &ndarray::ArrayView1<T>) -> usize where <ndarray::ViewRepr<&'a T> as ndarray::RawData>::Elem: std::cmp::PartialOrd + num::traits::Signed + Clone, { // let mut max = num::abs(c[0].clone()); let mut max = c[0].clone(); let mut max_idx = 0; c.iter() .enumerate() .map(|(i, ci)| { // let ci = num::abs(ci.clone()); let ci = ci.clone(); if ci > max { max = ci; max_idx = i } }) .count(); max_idx } /// Returns the index of the element with the largest absolute value in a 1D array pub fn index_of_largest_abs<'a, T>(c: &ndarray::ArrayView1<T>) -> usize where <ndarray::ViewRepr<&'a T> as ndarray::RawData>::Elem: std::cmp::PartialOrd + num::traits::Signed + Clone, { let mut max = num::abs(c[0].clone()); let mut max_idx = 0; c.iter() .enumerate() .map(|(i, ci)| { let ci = num::abs(ci.clone()); if ci > max { // if (ci - max) > T::from(std::f64::EPSILON * 1000000.0).unwrap() { // if (ci - max) > T::from(0.1).unwrap() { max = ci; max_idx = i } }) .count(); max_idx } /// Returns the permutation matrix for a vector of permuted indices pub fn index_to_permutation_mat(idxs: &[usize]) -> ndarray::Array2<f64> { let n = idxs.len(); let mut mat = ndarray::Array2::zeros((n, n)); for i in 0..n { mat[(i, idxs[i])] = 1.0; } mat } /// Builds a diagonal matrix from a 1D slice pub fn diag_mat_from_arr<T>(arr: &[T]) -> ndarray::Array2<T> where T: Clone + num::traits::identities::Zero, { let n = arr.len(); let mut mat: ndarray::Array2<T> = ndarray::Array2::zeros((n, n)); let diag: ndarray::Array1<T> = ndarray::Array::from_iter(arr.into_iter().cloned()); mat.diag_mut().assign(&diag); mat } /// Returns a random Householder matrix of dimension `dim` and with seed `seed`. pub fn random_householder(dim: usize, seed: u8) -> ndarray::Array2<f64> { // dear god I just want some random numbers with a given seed.... let mut rng = rand_xorshift::XorShiftRng::from_seed([seed; 16]); let w = ndarray::Array::random_using((dim, 1), Uniform::new_inclusive(-1.0, 1.0), &mut rng); let denom = w.fold(0.0, |acc, &x: &f64| acc + x.powi(2)); ndarray::Array::eye(dim) - 2.0 / denom * w.dot(&w.t()) } /// Returns a random diagonal matrix with Eigenvalues inbetween `eig_range_min` and /// `eig_range_max`. The minimum number of negative eigenvalues can be specified with /// `min_neg_eigenvalues`. Takes a `seed for random values`. pub fn random_diagonal( dim: usize, (eig_range_min, eig_range_max): (f64, f64), min_neg_eigenvalues: usize, seed: u8, ) -> ndarray::Array2<f64> { let mut rng = rand_xorshift::XorShiftRng::from_seed([seed; 16]); let mut w = ndarray::Array::random_using( dim, Uniform::new_inclusive(eig_range_min, eig_range_max), &mut rng, ); let mut idxs: Vec<usize> = (0..dim).collect(); for _ in 0..min_neg_eigenvalues { let idxidx: usize = (rng.gen::<f64>() * (idxs.len() - 1) as f64).floor() as usize; let idx = idxs.remove(idxidx); w[idx] = rng.gen::<f64>() - 1.0; } let mut out = ndarray::Array::eye(dim); out.diag_mut().assign(&w); out } #[cfg(test)] mod tests { use super::*; use approx::AbsDiffEq; #[test] fn test_swap_columns() { let mut a: ndarray::Array2<i64> = ndarray::arr2(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]); super::swap_columns(&mut a, 1, 2); let c: ndarray::Array2<i64> = ndarray::arr2(&[[1, 3, 2], [4, 6, 5], [7, 9, 8]]); a.iter() .zip(c.iter()) .map(|(x, y)| assert_eq!(*x, *y)) .count(); // this should work, but it doesn't. // assert_eq!(b, c); } #[test] fn test_swap_rows() { let mut a: ndarray::Array2<i64> = ndarray::arr2(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]); super::swap_rows(&mut a, 1, 2); let c: ndarray::Array2<i64> = ndarray::arr2(&[[1, 2, 3], [7, 8, 9], [4, 5, 6]]); a.iter() .zip(c.iter()) .map(|(x, y)| assert_eq!(*x, *y)) .count(); // this should work, but it doesn't. // assert_eq!(b, c); } #[test] fn test_swap_rows_and_columns() { let mut a: ndarray::Array2<i64> = ndarray::arr2(&[[1, 2, 3], [4, 5, 6], [7, 8, 9]]); super::swap_rows(&mut a, 1, 2); super::swap_columns(&mut a, 1, 2); let c: ndarray::Array2<i64> = ndarray::arr2(&[[1, 3, 2], [7, 9, 8], [4, 6, 5]]); a.iter() .zip(c.iter()) .map(|(x, y)| assert_eq!(*x, *y)) .count(); // this should work, but it doesn't. // assert_eq!(b, c); } #[test] fn test_biggest_index() { use ndarray::s; let j = 1; let a: ndarray::Array2<i64> = ndarray::arr2(&[[1, 2, 3, 0], [4, 2, 6, 0], [7, 8, 3, 0], [3, 4, 2, 8]]); let idx = super::index_of_largest(&a.diag().slice(s![j..])); assert_eq!(idx + j, 3); } #[test] fn test_biggest_index_abs() { use ndarray::s; let j = 1; let a: ndarray::Array2<f64> = ndarray::arr2(&[ [1.0, 2.0, 3.0, 0.0], [4.0, 2.0, 6.0, 0.0], [7.0, 8.0, 3.0, 0.0], [3.0, 4.0, 2.0, -8.0], ]); let idx = super::index_of_largest_abs(&a.diag().slice(s![j..])); assert_eq!(idx + j, 3); } #[test] fn test_rand_householder() { let q = random_householder(2, 84); let res: ndarray::Array2<f64> = ndarray::arr2(&[ [-0.0000034067079459632055, -0.9999999999941971], [-0.9999999999941971, 0.0000034067079460742278], ]); assert!(q.abs_diff_eq(&res, 1e-19)); } #[test] fn test_random_diagonal_all_pos() { let d = random_diagonal(2, (-1.0, 1.0), 0, 128); let res: ndarray::Array2<f64> = ndarray::arr2(&[[0.003923416145884984, 0.0], [0.0, 0.0039215684018965025]]); assert!(d.abs_diff_eq(&res, 1e-19)); } #[test] fn test_random_diagonal_one_neg() { let d = random_diagonal(2, (-1.0, 1.0), 1, 128); let res: ndarray::Array2<f64> = ndarray::arr2(&[[-0.49803921207376156, 0.0], [0.0, 0.0039215684018965025]]); assert!(d.abs_diff_eq(&res, 1e-19)); } }
#[macro_use] extern crate log; extern crate env_logger; #[macro_use] extern crate serde_derive; extern crate toml; extern crate gpgme; extern crate walkdir; extern crate clipboard; #[cfg(test)] extern crate tempfile; extern crate secstr; extern crate sha1; extern crate knock; mod config; mod password; mod gpg; mod pwned; pub use password::{ClearPassword, PasswordEdit}; use clipboard::ClipboardProvider; use clipboard::x11_clipboard::{X11ClipboardContext, Primary, Clipboard}; use config::Config; use gpg::GPG; use password::EncryptedPassword; use std::fs::{DirBuilder, metadata}; use std::io; use std::io::{Read, Write, stdout}; use std::os::unix::fs::DirBuilderExt; use std::path::{PathBuf, Path}; use std::process::{Command, Stdio}; use std::{thread, time}; use std::error::Error; use std::fmt::{self, Display, Formatter}; use walkdir::WalkDir; pub use config::NoConfig; static PASSWORDS_DIR_NAME: &'static str = "passwords"; pub static PROTECTED_MODE: u32 = 0o700; // Error type used for custom error strings. #[derive(Debug)] struct CustomErrorMessage(String); impl Error for CustomErrorMessage { fn description(&self) -> &str { "A custom error message" } } impl Display for CustomErrorMessage { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl CustomErrorMessage { fn boxed(msg: String) -> Box<Self> { Box::new(CustomErrorMessage(msg)) } } /// The "god struct". pub struct Tabr { config: Config, state_dir: PathBuf, gnupg_home: Option<PathBuf>, } impl Tabr { pub fn new(state_dir: PathBuf, gnupg_home: Option<PathBuf>) -> Result<Self, Box<Error>> { // Scaffold directories if necessary. let passwords_dir = Self::_passwords_dir(&state_dir); if !passwords_dir.exists() { info!("Creating: {:?}", passwords_dir); DirBuilder::new() .recursive(true) .mode(PROTECTED_MODE) .create(passwords_dir.as_path())?; } else { Self::check_secure(passwords_dir.as_path()); } Ok(Self { config: Config::new(&state_dir)?, state_dir: state_dir, gnupg_home, }) } /// Checks that the given path has secure mode. pub fn check_secure(path: &Path) { use std::os::unix::fs::PermissionsExt; const SECURE_PERMS: u32 = 0o700; const MODE_PERMS_MASK: u32 = 0o777; let res = metadata(path); if let Ok(md) = res { let mode = md.permissions().mode(); if mode & MODE_PERMS_MASK != SECURE_PERMS { eprintln!("warning: path {} has wrong permissions (should be 700)", path.display()); } } } /// Apply the function `f` to each password in the password directory. The closure is passed /// the path to each password file. fn map_password_ids<F>(&self, f: F) -> Result<(), Box<Error>> where F: Fn(&str) -> Result<(), Box<Error>> { let passwords_dir = self.passwords_dir(); let itr = WalkDir::new(&passwords_dir); for path in itr { let mut f_res = Ok(()); path.map(|entry| { let path = entry.path(); Self::check_secure(path); if !path.is_dir() { let stripped = path.strip_prefix(&passwords_dir).unwrap(); f_res = f(stripped.to_str().unwrap().trim_end_matches(".toml")); } })?; f_res?; } Ok(()) } /// The same as `map_password_ids`, but mutably borrows the environment. /// Public for testing. pub fn map_password_ids_mut<F>(&self, mut f: F) -> Result<(), Box<Error>> where F: FnMut(&str) -> Result<(), Box<Error>> { let passwords_dir = self.passwords_dir(); let itr = WalkDir::new(&passwords_dir); for path in itr { let mut f_res = Ok(()); path.map(|entry| { let path = entry.path(); Self::check_secure(path); if !path.is_dir() { let stripped = path.strip_prefix(&passwords_dir).unwrap(); f_res = f(stripped.to_str().unwrap().trim_end_matches(".toml")); } })?; f_res?; } Ok(()) } /// List passwords to stdout. /// If `verbose` is true, meta-data is also printed. pub fn list_passwords(&self, verbose: bool) -> Result<(), Box<Error>> { self.map_password_ids(|pwid| { println!("{}", pwid); if verbose { let pw = EncryptedPassword::from_file(self.password_path(pwid)) .map_err(|e| format!("Failed to load password '{}' from file: {}.", pwid, e))?; println!(" username: {}", pw.username().unwrap_or("")); println!(" email : {}", pw.email().unwrap_or("")); println!(" comment : {}\n", pw.comment().unwrap_or("")); } Ok(()) }).map_err(|e| CustomErrorMessage::boxed(format!("Failed to list passwords: {}.", e)) as Box<Error>) } fn load_password(&self, pwid: &str) -> Result<EncryptedPassword, Box<Error>> { let path = self.password_path(pwid); Self::check_secure(path.as_path()); Ok(EncryptedPassword::from_file(path)?) } fn get_clear_password(&mut self, pwid: &str) -> Result<ClearPassword, String> { info!("Loading and decrypting password '{}'", pwid); let epw = self.load_password(pwid) .map_err(|e| format!("Failed to load password '{}': {}", pwid, e))?; let mut gpg = GPG::new(self.gnupg_home.clone()); let cpw = epw.decrypt(&mut gpg) .map_err(|e| format!("Failed to decrypt password '{}': {}", pwid, e))?; Ok(cpw) } /// Print a password string in the clear to stdout. pub fn stdout(&mut self, pwid: &str) -> Result<(), Box<Error>> { let pw = self.get_clear_password(pwid)?; println!("{}", String::from_utf8(pw.clear_text().unsecure().to_vec())?); Ok(()) } /// Gets the path to the password file from the given password ID. fn password_path(&self, pwid: &str) -> PathBuf { let mut full_path = self.passwords_dir(); full_path.push(pwid); full_path.set_extension("toml"); full_path } /// Add a new password into the password directory with the given password ID. pub fn add_password(&mut self, pwid: &str, pw: ClearPassword) -> Result<(), Box<Error>> { info!("Adding password '{}'", pwid); let full_path = self.password_path(pwid); if full_path.exists() { return Err(CustomErrorMessage::boxed(format!("Password '{}' already exists", pwid))); } let dir = full_path.clone(); let dir_p = dir.parent().unwrap(); // Create intermediate directories (if necessary). let res = DirBuilder::new() .recursive(true) .mode(PROTECTED_MODE) .create(dir_p); if let Err(e) = res { let msg = format!("Create directory '{}' failed: {}", dir_p.display(), e); return Err(CustomErrorMessage::boxed(msg)); } // And commit to disk. let mut gpg = GPG::new(self.gnupg_home.clone()); let epw = pw.encrypt(&mut gpg, &self.config.encrypt_to()) .map_err(|e| format!("Failed to encrypt: {}", e))?; epw.to_disk(full_path, true) .map_err(|e| format!("Failed to write pasword file: {}", e))?; Ok(()) } pub fn passwords_dir(&self) -> PathBuf { Self::_passwords_dir(&self.state_dir) } /// Get the password storage directory. pub fn _passwords_dir(state_dir: &PathBuf) -> PathBuf { let mut passwords_dir = state_dir.clone(); passwords_dir.push(PASSWORDS_DIR_NAME); passwords_dir } fn get_menu_stdin(&self) -> Result<String, Box<Error>> { let mut elems: Vec<String> = Vec::new(); self.map_password_ids_mut(|pwid| { elems.push(String::from(pwid)); Ok(()) })?; Ok(elems.join("\n")) } fn notify(&self, msg: &str) -> io::Result<()> { if let &Some(ref prog) = self.config.notify_program() { info!("Running notify program: {}", prog.display()); let output = Command::new(prog) .arg(msg) .output()?; if !output.status.success() { let msg = format!("Failed to excute {}", prog.display()); return Err(io::Error::new(io::ErrorKind::Other, msg.as_str())); } } Ok(()) } /// Invoke a dmenu compatible menu program allowing the user to select a password. The selected /// password is loaded into the clipboard. pub fn menu(&mut self) -> Result<(), Box<Error>> { if self.config.menu_program().is_none() { let msg = String::from("No menu program configured or found"); return Err(CustomErrorMessage::boxed(msg)); } let mut child; { let menu_prog = self.config.menu_program().as_ref().unwrap(); info!("Running menu program: {}", menu_prog.display()); let menu_args = self.config.menu_args(); let stdin_str = self.get_menu_stdin() .map_err(|e| CustomErrorMessage::boxed(format!("Failed to build dmenu input: {}", e)))?; let mut dmenu = Command::new(menu_prog); child = dmenu.stdin(Stdio::piped()) .stdout(Stdio::piped()) .args(menu_args) .spawn() .map_err(|e| CustomErrorMessage::boxed(format!( "Menu program failed: {}: {}", menu_prog.display(), e)))?; { let pipe = child.stdin.as_mut().unwrap(); pipe.write_all(&stdin_str.as_bytes()).unwrap(); } let status = child.wait().unwrap(); if !status.success() { let msg = format!("Menu program failed: {}", menu_prog.display()); return Err(CustomErrorMessage::boxed(msg)); } } let mut chosen = String::new(); child.stdout.unwrap().read_to_string(&mut chosen).unwrap(); self.clip(chosen.trim()) } /// Load the clipboard with the specified password's decrypted cipher text. pub fn clip(&mut self, pwid: &str) -> Result<(), Box<Error>> { info!("Send password {} to clipboard", pwid); // Instantiate clipboard contexts. // We use `X11ClipboardContext` directly as this is a UNIX program. let mut pri_clip: X11ClipboardContext<Primary> = X11ClipboardContext::new() .map_err(|e| format!("Failed to init 'primary' clipboard: {}", e))?; let mut clip_clip: X11ClipboardContext<Clipboard> = X11ClipboardContext::new() .map_err(|e| format!("Failed to init 'clipboard' clipboard: {}", e))?; let epw = EncryptedPassword::from_file(self.password_path(pwid)) .map_err(|e| format!("Failed to read password '{}' from file: {}", pwid, e))?; let mut gpg = GPG::new(self.gnupg_home.clone()); let pw = epw.decrypt(&mut gpg) .map_err(|e| format!("Failed to decrypt password '{}': {}", pwid, e))?; let clear_text = pw.clear_text(); // Load the clipboards. New scope to drop clear text as soon as possible. { let clear = String::from_utf8(clear_text.unsecure().to_vec())?; pri_clip.set_contents(clear.clone()) .map_err(|e| format!("Failed to load 'primary' clipboard: {}", e))?; clip_clip.set_contents(clear) .map_err(|e| format!("Failed to load 'clipboard' clipboard: {}", e))?; } // Notify the user. let mut msg = String::new(); msg.push_str(&format!("Loaded password `{}' into clipboard\n", pwid)); msg.push_str(&format!(" username: {}\n", pw.username().unwrap_or(""))); msg.push_str(&format!(" email : {}\n", pw.email().unwrap_or(""))); msg.push_str(&format!(" comment : {}", pw.comment().unwrap_or(""))); self.notify(&msg) .map_err(|e| format!("Failed to notify: {}", e))?; // And we have to wait. If we allow the program to exit, the clipboard is cleared. let dur = time::Duration::new(1, 0); for i in (1..self.config.clipboard_timeout() + 1).rev() { print!("{}...", i); stdout().flush().unwrap(); thread::sleep(dur); } println!(""); // The clipboards should be cleared when we exit, but just to be certain. pri_clip.set_contents(String::from("")) .map_err(|e| format!("Failed to clear 'primary' clipboard: {}", e))?; clip_clip.set_contents(String::from("")) .map_err(|e| format!("Failed to clear 'clipboard' clipboard: {}", e))?; info!("Cleared clipboards"); self.notify("Cleared clipboards") .map_err(|e| format!("Failed to notify: {}", e))?; Ok(()) } /// Edit an existing password entry. pub fn edit_password(&mut self, pwid: &str, edit: PasswordEdit) -> Result<(), Box<Error>> { info!("Edit password '{}'", pwid); let epw = EncryptedPassword::from_file(self.password_path(pwid)) .map_err(|e|format!("Failed to read password '{}' from file: {}", pwid, e))?; let mut gpg = GPG::new(self.gnupg_home.clone()); let epw = epw.edit(edit, &mut gpg, &self.config.encrypt_to())?; epw.to_disk(self.password_path(pwid), false) .map_err(|e| format!("Failed to write pasword file: {}", e))?; Ok(()) } pub fn check_pwned(&mut self, pwids: Vec<&str>, verbose: bool) -> Result<(), Box<Error>> { let mut pwned_pws = Vec::new(); let mut gpg = GPG::new(self.gnupg_home.clone()); let all = pwids.is_empty(); if all && verbose { println!("\nChecking all passwords:\n"); } self.map_password_ids_mut(|pwid| { // Skip if necessary (could be more efficient). if !all && !pwids.contains(&pwid) { return Ok(()); } if verbose { print!("{}: ", pwid); io::stdout().flush().unwrap(); } let epw = EncryptedPassword::from_file(self.password_path(pwid)) .map_err(|e|format!("Failed to read password '{}' from file: {}", pwid, e))?; let pw = epw.decrypt(&mut gpg) .map_err(|e| format!("Failed to decrypt password '{}': {}", pwid, e))?; let pwnage = pwned::is_pwned(pw.clear_text())?; if pwnage { pwned_pws.push(pwid.to_owned()); } if verbose { if pwnage { println!("IN PWNED DB!"); } else { println!("ok"); } } Ok(()) })?; if !pwned_pws.is_empty() { println!("\nThe SHA1 hash for following passwords are in the pwnedpasswords.com database:"); for p in pwned_pws { println!(" {}", p); } println!("\nIt's possible these passwords are compromised."); } Ok(()) } } #[cfg(test)] mod tests { use super::{Tabr, GPG, ClearPassword, PasswordEdit}; use config::CONFIG_FILENAME; use tempfile::{self, TempDir}; use std::path::{PathBuf, Path}; use std::fs::File; use std::io::Write; use std::collections::HashSet; use secstr::SecStr; const TEST_KEY_FILENAME: &'static str = "test_key.asc"; const DEFAULT_CONFIG_TEXT: &'static str = "encrypt_to = [\"745727B1E02B76067B584B593DC6B84E4ACE6921\"]"; const GPG_CONFIG_FILENAME: &'static str = "gpg.conf"; /// Everything needed to run tests using using a temporary directories for the state directory and /// GnuPG home directory. /// /// When this falls out of scope the temporary directories are destroyed, so this must live long /// enough for the entirety of your test to run. struct TestState { // The dirs are not used, but their lifetime determines how long they last on disk #[allow(dead_code)] state_dir: TempDir, #[allow(dead_code)] gpg_dir: TempDir, app: Tabr, } impl TestState { fn new(config_text: Option<&str>) -> Self { let state_dir = tempfile::tempdir().unwrap(); let gpg_dir = tempfile::tempdir().unwrap(); let config_text = match config_text { None => DEFAULT_CONFIG_TEXT, Some(s) => s, }; let file_path = PathBuf::from(file!()); let mut key_path = file_path.parent().unwrap().parent().unwrap().to_owned(); key_path.push(TEST_KEY_FILENAME); GPG::new(Some(gpg_dir.path().to_owned())).import_key(key_path.as_path()).unwrap(); // We have to force GnuPG to trust our newly imported key, otherwise gpgme will report // "unusable key". Of course you would not do this is the real world! let mut path = gpg_dir.path().to_owned(); path.push(GPG_CONFIG_FILENAME); let mut fh = File::create(path).unwrap(); fh.write_all(b"trust-model always").unwrap(); Self::write_config_file(state_dir.path(), config_text); let app = Tabr::new( state_dir.path().to_path_buf(), Some(gpg_dir.path().to_owned()) ).unwrap(); Self { state_dir, gpg_dir, app, } } // Write the specified text into a config file in the specified state directory. fn write_config_file(state_dir: &Path, text: &str) { let mut path = state_dir.to_owned(); path.push(CONFIG_FILENAME); let mut fh = File::create(path).unwrap(); fh.write_all(text.as_bytes()).unwrap(); } fn count_passwords(&self) -> u32 { let mut count = 0; self.app.map_password_ids_mut(|_| { count += 1; Ok(()) }).unwrap(); count } } #[test] fn test_empty() { let st = TestState::new(None); assert_eq!(st.count_passwords(), 0); } #[test] fn test_map1() { let mut st = TestState::new(None); let pw = ClearPassword::new(None, None, None, SecStr::from("secret")); st.app.add_password("test123", pw).unwrap(); assert_eq!(st.count_passwords(), 1); } #[test] fn test_map2() { let mut st = TestState::new(None); let mut expect = HashSet::new(); for i in 0..10 { let name = format!("pass{}", i); let clear_text = format!("secret{}", i); let pw = ClearPassword::new(None, None, None, SecStr::from(clear_text)); st.app.add_password(&name, pw).unwrap(); expect.insert(name); } let mut got = HashSet::new(); st.app.map_password_ids_mut(|p| { got.insert(p.to_owned()); Ok(()) }).unwrap(); assert_eq!(st.count_passwords(), 10); assert_eq!(got, expect); } #[test] fn test_bogus_encrypt_to1() { let ctext = "encrypt_to = [\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]"; let mut st = TestState::new(Some(ctext)); let pw = ClearPassword::new(None, None, None, SecStr::from("secret")); let res = st.app.add_password("test123", pw); assert!(res.is_err()); assert_eq!(res.err().unwrap().to_string(), "Failed to encrypt: Can\'t find GnuPG key \ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'"); } #[test] fn test_already_exists() { let mut st = TestState::new(None); let pw = ClearPassword::new(None, None, None, SecStr::from("secret")); let pw2 = pw.clone(); st.app.add_password("abc", pw).unwrap(); match st.app.add_password("abc", pw2) { Err(s) => assert_eq!(s.to_string(), "Password 'abc' already exists"), _ => panic!(), }; } #[test] fn test_load_metadata_encrypted() { let pwid = "abc"; let mut st = TestState::new(None); let pw = ClearPassword::new(Some(String::from("the_user")), Some(String::from("the_email")), Some(String::from("the_comment")), SecStr::from("secret")); st.app.add_password(pwid, pw).unwrap(); match st.app.load_password(pwid) { Ok(epw) => { assert_eq!(epw.username(), Some("the_user")); assert_eq!(epw.email(), Some("the_email")); assert_eq!(epw.comment(), Some("the_comment")); }, _ => panic!(), } } #[test] fn test_load_metadata_decrypted() { let pwid = "abc"; let mut st = TestState::new(None); let pw = ClearPassword::new(Some(String::from("the_user")), Some(String::from("the_email")), Some(String::from("the_comment")), SecStr::from("secret")); st.app.add_password(pwid, pw).unwrap(); match st.app.get_clear_password(pwid) { Ok(epw) => { assert_eq!(epw.username(), Some("the_user")); assert_eq!(epw.email(), Some("the_email")); assert_eq!(epw.comment(), Some("the_comment")); }, _ => panic!(), } } #[test] fn test_decrypt_nonexistent() { let mut st = TestState::new(None); let expect = "Failed to load password \'woof\': No such file or directory (os error 2)"; match st.app.get_clear_password("woof") { Err(s) => assert_eq!(s, expect), _ => panic!(), } } // Test editting everything. #[test] fn test_edit1() { let pwid = "abc"; let mut st = TestState::new(None); let pw = ClearPassword::new(Some(String::from("username")), Some(String::from("email")), Some(String::from("comment")), SecStr::from("secret")); st.app.add_password(pwid, pw).unwrap(); let edit = PasswordEdit::new(Some(String::from("username2")), Some(String::from("email2")), Some(String::from("comment2")), Some(SecStr::from("secret2"))); st.app.edit_password(pwid, edit).unwrap(); let new_pw = st.app.get_clear_password(pwid).unwrap(); assert_eq!(new_pw.username().unwrap(), "username2"); assert_eq!(new_pw.email().unwrap(), "email2"); assert_eq!(new_pw.comment().unwrap(), "comment2"); assert_eq!(new_pw.clear_text(), &SecStr::from("secret2")); } // Test editting nothing. Should be a NOP. #[test] fn test_edit2() { let pwid = "abc"; let mut st = TestState::new(None); let pw = ClearPassword::new(Some(String::from("username")), Some(String::from("email")), Some(String::from("comment")), SecStr::from("secret")); st.app.add_password(pwid, pw).unwrap(); let edit = PasswordEdit::new(None, None, None, None); st.app.edit_password(pwid, edit).unwrap(); let new_pw = st.app.get_clear_password(pwid).unwrap(); assert_eq!(new_pw.username().unwrap(), "username"); assert_eq!(new_pw.email().unwrap(), "email"); assert_eq!(new_pw.comment().unwrap(), "comment"); assert_eq!(new_pw.clear_text(), &SecStr::from("secret")); } // Test case for issue #10: Editting fields shorter corrupts password file. #[test] fn test_edit3() { let pwid = "abc"; let mut st = TestState::new(None); let mut user = String::new(); let mut email = String::new(); let mut comment = String::new(); let mut pw = String::new(); for _ in 1..100 { user.push_str("longuser"); email.push_str("longemail"); comment.push_str("This is a really long comment"); pw.push_str("xxxyyyzzz"); } let pw = ClearPassword::new(Some(user), Some(email), Some(comment), SecStr::from(pw)); st.app.add_password(pwid, pw).unwrap(); let edit = PasswordEdit::new(Some(String::from("user")), Some(String::from("email")), Some(String::from("comment")), Some(SecStr::from("secret"))); st.app.edit_password(pwid, edit).unwrap(); let new_pw = st.app.get_clear_password(pwid).unwrap(); assert_eq!(new_pw.username().unwrap(), "user"); assert_eq!(new_pw.email().unwrap(), "email"); assert_eq!(new_pw.comment().unwrap(), "comment"); assert_eq!(new_pw.clear_text(), &SecStr::from("secret")); } }
#![recursion_limit = "1024"] // TODO change unsigned ints to signed extern crate byteorder; extern crate csv; #[macro_use] extern crate error_chain; pub mod error; pub mod executor; pub mod storage; // TODO this will be deprecated // Each node only needs to know column types #[derive(Debug, Clone)] pub struct Schema { pub column_names: Vec<String>, pub column_types: ColumnTypes, } #[derive(Debug, Clone)] pub struct RelationSchema { pub name: String, pub id: u32, pub column_names: Vec<String>, pub column_types: ColumnTypes, } type ColumnTypes = Vec<DataType>; #[derive(Debug, Clone, PartialEq)] pub enum DataType { SmallInt, //u16 Integer, //u32 Float, //f32 Text(usize), //String } impl DataType { pub fn bytes_length(&self) -> usize { use DataType::*; match *self { SmallInt => 2, Integer => 4, Float => 4, Text(x) => x, } } }
use aoc_runner_derive::{aoc, aoc_generator}; use fnv::FnvHashMap; use itertools::Itertools; #[aoc_generator(day4)] fn parse_input_day4(input: &str) -> Result<Vec<FnvHashMap<String, String>>, String> { Ok(input .split("\n\n") .map(|g| { g.split_whitespace() .flat_map(|kv| kv.split(':').map(|e| e.to_owned())) .tuples() .collect() }) .collect()) } fn is_valid(pass: &FnvHashMap<String, String>) -> bool { pass.iter().all(|(k, v)| match k.as_ref() { "byr" => (1920..=2002).contains(&v.parse().unwrap_or(0)), "iyr" => (2010..=2020).contains(&v.parse().unwrap_or(0)), "eyr" => (2020..=2030).contains(&v.parse().unwrap_or(0)), "pid" => v.len() == 9 && v.chars().all(|c| c.is_ascii_digit()), "ecl" => ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"].contains(&v.as_str()), "hcl" => { v.starts_with('#') && v.len() == 7 && v.chars().skip(1).all(|c| c.is_ascii_hexdigit()) } "hgt" => { let amount = &v[0..v.len() - 2].parse().unwrap_or(0); match v[v.len() - 2..].as_ref() { "cm" => (150..=193).contains(amount), "in" => (59..=76).contains(amount), _ => false, } } _ => true, }) } #[aoc(day4, part1)] fn part1(passports: &[FnvHashMap<String, String>]) -> usize { let fields = ["ecl", "eyr", "pid", "hcl", "byr", "iyr", "hgt"]; passports .iter() .filter(|p| fields.iter().all(|&k| p.contains_key(k))) .count() } #[aoc(day4, part2)] fn part2(passports: &[FnvHashMap<String, String>]) -> usize { let fields = ["ecl", "eyr", "pid", "hcl", "byr", "iyr", "hgt"]; passports .iter() .filter(|p| fields.iter().all(|&k| p.contains_key(k)) && is_valid(p)) .count() }
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use super::VersionBinding; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct PackageWithVersion { pub name: String, pub version: String, pub binding: VersionBinding, } impl PackageWithVersion { pub fn from_str(contents: &str) -> Self { let split: Vec<&str> = contents.split(')').collect::<Vec<&str>>()[0] .split(" (") .collect(); if split.len() == 2 { let name = split[0].to_string(); let mut version = split[1].to_string(); let mut version_binding = String::new(); loop { let first = version.chars().next().unwrap(); if !(first == '=' || first == '>' || first == '<' || first == ' ') { break; } else { version_binding.push(first); version.remove(0); } } PackageWithVersion { name, version, binding: VersionBinding::from_str(&version_binding), } } else { let name = split[0].to_string(); PackageWithVersion { name, version: String::new(), binding: VersionBinding::Any, } } } }
use holochain_json_api::error::JsonError; use holochain_persistence_api::{ cas::content::AddressableContent, eav::{Attribute, EaviQuery, EntityAttributeValueIndex, EntityAttributeValueStorage}, error::PersistenceResult, reporting::{ReportStorage, StorageReport}, }; use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod}; use std::{ collections::BTreeSet, fmt::{Debug, Error, Formatter}, marker::{PhantomData, Send, Sync}, path::Path, sync::{Arc, RwLock}, time::Duration, }; use uuid::Uuid; const PERSISTENCE_PERIODICITY_MS: Duration = Duration::from_millis(5000); #[derive(Clone)] pub struct EavPickleStorage<A: Attribute> { db: Arc<RwLock<PickleDb>>, id: Uuid, attribute: PhantomData<A>, } impl<A: Attribute> EavPickleStorage<A> { pub fn new<P: AsRef<Path> + Clone>(db_path: P) -> EavPickleStorage<A> { let eav_db = db_path.as_ref().join("eav").with_extension("db"); EavPickleStorage { id: Uuid::new_v4(), db: Arc::new(RwLock::new( PickleDb::load( eav_db.clone(), PickleDbDumpPolicy::PeriodicDump(PERSISTENCE_PERIODICITY_MS), SerializationMethod::Cbor, ) .unwrap_or_else(|_| { PickleDb::new( eav_db, PickleDbDumpPolicy::PeriodicDump(PERSISTENCE_PERIODICITY_MS), SerializationMethod::Cbor, ) }), )), attribute: PhantomData, } } } impl<A: Attribute> Debug for EavPickleStorage<A> { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.debug_struct("EavPickleStorage") .field("id", &self.id) .finish() } } impl<A: Attribute> EntityAttributeValueStorage<A> for EavPickleStorage<A> where A: Sync + Send + serde::de::DeserializeOwned, { fn add_eavi( &mut self, eav: &EntityAttributeValueIndex<A>, ) -> PersistenceResult<Option<EntityAttributeValueIndex<A>>> { let mut inner = self.db.write().unwrap(); //hate to introduce mutability but it is saved by the immutable clones at the end let mut index_str = eav.index().to_string(); let mut value = inner.get::<EntityAttributeValueIndex<A>>(&index_str); let mut new_eav = eav.clone(); while value.is_some() { new_eav = EntityAttributeValueIndex::new(&eav.entity(), &eav.attribute(), &eav.value())?; index_str = new_eav.index().to_string(); value = inner.get::<EntityAttributeValueIndex<A>>(&index_str); } inner .set(&*index_str, &new_eav) .map_err(|e| JsonError::ErrorGeneric(e.to_string()))?; Ok(Some(new_eav)) } fn fetch_eavi( &self, query: &EaviQuery<A>, ) -> PersistenceResult<BTreeSet<EntityAttributeValueIndex<A>>> { let inner = self.db.read()?; //this not too bad because it is lazy evaluated let entries = inner .iter() .map(|item| item.get_value()) .filter(|filter| filter.is_some()) .map(|y| y.unwrap()) .collect::<BTreeSet<EntityAttributeValueIndex<A>>>(); let entries_iter = entries.iter().cloned(); Ok(query.run(entries_iter)) } } impl<A: Attribute> ReportStorage for EavPickleStorage<A> where A: Sync + Send + serde::de::DeserializeOwned, { fn get_storage_report(&self) -> PersistenceResult<StorageReport> { let db = self.db.read()?; let total_bytes = db.iter().fold(0, |total_bytes, kv| { let value = kv.get_value::<EntityAttributeValueIndex<A>>().unwrap(); total_bytes + value.content().to_string().bytes().len() }); Ok(StorageReport::new(total_bytes)) } } #[cfg(test)] pub mod tests { use crate::eav::pickle::EavPickleStorage; use holochain_json_api::json::RawString; use holochain_persistence_api::{ cas::{ content::{AddressableContent, ExampleAddressableContent}, storage::EavTestSuite, }, eav::{Attribute, EavBencher, ExampleAttribute}, }; use tempfile::tempdir; fn new_store<A: Attribute>() -> EavPickleStorage<A> { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); EavPickleStorage::new(temp_path) } #[bench] fn bench_pickle_eav_add(b: &mut test::Bencher) { let store = new_store(); EavBencher::bench_add(b, store); } #[bench] fn bench_pickle_eav_fetch_all(b: &mut test::Bencher) { let store = new_store(); EavBencher::bench_fetch_all(b, store); } #[bench] fn bench_pickle_eav_fetch_exact(b: &mut test::Bencher) { let store = new_store(); EavBencher::bench_fetch_exact(b, store); } #[test] fn pickle_eav_round_trip() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let entity_content = ExampleAddressableContent::try_from_content(&RawString::from("foo").into()).unwrap(); let attribute = ExampleAttribute::WithPayload("favourite-color".to_string()); let value_content = ExampleAddressableContent::try_from_content(&RawString::from("blue").into()).unwrap(); EavTestSuite::test_round_trip( EavPickleStorage::new(temp_path), entity_content, attribute, value_content, ) } #[test] fn pickle_eav_one_to_many() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let eav_storage = EavPickleStorage::new(temp_path); EavTestSuite::test_one_to_many::< ExampleAddressableContent, ExampleAttribute, EavPickleStorage<ExampleAttribute>, >(eav_storage, &ExampleAttribute::default()); } #[test] fn pickle_eav_many_to_one() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let eav_storage = EavPickleStorage::new(temp_path); EavTestSuite::test_many_to_one::< ExampleAddressableContent, ExampleAttribute, EavPickleStorage<ExampleAttribute>, >(eav_storage, &ExampleAttribute::default()); } #[test] fn pickle_eav_range() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let eav_storage = EavPickleStorage::new(temp_path); EavTestSuite::test_range::< ExampleAddressableContent, ExampleAttribute, EavPickleStorage<ExampleAttribute>, >(eav_storage, &ExampleAttribute::default()); } #[test] fn pickle_eav_prefixes() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let eav_storage = EavPickleStorage::new(temp_path); EavTestSuite::test_multiple_attributes::< ExampleAddressableContent, ExampleAttribute, EavPickleStorage<ExampleAttribute>, >( eav_storage, vec!["a_", "b_", "c_", "d_"] .into_iter() .map(|p| ExampleAttribute::WithPayload(p.to_string() + "one_to_many")) .collect(), ); } #[test] fn pickle_tombstone() { let temp = tempdir().expect("test was supposed to create temp dir"); let temp_path = String::from(temp.path().to_str().expect("temp dir could not be string")); let eav_storage = EavPickleStorage::new(temp_path); EavTestSuite::test_tombstone::<ExampleAddressableContent, EavPickleStorage<_>>(eav_storage) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DimensionsListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Dimension>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dimension { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<DimensionProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DimensionProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "filterEnabled", default, skip_serializing_if = "Option::is_none")] pub filter_enabled: Option<bool>, #[serde(rename = "groupingEnabled", default, skip_serializing_if = "Option::is_none")] pub grouping_enabled: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub data: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub total: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "usageStart", default, skip_serializing_if = "Option::is_none")] pub usage_start: Option<String>, #[serde(rename = "usageEnd", default, skip_serializing_if = "Option::is_none")] pub usage_end: Option<String>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Query>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Query { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<QueryProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryProperties { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub columns: Vec<QueryColumn>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub rows: Vec<Vec<serde_json::Value>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryColumn { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryDefinition { #[serde(rename = "type")] pub type_: query_definition::Type, pub timeframe: query_definition::Timeframe, #[serde(rename = "timePeriod", default, skip_serializing_if = "Option::is_none")] pub time_period: Option<QueryTimePeriod>, #[serde(default, skip_serializing_if = "Option::is_none")] pub dataset: Option<QueryDataset>, } pub mod query_definition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Usage, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Timeframe { WeekToDate, MonthToDate, YearToDate, TheLastWeek, TheLastMonth, TheLastYear, Custom, BillingMonthToDate, TheLastBillingMonth, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryTimePeriod { pub from: String, pub to: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryDataset { #[serde(default, skip_serializing_if = "Option::is_none")] pub granularity: Option<query_dataset::Granularity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub configuration: Option<QueryDatasetConfiguration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub aggregation: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub grouping: Vec<QueryGrouping>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sorting: Vec<QuerySortingConfiguration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub filter: Option<QueryFilter>, } pub mod query_dataset { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Granularity { Daily, Hourly, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuerySortingConfiguration { #[serde(rename = "querySortingDirection", default, skip_serializing_if = "Option::is_none")] pub query_sorting_direction: Option<query_sorting_configuration::QuerySortingDirection>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } pub mod query_sorting_configuration { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum QuerySortingDirection { Ascending, Descending, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryDatasetConfiguration { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub columns: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryAggregation { pub name: String, pub function: query_aggregation::Function, } pub mod query_aggregation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Function { Sum, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryGrouping { #[serde(rename = "type")] pub type_: QueryColumnType, pub name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryFilter { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub and: Vec<QueryFilter>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub or: Vec<QueryFilter>, #[serde(default, skip_serializing_if = "Option::is_none")] pub not: Box<Option<QueryFilter>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub dimension: Option<QueryComparisonExpression>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<QueryComparisonExpression>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum QueryColumnType { Tag, Dimension, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryComparisonExpression { pub name: String, pub operator: query_comparison_expression::Operator, pub values: Vec<String>, } pub mod query_comparison_expression { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Operator { In, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Export>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Export { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExportProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportProperties { #[serde(flatten)] pub common_export_properties: CommonExportProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub schedule: Option<ExportSchedule>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CommonExportProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option<common_export_properties::Format>, #[serde(rename = "deliveryInfo")] pub delivery_info: ExportDeliveryInfo, pub definition: QueryDefinition, } pub mod common_export_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Format { Csv, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportSchedule { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<export_schedule::Status>, pub recurrence: export_schedule::Recurrence, #[serde(rename = "recurrencePeriod", default, skip_serializing_if = "Option::is_none")] pub recurrence_period: Option<ExportRecurrencePeriod>, } pub mod export_schedule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Active, Inactive, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Recurrence { Daily, Weekly, Monthly, Annually, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportDeliveryInfo { pub destination: ExportDeliveryDestination, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportRecurrencePeriod { pub from: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub to: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportDeliveryDestination { #[serde(rename = "resourceId")] pub resource_id: String, pub container: String, #[serde(rename = "rootFolderPath", default, skip_serializing_if = "Option::is_none")] pub root_folder_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportExecutionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ExportExecution>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportExecution { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExportExecutionProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportExecutionProperties { #[serde(rename = "executionType", default, skip_serializing_if = "Option::is_none")] pub execution_type: Option<export_execution_properties::ExecutionType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<export_execution_properties::Status>, #[serde(rename = "submittedBy", default, skip_serializing_if = "Option::is_none")] pub submitted_by: Option<String>, #[serde(rename = "submittedTime", default, skip_serializing_if = "Option::is_none")] pub submitted_time: Option<String>, #[serde(rename = "processingStartTime", default, skip_serializing_if = "Option::is_none")] pub processing_start_time: Option<String>, #[serde(rename = "processingEndTime", default, skip_serializing_if = "Option::is_none")] pub processing_end_time: Option<String>, #[serde(rename = "fileName", default, skip_serializing_if = "Option::is_none")] pub file_name: Option<String>, #[serde(rename = "runSettings", default, skip_serializing_if = "Option::is_none")] pub run_settings: Option<CommonExportProperties>, } pub mod export_execution_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ExecutionType { OnDemand, Scheduled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Queued, InProgress, Completed, Failed, Timeout, NewDataNotAvailable, DataNotAvailable, } }
pub mod allocator; pub mod heap; use crate::kernel::InitResult; use x86_64::{VirtAddr, structures::paging::{OffsetPageTable, PageTable}}; use crate::input::{serial_print, serial_println}; pub unsafe fn init(physical_memory_offset: VirtAddr) -> InitResult<OffsetPageTable<'static>> { let level_4_table = active_level_4_table(physical_memory_offset); Ok(OffsetPageTable::new(level_4_table, physical_memory_offset)) } /// Returns a mutable reference to the active level 4 table. /// /// This function is unsafe because the caller must guarantee that the /// complete physical memory is mapped to virtual memory at the passed /// `physical_memory_offset`. Also, this function must be only called once /// to avoid aliasing `&mut` references (which is undefined behavior). unsafe fn active_level_4_table(physical_memory_offset: VirtAddr) -> &'static mut PageTable { use x86_64::registers::control::Cr3; let (level_4_table_frame, _) = Cr3::read(); let phys = level_4_table_frame.start_address(); let virt = physical_memory_offset + phys.as_u64(); let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); //list_all_used(physical_memory_offset.as_u64(),0, &(*page_table_ptr)); &mut *page_table_ptr // unsafe } pub unsafe fn list_all_used(offset : u64,depth : usize, table : &PageTable) { for (i, frame) in table.iter().enumerate() { if !frame.is_unused() { if depth >= 1 { serial_print!("|"); } for _ in 1..depth { serial_print!("-"); } serial_println!("{}: D{} Frame: 0x{:0x}",i, depth, frame.addr()); list_all_used(offset, depth + 1, &get_page_table(offset, frame.addr().as_u64())); } if i >= 512 {return}; if depth >= 4 {return}; } } pub unsafe fn get_page_table(offset : u64, address : u64) -> &'static mut PageTable { let virt = VirtAddr::new_truncate(address + offset); let page_table_ptr: *mut PageTable = virt.as_mut_ptr(); &mut *page_table_ptr // unsafe }
fn main() { println!("{} {} {} {} {}", true as u8, false as u8, 'A' as u32, 'à' as u32, '€' as u32); }
//! This crate contains types that are used throughout the SVM project. //! Whenever a type has a usage that exceeds a local crate then it should be considered a candidate for this crate. #![deny(missing_docs)] #![deny(unused)] #![deny(dead_code)] #![deny(unreachable_code)] #![feature(const_type_id)] #![feature(const_type_name)] #![feature(vec_into_raw_parts)] #[macro_use] mod macros; mod account; mod address; mod error; mod spawn_account; mod state; mod template; mod transaction; mod wasm_type; mod wasm_value; /// Type for failed running transactions pub use error::RuntimeError; /// Gas-related types mod gas; pub use gas::{Gas, GasMode, OOGError}; /// `Receipt`-related types mod receipt; pub use receipt::{ into_spawn_receipt, CallReceipt, DeployReceipt, Receipt, ReceiptLog, ReceiptRef, SpawnReceipt, }; /// `Addressable` types pub use address::{Address, TemplateAddr}; pub use account::Account; pub use spawn_account::SpawnAccount; pub use state::State; pub use template::{ ApiSection, CodeKind, CodeSection, CtorsSection, DataSection, DeploySection, HeaderSection, SchemaSection, Section, SectionKind, SectionLike, Sections, SectionsIter, Template, }; pub use transaction::{Context, Envelope, Layer, Transaction, TransactionId}; pub use wasm_type::{WasmType, WasmTypeError}; pub use wasm_value::WasmValue; /// Represents a type in one of two ways: /// * `(std::any::TypeId, &'static str str)` /// /// * `&'static str` #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Type { /// An integer (`std::any::TypeId`) along it a static string. /// This string will usually be the value of `std::any::type_name::<T>()` TypeId(std::any::TypeId, &'static str), /// A static string. /// It enables the API user to attach descriptive names as types. /// /// One can name instances of the same Rust native `struct/enum` /// using different strings. It makes it easier to troubleshoot /// leaking resources since we can pinpoint each resource. Str(&'static str), } use std::fmt; impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Type::Str(s) => write!(f, "{}", s), Type::TypeId(_ty, s) => write!(f, "{}", s), } } } impl Type { /// Creates a `Type` out of generic type (the `T`) pub const fn of<T: 'static>() -> Self { let ty = std::any::TypeId::of::<T>(); let name = std::any::type_name::<T>(); Type::TypeId(ty, name) } } impl From<&'static str> for Type { fn from(s: &'static str) -> Self { Type::Str(s) } }
//! Kafka Consumer //! //! A simple consumer based on KafkaClient. Accepts an instance of KafkaClient, a group and a //! topic. Partitions can be specified using builder pattern (Assumes all partitions if not //! specified). //! //! # Example //! //! ```no_run //! let mut client = kafka::client::KafkaClient::new(vec!("localhost:9092".to_owned())); //! let res = client.load_metadata_all(); //! let con = kafka::consumer::Consumer::new(client, "test-group".to_owned(), "my-topic".to_owned()) //! .partition(0) //! .fallback_offset(-2); //! for msg in con { //! println!("{:?}", msg); //! } //! ``` //! //! Consumer auto-commits the offsets after consuming COMMIT_INTERVAL messages (Currently set at //! 100) //! //! Consumer implements Iterator. use std::collections::HashMap; use error::{Error, Result}; use utils::{TopicMessage, TopicPartitionOffset, TopicPartitionOffsetError}; use client::KafkaClient; const COMMIT_INTERVAL: i32 = 100; // Commit after every 100 message #[derive(Default, Debug)] pub struct Consumer { client: KafkaClient, group: String, topic: String, partitions: Vec<i32>, initialized: bool, messages: Vec<TopicMessage>, index: usize, offsets: HashMap<i32, i64>, consumed: i32, fallback_offset: Option<i64>, } impl Consumer { /// Constructor /// /// Create a new consumer. Expects a KafkaClient, group, and topic as arguments. pub fn new(client: KafkaClient, group: String, topic: String) -> Consumer { Consumer{ client: client, group: group, topic: topic, initialized: false, index: 0, ..Consumer::default() } } /// Set the partitions of this consumer. /// /// If this function is never called, all partitions are assumed. /// This function call be called multiple times to add more than 1 partitions. pub fn partition(mut self, partition: i32) -> Consumer { self.partitions.push(partition); self } /// Specify the offset to use when none was committed for the /// underlying group yet. /// /// Running the underlying group for the first time against a /// topic results in the question where to start reading from the /// topic? It might already contain a lot of messages. Common /// strategies are starting at the earliest available message /// (thereby consuming whatever is currently in the topic) or at /// the latest one (thereby staring to consume only newly arriving /// messages.) The parameter here corresponds to `time` in /// `KafkaClient::fetch_offsets`. /// /// Unless this method is called and there is no offset committed /// for the underlying group yet, this consumer will _not_ retrieve /// any messages from the underlying topic. pub fn fallback_offset(mut self, fallback_offset_time: i64) -> Consumer { self.fallback_offset = Some(fallback_offset_time); self } fn commit_offsets(&mut self) -> Result<()> { let tpos = self.offsets.iter() .map(|(p, o)| TopicPartitionOffset{ topic: self.topic.clone(), partition: p.clone(), offset: o.clone() }) .collect(); self.client.commit_offsets(self.group.clone(), tpos) } fn fetch_offsets(&mut self) -> Result<()> { // ~ fetch the so far commited group offsets let mut tpos = try!(self.client.fetch_group_topic_offset(self.group.clone(), self.topic.clone())); if self.partitions.len() == 0 { self.partitions = self.client.topic_partitions.get(&self.topic).unwrap_or(&vec!()).clone(); } // ~ it might well that there were no group offsets committed // yet ... fallback to default offsets. try!(self.set_fallback_offsets(&mut tpos)); // ~ now initialized from the fetched offsets for tpo in &tpos { if self.partitions.contains(&tpo.partition) { self.offsets.insert(tpo.partition, tpo.offset); } } Ok(()) } /// Try setting the "fallback offsets" for all of `tpos` where /// `offset == -1`. Fails if retrieving the fallback offset is not /// possible for some reason for the affected elements from /// `tpos`. fn set_fallback_offsets(&mut self, tpos: &mut [TopicPartitionOffsetError]) -> Result<()> { // ~ it looks like kafka (0.8.2.1) is sending an error code // (even though it documents it won't: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetFetchResponse) // so let's check only for `offset == -1` (and don't verify `error == None`) let has_missing_offs = tpos.iter().filter(|tpo| tpo.offset == -1).next().is_some(); if has_missing_offs { // ~ if the user specified a "fallback offset" strategy // will try to fetch the current offset for that strategy // and start consuming starting at those if let Some(fallback_offset) = self.fallback_offset { // ~ now fetch the offset according to the specified strategy let new_offs = { let mut r = try!(self.client.fetch_topic_offset(self.topic.clone(), fallback_offset)); match r.remove(&self.topic) { None => return Err(Error::UnknownTopicOrPartition), Some(pts) => pts, } }; // ehm ... not really fast (O(n^2)) for tpo in tpos.iter_mut() { if tpo.offset == -1 { if let Some(new_off) = new_offs.iter().find(|pt| pt.partition == tpo.partition) { tpo.offset = new_off.offset; tpo.error = None; } } } } else { // XXX might want to produce some log message and return a dedicated error code return Err(Error::Unknown); } } Ok(()) } fn make_request(&mut self) -> Result<()> { if ! self.initialized { try!(self.fetch_offsets()); } let tpos = self.offsets.iter() .map(|(p, o)| TopicPartitionOffset{ topic: self.topic.clone(), partition: p.clone(), offset: o.clone() }) .collect(); self.messages = try!(self.client.fetch_messages_multi(tpos)); self.initialized = true; self.index = 0; Ok(()) } } impl Iterator for Consumer { type Item = TopicMessage; fn next(&mut self) -> Option<TopicMessage> { if self.initialized { self.index += 1; self.consumed += 1; if self.consumed % COMMIT_INTERVAL == 0 { let _ = self.commit_offsets(); } if self.index <= self.messages.len() { if self.messages[self.index-1].error.is_none() { let curr = self.offsets.entry(self.messages[self.index-1].partition).or_insert(0); *curr = *curr+1; return Some(self.messages[self.index-1].clone()); } return None; } let _ = self.commit_offsets(); if self.messages.len() == 0 { return None; } } match self.make_request() { Err(_) => None, Ok(_) => self.next() } } }
use super::*; use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; #[derive(Clone, Debug, Default)] pub struct InferenceTable { pub(super) var_unification_table: InPlaceUnificationTable<TypeVarId>, } /// The ID of a type variable. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct TypeVarId(pub(super) u32); impl UnifyKey for TypeVarId { type Value = TypeVarValue; fn index(&self) -> u32 { self.0 } fn from_index(i: u32) -> Self { Self(i) } fn tag() -> &'static str { "TypeVarId" } } /// The value of a type variable: either we already know the type, or we don't /// know it yet. #[derive(Clone, PartialEq, Eq, Debug)] pub enum TypeVarValue { Known(Type), Unknown, } impl TypeVarValue { const fn as_known(&self) -> Option<&Type> { match self { Self::Known(ty) => Some(ty), Self::Unknown => None, } } } impl UnifyValue for TypeVarValue { type Error = NoError; fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> { match (value1, value2) { // We should never equate two type variables, both of which have // known types. Instead, we recursively equate those types. (Self::Known(t1), Self::Known(t2)) => panic!( "equating two type variables, both of which have known types: {:?} and {:?}", t1, t2 ), // If one side is known, prefer that one. (Self::Known(..), Self::Unknown) => Ok(value1.clone()), (Self::Unknown, Self::Known(..)) => Ok(value2.clone()), (Self::Unknown, Self::Unknown) => Ok(Self::Unknown), } } } impl InferenceTable { pub fn new_type_var(&mut self) -> TypeVarId { self.var_unification_table.new_key(TypeVarValue::Unknown) } /// Propagates the type completely; type variables without known type are /// replaced by `Type::Unknown`. pub(crate) fn propagate_type_completely(&mut self, ty: &Type) -> Type { self.propagate_type_completely_inner(&mut Vec::new(), ty) } pub(crate) fn propagate_type_completely_inner( &mut self, tv_stack: &mut Vec<TypeVarId>, ty: &Type, ) -> Type { ty.clone().fold(&mut |ty| match ty { Type::Infer(tv) => { let inner = tv.to_inner(); if tv_stack.contains(&inner) { return tv.fallback_value(); } self.var_unification_table .inlined_probe_value(inner) .as_known() .map_or_else( || tv.fallback_value(), |known_ty| { // known_ty may contain other variables that are known by now tv_stack.push(inner); let result = self.propagate_type_completely_inner(tv_stack, known_ty); tv_stack.pop(); result }, ) } _ => ty, }) } /// Propagates the type as far as currently possible, replacing type /// variables by their known types. All types returned by the `infer_*` /// functions should be propagated as far as possible, i.e. contain no /// type variables with known type. pub(crate) fn propagate_type_as_far_as_possible(&mut self, ty: &Type) -> Type { self.propagate_type_as_far_as_possible_inner(&mut Vec::new(), ty) } pub(crate) fn propagate_type_as_far_as_possible_inner( &mut self, tv_stack: &mut Vec<TypeVarId>, ty: &Type, ) -> Type { ty.clone().fold(&mut |ty| match ty { Type::Infer(tv) => { let inner = tv.to_inner(); if tv_stack.contains(&inner) { return tv.fallback_value(); } self.var_unification_table .inlined_probe_value(inner) .as_known() .map_or(ty, |known_ty| { tv_stack.push(inner); let result = self.propagate_type_as_far_as_possible_inner(tv_stack, known_ty); tv_stack.pop(); result }) } _ => ty, }) } fn propagate_type_shallow(&mut self, ty: &Type) -> Type { match ty { Type::Infer(tv) => { let inner = tv.to_inner(); let value = self.var_unification_table.inlined_probe_value(inner); match value.as_known() { Some(known_ty) => known_ty.clone(), None => ty.clone(), } } _ => ty.clone(), } } pub fn unify(&mut self, t1: &Type, t2: &Type) -> bool { if t1 == t2 { return true; } let t1 = self.propagate_type_shallow(&t1.clone()); let t2 = self.propagate_type_shallow(&t2.clone()); match (t1, t2) { (Type::Primitive(p1), Type::Primitive(p2)) => p1 == p2, (Type::Struct(s1), Type::Struct(s2)) => s1 == s2, (Type::Enum(s1), Type::Enum(s2)) => s1 == s2, (Type::Tuple(tys1), Type::Tuple(tys2)) => { tys1.iter() .zip(tys2.iter()) .all(|(t1, t2)| self.unify(t1, t2)) && tys1.len() == tys2.len() } (Type::Fn(fn1), Type::Fn(fn2)) => { fn1.params .iter() .zip(fn1.params.iter()) .all(|(t1, t2)| self.unify(t1, t2)) && self.unify(&fn1.ret, &fn2.ret) && fn1.params.len() == fn2.params.len() } (Type::Unknown, _) | (_, Type::Unknown) => true, (Type::Infer(InferType::Var(tv1)), Type::Infer(InferType::Var(tv2))) => { self.var_unification_table.union(tv1, tv2); true } (Type::Infer(InferType::Var(tv)), other) | (other, Type::Infer(InferType::Var(tv))) => { self.var_unification_table .union_value(tv, TypeVarValue::Known(other)); true } // below Type::Infer so that // unify(TypeVar, Never) => Never, instead of // unify(TypeVar, Never) => TypeVar (ty, _) | (_, ty) if ty == Type::NEVER => true, _ => false, } #[cfg(FALSE)] match (t1, t2) { ( Type::App { ctor: ctor1, params: params1, }, Type::App { ctor: ctor2, params: params2, }, ) if ctor1 == ctor2 => { params1.len() == params2.len() && (params1.iter()) .zip(params2.iter()) .all(|(t1, t2)| self.unify(t1, t2)) } (Type::Unknown, _) | (_, Type::Unknown) => true, (Type::Infer(InferType::Var(tv1)), Type::Infer(InferType::Var(tv2))) => { self.var_unification_table.union(tv1, tv2); true } (Type::Infer(InferType::Var(tv)), other) | (other, Type::Infer(InferType::Var(tv))) => { self.var_unification_table .union_value(tv, TypeVarValue::Known(other)); true } // below Type::Infer so that // unify(TypeVar, Never) => Never, instead of // unify(TypeVar, Never) => TypeVar (ty, _) | (_, ty) if ty == Type::NEVER => true, _ => false, } } }
pub mod graph { use graph_items::edge::Edge; use graph_items::node::Node; use std::collections::HashMap; type Attrs = HashMap<String, String>; pub trait Attributes { fn get_attrs<'a>(&'a mut self) -> &'a mut Attrs; fn with_attrs(mut self, attrs: &[(&str, &str)]) -> Self where Self: Sized, { for (k, v) in attrs.iter() { self.get_attrs().insert(k.to_string(), v.to_string()); } self } } #[derive(Default, Debug)] pub struct Graph { pub nodes: Vec<Node>, pub edges: Vec<Edge>, pub attrs: Attrs, } impl Attributes for Graph { fn get_attrs<'a>(&'a mut self) -> &'a mut Attrs { &mut self.attrs } } impl Graph { pub fn new() -> Self { Graph::default() } pub fn with_nodes(mut self, nodes: &[Node]) -> Self { self.nodes = nodes.into(); self } pub fn with_edges(mut self, edges: &[Edge]) -> Self { self.edges = edges.into(); self } pub fn get_node(&self, name: &str) -> Option<&Node> { self.nodes.iter().find(|node| node.name == name) } } pub mod graph_items { pub mod edge { use super::super::Attributes; use super::super::Attrs; #[derive(Debug, Default, Clone, PartialEq)] pub struct Edge { pub from: String, pub to: String, attrs: Attrs, } impl Attributes for Edge { fn get_attrs<'a>(&'a mut self) -> &'a mut Attrs { &mut self.attrs } } impl Edge { pub fn new(from: &str, to: &str) -> Self { Edge { from: from.into(), to: to.into(), ..Default::default() } } } } pub mod node { use super::super::Attributes; use super::super::Attrs; #[derive(Debug, Default, Clone, PartialEq)] pub struct Node { pub name: String, attrs: Attrs, } impl Attributes for Node { fn get_attrs<'a>(&'a mut self) -> &'a mut Attrs { &mut self.attrs } } impl Node { pub fn new(name: &str) -> Self { Node { name: name.to_owned(), ..Default::default() } } pub fn get_attr(&self, name: &str) -> Option<&str> { self.attrs.get(name).map(|s| s.as_ref()) } } } } }
//! Slider style #![allow(clippy::module_name_repetitions)] use iced::widget::slider::Appearance; use iced::widget::slider::{Handle, HandleShape, Rail}; use crate::gui::styles::style_constants::{BORDER_ROUNDED_RADIUS, BORDER_WIDTH}; use crate::gui::styles::types::palette::mix_colors; use crate::{get_colors, StyleType}; #[derive(Clone, Copy, Default)] pub enum SliderType { #[default] Standard, } impl iced::widget::slider::StyleSheet for StyleType { type Style = SliderType; fn active(&self, _: &Self::Style) -> Appearance { let colors = get_colors(*self); Appearance { rail: Rail { colors: (mix_colors(colors.secondary, colors.buttons), colors.buttons), width: 3.0, border_radius: BORDER_ROUNDED_RADIUS.into(), }, handle: Handle { shape: HandleShape::Circle { radius: 5.5 }, color: mix_colors(colors.secondary, colors.buttons), border_width: 0.0, border_color: colors.secondary, }, } } fn hovered(&self, _: &Self::Style) -> Appearance { let colors = get_colors(*self); Appearance { rail: Rail { colors: (colors.secondary, colors.buttons), width: 3.0, border_radius: BORDER_ROUNDED_RADIUS.into(), }, handle: Handle { shape: HandleShape::Circle { radius: 8.0 }, color: colors.secondary, border_width: 0.0, border_color: colors.secondary, }, } } fn dragging(&self, _: &Self::Style) -> Appearance { let colors = get_colors(*self); Appearance { rail: Rail { colors: (colors.secondary, colors.buttons), width: 3.0, border_radius: BORDER_ROUNDED_RADIUS.into(), }, handle: Handle { shape: HandleShape::Circle { radius: 8.0 }, color: colors.secondary, border_width: BORDER_WIDTH, border_color: mix_colors(colors.secondary, colors.buttons), }, } } }
fn main() { let s: String = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().to_owned() }; let n: u64 = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().parse().unwrap() }; let stdout = solve(&s, n); stdout.iter().for_each(|s| { println!("{}", s); }) } fn solve(s: &str, k: u64) -> Vec<String> { let mut ans = "".to_string(); for (i, c) in s.chars().enumerate() { ans = format!("{}", c); if c != '1' || (i as u64) >= (k - 1) { break; } } let mut buf = Vec::new(); buf.push(format!("{}", ans)); buf } #[test] fn test_solve_1() { assert_eq!(solve("1214", 4), vec!("2")); } #[test] fn test_solve_2() { assert_eq!(solve("3", 157), vec!("3")); } #[test] fn test_solve_3() { assert_eq!(solve("299792458", 9460730472580800), vec!("2")); } #[test] fn test_solve_4() { assert_eq!(solve("1234", 1), vec!("1")); } #[test] fn test_solve_5() { assert_eq!(solve("1234", 2), vec!("2")); } #[test] fn test_solve_6() { assert_eq!(solve("98", 1), vec!("9")); }
use std::collections::*; use std::{self, cmp::Ordering, io}; mod front_of_house; pub use crate::front_of_house::hosting; // pub use front_of_house::hosting; mod back_of_house; use crate::back_of_house::cooking::Breakfast as boh_breakfast; use back_of_house::cooking; mod util; pub fn eat_at_restaurant() { // // Absolute path crate::front_of_house::hosting::add_to_waitlist(); // // Relative path front_of_house::hosting::add_to_waitlist(); // // Making use of the 'use' keyword hosting::add_to_waitlist(); // Order a breakfast in the summer with Rye toast let mut meal = boh_breakfast::summer("Rye"); // Change our mind about what bread we'd like meal.toast = String::from("Wheat"); println!("I'd like {} toast please", meal.toast); // The next line won't compile if we uncomment it; we're not allowed // to see or modify the seasonal fruit that comes with the meal // meal.seasonal_fruit = String::from("blueberries"); let order1 = cooking::Appetizer::Soup; let order2 = cooking::Appetizer::Salad; util::get_cutlery(); } fn serve_order() {}
use crate::network_dialog::{self, NetworkDialog}; use crate::utils::{format_number, format_number_full}; use gtk::glib; use gtk::prelude::*; use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use std::sync::{Arc, Mutex}; fn append_column( title: &str, v: &mut Vec<gtk::TreeViewColumn>, tree: &gtk::TreeView, max_width: Option<i32>, ) { let id = v.len() as i32; let renderer = gtk::CellRendererText::new(); if title != "name" { renderer.set_xalign(1.0); } let column = gtk::TreeViewColumn::builder() .title(title) .resizable(true) .clickable(true) .min_width(10) .build(); if let Some(max_width) = max_width { column.set_max_width(max_width); column.set_expand(true); } column.pack_start(&renderer, true); column.add_attribute(&renderer, "text", id); tree.append_column(&column); v.push(column); } pub struct Network { list_store: gtk::ListStore, pub filter_entry: gtk::SearchEntry, pub search_bar: gtk::SearchBar, dialogs: Rc<RefCell<Vec<NetworkDialog>>>, } impl Network { pub fn new(stack: &gtk::Stack, sys: &Arc<Mutex<System>>) -> Network { let tree = gtk::TreeView::builder().headers_visible(true).build(); let scroll = gtk::ScrolledWindow::builder().child(&tree).build(); let info_button = gtk::Button::builder() .label("More information") .hexpand(true) .sensitive(false) .css_classes(vec!["button-with-margin".to_owned()]) .build(); let current_network = Rc::new(RefCell::new(None)); // We put the filter entry at the right bottom. let filter_entry = gtk::SearchEntry::new(); let search_bar = gtk::SearchBar::builder() .halign(gtk::Align::End) .valign(gtk::Align::End) .child(&filter_entry) .show_close_button(true) .build(); let overlay = gtk::Overlay::builder() .child(&scroll) .hexpand(true) .vexpand(true) .build(); overlay.add_overlay(&search_bar); let mut columns: Vec<gtk::TreeViewColumn> = Vec::new(); let list_store = gtk::ListStore::new(&[ // The first four columns of the model are going to be visible in the view. glib::Type::STRING, // name glib::Type::STRING, // received data glib::Type::STRING, // transmitted data glib::Type::STRING, // received packets glib::Type::STRING, // transmitted packets glib::Type::STRING, // errors on received glib::Type::STRING, // errors on transmitted // These two will serve as keys when sorting by interface name and other numerical // things. glib::Type::STRING, // name_lowercase glib::Type::U64, // received data glib::Type::U64, // transmitted data glib::Type::U64, // received packets glib::Type::U64, // transmitted packets glib::Type::U64, // errors on received glib::Type::U64, // errors on transmitted ]); // The filter model let filter_model = gtk::TreeModelFilter::new(&list_store, None); filter_model.set_visible_func( glib::clone!(@weak filter_entry => @default-return false, move |model, iter| { if !WidgetExt::is_visible(&filter_entry) { return true; } let text = filter_entry.text(); if text.is_empty() { return true; } let text: &str = text.as_ref(); // TODO: Maybe add an option to make searches case sensitive? let name = model.get_value(iter, 0) .get::<String>() .map(|s| s.to_lowercase()) .ok() .unwrap_or_default(); name.contains(text) }), ); // For the filtering to be taken into account, we need to add it directly into the // "global" model. let sort_model = gtk::TreeModelSort::with_model(&filter_model); tree.set_model(Some(&sort_model)); tree.set_search_entry(Some(&filter_entry)); append_column("name", &mut columns, &tree, Some(200)); append_column("received data", &mut columns, &tree, None); append_column("transmitted data", &mut columns, &tree, None); append_column("received packets", &mut columns, &tree, None); append_column("transmitted packets", &mut columns, &tree, None); append_column("errors on received", &mut columns, &tree, None); append_column("errors on transmitted", &mut columns, &tree, None); let columns_len = columns.len(); for (pos, column) in columns.iter().enumerate() { column.set_sort_column_id(pos as i32 + columns_len as i32); } // Sort by network name by default. sort_model.set_sort_column_id( gtk::SortColumn::Index(columns_len as _), gtk::SortType::Ascending, ); let vertical_layout = gtk::Box::new(gtk::Orientation::Vertical, 0); vertical_layout.append(&overlay); vertical_layout.append(&info_button); filter_entry.connect_search_changed(move |_| { filter_model.refilter(); }); stack.add_titled(&vertical_layout, Some("Networks"), "Networks"); tree.connect_cursor_changed( glib::clone!(@weak current_network, @weak info_button => move |tree_view| { let selection = tree_view.selection(); let (name, ret) = if let Some((model, iter)) = selection.selected() { if let Ok(x) = model.get_value(&iter, 0).get::<String>() { (Some(x), true) } else { (None, false) } } else { (None, false) }; *current_network.borrow_mut() = name; info_button.set_sensitive(ret); }), ); let dialogs = Rc::new(RefCell::new(Vec::new())); info_button.connect_clicked(glib::clone!(@weak dialogs, @weak sys => move |_| { let current_network = current_network.borrow(); if let Some(ref interface_name) = *current_network { create_network_dialog( &mut dialogs.borrow_mut(), interface_name, &sys.lock().expect("failed to lock for new network dialog"), ); } })); tree.connect_row_activated( glib::clone!(@weak sys, @weak dialogs => move |tree_view, path, _| { let model = tree_view.model().expect("couldn't get model"); let iter = model.iter(path).expect("couldn't get iter"); let interface_name = model.get_value(&iter, 0) .get::<String>() .expect("Model::get failed"); create_network_dialog( &mut dialogs.borrow_mut(), &interface_name, &sys.lock().expect("failed to lock for new network dialog (from tree)"), ); }), ); Network { list_store, filter_entry, search_bar, dialogs, } } pub fn update_networks(&mut self, sys: &System) { // first part, deactivate sorting let sorted = TreeSortableExtManual::sort_column_id(&self.list_store); self.list_store.set_unsorted(); let mut seen: HashSet<String> = HashSet::new(); let networks = sys.networks(); if let Some(iter) = self.list_store.iter_first() { let mut valid = true; while valid { let name = match self.list_store.get_value(&iter, 0).get::<glib::GString>() { Ok(n) => n, _ => { valid = self.list_store.iter_next(&iter); continue; } }; if let Some((_, data)) = networks .iter() .find(|(interface_name, _)| interface_name.as_str() == name) { self.list_store.set( &iter, &[ (1, &format_number(data.received())), (2, &format_number(data.transmitted())), (3, &format_number_full(data.packets_received(), false)), (4, &format_number_full(data.packets_transmitted(), false)), (5, &format_number_full(data.errors_on_received(), false)), (6, &format_number_full(data.errors_on_transmitted(), false)), (8, &data.received()), (9, &data.transmitted()), (10, &data.packets_received()), (11, &data.packets_transmitted()), (12, &data.errors_on_received()), (13, &data.errors_on_transmitted()), ], ); valid = self.list_store.iter_next(&iter); seen.insert(name.to_string()); } else { valid = self.list_store.remove(&iter); } } } for (interface_name, data) in networks.iter() { if !seen.contains(interface_name.as_str()) { create_and_fill_model( &self.list_store, interface_name, data.received(), data.transmitted(), data.packets_received(), data.packets_transmitted(), data.errors_on_received(), data.errors_on_transmitted(), ); } if let Some(dialog) = self .dialogs .borrow() .iter() .find(|x| x.name == *interface_name) { dialog.update(data); } } // we re-enable the sorting if let Some((col, order)) = sorted { self.list_store.set_sort_column_id(col, order); } self.dialogs.borrow_mut().retain(|x| !x.need_remove()); } } #[allow(clippy::too_many_arguments)] fn create_and_fill_model( list_store: &gtk::ListStore, interface_name: &str, in_usage: u64, out_usage: u64, incoming_packets: u64, outgoing_packets: u64, incoming_errors: u64, outgoing_errors: u64, ) { list_store.insert_with_values( None, &[ (0, &interface_name), (1, &format_number(in_usage)), (2, &format_number(out_usage)), (3, &format_number_full(incoming_packets, false)), (4, &format_number_full(outgoing_packets, false)), (5, &format_number_full(incoming_errors, false)), (6, &format_number_full(outgoing_errors, false)), // sort part (7, &interface_name.to_lowercase()), (8, &in_usage), (9, &out_usage), (10, &incoming_packets), (11, &outgoing_packets), (12, &incoming_errors), (13, &outgoing_errors), ], ); } fn create_network_dialog(dialogs: &mut Vec<NetworkDialog>, interface_name: &str, sys: &System) { for dialog in dialogs.iter() { if dialog.name == interface_name { dialog.show(); return; } } if let Some((_, data)) = sys .networks() .iter() .find(|(name, _)| name.as_str() == interface_name) { dialogs.push(network_dialog::create_network_dialog(data, interface_name)); } else { eprintln!("couldn't find {}...", interface_name); } }
use actix_web::http::header::HeaderMap; use crate::error::HeaderError; use std::str::FromStr; pub(crate) fn get_header_as<T: FromStr>( headers: &HeaderMap, header: &str ) -> Result<T, HeaderError> { headers.get(header) .ok_or_else(|| HeaderError::Missing(header.to_owned())) .and_then(|id| id.to_str().map_err(|_| HeaderError::Missing(header.to_owned()))) .and_then(|id| id.parse::<T>().map_err(|_| HeaderError::Parse(header.to_owned()))) }
use super::matcher; const EMAIL_REGEX: &'static str = r#"(?i)([A-Za-z0-9!#$%&'*+/=?^_{|.}~-]+@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"#; const URL_REGEX: &'static str = r#"(?:(?:https?://)?(?:[a-z0-9.\-]+|www|[a-z0-9.\-])[.](?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s!()\[\]{};:'".,<>?]))"#; /// Returns matched email addresses as a vector of strings /// /// # Arguments /// /// * `text` - A String representing the text in which to search. /// /// # Examples /// /// ``` /// extern crate commonregex_rs; /// /// use commonregex_rs::commonregex; /// /// let text = String::from("I'm the Doctor. Contact me at hello@tardis.com or hello@gallifrey.com."); /// /// assert_eq!(vec!["hello@tardis.com", "hello@gallifrey.com"], commonregex::internet::email(&text)); /// ``` pub fn email(text: &String) -> Vec<&str> { matcher::match_results(text, EMAIL_REGEX) } /// Returns matched URLs as a vector of strings /// /// # Arguments /// /// * `text` - A String representing the text in which to search. /// /// # Examples /// /// ``` /// extern crate commonregex_rs; /// /// use commonregex_rs::commonregex; /// /// let text = String::from("Contribute at https://github.com/fakenine/commonregex-rs !"); /// /// assert_eq!(vec!["https://github.com/fakenine/commonregex-rs"], commonregex::internet::url(&text)); /// ``` pub fn url(text: &String) -> Vec<&str> { matcher::match_results(text, URL_REGEX) } #[cfg(test)] mod tests { use super::*; #[test] fn valid_emails() { let text = String::from("I'm the Doctor. Contact me at hello@tardis.com or hello@gallifrey.com."); assert_eq!(vec!["hello@tardis.com", "hello@gallifrey.com"], email(&text)); } }
use neuralnetwork::dataset::{read_csv_by_path}; use neuralnetwork::matrix::MatrixOps; use neuralnetwork::nn::NeuralNetwork; fn main() { // read train data println!("Reading train data ..."); let (train_label, train_data) = read_csv_by_path("data/mnist_train_100.csv").unwrap(); // read test data println!("Reading test data ..."); let (test_label, test_data) = read_csv_by_path("data/mnist_test_10.csv").unwrap(); // new neural network let mut nn = NeuralNetwork::new(vec![784, 100, 10]); nn.show(); // train println!("Start train ..."); for j in 0..10 { println!("Epoch {}", j); for i in 0..train_data.len() { nn.train(&train_data[i].transpose(), &train_label[i].transpose()); } // start eval println!("Start eval ..."); for i in 0..test_data.len() { nn.eval(&test_data[i].transpose(), &test_label[i]); } println!("End eval"); } println!("End train"); // start eval println!("Start eval ..."); for i in 0..test_data.len() { nn.eval(&test_data[i].transpose(), &test_label[i]); } println!("End eval"); }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crate::{ProofOptions, TraceInfo}; use math::{log2, StarkField}; use utils::{ collections::Vec, string::ToString, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, }; // PROOF CONTEXT // ================================================================================================ /// Basic metadata about a specific execution of a computation. #[derive(Debug, Clone, Eq, PartialEq)] pub struct Context { trace_width: u8, trace_length: u8, // stored as power of two trace_meta: Vec<u8>, field_modulus_bytes: Vec<u8>, options: ProofOptions, } impl Context { // CONSTRUCTOR // -------------------------------------------------------------------------------------------- /// Creates a new context for a computation described by the specified field, trace info, and /// proof options. pub fn new<B: StarkField>(trace_info: &TraceInfo, options: ProofOptions) -> Self { Context { trace_width: trace_info.width() as u8, trace_length: log2(trace_info.length()) as u8, trace_meta: trace_info.meta().to_vec(), field_modulus_bytes: B::get_modulus_le_bytes(), options, } } // PUBLIC ACCESSORS // -------------------------------------------------------------------------------------------- /// Returns execution trace length of the computation described by this context. pub fn trace_length(&self) -> usize { 2_usize.pow(self.trace_length as u32) } /// Returns execution trace width of the computation described by this context. pub fn trace_width(&self) -> usize { self.trace_width as usize } /// Returns execution trace info for the computation described by this context. pub fn get_trace_info(&self) -> TraceInfo { TraceInfo::with_meta( self.trace_width(), self.trace_length(), self.trace_meta.clone(), ) } /// Returns the size of the LDE domain for the computation described by this context. pub fn lde_domain_size(&self) -> usize { self.trace_length() * self.options.blowup_factor() } /// Returns modulus of the field for the computation described by this context. pub fn field_modulus_bytes(&self) -> &[u8] { &self.field_modulus_bytes } /// Returns number of bits in the base field modulus for the computation described by this /// context. /// /// The modulus is assumed to be encoded in little-endian byte order. pub fn num_modulus_bits(&self) -> u32 { let mut num_bits = self.field_modulus_bytes.len() as u32 * 8; for &byte in self.field_modulus_bytes.iter().rev() { if byte != 0 { num_bits -= byte.leading_zeros(); return num_bits; } num_bits -= 8; } 0 } /// Returns proof options which were used to a proof in this context. pub fn options(&self) -> &ProofOptions { &self.options } } impl Serializable for Context { /// Serializes `self` and writes the resulting bytes into the `target`. fn write_into<W: ByteWriter>(&self, target: &mut W) { target.write_u8(self.trace_width); target.write_u8(self.trace_length); target.write_u16(self.trace_meta.len() as u16); target.write_u8_slice(&self.trace_meta); assert!(self.field_modulus_bytes.len() < u8::MAX as usize); target.write_u8(self.field_modulus_bytes.len() as u8); target.write_u8_slice(&self.field_modulus_bytes); self.options.write_into(target); } } impl Deserializable for Context { /// Reads proof context from the specified `source` and returns the result. /// /// # Errors /// Returns an error of a valid Context struct could not be read from the specified `source`. fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { // read and validate trace width let trace_width = source.read_u8()?; if trace_width == 0 { return Err(DeserializationError::InvalidValue( "trace width must be greater than zero".to_string(), )); } if trace_width as usize >= TraceInfo::MAX_TRACE_WIDTH { return Err(DeserializationError::InvalidValue(format!( "Trace width cannot be greater than {}, but had {}", TraceInfo::MAX_TRACE_WIDTH, trace_width ))); } // read and validate trace length let trace_length = source.read_u8()?; if 2_usize.pow(trace_length as u32) < TraceInfo::MIN_TRACE_LENGTH { return Err(DeserializationError::InvalidValue(format!( "Trace length cannot be smaller than {}, but had {}", TraceInfo::MIN_TRACE_LENGTH, 2_usize.pow(trace_length as u32) ))); } // read trace metadata let num_meta_bytes = source.read_u16()? as usize; let trace_meta = if num_meta_bytes != 0 { source.read_u8_vec(num_meta_bytes)? } else { vec![] }; // read and validate field modulus bytes let num_modulus_bytes = source.read_u8()? as usize; if num_modulus_bytes == 0 { return Err(DeserializationError::InvalidValue( "filed modulus cannot be an empty value".to_string(), )); } let field_modulus_bytes = source.read_u8_vec(num_modulus_bytes)?; // read options let options = ProofOptions::read_from(source)?; Ok(Context { trace_width, trace_length, trace_meta, field_modulus_bytes, options, }) } }
#[macro_export] macro_rules! caml_ffi { ($code:tt) => { let mut caml_frame = $crate::core::state::local_roots(); $code; return; }; ($code:tt => $result:expr) => { let mut caml_frame = $crate::core::state::local_roots(); $code; return $crate::core::mlvalues::Value::from($result); }; } #[macro_export] /// Registers OCaml parameters with the GC macro_rules! caml_param { (@step $idx:expr, $caml_roots:ident,) => { $caml_roots.ntables = $idx; }; (@step $idx:expr, $caml_roots:ident, $param:expr, $($tail:expr,)*) => { $caml_roots.tables[$idx] = &mut $param; $crate::caml_param!(@step $idx + 1usize, $caml_roots, $($tail,)*); }; ($($n:expr),*) => { let mut caml_roots: $crate::core::memory::CamlRootsBlock = ::std::default::Default::default(); #[allow(unused_unsafe)] { caml_roots.next = unsafe { $crate::core::state::local_roots() }; unsafe { $crate::core::state::set_local_roots(&mut caml_roots); } }; caml_roots.nitems = 1; // this is = N when CAMLxparamN is used $crate::caml_param!(@step 0usize, caml_roots, $($n,)*); } } /// Initializes and registers the given identifier(s) as a local value with the OCaml runtime. /// /// ## Original C code /// /// ```c /// #define CAMLlocal1(x) \ /// value x = Val_unit; \ /// CAMLxparam1 (x) /// ``` /// #[macro_export] macro_rules! caml_local { ($($local:ident),*) => { #[allow(unused_mut)] $(let mut $local = $crate::Value::new($crate::core::mlvalues::UNIT);)* $crate::caml_param!($($local.0),*); } } #[macro_export] /// Defines an OCaml frame macro_rules! caml_frame { (|$($local:ident),*| $code:block) => { { #[allow(unused_unsafe)] let caml_frame = unsafe { $crate::core::state::local_roots() }; caml_local!($($local),*); let res = $code; #[allow(unused_unsafe)] unsafe { $crate::core::state::set_local_roots(caml_frame) }; res } }; } #[macro_export] /// Defines an OCaml FFI body, including any locals, as well as a return if provided; it is up to you to define the parameters. macro_rules! caml_body { (||, <$($local:ident),*>, $code:block) => { #[allow(unused_unsafe)] let caml_frame = unsafe { $crate::core::state::local_roots() }; $crate::caml_local!($($local),*); $code; #[allow(unused_unsafe)] unsafe { $crate::core::state::set_local_roots(caml_frame) }; }; (|$($param:ident),*|, @code $code:block) => { #[allow(unused_unsafe)] let caml_frame = unsafe { $crate::core::state::local_roots() }; $($crate::caml_param!($param); let $param = $crate::Value::new($param);)* $code; #[allow(unused_unsafe)] unsafe { $crate::core::state::set_local_roots(caml_frame) }; }; (|$($param:ident),*|, <$($local:ident),*>, $code:block) => { #[allow(unused_unsafe)] let caml_frame = unsafe { $crate::core::state::local_roots() }; $($crate::caml_param!($param); let $param = $crate::Value::new($param);)* $crate::caml_local!($($local),*); $code #[allow(unused_unsafe)] unsafe { $crate::core::state::set_local_roots(caml_frame) }; } } #[macro_export] /// Defines an external Rust function for FFI use by an OCaml program, with automatic `CAMLparam`, `CAMLlocal`, and `CAMLreturn` inserted for you. macro_rules! caml { ($name:ident($($param:ident),*) $code:block) => { #[allow(unused_mut)] #[no_mangle] pub unsafe extern fn $name ($(mut $param: $crate::core::mlvalues::Value,)*) -> $crate::core::mlvalues::Value { let x: $crate::Value; $crate::caml_body!(|$($param),*|, <>, { x = (|| -> $crate::Value { $code })(); }); return x.0; } }; ($name:ident, |$($param:ident),*|, <$($local:ident),*>, $code:block -> $retval:ident) => { #[allow(unused_mut)] #[no_mangle] pub unsafe extern fn $name ($(mut $param: $crate::core::mlvalues::Value,)*) -> $crate::core::mlvalues::Value { $crate::caml_body!(|$($param),*|, <$($local),*>, $code); return $crate::core::mlvalues::Value::from($retval); } }; ($name:ident, |$($param:ident),*|, <$($local:ident),*>, $code:block) => { #[allow(unused_mut)] #[no_mangle] pub unsafe extern fn $name ($(mut $param: $crate::core::mlvalues::Value,)*) -> $crate::core::mlvalues::Value { $crate::caml_body!(|$($param),*|, <$($local),*>, $code); return $crate::core::mlvalues::UNIT; } }; ($name:ident, |$($param:ident),*|, $code:block) => { #[allow(unused_mut)] #[no_mangle] pub unsafe extern fn $name ($(mut $param: $crate::core::mlvalues::Value,)*) -> $crate::core::mlvalues::Value { $crate::caml_body!(|$($param),*|, @code $code); return $crate::core::mlvalues::UNIT; } }; ($name:ident, |$($param:ident),*|, $code:block -> $retval:ident) => { #[allow(unused_mut)] #[no_mangle] pub unsafe extern fn $name ($(mut $param: $crate::core::mlvalues::Value,)*) -> $crate::core::mlvalues::Value { $crate::caml_body!(|$($param),*|, @code $code); return $crate::core::mlvalues::Value::from($retval); } }; } #[macro_export] /// Create an OCaml tuple macro_rules! tuple { (_ $x:expr) => { { let mut t = $crate::Tuple::new($x.len()); for (n, i) in $x.into_iter().enumerate() { let _ = t.set(n, $crate::ToValue::to_value(&i)); } t } }; ($($x:expr),*) => { { let x = &[$($x.to_value(),)*]; let x = tuple!(_ x); x } } } #[macro_export] /// Create an OCaml array macro_rules! array { (_ $x:expr) => { { let mut a = $crate::Array::new($x.len()); for (n, i) in $x.into_iter().enumerate() { let _ = a.set(n, $crate::ToValue::to_value(&i)); } a } }; ($($x:expr),*) => { { let x = &[$($x.to_value(),)*]; let x = array!(_ x); x } } } #[macro_export] /// Create an OCaml list macro_rules! list { (_ $x:expr) => { { let mut l = $crate::List::new(); for i in $x.into_iter().rev() { l.push_hd($crate::ToValue::to_value(&i)); } l } }; ($($x:expr),*) => { { let x = &[$($x.to_value(),)*]; let x = list!(_ x); x } } }
use EventType; use RawXEvent; pub struct Event { pub typ: EventType, pub event: RawXEvent } impl ::std::fmt::Debug for Event { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{:?}{:?}",self.typ,self.event) } } impl From<RawXEvent> for Event { fn from(f: RawXEvent) -> Event { let event_type = f.get_type(); Event { typ: From::from(event_type), event: f } } }
use crate::color_config::lookup_ansi_color_style; use nu_ansi_term::{Color, Style}; use nu_protocol::Config; pub fn get_shape_color(shape: String, conf: &Config) -> Style { match conf.color_config.get(shape.as_str()) { Some(int_color) => match int_color.as_string() { Ok(int_color) => lookup_ansi_color_style(&int_color), Err(_) => Style::default(), }, None => match shape.as_ref() { "shape_garbage" => Style::new().fg(Color::White).on(Color::Red).bold(), "shape_binary" => Style::new().fg(Color::Purple).bold(), "shape_bool" => Style::new().fg(Color::LightCyan), "shape_int" => Style::new().fg(Color::Purple).bold(), "shape_float" => Style::new().fg(Color::Purple).bold(), "shape_range" => Style::new().fg(Color::Yellow).bold(), "shape_internalcall" => Style::new().fg(Color::Cyan).bold(), "shape_external" => Style::new().fg(Color::Cyan), "shape_externalarg" => Style::new().fg(Color::Green).bold(), "shape_literal" => Style::new().fg(Color::Blue), "shape_operator" => Style::new().fg(Color::Yellow), "shape_signature" => Style::new().fg(Color::Green).bold(), "shape_string" => Style::new().fg(Color::Green), "shape_string_interpolation" => Style::new().fg(Color::Cyan).bold(), "shape_datetime" => Style::new().fg(Color::Cyan).bold(), "shape_list" => Style::new().fg(Color::Cyan).bold(), "shape_table" => Style::new().fg(Color::Blue).bold(), "shape_record" => Style::new().fg(Color::Cyan).bold(), "shape_block" => Style::new().fg(Color::Blue).bold(), "shape_filepath" => Style::new().fg(Color::Cyan), "shape_directory" => Style::new().fg(Color::Cyan), "shape_globpattern" => Style::new().fg(Color::Cyan).bold(), "shape_variable" => Style::new().fg(Color::Purple), "shape_flag" => Style::new().fg(Color::Blue).bold(), "shape_custom" => Style::new().fg(Color::Green), "shape_nothing" => Style::new().fg(Color::LightCyan), _ => Style::default(), }, } }
extern crate bytes; extern crate httparse; #[macro_use] extern crate may; use std::io::{Read, Write}; use bytes::BufMut; use httparse::Status; use may::net::TcpListener; fn req_done(buf: &[u8], path: &mut String) -> Option<usize> { let mut headers = [httparse::EMPTY_HEADER; 16]; let mut req = httparse::Request::new(&mut headers); if let Ok(Status::Complete(i)) = req.parse(buf) { path.clear(); path.push_str(req.path.unwrap_or("/")); return Some(i); } None } fn main() { may::config().set_workers(4); let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); while let Ok((mut stream, _)) = listener.accept() { go!(move || { let mut buf = Vec::new(); let mut path = String::new(); loop { if let Some(i) = req_done(&buf, &mut path) { let response = match &*path { "/" => "Welcome to May http demo\n", "/hello" => "Hello, World!\n", "/quit" => std::process::exit(1), _ => "Cannot find page\n", }; let s = format!( "\ HTTP/1.1 200 OK\r\n\ Server: May\r\n\ Content-Length: {}\r\n\ Date: 1-1-2000\r\n\ \r\n\ {}", response.len(), response ); stream .write_all(s.as_bytes()) .expect("Cannot write to socket"); buf = buf.split_off(i); } else { let mut temp_buf = vec![0; 512]; match stream.read(&mut temp_buf) { Ok(0) => return, // connection was closed Ok(n) => buf.put(&temp_buf[0..n]), Err(err) => println!("err = {err:?}"), } } } }); } }
extern crate advent_of_code; use advent_of_code::day1; use advent_of_code::input; use std::str::FromStr; fn main() { let input = input::read_file_to_string("input/day1part1"); // Part 1 let mut fuel = 0; for line in input.lines() { let mass: usize = usize::from_str(line).unwrap(); fuel += day1::fuel_from_mass(mass); } println!("Fuel: {}", fuel); // Part 2 let mut fuel_fuel = 0; for line in input.lines() { let mass: usize = usize::from_str(line).unwrap(); fuel_fuel += day1::fuel_for_module(mass); } println!("Fuel fuel: {}", fuel_fuel); }
use specs::Join; pub struct LifeSystem; impl<'a> ::specs::System<'a> for LifeSystem { type SystemData = ( ::specs::WriteStorage<'a, ::component::PhysicBody>, ::specs::WriteStorage<'a, ::component::DynamicDraw>, ::specs::WriteStorage<'a, ::component::DynamicEraser>, ::specs::WriteStorage<'a, ::component::DynamicGraphicsAssets>, ::specs::WriteStorage<'a, ::component::Life>, ::specs::WriteStorage<'a, ::component::Reducer>, ::specs::FetchMut<'a, ::resource::PhysicWorld>, ::specs::Entities<'a>, ); fn run( &mut self, (mut bodies, mut dynamic_draws, mut dynamic_erasers, mut dynamic_graphics_assets, mut lives, mut reducers, mut physic_world, entities): Self::SystemData, ) { use component::Life; for (life, entity) in (&mut lives, &*entities).join() { match *life { Life::EraserDead => { *life = Life::DrawAlive; dynamic_draws.insert(entity, ::component::DynamicDraw); dynamic_erasers.remove(entity).unwrap(); } Life::DrawDead => { let body = bodies.get_mut(entity).unwrap(); let death_animation_assets = { let assets = dynamic_graphics_assets.get(entity).unwrap(); let position = body.get(&physic_world).position(); ::component::DynamicGraphicsAssets::new( assets.primitive, assets.groups.clone(), assets.color, position * assets.primitive_trans, ) }; let death_animation_entity = entities.create(); dynamic_draws.insert(death_animation_entity, ::component::DynamicDraw); dynamic_graphics_assets.insert(death_animation_entity, death_animation_assets); reducers.insert(death_animation_entity, ::component::Reducer::new(::CONFIG.death_duration, true, true, true)); body.remove(&mut physic_world); entities.delete(entity).unwrap(); } _ => (), } } } }
mod manager; mod shim; pub(crate) use manager::*; pub(crate) use shim::*;
mod git_project; mod id; mod project; mod column; mod task; pub use id::*; pub use git_project::*; pub use project::*; pub use column::*; pub use task::*;
#[doc = "Reader of register TICK"] pub type R = crate::R<u32, super::TICK>; #[doc = "Writer for register TICK"] pub type W = crate::W<u32, super::TICK>; #[doc = "Register TICK `reset()`'s with value 0x0200"] impl crate::ResetValue for super::TICK { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0200 } } #[doc = "Reader of field `COUNT`"] pub type COUNT_R = crate::R<u16, u16>; #[doc = "Reader of field `RUNNING`"] pub type RUNNING_R = crate::R<bool, bool>; #[doc = "Reader of field `ENABLE`"] pub type ENABLE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ENABLE`"] pub struct ENABLE_W<'a> { w: &'a mut W, } impl<'a> ENABLE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `CYCLES`"] pub type CYCLES_R = crate::R<u16, u16>; #[doc = "Write proxy for field `CYCLES`"] pub struct CYCLES_W<'a> { w: &'a mut W, } impl<'a> CYCLES_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 & !0x01ff) | ((value as u32) & 0x01ff); self.w } } impl R { #[doc = "Bits 11:19 - Count down timer: the remaining number clk_tick cycles before the next tick is generated."] #[inline(always)] pub fn count(&self) -> COUNT_R { COUNT_R::new(((self.bits >> 11) & 0x01ff) as u16) } #[doc = "Bit 10 - Is the tick generator running?"] #[inline(always)] pub fn running(&self) -> RUNNING_R { RUNNING_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - start / stop tick generation"] #[inline(always)] pub fn enable(&self) -> ENABLE_R { ENABLE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bits 0:8 - Total number of clk_tick cycles before the next tick."] #[inline(always)] pub fn cycles(&self) -> CYCLES_R { CYCLES_R::new((self.bits & 0x01ff) as u16) } } impl W { #[doc = "Bit 9 - start / stop tick generation"] #[inline(always)] pub fn enable(&mut self) -> ENABLE_W { ENABLE_W { w: self } } #[doc = "Bits 0:8 - Total number of clk_tick cycles before the next tick."] #[inline(always)] pub fn cycles(&mut self) -> CYCLES_W { CYCLES_W { w: self } } }
#![cfg(feature = "std")] use tabled::settings::{ locator::ByColumnName, object::{Columns, Rows, Segment}, Alignment, Modify, Padding, Style, }; use crate::matrix::Matrix; use testing_table::test_table; test_table!( full_alignment, Matrix::new(3, 3).with(Style::psql()).with(Modify::new(Segment::all()).with(Alignment::left())), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | 2-1 | 2-2 " ); test_table!( head_and_data_alignment, Matrix::new(3, 3) .with(Modify::new(Rows::first()).with(Alignment::left())) .with(Modify::new(Rows::new(1..)).with(Alignment::right())), "+---+----------+----------+----------+" "| N | column 0 | column 1 | column 2 |" "+---+----------+----------+----------+" "| 0 | 0-0 | 0-1 | 0-2 |" "+---+----------+----------+----------+" "| 1 | 1-0 | 1-1 | 1-2 |" "+---+----------+----------+----------+" "| 2 | 2-0 | 2-1 | 2-2 |" "+---+----------+----------+----------+" ); test_table!( full_alignment_multiline, Matrix::new(3, 3).insert((3, 2), "https://\nwww\n.\nredhat\n.com\n/en") .with(Style::psql()) .with(Modify::new(Segment::all()).with(Alignment::left())), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | https:// | 2-2 " " | | www | " " | | . | " " | | redhat | " " | | .com | " " | | /en | " ); test_table!( vertical_alignment_test, Matrix::new(3, 3) .insert((2, 2), "E\nnde\navou\nros") .insert((3, 2), "Red\nHat") .insert((3, 3), "https://\nwww\n.\nredhat\n.com\n/en") .with(Style::psql()) .with(Modify::new(Columns::new(1..)).with(Alignment::bottom())), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | | E | " " | | nde | " " | | avou | " " | 1-0 | ros | 1-2 " " 2 | | | https:// " " | | | www " " | | | . " " | | | redhat " " | | Red | .com " " | 2-0 | Hat | /en " ); test_table!( alignment_doesnt_change_padding, Matrix::new(3, 3) .with(Style::psql()) .with(Modify::new(Segment::all()).with(Padding::new(3, 0, 0, 0))) .with(Modify::new(Segment::all()).with(Alignment::left())), " N| column 0| column 1| column 2" "----+-----------+-----------+-----------" " 0| 0-0 | 0-1 | 0-2 " " 1| 1-0 | 1-1 | 1-2 " " 2| 2-0 | 2-1 | 2-2 " ); test_table!( alignment_global, Matrix::new(3, 3).with(Style::psql()).with(Alignment::right()), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | 2-1 | 2-2 " ); test_table!( padding_by_column_name, Matrix::new(3, 3) .with(Style::psql()) .with(Modify::new(ByColumnName::new("column 0")).with(Padding::new(3, 3, 0, 0))) .with(Modify::new(Segment::all()).with(Alignment::center())), " N | column 0 | column 1 | column 2 " "---+--------------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | 2-1 | 2-2 " ); test_table!( padding_by_column_name_not_first_row, Matrix::new(3, 3) .with(Style::psql()) .with(Modify::new(ByColumnName::new("0-2")).with(Padding::new(3, 3, 0, 0))) .with(Modify::new(Segment::all()).with(Alignment::center())), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | 2-1 | 2-2 " ); test_table!( padding_by_column_name_not_existing, Matrix::new(3, 3) .with(Style::psql()) .with(Modify::new(ByColumnName::new("column 01123123")).with(Padding::new(3, 3, 0, 0))) .with(Modify::new(Segment::all()).with(Alignment::center())), " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | 0-0 | 0-1 | 0-2 " " 1 | 1-0 | 1-1 | 1-2 " " 2 | 2-0 | 2-1 | 2-2 " );
use crate::vector::Vector; use crate::point::Point; use crate::game::ColourIndex; /// A model representing a particle /// /// Particles are visible objects that have a time to live and move around /// in a given direction until their time is up. They are spawned when the /// player or an enemy is killed pub struct Particle { pub vector: Vector, pub ttl: f64, pub colour_index: ColourIndex, } //derive_position_direction!(Particle); impl Particle { /// Create a particle with the given vector and time to live in seconds pub fn new(vector: Vector, ttl: f64, colour_index: ColourIndex) -> Particle { Particle { vector: vector, ttl: ttl, colour_index: colour_index } } pub fn x_mut(&mut self) -> &mut f64 { &mut self.vector.position.x } pub fn y_mut(&mut self) -> &mut f64 { &mut self.vector.position.y } pub fn dir(&self) -> f64 { self.vector.direction } /// Update the particle pub fn update(&mut self, elapsed_time: f64) { self.ttl -= elapsed_time; let speed = 1000.0 * self.ttl * self.ttl; self.advance(elapsed_time * speed); } pub fn get_colour_index(&self) -> i32 { match self.colour_index { ColourIndex::BLUE => 1, ColourIndex::RED => 2, ColourIndex::WHITE => 0, } } fn advance(&mut self, units: f64) { *self.x_mut() += self.dir().cos() * units; *self.y_mut() += self.dir().sin() * units; } } /// Generates a new explosion of the given intensity at the given position. /// This works best with values between 5 and 25 pub fn make_explosion(particles: &mut Vec<Particle>, position: &Point, intensity: u8, colour_index: ColourIndex) { for rotation in itertools_num::linspace(0.0, 2.0 * ::std::f64::consts::PI, 15) { for ttl in (1..intensity).map(|x| (x as f64) / 10.0) { particles.push(Particle::new(Vector::new(position.clone(), rotation), ttl, colour_index)); } } }
// This file is part of Substrate. // Copyright (C) 2020 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. //! Implementation of the `insert` subcommand use crate::{utils, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, SharedParams}; use sc_keystore::Store as KeyStore; use sc_service::config::KeystoreConfig; use sp_core::crypto::SecretString; use sp_core::{crypto::KeyTypeId, traits::BareCryptoStore}; use std::convert::TryFrom; use structopt::StructOpt; /// The `insert` command #[derive(Debug, StructOpt)] #[structopt(name = "insert", about = "Insert a key to the keystore of a node.")] pub struct InsertCmd { /// The secret key URI. /// If the value is a file, the file content is used as URI. /// If not given, you will be prompted for the URI. #[structopt(long)] suri: Option<String>, /// Key type, examples: "gran", or "imon" #[structopt(long)] key_type: String, #[allow(missing_docs)] #[structopt(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] #[structopt(flatten)] pub keystore_params: KeystoreParams, #[allow(missing_docs)] #[structopt(flatten)] pub crypto_scheme: CryptoSchemeFlag, } impl InsertCmd { /// Run the command pub fn run(&self) -> Result<(), Error> { let suri = utils::read_uri(self.suri.as_ref())?; let base_path = self .shared_params .base_path .as_ref() .ok_or_else(|| Error::Other("please supply base path".into()))?; let (keystore, public) = match self.keystore_params.keystore_config(base_path)? { KeystoreConfig::Path { path, password } => { let public = with_crypto_scheme!( self.crypto_scheme.scheme, to_vec(&suri, password.clone()) )?; let keystore = KeyStore::open(path, password).map_err(|e| format!("{}", e))?; (keystore, public) }, _ => unreachable!("keystore_config always returns path and password; qed"), }; let key_type = KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| { Error::Other( "Cannot convert argument to keytype: argument should be 4-character string".into(), ) })?; keystore .write() .insert_unknown(key_type, &suri, &public[..]) .map_err(|e| Error::Other(format!("{:?}", e)))?; Ok(()) } } fn to_vec<P: sp_core::Pair>(uri: &str, pass: Option<SecretString>) -> Result<Vec<u8>, Error> { let p = utils::pair_from_suri::<P>(uri, pass)?; Ok(p.public().as_ref().to_vec()) }
pub const T_EMPTY: u8 = 0; pub const T_FOOD: u8 = 1; pub const T_BODY: u8 = 2; pub const T_HEAD: u8 = 3; pub const T_CORNER: u8 = 4; pub const T_TAIL: u8 = 5;
fn find_digit(num: i32, nth: i32) -> i32 { if nth <= 0 {return -1;} let mut num = num.abs(); let mut nth = nth; loop { if nth == 1 {return num % 10; } num /= 10; nth -= 1; } } #[test] fn test0() { assert_eq!(find_digit(0, 0), -1); } #[test] fn test1() { assert_eq!(find_digit(0, 1), 0); } #[test] fn test2() { assert_eq!(find_digit(-1, 1), 1); } #[test] fn test3() { assert_eq!(find_digit(-1, 2), 0); } #[test] fn test4() { assert_eq!(find_digit(5673, 4), 5); } #[test] fn test5() { assert_eq!(find_digit(129, 2), 2); } #[test] fn test6() { assert_eq!(find_digit(-2825, 3), 8); } #[test] fn test7() { assert_eq!(find_digit(-456, 4), 0); } #[test] fn test8() { assert_eq!(find_digit(0, 20), 0); } #[test] fn test9() { assert_eq!(find_digit(65, 0), -1); } fn main() { }
#![no_main] #![no_std] #[allow(unused_extern_crates)] #[allow(unused_imports)] use panic_halt; extern crate embedded_hal; extern crate stm32f4xx_hal; use stm32f4xx_hal::block; use stm32f4xx_hal::serial::{config::Config, Serial}; use cortex_m_rt as rt; use stm32f4xx_hal as hal; use hal::prelude::*; // need for the GpioExt trait (-> .split) #[rt::entry] fn main() -> ! { if let Some(peripherals) = hal::stm32::Peripherals::take(){ // let rcc= peripherals.SYSCFG.exticr4. let rcc = peripherals.RCC.constrain(); let clocks = rcc.cfgr.sysclk(48.mhz()).freeze(); let gpiod = peripherals.GPIOD.split(); let tx = gpiod.pd8.into_alternate_af7(); let rx = gpiod.pd9.into_alternate_af7(); let serial = Serial::usart3( peripherals.USART3, (tx, rx), Config::default().baudrate(115_200.bps()), clocks, ) .unwrap(); // Separate out the sender and receiver of the serial port let (mut tx, mut rx) = serial.split(); loop { // Read character and echo it back let received = block!(rx.read()).unwrap(); block!(tx.write(received)).ok(); } } loop { continue; } }
use bytes::{Buf, BufMut, Bytes, BytesMut}; use crate::error::RSocketError; use crate::utils::Writeable; const MAX_ROUTING_TAG_LEN: usize = 0xFF; #[derive(Debug, Clone)] pub struct RoutingMetadata { tags: Vec<String>, } pub struct RoutingMetadataBuilder { inner: RoutingMetadata, } impl RoutingMetadataBuilder { pub fn push_str(self, tag: &str) -> Self { self.push(String::from(tag)) } pub fn push(mut self, tag: String) -> Self { assert!( tag.len() <= MAX_ROUTING_TAG_LEN, "exceeded maximum routing tag length!" ); self.inner.tags.push(tag); self } pub fn build(self) -> RoutingMetadata { self.inner } } impl RoutingMetadata { pub fn builder() -> RoutingMetadataBuilder { RoutingMetadataBuilder { inner: RoutingMetadata { tags: vec![] }, } } pub fn decode(bf: &mut BytesMut) -> crate::Result<RoutingMetadata> { let mut bu = RoutingMetadata::builder(); loop { match Self::decode_once(bf) { Ok(v) => match v { Some(tag) => bu = bu.push(tag), None => break, }, Err(e) => return Err(e), } } Ok(bu.build()) } pub fn get_tags(&self) -> &Vec<String> { &self.tags } fn decode_once(bf: &mut BytesMut) -> crate::Result<Option<String>> { if bf.is_empty() { return Ok(None); } let size = bf.get_u8() as usize; if bf.len() < size { return Err(RSocketError::WithDescription("require more bytes!".into()).into()); } let tag = String::from_utf8(bf.split_to(size).to_vec())?; Ok(Some(tag)) } } impl Writeable for RoutingMetadata { fn write_to(&self, bf: &mut BytesMut) { for tag in &self.tags { let size = tag.len() as u8; bf.put_u8(size); bf.put_slice(tag.as_bytes()); } } fn len(&self) -> usize { let mut n = 0; for tag in &self.tags { n += 1 + tag.as_bytes().len(); } n } }
use chrono::naive::NaiveDateTime; use lazy_static::lazy_static; use regex::Regex; use std::str::FromStr; use super::error; #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Record { pub timestamp: NaiveDateTime, pub event: Event, } impl FromStr for Record { type Err = error::ParseRecordError; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { lazy_static! { static ref RECORD_REGEX: Regex = Regex::new(r"\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2})\] ([\w #]+)") .expect("Failed to compile Record regex"); } let c = RECORD_REGEX .captures(s) .ok_or(error::ParseRecordError::RecordFormatError)?; Ok(Record { timestamp: NaiveDateTime::parse_from_str(&c[1], "%Y-%m-%d %H:%M")?, event: Event::from_str(&c[2])?, }) } } #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum Event { StartShift(usize), FallAsleep, WakeUp, } impl FromStr for Event { type Err = error::ParseRecordError; fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { lazy_static! { static ref EVENT_REGEX: Regex = Regex::new(r"(\d+)").expect("Failed to compile Event regex"); } Ok(match s { "wakes up" => Event::WakeUp, "falls asleep" => Event::FallAsleep, s => Event::StartShift( EVENT_REGEX .captures(s) .ok_or(error::ParseRecordError::RecordFormatError)?[1] .parse()?, ), }) } }
mod comment_reader; mod identifiers_reader; mod operators_reader; mod strings_reader; mod unambiguous_single_chars_reader; mod whitespace_reader; pub use self::comment_reader::CommentReader; pub use self::identifiers_reader::IdentifiersReader; pub use self::operators_reader::OperatorsReader; pub use self::strings_reader::StringReader; pub use self::unambiguous_single_chars_reader::UnambiguousSingleCharsReader; pub use self::whitespace_reader::WhitespaceReader;
use mongodb::sync::Client; use std::env; use crate::persistence::{Error, Result}; pub fn get_mongo_client() -> Result<Client> { let mongo_url = match env::var("DATABASE_URL") { Ok(url) => url, Err(_) => { return Err(Error::DatabaseURLNotSet); } }; Ok(Client::with_uri_str(&mongo_url)?) }
// Problem 12 - Highly divisible triangular number // // The sequence of triangle numbers is generated by adding the natural numbers. So // the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten // terms would be: // // 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... // // Let us list the factors of the first seven triangle numbers: // // 1: 1 // 3: 1,3 // 6: 1,2,3,6 // 10: 1,2,5,10 // 15: 1,3,5,15 // 21: 1,3,7,21 // 28: 1,2,4,7,14,28 // // We can see that 28 is the first triangle number to have over five divisors. // // What is the value of the first triangle number to have over five hundred // divisors? fn main() { println!("{}", solution()); } fn solution() -> u64 { let target = 500; let mut triangular = 0; for n in 1.. { triangular += n; if divisor_count(triangular) > target { break; } } triangular } fn divisor_count(n: u64) -> u64 { let isqrn = (n as f64).sqrt().floor() as u64; let mut count = 2; for k in 2..(isqrn + 1) { if n % k == 0 { count += if n/k == k { 1 } else { 2 }; } } count }
use crate::utils; use chrono::{Duration, Utc}; use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation}; use lazy_static::lazy_static; use scrypt::{errors::CheckError, ScryptParams}; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, env, sync::{Arc, Mutex}, }; use thiserror::Error; const PASSWORD_MIN_LENGTH: usize = 8; lazy_static! { /// Secret key used to create JWTs. In production, this should be set to an /// actually secure value. static ref JWT_SECRET: String = env::var("JWT_SECRET").unwrap_or("JWT_SECRET".to_string()); } #[derive(Debug, Error, Eq, PartialEq)] pub enum ValidationError { #[error("Fatal hashing error")] HashError, #[error("Invalid password")] InvalidPassword, #[error("User unathorized for this request.")] Unauthorized, } #[derive(Serialize, Debug)] pub struct JWTResponse { token_type: String, access_token: String, expires_at: i64, } #[derive(Clone, Debug)] pub struct RefreshTokenInfo { pub token: String, pub expires_at: i64, pub player_id: String, } #[derive(Debug, Serialize, Deserialize)] struct JWTClaims { aud: String, exp: i64, iat: i64, iss: String, nbf: i64, sub: String, } #[derive(Clone)] pub struct TokenManager { sub: &'static str, iss: &'static str, refresh_tokens: Arc<Mutex<HashMap<String, RefreshTokenInfo>>>, } impl TokenManager { /// Creates a new TokenManager with default values for JWT subject and issuer. pub fn new() -> TokenManager { TokenManager { sub: "ThavalonAuthenticatedUser", iss: "ThavalonGameServer", refresh_tokens: Arc::new(Mutex::new(HashMap::new())), } } /// Creates a valid JWT using a user's ID. /// /// # Arguments /// /// * `player_id` - The user's ID to create a JWT with. /// /// # Returns /// /// A JWTResponse with the JWT pub async fn create_jwt(&mut self, player_id: &String) -> (JWTResponse, RefreshTokenInfo) { log::info!("Creating a new JWT for {}.", player_id); let time = Utc::now(); let expiration_time = time .checked_add_signed(Duration::minutes(15)) .expect("Failed to get expiration time."); let claims = JWTClaims { aud: player_id.clone(), exp: expiration_time.timestamp(), iat: time.timestamp(), iss: self.iss.to_string(), nbf: time.timestamp(), sub: self.sub.to_string(), }; let token = jsonwebtoken::encode( &Header::default(), &claims, &EncodingKey::from_secret(JWT_SECRET.as_bytes()), ) .expect("Failed to generate a JWT for this claim."); log::info!("Successfully created a JWT for {}.", player_id); ( JWTResponse { token_type: "Bearer".to_string(), access_token: token, expires_at: expiration_time.timestamp(), }, self.create_refresh_token(player_id).await, ) } /// Validates a JWT given the token. /// /// # Arguments /// /// * `token` - A JWT to authenticate /// /// # Returns /// /// User ID on success, ValidationError on failure. pub async fn validate_jwt(&self, token: &str) -> Result<String, ValidationError> { log::info!("Validating received JWT"); let validation = Validation { leeway: 60, validate_exp: true, validate_nbf: true, iss: Some(self.iss.to_string()), sub: Some(self.sub.to_string()), ..Validation::default() }; let token_claims = match jsonwebtoken::decode::<JWTClaims>( &token, &DecodingKey::from_secret(JWT_SECRET.as_bytes()), &validation, ) { Ok(data) => data.claims, Err(e) => { log::info!("Unable to validate claims for the the request. {}", e); return Err(ValidationError::Unauthorized); } }; log::info!("Successfully validated {}.", token_claims.aud); Ok(token_claims.aud) } /// Creates a refresh token with a given expiration time and updates the token store. /// /// # Arguments /// /// * `user` - The ID of the user of the refresh token. /// /// # Returns /// /// A RefreshTokenInfo struct with all required information. pub async fn create_refresh_token(&mut self, user: &String) -> RefreshTokenInfo { log::info!("Creating a refresh token for {}.", user); let token = utils::generate_random_string(32, false); let token_info = RefreshTokenInfo { token: token.clone(), expires_at: Utc::now() .checked_add_signed(Duration::weeks(1)) .expect("Could not create refresh token expires time.") .timestamp(), player_id: user.clone(), }; self.refresh_tokens .lock() .expect("Could not lock refresh token store.") .insert(token, token_info.clone()); token_info } /// Validates a refresh token, generating a new JWT and refresh token if valid. /// /// # Arguments /// /// * `refresh_token` - String of the refresh token to validate /// /// # Returns /// /// A new JWT and refresh token with an updated store. pub async fn renew_refresh_token( &mut self, refresh_token: String, ) -> Result<(JWTResponse, RefreshTokenInfo), ValidationError> { log::info!("Attempting to validate refresh token {}.", refresh_token); let token_info; { let mut token_store_locked = self .refresh_tokens .lock() .expect("Could not lock token store for validation."); token_info = match token_store_locked.remove(&refresh_token) { Some(info) => info, None => { log::info!("Could not validate this request."); return Err(ValidationError::Unauthorized); } }; log::info!("Refresh token exists in DB. Validating expiration time."); } let time = Utc::now().timestamp(); if time > token_info.expires_at { log::info!( "Token is not valid. Expired at {}, current time is {}.", token_info.expires_at, time ); return Err(ValidationError::Unauthorized); } log::info!("Token is valid. Sending new JWT."); Ok(self.create_jwt(&token_info.player_id).await) } /// Revokes a refresh token, making the token invalid. /// /// # Arguments /// /// * `refresh_token` - The refresh token to remove. pub async fn revoke_refresh_token(&mut self, refresh_token: &String) { log::info!("Revoking refresh token {}.", refresh_token); match self .refresh_tokens .lock() .expect("Failed to acquire lock on refresh token store.") .remove(refresh_token) { Some(_) => log::info!("Successfully revoked the refresh token."), None => log::info!("Refresh token does not exist to revoke."), }; } } /// Hashes a plaintext password using the currently selected hashing algorithm. /// /// # Arguments /// /// * `plaintext` - the plain text password to be hashed /// /// # Returns /// /// * `Result<password_hash, error>` pub async fn hash_password(plaintext: &String) -> Result<String, ValidationError> { if plaintext.len() < PASSWORD_MIN_LENGTH { log::warn!("Received a password below minimum security specs"); return Err(ValidationError::InvalidPassword); } let hash = scrypt::scrypt_simple(plaintext, &ScryptParams::recommended()).map_err(|e| { log::error!("An RNG error occurred with the underlying OS. {}", e); ValidationError::HashError }); hash } /// Validates a plaintext password against a given hash. /// /// # Arguments /// /// * `plaintext` - the plain text password to check /// * `hash` - Password hash in scrypt format /// /// # Returns /// True if passwords match. False otherwise. pub async fn validate_password(plaintext: &String, hash: &String) -> bool { let result = match scrypt::scrypt_check(plaintext, hash) { Ok(_) => true, Err(e) => { if e == CheckError::InvalidFormat { log::error!("Database hash is not in a valid scrypt format."); } false } }; result } #[cfg(test)] mod tests { use super::*; use chrono::{Duration, Utc}; use scrypt::ScryptParams; /// Tests hashing passwords against an insecure password. #[tokio::test] async fn test_hash_password_insecure() { let result = hash_password(&String::from("not_sec")).await; assert!(result.unwrap_err() == ValidationError::InvalidPassword); } /// Tests hasing passwords against a secure password. #[tokio::test] async fn test_hash_password_normal_pw() { let password = String::from("32fdsfjidsfj293423"); let result = hash_password(&password) .await .expect("Failed to hash password correctly."); scrypt::scrypt_check(&password, &result).expect("Failed to match password hashes."); } /// Tests validating a password with a matching hash. #[tokio::test] async fn test_validate_password_match() { let password = String::from("asdfwe322ef2342"); let hash = scrypt::scrypt_simple(&password, &ScryptParams::recommended()).unwrap(); assert!(validate_password(&password, &hash).await); } /// Tests validating a password with an invalid hash. This shouldn't match. #[tokio::test] async fn test_validate_password_bad_hash() { let password = String::from("23qsadf2323f"); assert!(!validate_password(&password, &password).await); } /// Tests validating a password with a mismatched hash. #[tokio::test] async fn test_validate_password_mismatch() { let password = String::from("32f23f2ef23"); let other_password = String::from("342f98j98j34gf"); let hash = scrypt::scrypt_simple(&other_password, &ScryptParams::recommended()).unwrap(); assert!(!validate_password(&password, &hash).await); } /// Tests creating a JWT for a given player ID. Expected results generated from jwt.io. #[tokio::test] async fn test_create_jwt_valid() { let mut mananger = TokenManager::new(); let (jwt, _) = mananger.create_jwt(&String::from("TESTING_THIS")).await; let expires_at = Utc::now() .checked_add_signed(Duration::minutes(15)) .unwrap() .timestamp(); assert!(expires_at - 60 <= jwt.expires_at); assert!(jwt.expires_at <= expires_at + 60); assert_eq!(jwt.token_type.as_str(), "Bearer"); } /// Tests validate_jwt with a valid JWT. #[tokio::test] async fn test_validate_jwt_valid() { let mut manager = TokenManager::new(); let input_player = String::from("TESTING"); let (jwt, _) = manager.create_jwt(&input_player).await; let player_id = manager .validate_jwt(&jwt.access_token) .await .expect("Token was marked as invalid, but should be valid."); assert_eq!(player_id, input_player); } /// Tests validate_jwt with a tampered JWT. #[tokio::test] async fn test_validate_jwt_invalid() { let mut manager = TokenManager::new(); let input_player = String::from("TESTING"); let (mut jwt, _) = manager.create_jwt(&input_player).await; jwt.access_token.insert(5, 'A'); let result = manager .validate_jwt(&jwt.access_token) .await .expect_err("WARNING: invalid JWT showing as valid."); assert_eq!(result, ValidationError::Unauthorized); } /// Tests create_refresh_token for a valid refresh token. #[tokio::test] async fn test_create_refresh_token() { let mut manager = TokenManager::new(); let player = String::from("TESTING"); let token = manager.create_refresh_token(&player).await; let expires_at = Utc::now() .checked_add_signed(Duration::weeks(1)) .unwrap() .timestamp(); assert_eq!(token.player_id, player); assert!(expires_at - 60 <= token.expires_at); assert!(token.expires_at <= expires_at + 60); assert_eq!( manager .refresh_tokens .lock() .unwrap() .get(&token.token) .unwrap() .player_id, player ); } /// Tests renewing a refresh token with a valid refresh token #[tokio::test] async fn test_renew_refresh_token_valid() { let mut manager = TokenManager::new(); let player_id = String::from("TESTING"); let token = manager.create_refresh_token(&player_id).await; let (_, new_token) = manager .renew_refresh_token(token.token.clone()) .await .expect("Failed to generate a new refresh token with a valid refresh token."); assert!(new_token.player_id == player_id); assert!(manager .refresh_tokens .lock() .unwrap() .contains_key(&new_token.token)); assert!(!manager .refresh_tokens .lock() .unwrap() .contains_key(&token.token)); } /// Tests renewing a refresh token with an invalid refresh token. #[tokio::test] async fn test_renew_refresh_token_invalid() { let mut manager = TokenManager::new(); manager.create_refresh_token(&String::from("TESTING")).await; if let Err(e) = manager .renew_refresh_token(String::from("WER@#R@F@#")) .await { assert_eq!(e, ValidationError::Unauthorized); } else { panic!("ERROR: Successfully validated an invalid refresh token."); } } /// Tests revoking a refresh token with both a valid and invalid token. The results should be the same. #[tokio::test] async fn test_revoke_refresh_token() { let mut manager = TokenManager::new(); let info = manager.create_refresh_token(&String::from("TESTING")).await; manager.revoke_refresh_token(&info.token).await; assert!(!manager .refresh_tokens .lock() .unwrap() .contains_key(&info.token)); let result = manager .renew_refresh_token(info.token.clone()) .await .expect_err("ERROR: revoked refresh token is still valid."); assert_eq!(result, ValidationError::Unauthorized); // This shouldn't crash here. manager .revoke_refresh_token(&"This shouldn't crash".to_string()) .await; } }
use amethyst::ecs::{Component, NullStorage}; #[derive(Debug, Default)] pub struct Mob; impl Component for Mob { type Storage = NullStorage<Self>; }
use std::path::PathBuf; use serde::{Deserialize, Serialize}; use crate::util::random_string; pub static CONFIG_ENV_PREFIX: &str = "PT_"; /// Available configuration values. /// These are mapped to SCREAMING_UPPER_CASE environment variables. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(default)] pub struct Config { /// Server host pub host: String, /// Server port pub port: usize, /// Log output as JSON. pub log_json: bool, /// Postgres database URL. pub database_url: String, /// Secret for generating JWTs. pub token_secret: String, /// API docs at server root URL. pub api_docs: bool, /// Where the uploaded images are stored. pub image_storage_path: PathBuf, } impl Config { pub fn from_env() -> Result<Self, anyhow::Error> { let c = envy::prefixed(CONFIG_ENV_PREFIX).from_env()?; Ok(c) } } impl Default for Config { fn default() -> Self { Self { host: "localhost".into(), port: 8080, log_json: false, database_url: "postgresql://postgres:postgres@localhost:5432/postgres".into(), token_secret: random_string(32), api_docs: true, image_storage_path: PathBuf::from("./uploaded_images/"), } } }