text
stringlengths
8
4.13M
use std::io; use std::sync::atomic::Ordering; #[cfg(feature = "io_timeout")] use std::time::Duration; use super::super::{co_io_result, from_nix_error, IoData}; #[cfg(feature = "io_cancel")] use crate::coroutine_impl::co_cancel_data; use crate::coroutine_impl::{is_coroutine, CoroutineImpl, EventSource}; use crate::io::AsIoData; use crate::yield_now::yield_with_io; use nix::unistd::read; pub struct SocketRead<'a> { io_data: &'a IoData, buf: &'a mut [u8], #[cfg(feature = "io_timeout")] timeout: Option<Duration>, pub(crate) is_coroutine: bool, } impl<'a> SocketRead<'a> { pub fn new<T: AsIoData>( s: &'a T, buf: &'a mut [u8], #[cfg(feature = "io_timeout")] timeout: Option<Duration>, ) -> Self { SocketRead { io_data: s.as_io_data(), buf, #[cfg(feature = "io_timeout")] timeout, is_coroutine: is_coroutine(), } } pub fn done(&mut self) -> io::Result<usize> { loop { co_io_result(self.is_coroutine)?; // clear the io_flag self.io_data.io_flag.store(false, Ordering::Relaxed); // finish the read operation match read(self.io_data.fd, self.buf) { Ok(n) => return Ok(n), Err(e) => { if e == nix::errno::Errno::EAGAIN { // do nothing } else { return Err(from_nix_error(e)); } } } if self.io_data.io_flag.load(Ordering::Relaxed) { continue; } // the result is still WouldBlock, need to try again yield_with_io(self, self.is_coroutine); } } } impl<'a> EventSource for SocketRead<'a> { fn subscribe(&mut self, co: CoroutineImpl) { #[cfg(feature = "io_cancel")] let cancel = co_cancel_data(&co); let io_data = self.io_data; #[cfg(feature = "io_timeout")] if let Some(dur) = self.timeout { crate::scheduler::get_scheduler() .get_selector() .add_io_timer(self.io_data, dur); } // after register the coroutine, it's possible that other thread run it immediately // and cause the process after it invalid, this is kind of user and kernel competition // so we need to delay the drop of the EventSource, that's why _g is here unsafe { io_data.co.unsync_store(co) }; // till here the io may be done in other thread // there is event, re-run the coroutine if io_data.io_flag.load(Ordering::Acquire) { #[allow(clippy::needless_return)] return io_data.fast_schedule(); } #[cfg(feature = "io_cancel")] { // register the cancel io data cancel.set_io((*io_data).clone()); // re-check the cancel status if cancel.is_canceled() { unsafe { cancel.cancel() }; } } } }
pub trait RLayout { fn layout( &self ); }
use std::default::Default; /// A resource holding the render settings that can be adjusted by the player. #[derive(Debug, Clone)] pub struct RenderConfig { /// The size of a tile in Pixels in f32. Needed to calculate offsets, /// otherwise width and height could only be retrieved from the Sprite itself, which is not available most of the time. /// (y, x) pub tile_size: (f32, f32,), /// The dimension of a chunk expressed in the count of tiles in x and y direction. /// The bigger a chunk is, the more tiles have to be rendered, which takes up both memory and computing time. /// A distance of 0 would mean that only the chunk the player currently is on would be rendered. pub chunk_render_distance: u64, /// Current rendered screen size pub view_dim: (u32, u32,), } impl Default for RenderConfig { fn default() -> Self { RenderConfig { tile_size: (128.0, 128.0,), chunk_render_distance: 1, view_dim: (1920, 1080,), } } } impl RenderConfig { /// Creates a new RenderConfig based on input parameters. /// (Does a new function even make sense if all members are public?) pub fn new(tile_size: (f32, f32), chunk_render_distance: u64, view_dim: (u32, u32)) -> Self { RenderConfig { tile_size, chunk_render_distance, view_dim } } /// Sets the tile size, should be done when loading the Tilesheet. /// This is not visible to they player, as its an internal measure. pub fn set_tile_size(&mut self, width: f32, height: f32) { self.tile_size = (width, height); } /// Sets the number of chunks in each direction to be rendered, /// zero would mean only the chunk the player stands on is visible. /// Should be adjustable via ingame options. pub fn set_chunk_render_distance(&mut self, render_distance: u64) { self.chunk_render_distance = render_distance; } }
use core::borrow::{Borrow, BorrowMut}; use core::convert::{AsMut, AsRef}; use core::fmt; use core::marker::PhantomData; use core::mem::{self, ManuallyDrop}; use core::ops::{Deref, DerefMut}; use core::ptr::NonNull; cfg_if::cfg_if! { if #[cfg(feature = "std")] { use std::boxed::Box; } else { use alloc::boxed::Box; } } use conquer_pointer::{MarkedNonNull, MarkedPtr}; use crate::alias::AssocRecord; use crate::atomic::Storable; use crate::record::Record; use crate::traits::Reclaim; use crate::Owned; /********** impl Send + Sync **********************************************************************/ unsafe impl<T, R: Reclaim<T>, const N: usize> Send for Owned<T, R, N> where T: Send {} unsafe impl<T, R: Reclaim<T>, const N: usize> Sync for Owned<T, R, N> where T: Sync {} /********** impl inherent (default header) ********************************************************/ impl<T, R: Reclaim<T>, const N: usize> Owned<T, R, N> where R::Header: Default, { #[inline] pub fn new(value: T) -> Self { unsafe { Self::with_header(Default::default(), value) } } #[inline] pub fn with_tag(value: T, tag: usize) -> Self { unsafe { Self::with_header_and_tag(Default::default(), value, tag) } } } impl<T, R: Reclaim<T>, const N: usize> Owned<T, R, N> { /// Creates a new heap-allocated record with the given `header` and `value` /// and returns an owning handle to the allocated `value`. /// /// # Safety /// /// The `header` must be in a state that allows correct reclamation /// handling, as defined by the reclamation mechanism itself. #[inline] pub unsafe fn with_header(header: R::Header, value: T) -> Self { Self { inner: MarkedNonNull::compose_unchecked(Self::alloc_record(header, value), 0), _marker: PhantomData, } } /// Creates a new `Owned` like [`new`](Owned::new) but composes the /// returned pointer with an initial `tag` value. /// /// # Example /// /// The primary use case for this is to pre-mark newly allocated values. /// /// ``` /// use core::sync::atomic::Ordering; /// /// use reclaim::typenum::U1; /// use reclaim::Shared; /// /// type Atomic<T> = reclaim::leak::Atomic<T, U1>; /// type Owned<T> = reclaim::leak::Owned<T, U1>; /// /// let atomic = Atomic::null(); /// let owned = Owned::with_tag("string", 0b1); /// /// atomic.store(owned, Ordering::Relaxed); /// let shared = atomic.load_shared(Ordering::Relaxed); /// /// assert_eq!((&"string", 0b1), shared.unwrap().decompose_ref()); /// ``` #[inline] pub unsafe fn with_header_and_tag(header: R::Header, value: T, tag: usize) -> Self { Self { inner: MarkedNonNull::compose_unchecked(Self::alloc_record(header, value), tag), _marker: PhantomData, } } impl_from_ptr!(); impl_from_non_null!(); /// Consumes the [`Owned`], de-allocates its memory and extracts the /// contained value. /// /// This has the same semantics as destructuring a [`Box`]. #[inline] #[allow(clippy::wrong_self_convention)] pub fn into_inner(owned: Self) -> T { let boxed: Box<AssocRecord<_, R>> = owned.into(); (*boxed).data } #[inline] #[allow(clippy::wrong_self_convention)] pub fn into_marked_ptr(owned: Self) -> MarkedPtr<T, N> { let owned = ManuallyDrop::new(owned); owned.inner.into_marked_ptr() } #[inline] #[allow(clippy::wrong_self_convention)] pub fn into_marked_non_null(owned: Self) -> MarkedNonNull<T, N> { let owned = ManuallyDrop::new(owned); owned.inner } #[inline] #[allow(clippy::wrong_self_convention)] pub fn as_marked_ptr(owned: &Self) -> MarkedPtr<T, N> { owned.inner.into_marked_ptr() } #[inline] pub fn as_marked_non_null(owned: &Self) -> MarkedNonNull<T, N> { owned.inner } #[inline] pub fn clear_tag(owned: Self) -> Self { let owned = ManuallyDrop::new(owned); Self { inner: owned.inner.clear_tag(), _marker: PhantomData } } #[inline] pub fn set_tag(owned: Self, tag: usize) -> Self { let owned = ManuallyDrop::new(owned); Self { inner: owned.inner.set_tag(tag), _marker: PhantomData } } #[inline] pub fn decompose_tag(owned: &Self) -> usize { owned.inner.decompose_tag() } /// Decomposes the internal marked pointer, returning a reference and the /// separated tag. #[inline] pub fn decompose_ref(owned: &Self) -> (&T, usize) { // this is safe because is `inner` is guaranteed to be backed by a valid allocation unsafe { owned.inner.decompose_ref() } } /// Decomposes the internal marked pointer, returning a mutable reference /// and the separated tag. #[inline] pub fn decompose_mut(owned: &mut Self) -> (&mut T, usize) { // this is safe because is `inner` is guaranteed to be backed by a valid allocation unsafe { owned.inner.decompose_mut() } } #[inline] pub fn leak(owned: Self) -> Storable<T, R, N> { let owned = ManuallyDrop::new(owned); Storable::new(owned.inner.into()) } #[inline] pub unsafe fn from_storable(storable: Storable<T, R, N>) -> Self { Self { inner: MarkedNonNull::new_unchecked(storable.into_marked_ptr()), _marker: PhantomData, } } /// Allocates a records wrapping `owned` and returns the pointer to the /// wrapped value. #[inline] fn alloc_record(header: R::Header, value: T) -> NonNull<T> { let record = Box::leak(Box::new(Record { header, data: value })); NonNull::from(&record.data) } #[inline] unsafe fn record_ptr(data: *mut T) -> *mut AssocRecord<T, R> { AssocRecord::<_, R>::header_from_data(data).cast() } } /********** impl AsRef ****************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> AsRef<T> for Owned<T, R, N> { #[inline] fn as_ref(&self) -> &T { self.deref() } } /********** impl AsMut ****************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> AsMut<T> for Owned<T, R, N> { #[inline] fn as_mut(&mut self) -> &mut T { self.deref_mut() } } /********** impl Borrow ***************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> Borrow<T> for Owned<T, R, N> { #[inline] fn borrow(&self) -> &T { self.deref() } } /********** impl BorrowMut ************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> BorrowMut<T> for Owned<T, R, N> { #[inline] fn borrow_mut(&mut self) -> &mut T { self.deref_mut() } } /********** impl Debug ****************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> fmt::Debug for Owned<T, R, N> where T: fmt::Debug, { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (reference, tag) = unsafe { self.inner.decompose_ref() }; f.debug_struct("Owned").field("value", reference).field("tag", &tag).finish() } } /********** impl Deref ****************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> Deref for Owned<T, R, N> { type Target = T; #[inline] fn deref(&self) -> &Self::Target { unsafe { self.inner.as_ref() } } } /********** impl DerefMut *************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> DerefMut for Owned<T, R, N> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { unsafe { self.inner.as_mut() } } } /********** impl Pointer **************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> fmt::Pointer for Owned<T, R, N> { impl_fmt_pointer!(); } /********** impl Drop *****************************************************************************/ impl<T, R: Reclaim<T>, const N: usize> Drop for Owned<T, R, N> { #[inline] fn drop(&mut self) { unsafe { let record = Self::record_ptr(self.inner.decompose_ptr()); mem::drop(Box::from_raw(record)); } } } /********** impl From (Owned) for Box<Record<T, R>> ***********************************************/ impl<T, R: Reclaim<T>, const N: usize> From<Owned<T, R, N>> for Box<AssocRecord<T, R>> { #[inline] fn from(owned: Owned<T, R, N>) -> Self { unsafe { let record = Owned::<T, R, N>::record_ptr(owned.inner.decompose_ptr()); Box::from_raw(record) } } }
use std::io::{Read, Write, Result}; use std::mem; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; pub fn read_string(read: &mut Read) -> Result<String> { let string_length = try!(read.read_u16::<BigEndian>()) as usize; let mut string_bytes = Vec::with_capacity(string_length); unsafe { string_bytes.set_len(string_length); } let result = try!(read.read(&mut string_bytes[..])); if result != string_length { panic!("Read length {} does not equal the string length {}.", result, string_length); } Ok(String::from_utf8(string_bytes).unwrap()) } pub fn write_string(write: &mut Write, string: &str) -> Result<()> { try!(write.write_u16::<BigEndian>(string.len() as u16)); try!(write.write_all(string.as_bytes())); Ok(()) } pub fn string_disk_size(string: &str) -> usize { return mem::size_of::<u16>() + string.len(); }
use crate::Result; use byteorder::*; #[repr(u32)] #[derive(Copy, Clone)] pub enum Shdr_type { NULL = 0x0, PROGBITS = 0x1, SYMTAB = 0x2, STRTAB = 0x3, RELA = 0x4, HASH = 0x5, DYNAMIC = 0x6, NOTE = 0x7, NOBITS = 0x8, REL = 0x9, SHLIB = 0x0A, DYNSYM = 0x0B, INIT_ARRAY = 0x0E, FINI_ARRAY = 0x0F, PRE_INIT_ARRAY = 0x10, GROUP = 0x11, SYMTAB_SHNDX = 0x12, NUM = 0x13, LOOS = 0x60000000, GNU_VERDEF, GNU_VERNEED, GNU_VERSYM, } #[repr(u64)] #[derive(Copy, Clone)] enum Shdr_flags { NONE = 0x0, WRITE = 0x1, ALLOC = 0x2, EXECINSTR = 0x4, MERGE = 0x10, STRINGS = 0x20, INFO_LINK = 0x40, LINK_ORDER = 0x80, OS_NONCONFORMING = 0x100, GROUP = 0x200, TLS = 0x400, MASKOS = 0x0ff00000, MASKPROC = 0xf0000000, ORDERED = 0x4000000, EXCLUDE = 0x8000000 } #[derive(Clone)] pub struct SectionHeader { pub name: String, shstrndx_offset: u32, pub sh_type: Shdr_type, flags: Shdr_flags, addr: u64, pub offset: u64, pub size: u64, link: u32, info: u32, addralign: u64, entsize: u64, } fn parse_shdr_type(phdr: &[u8]) -> Shdr_type { return match LittleEndian::read_u32(&phdr[0x04..0x08]) { 0x0 => return Shdr_type::NULL, 0x1 => return Shdr_type::PROGBITS, 0x2 => return Shdr_type::SYMTAB, 0x3 => return Shdr_type::STRTAB, 0x4 => return Shdr_type::RELA, 0x5 => return Shdr_type::HASH, 0x6 => return Shdr_type::DYNAMIC, 0x7 => return Shdr_type::NOTE, 0x8 => return Shdr_type::NOBITS, 0x9 => return Shdr_type::REL, 0xA => return Shdr_type::SHLIB, 0xB => return Shdr_type::DYNSYM, 0xE => return Shdr_type::INIT_ARRAY, 0xF => return Shdr_type::FINI_ARRAY, 0x10 => return Shdr_type::PRE_INIT_ARRAY, 0x11 => return Shdr_type::GROUP, 0x12 => return Shdr_type::SYMTAB_SHNDX, 0x13 => return Shdr_type::NUM, 0x60000000 => return Shdr_type::LOOS, // 0xXXXXX => return Shdr_type::GNU_VERDEF, // 0xXXXXX => return Shdr_type::GNU_VERNEED, // 0xXXXXX => return Shdr_type::GNU_VERSYM, _ => return Shdr_type::NULL } } fn parse_shdr_flags(phdr: &[u8]) -> Shdr_flags { return match LittleEndian::read_u32(&phdr[0x08..0x10]) { 0x0 => return Shdr_flags::NONE, 0x1 => return Shdr_flags::WRITE, 0x2 => return Shdr_flags::ALLOC, 0x4 => return Shdr_flags::EXECINSTR, 0x10 => return Shdr_flags::MERGE, 0x20 => return Shdr_flags::STRINGS, 0x40 => return Shdr_flags::INFO_LINK, 0x80 => return Shdr_flags::LINK_ORDER, 0x100 => return Shdr_flags::OS_NONCONFORMING, 0x200 => return Shdr_flags::GROUP, 0x400 => return Shdr_flags::TLS, 0x0ff00000 => return Shdr_flags::MASKOS, 0xf0000000 => return Shdr_flags::MASKPROC, 0x4000000 => return Shdr_flags::ORDERED, 0x8000000 => return Shdr_flags::EXCLUDE, // TODO: Throw error here instead -> and return Result _ => return Shdr_flags::NONE } } impl SectionHeader{ // Parse programheaders pub fn parse(shdr: &[u8], name: &str) -> Result< SectionHeader > { Ok(SectionHeader{ name: String::from(name), shstrndx_offset: LittleEndian::read_u32(&shdr[0x0..0x4]), sh_type: parse_shdr_type(&shdr), flags: parse_shdr_flags(&shdr), addr: LittleEndian::read_u64(&shdr[0x10..0x18]), offset: LittleEndian::read_u64(&shdr[0x18..0x20]), size: LittleEndian::read_u64(&shdr[0x20..0x28]), link: LittleEndian::read_u32(&shdr[0x28..0x2C]), info: LittleEndian::read_u32(&shdr[0x2C..0x30]), addralign: LittleEndian::read_u64(&shdr[0x30..0x38]), entsize: LittleEndian::read_u64(&shdr[0x38..0x40]), }) } // print the section header as a LittleEndian formatted object // should this come with/or without padding??? pub fn to_le(&self) -> Vec<u8> { self.to_le_offset(0) } pub fn to_le_offset(&self, offset: usize) -> Vec<u8> { // bin.append([1,2,3].to_vec()) let mut bin = vec![]; bin.extend_from_slice(&self.shstrndx_offset.to_le_bytes()); // do i end up owning this data, thus preventing me from using sh_type elsewhere? bin.extend_from_slice(&(self.sh_type as u32).to_le_bytes()); bin.extend_from_slice(&(self.flags as u64).to_le_bytes()); bin.extend_from_slice(&self.addr.to_le_bytes()); bin.extend_from_slice(&(self.offset + offset as u64).to_le_bytes()); bin.extend_from_slice(&self.size.to_le_bytes()); bin.extend_from_slice(&self.link.to_le_bytes()); bin.extend_from_slice(&self.info.to_le_bytes()); bin.extend_from_slice(&self.addralign.to_le_bytes()); bin.extend_from_slice(&self.entsize.to_le_bytes()); return bin; } } pub fn parse_section_header(bin: &Vec<u8>, shstrndx: u16) -> Result<Vec<SectionHeader>> { let shdr_offset = LittleEndian::read_u64(&bin[0x28..0x30]); let shdr_size = LittleEndian::read_u16(&bin[0x3A..0x3C]); let shdr_num = LittleEndian::read_u16(&bin[0x3C..0x3E]); let shstr_table_offset: usize = (shdr_offset + (shdr_size * shstrndx) as u64 ) as usize; let str_table_offset = LittleEndian::read_u64(&bin[shstr_table_offset+0x18..shstr_table_offset+0x20]) as usize; let str_table_size = LittleEndian::read_u64(&bin[shstr_table_offset+0x20..shstr_table_offset+0x28]) as usize; let mut shdrs:Vec<SectionHeader> = vec![]; // loop through all section headers for i in 0..shdr_num { let start = (shdr_offset+(shdr_size as u64*i as u64) ) as usize; let end = (shdr_offset+(shdr_size as u64*i as u64)+shdr_size as u64 ) as usize; let name_offset = str_table_offset + LittleEndian::read_u32(&bin[start..start+0x4]) as usize; let name = str_from_u8_nul_utf8(&bin[name_offset..str_table_offset+str_table_size])?; let section = SectionHeader::parse(&bin[start..end], name)?; // println!("{}", String::from_utf8_lossy(&bin[name_offset..name_offset+0x4])); // add the section to the table of sections shdrs.push(section); } // loop through them again populating their names // we do this because we haven't mapped the shstrndx yet. return Ok(shdrs); } pub fn str_from_u8_nul_utf8(utf8_src: &[u8]) -> Result<&str> { let nul_range_end = utf8_src.iter() .position(|&c| c == b'\0') .unwrap_or(utf8_src.len()); // default to length if no `\0` present return Ok(::std::str::from_utf8(&utf8_src[0..nul_range_end]).unwrap()) }
fn diverges() { println!("fuck you"); panic!(); } fn return_i(x: i32) -> i32 { println!("hello there"); if x==40 { x } else { println!("oh god are you kidding me"); diverges(); } } fn main() { println!("start"); let x: i32=return_i(42); x; println!("end"); }
#[doc = "Reader of register RANDOMBIT"] pub type R = crate::R<u32, super::RANDOMBIT>; #[doc = "Reader of field `RANDOMBIT`"] pub type RANDOMBIT_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0"] #[inline(always)] pub fn randombit(&self) -> RANDOMBIT_R { RANDOMBIT_R::new((self.bits & 0x01) != 0) } }
// // Process viewer // // Copyright (c) 2019 Guillaume Gomez // use gtk::glib; use gtk::prelude::*; use serde_derive::{Deserialize, Serialize}; use std::cell::RefCell; use std::fs::{create_dir_all, File}; use std::io::Read; use std::path::{Path, PathBuf}; use std::rc::Rc; use crate::utils::{get_app, get_main_window}; use crate::RequiredForSettings; use crate::APPLICATION_NAME; #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Settings { pub display_fahrenheit: bool, pub display_graph: bool, // Timer length in milliseconds (500 minimum!). pub refresh_processes_rate: u32, // Timer length in milliseconds (500 minimum!). pub refresh_system_rate: u32, // Timer length in milliseconds (500 minimum!). pub refresh_network_rate: u32, } impl Default for Settings { fn default() -> Settings { Settings { display_fahrenheit: false, display_graph: false, refresh_processes_rate: 1500, refresh_system_rate: 2000, refresh_network_rate: 1500, } } } impl Settings { fn load_from_file(p: &Path) -> Result<Settings, String> { let mut input = String::new(); let mut file = File::open(p).map_err(|e| format!("Error while opening '{}': {}", p.display(), e))?; file.read_to_string(&mut input) .map_err(|e| format!("Error while opening '{}': {}", p.display(), e))?; toml::from_str(&input).map_err(|e| format!("Error while opening '{}': {}", p.display(), e)) } pub fn load() -> Settings { let s = Self::get_settings_file_path(); if s.exists() && s.is_file() { match Self::load_from_file(&s) { Ok(settings) => settings, Err(e) => { show_error_dialog(false, &e); Settings::default() } } } else { Settings::default() } } pub fn get_settings_file_path() -> PathBuf { let mut path = glib::user_config_dir(); path.push(APPLICATION_NAME); path.push("settings.toml"); path } pub fn save(&self) { let s = Self::get_settings_file_path(); if !s.exists() { if let Some(parent_dir) = s.parent() { if !parent_dir.exists() { if let Err(e) = create_dir_all(parent_dir) { show_error_dialog( false, format!( "Error while trying to build settings snapshot_directory '{}': {}", parent_dir.display(), e ) .as_str(), ); return; } } } } match toml::to_string_pretty(&self) { Ok(output) => { if let Err(e) = std::fs::write(&s, output) { show_error_dialog( false, format!("Error while trying to save file: {}", e).as_str(), ); } } Err(e) => { show_error_dialog( false, format!("Error while trying to save file: {}", e).as_str(), ); } } } } fn show_error_dialog(fatal: bool, text: &str) { let dialog = gtk::MessageDialog::new( get_main_window().as_ref(), gtk::DialogFlags::MODAL, gtk::MessageType::Error, gtk::ButtonsType::Ok, text, ); dialog.connect_response(move |dialog, _| { dialog.close(); if fatal { get_app().quit(); } }); dialog.set_resizable(false); dialog.show(); } pub fn build_spin(label: &str, grid: &gtk::Grid, top: i32, refresh: u32) -> gtk::SpinButton { // Refresh rate. let refresh_label = gtk::Label::builder() .label(label) .halign(gtk::Align::Start) .hexpand(true) .build(); // We allow 0.5 to 5 seconds, in 0.1 second steps. let refresh_entry = gtk::SpinButton::with_range(0.5, 5., 0.1); refresh_entry.set_value(f64::from(refresh) / 1_000.); grid.attach(&refresh_label, 0, top, 1, 1); grid.attach(&refresh_entry, 1, top, 3, 1); refresh_entry } pub fn show_settings_dialog(settings: &Rc<RefCell<Settings>>, rfs: &RequiredForSettings) { let bsettings = &*settings.borrow(); // Create an empty dialog with close button. let dialog = gtk::Dialog::with_buttons( Some("Process Viewer settings"), get_main_window().as_ref(), gtk::DialogFlags::MODAL, &[("Close", gtk::ResponseType::Close)], ); // All the UI widgets are going to be stored in a grid. let grid = gtk::Grid::builder() .column_spacing(4) .row_spacing(4) .margin_bottom(12) .build(); let refresh_procs = build_spin( "Processes refresh rate (in seconds)", &grid, 0, bsettings.refresh_processes_rate, ); let refresh_network = build_spin( "System network refresh rate (in seconds)", &grid, 1, bsettings.refresh_network_rate, ); let refresh_sys = build_spin( "System information refresh rate (in seconds)", &grid, 2, bsettings.refresh_system_rate, ); // Put the grid into the dialog's content area. let content_area = dialog.content_area(); content_area.append(&grid); // content_area.set_border_width(10); // Finally connect to all kinds of change notification signals for the different UI widgets. // Whenever something is changing we directly save the configuration file with the new values. refresh_procs.connect_value_changed(glib::clone!( @weak settings, @weak rfs.process_refresh_timeout as process_refresh_timeout => move |entry| { let mut settings = settings.borrow_mut(); settings.refresh_processes_rate = (entry.value() * 1_000.) as _; *process_refresh_timeout.lock().expect("failed to lock process_refresh_timeout") = settings.refresh_processes_rate; settings.save(); })); refresh_network.connect_value_changed(glib::clone!(@weak settings, @weak rfs.network_refresh_timeout as network_refresh_timeout => move |entry| { let mut settings = settings.borrow_mut(); settings.refresh_network_rate = (entry.value() * 1_000.) as _; *network_refresh_timeout.lock().expect("failed to lock network_refresh_timeout") = settings.refresh_network_rate; settings.save(); })); refresh_sys.connect_value_changed(glib::clone!(@weak settings, @weak rfs.system_refresh_timeout as system_refresh_timeout => move |entry| { let mut settings = settings.borrow_mut(); settings.refresh_system_rate = (entry.value() * 1_000.) as _; *system_refresh_timeout.lock().expect("failed to lock system_refresh_timeout") = settings.refresh_system_rate; settings.save(); })); dialog.connect_response(move |dialog, _| { dialog.close(); }); dialog.set_resizable(false); dialog.show(); }
//! Defines common `async` tasks used by Krator's Controller //! [Manager](crate::manager::Manager). use std::future::Future; use futures::FutureExt; use kube::{api::ApiResource, api::GroupVersionKind, Resource}; use kube_runtime::watcher::Event; use tracing::{debug, info, warn}; use crate::{ manager::controller::ControllerBuilder, operator::Operator, store::Store, util::{concrete_event, DynamicEvent, PrettyEvent}, }; use super::watch::WatchHandle; use super::Controller; /// Watcher task which forwards [DynamicEvent](crate::util::DynamicEvent) to /// a [channel](tokio::sync::mpsc::channel). pub(crate) async fn launch_watcher(client: kube::Client, handle: WatchHandle) { use futures::StreamExt; use futures::TryStreamExt; info!( watch=?handle.watch, "Starting Watcher." ); let api: kube::Api<kube::api::DynamicObject> = match handle.watch.namespace { Some(namespace) => kube::Api::namespaced_with( client, &namespace, &ApiResource::from_gvk(&handle.watch.gvk), ), None => kube::Api::all_with(client, &ApiResource::from_gvk(&handle.watch.gvk)), }; let mut watcher = kube_runtime::watcher(api, handle.watch.list_params).boxed(); loop { match watcher.try_next().await { Ok(Some(event)) => { debug!( event = ?PrettyEvent::from(&event), "Handling event." ); handle.tx.send(event).await.unwrap() } Ok(None) => break, Err(error) => warn!(?error, "Error streaming object events."), } } } /// Task for executing a single Controller / Operator. Listens for /// [DynamicEvent](crate::util::DynamicEvent) on a /// [channel](tokio::sync::mpsc::channel) and forwards them to a Krator /// [OperatorRuntime](crate::OperatorRuntime). /// /// # Errors /// /// A warning will be logged if a `DynamicEvent` cannot be converted to a /// concrete `Event<O::Manifest>`. async fn launch_runtime<O: Operator>( kubeconfig: kube::Config, controller: O, mut rx: tokio::sync::mpsc::Receiver<DynamicEvent>, store: Store, ) { info!( group = &*O::Manifest::group(&()), version = &*O::Manifest::version(&()), kind = &*O::Manifest::kind(&()), "Starting OperatorRuntime." ); let mut runtime = crate::OperatorRuntime::new_with_store(&kubeconfig, controller, Default::default(), store); while let Some(dynamic_event) = rx.recv().await { debug!( group=&*O::Manifest::group(&()), version=&*O::Manifest::version(&()), kind=&*O::Manifest::kind(&()), event = ?PrettyEvent::from(&dynamic_event), "Handling managed event." ); match concrete_event::<O::Manifest>(dynamic_event.clone()) { Ok(event) => runtime.handle_event(event).await, Err(e) => { warn!( group=&*O::Manifest::group(&()), version=&*O::Manifest::version(&()), kind=&*O::Manifest::kind(&()), error=?e, "Error deserializing dynamic object: {:#?}", dynamic_event ); } } } warn!( group = &*O::Manifest::group(&()), version = &*O::Manifest::version(&()), kind = &*O::Manifest::kind(&()), "Managed Sender dropped." ); } /// Task for monitoring `watched` or `owned` resources. Listens for /// [DynamicEvent](crate::util::DynamicEvent) on a /// [channel](tokio::sync::mpsc::channel) and updates /// [Store](crate::store::Store). /// /// # Errors /// /// Will warn on and drop objects with no `metadata.name` field set. /// /// # TODO /// /// * Support notifications for `owned` resources. async fn launch_watches( mut rx: tokio::sync::mpsc::Receiver<DynamicEvent>, gvk: GroupVersionKind, store: Store, ) { while let Some(dynamic_event) = rx.recv().await { debug!( gvk=?gvk, event = ?PrettyEvent::from(&dynamic_event), "Handling watched event." ); match dynamic_event { Event::Applied(dynamic_object) => { let namespace = dynamic_object.metadata.namespace.clone(); let name = match dynamic_object.metadata.name.clone() { Some(name) => name, None => { warn!( gvk=?gvk, "Object without name." ); continue; } }; store .insert_gvk(namespace, name, &gvk, dynamic_object) .await; } Event::Deleted(dynamic_object) => { let namespace = dynamic_object.metadata.namespace.clone(); let name = match dynamic_object.metadata.name.clone() { Some(name) => name, None => { warn!( gvk=?gvk, "Object without name." ); continue; } }; store.delete_gvk(namespace, name, &gvk).await; } Event::Restarted(dynamic_objects) => { store.reset(&gvk).await; for dynamic_object in dynamic_objects { let namespace = dynamic_object.metadata.namespace.clone(); let name = match dynamic_object.metadata.name.clone() { Some(name) => name, None => { warn!( gvk=?gvk, "Object without name." ); continue; } }; store .insert_gvk(namespace, name, &gvk, dynamic_object) .await; } } } } } /// Shorthand for the opaque Future type of the tasks in this module. These /// must be `awaited` in order to execute. pub(crate) type OperatorTask = std::pin::Pin<Box<dyn Future<Output = ()> + Send>>; /// Generates the `async` tasks needed to run a single controller / operator. /// /// In general, converts a /// [ControllerBuilder](crate::manager::controller::ControllerBuilder) to a /// `Vec` of [OperatorTask](crate::manager::tasks::OperatorTask) which can be /// executed using [join_all](futures::future::join_all). pub(crate) fn controller_tasks<C: Operator>( kubeconfig: kube::Config, controller: ControllerBuilder<C>, store: Store, ) -> (Controller, Vec<OperatorTask>) { let mut watches = Vec::new(); let mut owns = Vec::new(); let mut tasks = Vec::new(); let buffer = controller.buffer(); // Create main Operator task. let (manages, rx) = controller.manages().handle(buffer); let task = launch_runtime(kubeconfig, controller.controller, rx, store.clone()).boxed(); tasks.push(task); for watch in controller.watches { let (handle, rx) = watch.handle(buffer); let task = launch_watches(rx, handle.watch.gvk.clone(), store.clone()).boxed(); watches.push(handle); tasks.push(task); } for own in controller.owns { let (handle, rx) = own.handle(buffer); let task = launch_watches(rx, handle.watch.gvk.clone(), store.clone()).boxed(); owns.push(handle); tasks.push(task); } ( Controller { manages, owns, watches, }, tasks, ) }
use super::{ Action, Pause, Initialization}; use dotrix::ecs::{ Mut, Const }; use dotrix::{ Window, State}; use dotrix::math::{ Vec2i, Vec2u }; use dotrix::services::{ Input, }; use dotrix::overlay::Overlay; use dotrix::window::{ Fullscreen, }; use dotrix::egui::{ self, Egui, }; pub struct Settings { pub show_info_panel: bool, pub god_mode: bool, window_mode: WindowMode, } impl Default for Settings { fn default() -> Self { Self { show_info_panel: true, god_mode: false, window_mode: WindowMode::Windowed, } } } pub fn startup( window: Const<Window>, ) { window.set_outer_position( Vec2i::new( (window.screen_size().x - window.outer_size().x) as i32 / 2, (window.screen_size().y - window.outer_size().y) as i32 / 2, ) ); window.set_inner_size(Vec2u::new(1280, 720)); } pub fn init( mut window: Mut<Window>, ) { window.set_cursor_grab(true); window.set_cursor_visible(false); } pub fn ui_update ( input: Const<Input>, mut state: Mut<State>, ) { if input.is_action_activated(Action::Menu) { state.push( Pause { handled: false} ); } } pub fn pause_menu ( overlay: Const<Overlay>, mut settings: Mut<Settings>, mut window: Mut<Window>, mut state: Mut<State>, input: Const<Input>, ) { window.set_cursor_grab(false); window.set_cursor_visible(true); let egui = overlay.get::<Egui>() .expect("Renderer does not contain an Overlay instance"); let mut exit_pause = false; egui::containers::Window::new("Pause") .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::new(0.0, 0.0)) .collapsible(false) .resizable(false) .default_width(130.0) .show(&egui.ctx, |ui| { ui.vertical_centered_justified(|ui| { if ui.button("Resume").clicked() { exit_pause = true; } if settings.show_info_panel == true { if ui.button("Hide info panel").clicked() { settings.show_info_panel = false; } } else { if ui.button("Show info panel").clicked() { settings.show_info_panel = true; } } if settings.god_mode == true { if ui.button("God mode: on").clicked() { settings.god_mode = false; } } else { if ui.button("God mode: off").clicked() { settings.god_mode = true; } } if settings.window_mode == WindowMode::BorderlessFullscreen { if ui.button("Windowed").clicked() { window.set_fullscreen(None); settings.window_mode = WindowMode::Windowed; } } else { if ui.button("Fullscreen").clicked() { window.set_fullscreen(Some(Fullscreen::Borderless(0))); settings.window_mode = WindowMode::BorderlessFullscreen; } } if ui.button("Reset the game").clicked() { state.push(Initialization {}); } if ui.button("Exit").clicked() { window.close(); } } ) }); match state.get_mut::<Pause>() { None => {}, Some(paused) => { if paused.handled & input.is_action_activated(Action::Menu) { exit_pause = true; } paused.handled = true; } } if exit_pause { window.set_cursor_grab(true); window.set_cursor_visible(false); state.pop_any(); } } #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum WindowMode { BorderlessFullscreen, Windowed, }
#[doc = "Register `TTOST` reader"] pub type R = crate::R<TTOST_SPEC>; #[doc = "Register `TTOST` writer"] pub type W = crate::W<TTOST_SPEC>; #[doc = "Field `EL` reader - Error Level"] pub type EL_R = crate::FieldReader; #[doc = "Field `EL` writer - Error Level"] pub type EL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `MS` reader - Master State."] pub type MS_R = crate::FieldReader; #[doc = "Field `MS` writer - Master State."] pub type MS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `SYS` reader - Synchronization State"] pub type SYS_R = crate::FieldReader; #[doc = "Field `SYS` writer - Synchronization State"] pub type SYS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `QGTP` reader - Quality of Global Time Phase"] pub type QGTP_R = crate::BitReader; #[doc = "Field `QGTP` writer - Quality of Global Time Phase"] pub type QGTP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `QCS` reader - Quality of Clock Speed"] pub type QCS_R = crate::BitReader; #[doc = "Field `QCS` writer - Quality of Clock Speed"] pub type QCS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTO` reader - Reference Trigger Offset"] pub type RTO_R = crate::FieldReader; #[doc = "Field `RTO` writer - Reference Trigger Offset"] pub type RTO_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `WGTD` reader - Wait for Global Time Discontinuity"] pub type WGTD_R = crate::BitReader; #[doc = "Field `WGTD` writer - Wait for Global Time Discontinuity"] pub type WGTD_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GFI` reader - Gap Finished Indicator."] pub type GFI_R = crate::BitReader; #[doc = "Field `GFI` writer - Gap Finished Indicator."] pub type GFI_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TMP` reader - Time Master Priority"] pub type TMP_R = crate::FieldReader; #[doc = "Field `TMP` writer - Time Master Priority"] pub type TMP_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `GSI` reader - Gap Started Indicator."] pub type GSI_R = crate::BitReader; #[doc = "Field `GSI` writer - Gap Started Indicator."] pub type GSI_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WFE` reader - Wait for Event"] pub type WFE_R = crate::BitReader; #[doc = "Field `WFE` writer - Wait for Event"] pub type WFE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AWE` reader - Application Watchdog Event"] pub type AWE_R = crate::BitReader; #[doc = "Field `AWE` writer - Application Watchdog Event"] pub type AWE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WECS` reader - Wait for External Clock Synchronization"] pub type WECS_R = crate::BitReader; #[doc = "Field `WECS` writer - Wait for External Clock Synchronization"] pub type WECS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPL` reader - Schedule Phase Lock"] pub type SPL_R = crate::BitReader; #[doc = "Field `SPL` writer - Schedule Phase Lock"] pub type SPL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bits 0:1 - Error Level"] #[inline(always)] pub fn el(&self) -> EL_R { EL_R::new((self.bits & 3) as u8) } #[doc = "Bits 2:3 - Master State."] #[inline(always)] pub fn ms(&self) -> MS_R { MS_R::new(((self.bits >> 2) & 3) as u8) } #[doc = "Bits 4:5 - Synchronization State"] #[inline(always)] pub fn sys(&self) -> SYS_R { SYS_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bit 6 - Quality of Global Time Phase"] #[inline(always)] pub fn qgtp(&self) -> QGTP_R { QGTP_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Quality of Clock Speed"] #[inline(always)] pub fn qcs(&self) -> QCS_R { QCS_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bits 8:15 - Reference Trigger Offset"] #[inline(always)] pub fn rto(&self) -> RTO_R { RTO_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bit 22 - Wait for Global Time Discontinuity"] #[inline(always)] pub fn wgtd(&self) -> WGTD_R { WGTD_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Gap Finished Indicator."] #[inline(always)] pub fn gfi(&self) -> GFI_R { GFI_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bits 24:26 - Time Master Priority"] #[inline(always)] pub fn tmp(&self) -> TMP_R { TMP_R::new(((self.bits >> 24) & 7) as u8) } #[doc = "Bit 27 - Gap Started Indicator."] #[inline(always)] pub fn gsi(&self) -> GSI_R { GSI_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Wait for Event"] #[inline(always)] pub fn wfe(&self) -> WFE_R { WFE_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - Application Watchdog Event"] #[inline(always)] pub fn awe(&self) -> AWE_R { AWE_R::new(((self.bits >> 29) & 1) != 0) } #[doc = "Bit 30 - Wait for External Clock Synchronization"] #[inline(always)] pub fn wecs(&self) -> WECS_R { WECS_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - Schedule Phase Lock"] #[inline(always)] pub fn spl(&self) -> SPL_R { SPL_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bits 0:1 - Error Level"] #[inline(always)] #[must_use] pub fn el(&mut self) -> EL_W<TTOST_SPEC, 0> { EL_W::new(self) } #[doc = "Bits 2:3 - Master State."] #[inline(always)] #[must_use] pub fn ms(&mut self) -> MS_W<TTOST_SPEC, 2> { MS_W::new(self) } #[doc = "Bits 4:5 - Synchronization State"] #[inline(always)] #[must_use] pub fn sys(&mut self) -> SYS_W<TTOST_SPEC, 4> { SYS_W::new(self) } #[doc = "Bit 6 - Quality of Global Time Phase"] #[inline(always)] #[must_use] pub fn qgtp(&mut self) -> QGTP_W<TTOST_SPEC, 6> { QGTP_W::new(self) } #[doc = "Bit 7 - Quality of Clock Speed"] #[inline(always)] #[must_use] pub fn qcs(&mut self) -> QCS_W<TTOST_SPEC, 7> { QCS_W::new(self) } #[doc = "Bits 8:15 - Reference Trigger Offset"] #[inline(always)] #[must_use] pub fn rto(&mut self) -> RTO_W<TTOST_SPEC, 8> { RTO_W::new(self) } #[doc = "Bit 22 - Wait for Global Time Discontinuity"] #[inline(always)] #[must_use] pub fn wgtd(&mut self) -> WGTD_W<TTOST_SPEC, 22> { WGTD_W::new(self) } #[doc = "Bit 23 - Gap Finished Indicator."] #[inline(always)] #[must_use] pub fn gfi(&mut self) -> GFI_W<TTOST_SPEC, 23> { GFI_W::new(self) } #[doc = "Bits 24:26 - Time Master Priority"] #[inline(always)] #[must_use] pub fn tmp(&mut self) -> TMP_W<TTOST_SPEC, 24> { TMP_W::new(self) } #[doc = "Bit 27 - Gap Started Indicator."] #[inline(always)] #[must_use] pub fn gsi(&mut self) -> GSI_W<TTOST_SPEC, 27> { GSI_W::new(self) } #[doc = "Bit 28 - Wait for Event"] #[inline(always)] #[must_use] pub fn wfe(&mut self) -> WFE_W<TTOST_SPEC, 28> { WFE_W::new(self) } #[doc = "Bit 29 - Application Watchdog Event"] #[inline(always)] #[must_use] pub fn awe(&mut self) -> AWE_W<TTOST_SPEC, 29> { AWE_W::new(self) } #[doc = "Bit 30 - Wait for External Clock Synchronization"] #[inline(always)] #[must_use] pub fn wecs(&mut self) -> WECS_W<TTOST_SPEC, 30> { WECS_W::new(self) } #[doc = "Bit 31 - Schedule Phase Lock"] #[inline(always)] #[must_use] pub fn spl(&mut self) -> SPL_W<TTOST_SPEC, 31> { SPL_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 = "FDCAN TT Operation Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ttost::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 [`ttost::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TTOST_SPEC; impl crate::RegisterSpec for TTOST_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ttost::R`](R) reader structure"] impl crate::Readable for TTOST_SPEC {} #[doc = "`write(|w| ..)` method takes [`ttost::W`](W) writer structure"] impl crate::Writable for TTOST_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TTOST to value 0"] impl crate::Resettable for TTOST_SPEC { const RESET_VALUE: Self::Ux = 0; }
extern crate bodyparser; extern crate exonum; extern crate iron; extern crate router; extern crate serde; extern crate serde_json; use std::collections::HashMap; use exonum::api::Api; use exonum::blockchain::Blockchain; use exonum::crypto::PublicKey; // use exonum::encoding::serialize::FromHex; use hyper::header::ContentType; use iron::headers::AccessControlAllowOrigin; use iron::prelude::*; use iron::status; use router::Router; use currency::api::error::ApiError; use currency::error::Error; use currency::transactions::components::FeesCalculator; use currency::transactions::{ AddAssets, DeleteAssets, Exchange, ExchangeIntermediary, Trade, TradeIntermediary, Transfer, }; #[derive(Clone)] pub struct FeesApi { pub blockchain: Blockchain, } #[serde(untagged)] #[derive(Clone, Serialize, Deserialize, Debug)] pub enum FeesRequest { Transfer(Transfer), AddAssets(AddAssets), DeleteAssets(DeleteAssets), Trade(Trade), TradeIntermediary(TradeIntermediary), Exchange(Exchange), ExchangeIntermediary(ExchangeIntermediary), } impl Into<Box<FeesCalculator>> for FeesRequest { fn into(self) -> Box<FeesCalculator> { match self { FeesRequest::Transfer(trans) => Box::new(trans), FeesRequest::AddAssets(trans) => Box::new(trans), FeesRequest::DeleteAssets(trans) => Box::new(trans), FeesRequest::Trade(trans) => Box::new(trans), FeesRequest::TradeIntermediary(trans) => Box::new(trans), FeesRequest::Exchange(trans) => Box::new(trans), FeesRequest::ExchangeIntermediary(trans) => Box::new(trans), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct FeesResponseBody { pub fees: HashMap<PublicKey, u64>, } pub type FeesResponse = Result<Result<FeesResponseBody, Error>, ApiError>; impl Api for FeesApi { fn wire(&self, router: &mut Router) { let self_ = self.clone(); let fees = move |req: &mut Request| -> IronResult<Response> { let result: FeesResponse = match req.get::<bodyparser::Struct<FeesRequest>>() { Ok(Some(request)) => { let calculator: Box<FeesCalculator> = request.into(); let view = &mut self_.blockchain.fork(); match calculator.calculate_fees(view) { Ok(fees) => Ok(Ok(FeesResponseBody { fees })), Err(e) => Ok(Err(e)), } } Ok(None) => Err(ApiError::EmptyRequestBody), Err(_) => Err(ApiError::IncorrectRequest), }; let status_code = result .clone() .ok() .map(|r| r.err().map(|_| status::BadRequest).unwrap_or(status::Ok)) .unwrap_or(status::BadRequest); let mut res = Response::with((status_code, serde_json::to_string_pretty(&result).unwrap())); res.headers.set(ContentType::json()); res.headers.set(AccessControlAllowOrigin::Any); Ok(res) }; router.post("/v1/fees/transactions", fees, "transaction_fee"); } }
use Packages_and_Crates::mode1::detail as A; use rand::Rng; use Packages_and_Crates::HashMap; fn main() { // Externel Crates from crate.io let number = rand::thread_rng().gen_range(1,11); println!("{}",number); let mut v = HashMap::new(); v.insert("1","Abbas"); println!("Hello, world!"); detail(); A(); } fn detail(){ println!("Hello! from Binary Crates"); }
use std::mem; use std::rc::Rc; #[derive(Debug)] pub struct ParseTree<K> { pub kind: K, pub span: Span, pub child: Option<Rc<ParseTree<K>>>, pub sibling: Option<Rc<ParseTree<K>>>, } #[derive(Debug)] pub struct Span { pub lo: usize, pub hi: usize, } pub const DUMMY_SPAN: Span = Span { lo: 0, hi: 0 }; /////////////////////////////////////////////////////////////////////////// impl<K> ParseTree<K> { #[cfg(test)] fn build(value: K, span: Span, children: Vec<ParseTree<K>>) -> ParseTree<K> { ParseTree::new(value, span, ParseTree::sibling_chain(children)) } pub fn new(kind: K, span: Span, child: Option<ParseTree<K>>) -> ParseTree<K> { let child = child.map(Rc::new); ParseTree { kind: kind, span: span, child: child, sibling: None } } pub fn sibling_chain(mut children: Vec<ParseTree<K>>) -> Option<ParseTree<K>> { let mut p = match children.pop() { Some(p) => p, None => { return None; } }; while let Some(mut q) = children.pop() { q.sibling = Some(Rc::new(p)); p = q; } Some(p) } pub fn add_child_front(&mut self, mut child: ParseTree<K>) { assert!(child.sibling.is_none()); let old_child = mem::replace(&mut self.child, None); child.sibling = old_child; self.child = Some(Rc::new(child)); } pub fn children(&self) -> ChildIterator<K> { ChildIterator { next: to_ref(&self.child) } } } fn to_ref<K>(tree: &Option<Rc<ParseTree<K>>>) -> Option<&ParseTree<K>> { tree.as_ref().map(|t| &**t) } /////////////////////////////////////////////////////////////////////////// pub struct ChildIterator<'tree, K: 'tree> { next: Option<&'tree ParseTree<K>> } impl<'tree, K> Iterator for ChildIterator<'tree, K> { type Item = &'tree ParseTree<K>; fn next(&mut self) -> Option<&'tree ParseTree<K>> { match self.next { Some(ptr) => { self.next = to_ref(&ptr.sibling); Some(ptr) } None => None, } } } /////////////////////////////////////////////////////////////////////////// impl Span { pub fn new(lo: usize, hi: usize) -> Span { Span { lo: lo, hi: hi } } } #[cfg(test)] mod test { use super::*; macro_rules! test_tree { ({ $value:expr; $($children:tt)* }) => { ParseTree::build($value, DUMMY_SPAN, vec![$(test_tree!($children)),*]) } } #[test] fn iterate() { let tree = test_tree!({22; {44; {66;}} {88;}}); let kids: Vec<_> = tree.children().map(|x| x.kind).collect(); assert_eq!(kids, vec![44, 88]); } }
#[cfg(test)] mod param_test; pub(crate) mod param_chunk_list; pub(crate) mod param_forward_tsn_supported; pub(crate) mod param_header; pub(crate) mod param_heartbeat_info; pub(crate) mod param_outgoing_reset_request; pub(crate) mod param_random; pub(crate) mod param_reconfig_response; pub(crate) mod param_requested_hmac_algorithm; pub(crate) mod param_state_cookie; pub(crate) mod param_supported_extensions; pub(crate) mod param_type; use crate::error::Error; use crate::param::{ param_chunk_list::ParamChunkList, param_forward_tsn_supported::ParamForwardTsnSupported, param_heartbeat_info::ParamHeartbeatInfo, param_outgoing_reset_request::ParamOutgoingResetRequest, param_random::ParamRandom, param_reconfig_response::ParamReconfigResponse, param_requested_hmac_algorithm::ParamRequestedHmacAlgorithm, param_state_cookie::ParamStateCookie, param_supported_extensions::ParamSupportedExtensions, }; use param_header::*; use param_type::*; use bytes::{Buf, Bytes, BytesMut}; use std::{any::Any, fmt}; pub(crate) trait Param: fmt::Display + fmt::Debug { fn header(&self) -> ParamHeader; fn unmarshal(raw: &Bytes) -> Result<Self, Error> where Self: Sized; fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize, Error>; fn value_length(&self) -> usize; fn clone_to(&self) -> Box<dyn Param + Send + Sync>; fn as_any(&self) -> &(dyn Any + Send + Sync); fn marshal(&self) -> Result<Bytes, Error> { let capacity = PARAM_HEADER_LENGTH + self.value_length(); let mut buf = BytesMut::with_capacity(capacity); self.marshal_to(&mut buf)?; Ok(buf.freeze()) } } impl Clone for Box<dyn Param + Send + Sync> { fn clone(&self) -> Box<dyn Param + Send + Sync> { self.clone_to() } } pub(crate) fn build_param(raw_param: &Bytes) -> Result<Box<dyn Param + Send + Sync>, Error> { if raw_param.len() < PARAM_HEADER_LENGTH { return Err(Error::ErrParamHeaderTooShort); } let reader = &mut raw_param.slice(..2); let t: ParamType = reader.get_u16().into(); match t { ParamType::ForwardTsnSupp => Ok(Box::new(ParamForwardTsnSupported::unmarshal(raw_param)?)), ParamType::SupportedExt => Ok(Box::new(ParamSupportedExtensions::unmarshal(raw_param)?)), ParamType::Random => Ok(Box::new(ParamRandom::unmarshal(raw_param)?)), ParamType::ReqHmacAlgo => Ok(Box::new(ParamRequestedHmacAlgorithm::unmarshal(raw_param)?)), ParamType::ChunkList => Ok(Box::new(ParamChunkList::unmarshal(raw_param)?)), ParamType::StateCookie => Ok(Box::new(ParamStateCookie::unmarshal(raw_param)?)), ParamType::HeartbeatInfo => Ok(Box::new(ParamHeartbeatInfo::unmarshal(raw_param)?)), ParamType::OutSsnResetReq => Ok(Box::new(ParamOutgoingResetRequest::unmarshal(raw_param)?)), ParamType::ReconfigResp => Ok(Box::new(ParamReconfigResponse::unmarshal(raw_param)?)), _ => Err(Error::ErrParamTypeUnhandled), } }
/*! Day2 * http://adventofcode.com/2018/day/2 */ extern crate day02; type Result<T> = std::result::Result<T, Box<std::error::Error>>; static INPUT: &'static str = include_str!("../../input.txt"); pub fn main() { println!( "Solution 2a: {}", day02::solve2a(parse_input(INPUT).expect("Error Parsing Input")) ); println!( "Solution 2b: {}", day02::solve2b(parse_input(INPUT).expect("Error Parsing Input")) ); } fn parse_input(input: &str) -> Result<Vec<&str>> { input.trim().lines().map(|line| Ok(line.trim())).collect() } #[cfg(test)] mod tests { use super::*; #[test] fn day02a() { let ans = day02::solve2a( parse_input("abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab") .expect("Error Parsing Input"), ); assert_eq!(ans, 12, "Expected 12 for solve2a"); } #[test] fn day02b() { let ans = day02::solve2b( parse_input("abcde\nfghij\nklmno\npqrst\nfguij\naxcye\nwvxyz") .expect("Error Parsing Input"), ); assert_eq!(ans, "fgij", "Expected 'fgij' for solve2b"); } }
mod async_smoltcp; mod virtual_tun; pub mod socket; pub mod vpn_client; pub use async_smoltcp::*; pub const DEFAULT_MTU: usize = 1500;
mod weather; use serde_json; use std::{fs, env}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { // Load config let contents = fs::read_to_string("config.json")?; let cfg: serde_json::Value = serde_json::from_str(&contents)?; // Load args let args: Vec<String> = env::args().collect(); // Load and print data let api = weather::OpenWeatherApi {api_key: cfg["API_KEY"].to_string().replace("\"", "")}; let json = api.get_json(args[1].to_string()).await; let raw_json = format!(r#"{}"#, json[10..json.len() - 3].to_string().replace("\\", "")); let v: serde_json::Value = serde_json::from_str(&raw_json)?; api.print_data(v); Ok(()) }
use std::collections::HashMap; use std::collections::HashSet; use std::io; use std::io::BufRead; use std::io::BufReader; use std::num::ParseIntError; use std::str::FromStr; #[derive(Debug)] struct Program { name: String, weight: u32, children: Vec<String>, } impl FromStr for Program { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { let parts: Vec<&str> = s.split(" -> ").collect(); let name_weight: Vec<&str> = parts[0].split_whitespace().collect(); let name = name_weight[0].to_string(); let weight: u32 = name_weight[1] .trim_matches(|p| p == '(' || p == ')') .parse()?; let children: Vec<String> = if let Some(children) = parts.get(1) { children .split(", ") .map(|child| child.to_string()) .collect() } else { Vec::new() }; Ok(Program { name, weight, children, }) } } fn total_weight(programs: &HashMap<String, Program>, name: &String) -> Result<u32, u32> { let program = &programs.get(name).unwrap(); let mut weights = HashMap::new(); for child in &program.children { let weight = total_weight(programs, child)?; let entry = weights.entry(weight).or_insert((child, 0)); entry.0 = child; entry.1 += 1; } match weights.len() { 0 => Ok(program.weight), 1 => Ok(program.weight + weights.iter().next().unwrap().0 * program.children.len() as u32), 2 => { let wrong_weight = *weights.iter().find(|(_, entry)| entry.1 == 1).unwrap().0; let wrong_name = weights.get(&wrong_weight).unwrap().0; let ok_weight = *weights .iter() .find(|(weight, _)| **weight != wrong_weight) .unwrap() .0; let diff = ok_weight as i32 - wrong_weight as i32; Err((programs.get(wrong_name).unwrap().weight as i32 + diff) as u32) } _ => Err(0), } } fn insert_or_remove_if_present(set: &mut HashSet<String>, name: &String) { if set.contains(name) { set.remove(name); } else { set.insert(name.clone()); } } fn main() { let reader = BufReader::new(io::stdin()); let programs: HashMap<String, Program> = reader .lines() .map(|line| { let p: Program = line.unwrap().trim().parse().unwrap(); (p.name.clone(), p) }) .collect(); let mut set: HashSet<String> = HashSet::new(); programs.iter().for_each(|(name, program)| { insert_or_remove_if_present(&mut set, &name); program .children .iter() .for_each(|child| insert_or_remove_if_present(&mut set, &child)); }); assert_eq!(set.len(), 1); let bottom = set.iter().next().unwrap(); println!("part 1: {}", bottom); println!("part 2: {}", total_weight(&programs, bottom).err().unwrap()); }
#[doc = "Register `RCC_AHB3RSTSETR` reader"] pub type R = crate::R<RCC_AHB3RSTSETR_SPEC>; #[doc = "Register `RCC_AHB3RSTSETR` writer"] pub type W = crate::W<RCC_AHB3RSTSETR_SPEC>; #[doc = "Field `DCMIRST` reader - DCMIRST"] pub type DCMIRST_R = crate::BitReader; #[doc = "Field `DCMIRST` writer - DCMIRST"] pub type DCMIRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRYP2RST` reader - CRYP2RST"] pub type CRYP2RST_R = crate::BitReader; #[doc = "Field `CRYP2RST` writer - CRYP2RST"] pub type CRYP2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HASH2RST` reader - HASH2RST"] pub type HASH2RST_R = crate::BitReader; #[doc = "Field `HASH2RST` writer - HASH2RST"] pub type HASH2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RNG2RST` reader - RNG2RST"] pub type RNG2RST_R = crate::BitReader; #[doc = "Field `RNG2RST` writer - RNG2RST"] pub type RNG2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRC2RST` reader - CRC2RST"] pub type CRC2RST_R = crate::BitReader; #[doc = "Field `CRC2RST` writer - CRC2RST"] pub type CRC2RST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSEMRST` reader - HSEMRST"] pub type HSEMRST_R = crate::BitReader; #[doc = "Field `HSEMRST` writer - HSEMRST"] pub type HSEMRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `IPCCRST` reader - IPCCRST"] pub type IPCCRST_R = crate::BitReader; #[doc = "Field `IPCCRST` writer - IPCCRST"] pub type IPCCRST_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - DCMIRST"] #[inline(always)] pub fn dcmirst(&self) -> DCMIRST_R { DCMIRST_R::new((self.bits & 1) != 0) } #[doc = "Bit 4 - CRYP2RST"] #[inline(always)] pub fn cryp2rst(&self) -> CRYP2RST_R { CRYP2RST_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - HASH2RST"] #[inline(always)] pub fn hash2rst(&self) -> HASH2RST_R { HASH2RST_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - RNG2RST"] #[inline(always)] pub fn rng2rst(&self) -> RNG2RST_R { RNG2RST_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - CRC2RST"] #[inline(always)] pub fn crc2rst(&self) -> CRC2RST_R { CRC2RST_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 11 - HSEMRST"] #[inline(always)] pub fn hsemrst(&self) -> HSEMRST_R { HSEMRST_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - IPCCRST"] #[inline(always)] pub fn ipccrst(&self) -> IPCCRST_R { IPCCRST_R::new(((self.bits >> 12) & 1) != 0) } } impl W { #[doc = "Bit 0 - DCMIRST"] #[inline(always)] #[must_use] pub fn dcmirst(&mut self) -> DCMIRST_W<RCC_AHB3RSTSETR_SPEC, 0> { DCMIRST_W::new(self) } #[doc = "Bit 4 - CRYP2RST"] #[inline(always)] #[must_use] pub fn cryp2rst(&mut self) -> CRYP2RST_W<RCC_AHB3RSTSETR_SPEC, 4> { CRYP2RST_W::new(self) } #[doc = "Bit 5 - HASH2RST"] #[inline(always)] #[must_use] pub fn hash2rst(&mut self) -> HASH2RST_W<RCC_AHB3RSTSETR_SPEC, 5> { HASH2RST_W::new(self) } #[doc = "Bit 6 - RNG2RST"] #[inline(always)] #[must_use] pub fn rng2rst(&mut self) -> RNG2RST_W<RCC_AHB3RSTSETR_SPEC, 6> { RNG2RST_W::new(self) } #[doc = "Bit 7 - CRC2RST"] #[inline(always)] #[must_use] pub fn crc2rst(&mut self) -> CRC2RST_W<RCC_AHB3RSTSETR_SPEC, 7> { CRC2RST_W::new(self) } #[doc = "Bit 11 - HSEMRST"] #[inline(always)] #[must_use] pub fn hsemrst(&mut self) -> HSEMRST_W<RCC_AHB3RSTSETR_SPEC, 11> { HSEMRST_W::new(self) } #[doc = "Bit 12 - IPCCRST"] #[inline(always)] #[must_use] pub fn ipccrst(&mut self) -> IPCCRST_W<RCC_AHB3RSTSETR_SPEC, 12> { IPCCRST_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register is used to activate the reset of the corresponding peripheral.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_ahb3rstsetr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_ahb3rstsetr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RCC_AHB3RSTSETR_SPEC; impl crate::RegisterSpec for RCC_AHB3RSTSETR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rcc_ahb3rstsetr::R`](R) reader structure"] impl crate::Readable for RCC_AHB3RSTSETR_SPEC {} #[doc = "`write(|w| ..)` method takes [`rcc_ahb3rstsetr::W`](W) writer structure"] impl crate::Writable for RCC_AHB3RSTSETR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets RCC_AHB3RSTSETR to value 0"] impl crate::Resettable for RCC_AHB3RSTSETR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::cmp::Ordering; use std::time::Duration; use std::{env, path}; use ggez::event::{self, EventHandler}; use ggez::nalgebra::Point2; use ggez::{filesystem, graphics, timer}; use ggez::{Context, GameResult}; impl EventHandler for SemiFixedTimeStep { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { let mut frame_time = timer::delta(ctx).as_secs_f64(); while frame_time > 0.0 { let cmp = frame_time.partial_cmp(&self.dt).expect("float NaN error"); let delta_time: f64 = if let Ordering::Less = cmp { frame_time } else { self.dt }; self.simulate(delta_time); frame_time -= delta_time; } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::clear(ctx, graphics::WHITE); self.draw_fps_counter(ctx)?; self.draw_circle(ctx, self.pos_x)?; graphics::present(ctx)?; // timer::sleep(Duration::from_secs(2)); Ok(()) } } struct SemiFixedTimeStep { pos_x: f32, velocity_x: f32, dt: f64, // upper bound for our time step; } impl SemiFixedTimeStep { pub fn new(_ctx: &mut Context) -> SemiFixedTimeStep { SemiFixedTimeStep { pos_x: 0.0, velocity_x: 60.0, dt: 1.0f64 / 60.0f64, } } pub fn draw_fps_counter(&self, ctx: &mut Context) -> GameResult<()> { let fps = timer::fps(ctx); let delta = timer::delta(ctx); let stats_display = graphics::Text::new(format!("FPS: {}, delta: {:?}", fps, delta)); println!( "[draw] ticks: {}\tfps: {}\tdelta: {:?}", timer::ticks(ctx), fps, delta, ); graphics::draw( ctx, &stats_display, (Point2::new(0.0, 0.0), graphics::BLACK), ) } pub fn draw_circle(&self, ctx: &mut Context, x: f32) -> GameResult<()> { let circle = graphics::Mesh::new_circle( ctx, graphics::DrawMode::fill(), Point2::new(0.0, 0.0), 100.0, 2.0, graphics::BLACK, )?; graphics::draw(ctx, &circle, (Point2::new(x, 380.0),)) } pub fn simulate(&mut self, time: f64) { let distance = self.velocity_x as f64 * time; self.pos_x = self.pos_x % 800.0 + distance as f32; println!("[update] distance {}", distance); } } fn main() -> GameResult { let mut cb = ggez::ContextBuilder::new("name", "author"); if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { let path = path::PathBuf::from(manifest_dir).join("resources"); cb = cb.add_resource_path(path); } let (ctx, event_loop) = &mut cb.build()?; println!("{:#?}", filesystem::read_config(ctx)); let mut vsync_demo = SemiFixedTimeStep::new(ctx); event::run(ctx, event_loop, &mut vsync_demo) }
mod piece; pub use piece::*; mod bishop; pub use bishop::*; mod king; pub use king::*; mod knight; pub use knight::*; mod pawn; pub use pawn::*; mod queen; pub use queen::*; mod rook; pub use rook::*;
use core::ffi::c_void; use std::mem::{size_of, transmute, MaybeUninit}; use std::ptr; use std::slice; use ash::prelude::VkResult; use ash::version::{DeviceV1_0, InstanceV1_0}; use ash::{self, vk}; use super::error::VulkanError; #[allow(unused_unsafe)] pub unsafe fn create_empty_image( instance: &ash::Instance, logical_device: &ash::Device, physical_device: vk::PhysicalDevice, dimensions: (u32, u32), format: vk::Format, tiling: vk::ImageTiling, initial_layout: vk::ImageLayout, sharing_mode: vk::SharingMode, usage: vk::ImageUsageFlags, required_memory_properties: vk::MemoryPropertyFlags, unpreferred_memory_properties: Option<vk::MemoryPropertyFlags>, ) -> Result<(vk::Image, vk::DeviceMemory), VulkanError> { let image_info = vk::ImageCreateInfo::builder() .image_type(vk::ImageType::TYPE_2D) .format(format) .tiling(tiling) .initial_layout(initial_layout) .sharing_mode(sharing_mode) .mip_levels(1) .array_layers(1) .usage(usage) .samples(vk::SampleCountFlags::TYPE_1) .extent(vk::Extent3D { width: dimensions.0, height: dimensions.1, depth: 1, }); let image = unsafe { logical_device.create_image(&image_info, None)? }; let img_mem_requirements = unsafe { logical_device.get_image_memory_requirements(image) }; let device_mem_props = unsafe { instance.get_physical_device_memory_properties(physical_device) }; let mem_type_index = unsafe { match get_mem_type_index( required_memory_properties, unpreferred_memory_properties, img_mem_requirements, device_mem_props, ) { Ok(i) => i, Err(e) => { logical_device.destroy_image(image, None); return Err(e); } } }; let alloc_info = vk::MemoryAllocateInfo::builder() .allocation_size(img_mem_requirements.size) .memory_type_index(mem_type_index as u32); let memory = unsafe { match logical_device.allocate_memory(&alloc_info, None) { Ok(m) => m, Err(e) => { logical_device.destroy_image(image, None); return Err(VulkanError::Result(e)); } } }; // bind memory to buffer unsafe { match logical_device.bind_image_memory(image, memory, 0) { Ok(()) => (), Err(e) => { logical_device.destroy_image(image, None); logical_device.free_memory(memory, None); return Err(VulkanError::Result(e)); } } } Ok((image, memory)) } // attempts to find the memory type index for the physical device that fits // the given parameters. if there are no memory types with 'required_mem_props' // that don't also contain 'unpreferred_mem_props', a fallback "best" candidate // may be returned. if no fallback is found, the function returns an error pub fn get_mem_type_index( required_mem_props: vk::MemoryPropertyFlags, unpreferred_mem_props: Option<vk::MemoryPropertyFlags>, buffer_mem_requirements: vk::MemoryRequirements, phys_device_mem_props: vk::PhysicalDeviceMemoryProperties, ) -> Result<usize, VulkanError> { let mut best_candidate = None; for (i, mem_type) in phys_device_mem_props.memory_types.iter().enumerate() { // if memory type corresponding to index i is supported for the buffer/image if buffer_mem_requirements.memory_type_bits & (1 << i) != 0 { // if memory type has the required properties if mem_type.property_flags.contains(required_mem_props) { if let Some(unpreferred) = unpreferred_mem_props { // if memory type also has unpreferred props if mem_type.property_flags.contains(unpreferred) { best_candidate = Some(i); continue; } } return Ok(i); } } } best_candidate.ok_or(VulkanError::NoMemoryType( "failed to find suitable memory type for buffer/image", )) } // copies a slice of T to the memory pointed to by 'mapped'. the size of // the memory must not be less than the size of the entire slice ('data') for // this to be safe. used for copying into the mapped memory given by vkMapMemory() pub unsafe fn copy_to_mapped<T>(data: &[T], mapped: *mut c_void) { // SAFETY: TODO: this is all very spooky and unsafe, and still // probably invokes U.B somehow. so take a look at this again // cast from void ptr and then to slice let data_size = (size_of::<T>() * data.len()) as u64; let mapped_cast: *mut MaybeUninit<T> = transmute::<*mut c_void, _>(mapped); let mapped_slice: &mut [MaybeUninit<T>] = slice::from_raw_parts_mut(mapped_cast, data_size as usize); // alignment must be correct assert!(mapped as usize % std::mem::align_of::<T>() == 0); // TODO: if the alignment of the mapped memory isn't correct // for the type, we can use ash::util::Align // equivalent to memcpy ptr::copy_nonoverlapping::<T>(&data[0], mapped_slice[0].as_mut_ptr(), data.len()); } #[allow(unused_unsafe)] pub unsafe fn create_image_view( image: vk::Image, format: vk::Format, logical_device: &ash::Device, ) -> VkResult<vk::ImageView> { let components = vk::ComponentMapping::builder() .r(vk::ComponentSwizzle::IDENTITY) .g(vk::ComponentSwizzle::IDENTITY) .b(vk::ComponentSwizzle::IDENTITY) .a(vk::ComponentSwizzle::IDENTITY); let subresource_range = vk::ImageSubresourceRange::builder() .aspect_mask(vk::ImageAspectFlags::COLOR) .base_mip_level(0) .level_count(1) .base_array_layer(0) .layer_count(1); let img_info = vk::ImageViewCreateInfo::builder() .image(image) .view_type(vk::ImageViewType::TYPE_2D) .format(format) .components(*components) .subresource_range(*subresource_range); unsafe { logical_device.create_image_view(&img_info, None) } } pub fn to_raw_ptrs(slice_array: &[&[i8]]) -> Vec<*const i8> { slice_array .iter() .map(|l| l.as_ptr()) .collect::<Vec<*const i8>>() } pub fn strcmp(a: &[i8], b: &[i8]) -> bool { let mut a_iter = a.iter(); let mut b_iter = b.iter(); loop { match (a_iter.next(), b_iter.next()) { (Some(a_byte), Some(b_byte)) => { // reached nul on both strings if *a_byte == 0 && *b_byte == 0 { return true; } if *a_byte == *b_byte { continue; } else { return false; } } // end of both strings (None, None) => return true, // one ends before the other (Some(a_byte), None) => { if *a_byte == 0 { return true; } else { return false; } } // one ends before the other (None, Some(b_byte)) => { if *b_byte == 0 { return true; } else { return false; } } } } } #[test] fn strcmp_test() { let bytes1 = b"test!\0\0"; let bytes2 = b"test!"; let string1: &[i8] = unsafe { slice::from_raw_parts(bytes1.as_ptr() as *const i8, bytes1.len()) }; let string2: &[i8] = unsafe { slice::from_raw_parts(bytes2.as_ptr() as *const i8, bytes2.len()) }; assert!(strcmp(string1, string2)); let bytes3 = b"test!\0"; let bytes4 = b"test!\0"; let string3: &[i8] = unsafe { slice::from_raw_parts(bytes3.as_ptr() as *const i8, bytes3.len()) }; let string4: &[i8] = unsafe { slice::from_raw_parts(bytes4.as_ptr() as *const i8, bytes4.len()) }; assert!(strcmp(string3, string4)); let bytes5 = b"test!"; let bytes6 = b"test!"; let string5: &[i8] = unsafe { slice::from_raw_parts(bytes5.as_ptr() as *const i8, bytes5.len()) }; let string6: &[i8] = unsafe { slice::from_raw_parts(bytes6.as_ptr() as *const i8, bytes6.len()) }; assert!(strcmp(string5, string6)); }
#![allow(unstable)] #![feature(quote)] #![feature(plugin_registrar)] extern crate lalr; extern crate syntax; use lalr::*; use syntax::ast; use syntax::codemap::{self, DUMMY_SP}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use std::collections::BTreeMap; use syntax::parse::token::str_to_ident; use lib as lalrgen; mod lib; fn N<T>(x: &str) -> Symbol<T, syntax::ast::Ident> { Nonterminal(str_to_ident(x)) } fn T<N>(x: char) -> Symbol<char, N> { Terminal(x) } macro_rules! map { ($($l: expr => $r: expr),*) => ({ let mut r = BTreeMap::new(); $(r.insert(str_to_ident($l), $r);)* r }) } fn rhs<T, N, A>(syms: Vec<Symbol<T, N>>, act: A) -> Rhs<T, N, A> { Rhs { syms: syms, act: act, } } fn main() { let ps = syntax::parse::new_parse_sess(); let cx = &mut ExtCtxt::new(&ps, vec![], syntax::ext::expand::ExpansionConfig::default("larlgen-test".to_string()) ); cx.bt_push(codemap::ExpnInfo { call_site: DUMMY_SP, callee: codemap::NameAndSpan { name: "".to_string(), format: codemap::MacroBang, span: None, } }); let g = Grammar { rules: map![ "S" => vec![ rhs(vec![N("N")], ()), ], "N" => vec![ rhs(vec![N("V"), T('='), N("E")], ()), rhs(vec![N("E")], ()), ], "E" => vec![ rhs(vec![N("V")], ()), ], "V" => vec![ rhs(vec![T('x')], ()), rhs(vec![T('*'), N("E")], ()), ] ], start: str_to_ident("S") }; let types = g.rules.keys().map(|k| (*k, quote_ty!(cx, ())) ).collect(); let token_ty = quote_ty!(cx, char); let x = lalrgen::lr1_machine( cx, &g, &types, token_ty, syntax::parse::token::str_to_ident("parse"), |&ch, cx| { cx.pat_lit(DUMMY_SP, cx.expr_lit(DUMMY_SP, ast::LitChar(ch))) }, |&(), cx, syms| { // let arg_ids: Vec<_> = (0..syms.len()).map(|i| // cx.pat_ident(DUMMY_SP, token::gensym_ident(&format!("arg{}", i)[]))).collect(); let arg_ids = (0..syms.len()).map(|_| cx.pat_wild(DUMMY_SP)).collect(); (cx.block(DUMMY_SP, vec![], None), arg_ids, DUMMY_SP) }, ); println!("{}", syntax::print::pprust::item_to_string(&*x)); }
pub fn lin_grad(c1 : [u8;3], c2 : [u8;3], n : u32) -> Vec<[u8;3]> { let mut grad = Vec::new(); for i in 0..= n { let t = (i as f32)/(n as f32); let [r1, g1, b1] = c1; let [r2, g2, b2] = c2; let r = ((r1 as f32) * (1.0 - t) + (r2 as f32)*t).round() as u8; let g = ((g1 as f32) * (1.0 - t) + (g2 as f32)*t).round() as u8; let b = ((b1 as f32) * (1.0 - t) + (b2 as f32)*t).round() as u8; grad.push([r, g, b]); } grad } pub fn multi_lin_grad(colors : &[[u8;3]], n : u32) -> Vec<[u8;3]> { let l = colors.len(); let n_out = ((n as f32)/(l as f32)).round() as u32; let mut grad = Vec::new(); for i in 0..(l-1) { grad.extend(lin_grad(colors[i], colors[i+1], n_out)); } while grad.len() <= n as usize { grad.push(colors[l-1]) } grad }
/// An enum to represent all characters in the Ahom block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Ahom { /// \u{11700}: '𑜀' LetterKa, /// \u{11701}: '𑜁' LetterKha, /// \u{11702}: '𑜂' LetterNga, /// \u{11703}: '𑜃' LetterNa, /// \u{11704}: '𑜄' LetterTa, /// \u{11705}: '𑜅' LetterAlternateTa, /// \u{11706}: '𑜆' LetterPa, /// \u{11707}: '𑜇' LetterPha, /// \u{11708}: '𑜈' LetterBa, /// \u{11709}: '𑜉' LetterMa, /// \u{1170a}: '𑜊' LetterJa, /// \u{1170b}: '𑜋' LetterCha, /// \u{1170c}: '𑜌' LetterTha, /// \u{1170d}: '𑜍' LetterRa, /// \u{1170e}: '𑜎' LetterLa, /// \u{1170f}: '𑜏' LetterSa, /// \u{11710}: '𑜐' LetterNya, /// \u{11711}: '𑜑' LetterHa, /// \u{11712}: '𑜒' LetterA, /// \u{11713}: '𑜓' LetterDa, /// \u{11714}: '𑜔' LetterDha, /// \u{11715}: '𑜕' LetterGa, /// \u{11716}: '𑜖' LetterAlternateGa, /// \u{11717}: '𑜗' LetterGha, /// \u{11718}: '𑜘' LetterBha, /// \u{11719}: '𑜙' LetterJha, /// \u{1171a}: '𑜚' LetterAlternateBa, /// \u{1171d}: '𑜝' ConsonantSignMedialLa, /// \u{1171e}: '𑜞' ConsonantSignMedialRa, /// \u{1171f}: '𑜟' ConsonantSignMedialLigatingRa, /// \u{11720}: '𑜠' VowelSignA, /// \u{11721}: '𑜡' VowelSignAa, /// \u{11722}: '𑜢' VowelSignI, /// \u{11723}: '𑜣' VowelSignIi, /// \u{11724}: '𑜤' VowelSignU, /// \u{11725}: '𑜥' VowelSignUu, /// \u{11726}: '𑜦' VowelSignE, /// \u{11727}: '𑜧' VowelSignAw, /// \u{11728}: '𑜨' VowelSignO, /// \u{11729}: '𑜩' VowelSignAi, /// \u{1172a}: '𑜪' VowelSignAm, /// \u{1172b}: '𑜫' SignKiller, /// \u{11730}: '𑜰' DigitZero, /// \u{11731}: '𑜱' DigitOne, /// \u{11732}: '𑜲' DigitTwo, /// \u{11733}: '𑜳' DigitThree, /// \u{11734}: '𑜴' DigitFour, /// \u{11735}: '𑜵' DigitFive, /// \u{11736}: '𑜶' DigitSix, /// \u{11737}: '𑜷' DigitSeven, /// \u{11738}: '𑜸' DigitEight, /// \u{11739}: '𑜹' DigitNine, /// \u{1173a}: '𑜺' NumberTen, /// \u{1173b}: '𑜻' NumberTwenty, /// \u{1173c}: '𑜼' SignSmallSection, /// \u{1173d}: '𑜽' SignSection, /// \u{1173e}: '𑜾' SignRulai, } impl Into<char> for Ahom { fn into(self) -> char { match self { Ahom::LetterKa => '𑜀', Ahom::LetterKha => '𑜁', Ahom::LetterNga => '𑜂', Ahom::LetterNa => '𑜃', Ahom::LetterTa => '𑜄', Ahom::LetterAlternateTa => '𑜅', Ahom::LetterPa => '𑜆', Ahom::LetterPha => '𑜇', Ahom::LetterBa => '𑜈', Ahom::LetterMa => '𑜉', Ahom::LetterJa => '𑜊', Ahom::LetterCha => '𑜋', Ahom::LetterTha => '𑜌', Ahom::LetterRa => '𑜍', Ahom::LetterLa => '𑜎', Ahom::LetterSa => '𑜏', Ahom::LetterNya => '𑜐', Ahom::LetterHa => '𑜑', Ahom::LetterA => '𑜒', Ahom::LetterDa => '𑜓', Ahom::LetterDha => '𑜔', Ahom::LetterGa => '𑜕', Ahom::LetterAlternateGa => '𑜖', Ahom::LetterGha => '𑜗', Ahom::LetterBha => '𑜘', Ahom::LetterJha => '𑜙', Ahom::LetterAlternateBa => '𑜚', Ahom::ConsonantSignMedialLa => '𑜝', Ahom::ConsonantSignMedialRa => '𑜞', Ahom::ConsonantSignMedialLigatingRa => '𑜟', Ahom::VowelSignA => '𑜠', Ahom::VowelSignAa => '𑜡', Ahom::VowelSignI => '𑜢', Ahom::VowelSignIi => '𑜣', Ahom::VowelSignU => '𑜤', Ahom::VowelSignUu => '𑜥', Ahom::VowelSignE => '𑜦', Ahom::VowelSignAw => '𑜧', Ahom::VowelSignO => '𑜨', Ahom::VowelSignAi => '𑜩', Ahom::VowelSignAm => '𑜪', Ahom::SignKiller => '𑜫', Ahom::DigitZero => '𑜰', Ahom::DigitOne => '𑜱', Ahom::DigitTwo => '𑜲', Ahom::DigitThree => '𑜳', Ahom::DigitFour => '𑜴', Ahom::DigitFive => '𑜵', Ahom::DigitSix => '𑜶', Ahom::DigitSeven => '𑜷', Ahom::DigitEight => '𑜸', Ahom::DigitNine => '𑜹', Ahom::NumberTen => '𑜺', Ahom::NumberTwenty => '𑜻', Ahom::SignSmallSection => '𑜼', Ahom::SignSection => '𑜽', Ahom::SignRulai => '𑜾', } } } impl std::convert::TryFrom<char> for Ahom { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '𑜀' => Ok(Ahom::LetterKa), '𑜁' => Ok(Ahom::LetterKha), '𑜂' => Ok(Ahom::LetterNga), '𑜃' => Ok(Ahom::LetterNa), '𑜄' => Ok(Ahom::LetterTa), '𑜅' => Ok(Ahom::LetterAlternateTa), '𑜆' => Ok(Ahom::LetterPa), '𑜇' => Ok(Ahom::LetterPha), '𑜈' => Ok(Ahom::LetterBa), '𑜉' => Ok(Ahom::LetterMa), '𑜊' => Ok(Ahom::LetterJa), '𑜋' => Ok(Ahom::LetterCha), '𑜌' => Ok(Ahom::LetterTha), '𑜍' => Ok(Ahom::LetterRa), '𑜎' => Ok(Ahom::LetterLa), '𑜏' => Ok(Ahom::LetterSa), '𑜐' => Ok(Ahom::LetterNya), '𑜑' => Ok(Ahom::LetterHa), '𑜒' => Ok(Ahom::LetterA), '𑜓' => Ok(Ahom::LetterDa), '𑜔' => Ok(Ahom::LetterDha), '𑜕' => Ok(Ahom::LetterGa), '𑜖' => Ok(Ahom::LetterAlternateGa), '𑜗' => Ok(Ahom::LetterGha), '𑜘' => Ok(Ahom::LetterBha), '𑜙' => Ok(Ahom::LetterJha), '𑜚' => Ok(Ahom::LetterAlternateBa), '𑜝' => Ok(Ahom::ConsonantSignMedialLa), '𑜞' => Ok(Ahom::ConsonantSignMedialRa), '𑜟' => Ok(Ahom::ConsonantSignMedialLigatingRa), '𑜠' => Ok(Ahom::VowelSignA), '𑜡' => Ok(Ahom::VowelSignAa), '𑜢' => Ok(Ahom::VowelSignI), '𑜣' => Ok(Ahom::VowelSignIi), '𑜤' => Ok(Ahom::VowelSignU), '𑜥' => Ok(Ahom::VowelSignUu), '𑜦' => Ok(Ahom::VowelSignE), '𑜧' => Ok(Ahom::VowelSignAw), '𑜨' => Ok(Ahom::VowelSignO), '𑜩' => Ok(Ahom::VowelSignAi), '𑜪' => Ok(Ahom::VowelSignAm), '𑜫' => Ok(Ahom::SignKiller), '𑜰' => Ok(Ahom::DigitZero), '𑜱' => Ok(Ahom::DigitOne), '𑜲' => Ok(Ahom::DigitTwo), '𑜳' => Ok(Ahom::DigitThree), '𑜴' => Ok(Ahom::DigitFour), '𑜵' => Ok(Ahom::DigitFive), '𑜶' => Ok(Ahom::DigitSix), '𑜷' => Ok(Ahom::DigitSeven), '𑜸' => Ok(Ahom::DigitEight), '𑜹' => Ok(Ahom::DigitNine), '𑜺' => Ok(Ahom::NumberTen), '𑜻' => Ok(Ahom::NumberTwenty), '𑜼' => Ok(Ahom::SignSmallSection), '𑜽' => Ok(Ahom::SignSection), '𑜾' => Ok(Ahom::SignRulai), _ => Err(()), } } } impl Into<u32> for Ahom { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for Ahom { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for Ahom { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl Ahom { /// The character with the lowest index in this unicode block pub fn new() -> Self { Ahom::LetterKa } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("Ahom{:#?}", self); string_morph::to_sentence_case(&s) } }
use serde::Deserialize; use crate::geometry2d::*; use super::{Asset, AssetExt, AssetResult, AssetError, category}; // ------------------------------------------------------------------------------------------------- #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum ImageFormat { RGB24, RGBA32, } impl ImageFormat { fn from(color_type: png::ColorType, bit_depth: png::BitDepth) -> AssetResult<ImageFormat> { if bit_depth != png::BitDepth::Eight { return Err(AssetError::InvalidFormat(format!("invalid bit depth: {:?}", bit_depth))); } match color_type { png::ColorType::RGB => Ok(ImageFormat::RGB24), png::ColorType::RGBA => Ok(ImageFormat::RGBA32), _ => Err(AssetError::InvalidFormat(format!("invalid color type: {:?}", color_type))), } } } impl From<ImageFormat> for vulkano::format::Format { fn from(format: ImageFormat) -> Self { match format { ImageFormat::RGB24 => vulkano::format::Format::R8G8B8Srgb, ImageFormat::RGBA32 => vulkano::format::Format::R8G8B8A8Srgb, } } } pub struct Image { size: Size, format: ImageFormat, buffer: Vec<u8>, } impl Image { pub fn size(&self) -> Size { self.size } pub fn format(&self) -> ImageFormat { self.format } pub fn data(&self) -> &[u8] { &self.buffer } pub fn new_1x1_white() -> Image { Image { size: Size { width: 1, height: 1 }, format: ImageFormat::RGBA32, buffer: vec![255, 255, 255, 255], } } } impl Asset for Image { type Category = category::Data; fn read(asset_path: &str) -> AssetResult<Self> { let decoder = png::Decoder::new(Self::open_file(asset_path, "png")?); let (info, mut reader) = decoder.read_info().unwrap(); let format = ImageFormat::from(info.color_type, info.bit_depth)?; let mut buffer = vec![0; info.buffer_size()]; reader.next_frame(&mut buffer).unwrap(); Ok(Image { size: Size { width: info.width, height: info.height }, format, buffer, }) } } pub struct NineSliceImage { image: Image, slices: EdgeRect, } impl NineSliceImage { pub fn size(&self) -> Size { self.image.size() } pub fn format(&self) -> ImageFormat { self.image.format() } pub fn data(&self) -> &[u8] { self.image.data() } pub fn slices(&self) -> EdgeRect { self.slices } pub fn as_image(&self) -> &Image { &self.image } } impl Asset for NineSliceImage { type Category = category::Data; fn read(asset_path: &str) -> AssetResult<Self> { let slices = Self::read_ron(asset_path)?; let image = Image::read(asset_path)?; Ok(NineSliceImage { image, slices }) } } #[derive(Deserialize)] struct TileAtlasInfo { tile_size: Size, tile_offset: Point, tile_gap: Point, } pub struct TileAtlasImage { image: Image, info: TileAtlasInfo, } impl TileAtlasImage { pub fn size(&self) -> Size { self.image.size() } pub fn format(&self) -> ImageFormat { self.image.format() } pub fn data(&self) -> &[u8] { self.image.data() } pub fn tile_size(&self) -> Size { self.info.tile_size } pub fn tile_offset(&self) -> Point { self.info.tile_offset } pub fn tile_gap(&self) -> Point { self.info.tile_gap } pub fn as_image(&self) -> &Image { &self.image } } impl Asset for TileAtlasImage { type Category = category::Data; fn read(asset_path: &str) -> AssetResult<Self> { let info = Self::read_ron(asset_path)?; let image = Image::read(asset_path)?; Ok(TileAtlasImage { image, info }) } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DCMI control register"] pub dcmi_cr: DCMI_CR, #[doc = "0x04 - DCMI status register"] pub dcmi_sr: DCMI_SR, #[doc = "0x08 - DCMI_RIS gives the raw interrupt status and is accessible in read only. When read, this register returns the status of the corresponding interrupt before masking with the DCMI_IER register value."] pub dcmi_ris: DCMI_RIS, #[doc = "0x0c - The DCMI_IER register is used to enable interrupts. When one of the DCMI_IER bits is set, the corresponding interrupt is enabled. This register is accessible in both read and write."] pub dcmi_ier: DCMI_IER, #[doc = "0x10 - This DCMI_MIS register is a read-only register. When read, it returns the current masked status value (depending on the value in DCMI_IER) of the corresponding interrupt. A bit in this register is set if the corresponding enable bit in DCMI_IER is set and the corresponding bit in DCMI_RIS is set."] pub dcmi_mis: DCMI_MIS, #[doc = "0x14 - The DCMI_ICR register is write-only"] pub dcmi_icr: DCMI_ICR, #[doc = "0x18 - DCMI embedded synchronization code register"] pub dcmi_escr: DCMI_ESCR, #[doc = "0x1c - DCMI embedded synchronization unmask register"] pub dcmi_esur: DCMI_ESUR, #[doc = "0x20 - DCMI crop window start"] pub dcmi_cwstrt: DCMI_CWSTRT, #[doc = "0x24 - DCMI crop window size"] pub dcmi_cwsize: DCMI_CWSIZE, #[doc = "0x28 - DCMI data register"] pub dcmi_dr: DCMI_DR, } #[doc = "DCMI control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_cr](dcmi_cr) module"] pub type DCMI_CR = crate::Reg<u32, _DCMI_CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_CR; #[doc = "`read()` method returns [dcmi_cr::R](dcmi_cr::R) reader structure"] impl crate::Readable for DCMI_CR {} #[doc = "`write(|w| ..)` method takes [dcmi_cr::W](dcmi_cr::W) writer structure"] impl crate::Writable for DCMI_CR {} #[doc = "DCMI control register"] pub mod dcmi_cr; #[doc = "DCMI status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_sr](dcmi_sr) module"] pub type DCMI_SR = crate::Reg<u32, _DCMI_SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_SR; #[doc = "`read()` method returns [dcmi_sr::R](dcmi_sr::R) reader structure"] impl crate::Readable for DCMI_SR {} #[doc = "DCMI status register"] pub mod dcmi_sr; #[doc = "DCMI_RIS gives the raw interrupt status and is accessible in read only. When read, this register returns the status of the corresponding interrupt before masking with the DCMI_IER register value.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_ris](dcmi_ris) module"] pub type DCMI_RIS = crate::Reg<u32, _DCMI_RIS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_RIS; #[doc = "`read()` method returns [dcmi_ris::R](dcmi_ris::R) reader structure"] impl crate::Readable for DCMI_RIS {} #[doc = "DCMI_RIS gives the raw interrupt status and is accessible in read only. When read, this register returns the status of the corresponding interrupt before masking with the DCMI_IER register value."] pub mod dcmi_ris; #[doc = "The DCMI_IER register is used to enable interrupts. When one of the DCMI_IER bits is set, the corresponding interrupt is enabled. This register is accessible in both read and write.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_ier](dcmi_ier) module"] pub type DCMI_IER = crate::Reg<u32, _DCMI_IER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_IER; #[doc = "`read()` method returns [dcmi_ier::R](dcmi_ier::R) reader structure"] impl crate::Readable for DCMI_IER {} #[doc = "`write(|w| ..)` method takes [dcmi_ier::W](dcmi_ier::W) writer structure"] impl crate::Writable for DCMI_IER {} #[doc = "The DCMI_IER register is used to enable interrupts. When one of the DCMI_IER bits is set, the corresponding interrupt is enabled. This register is accessible in both read and write."] pub mod dcmi_ier; #[doc = "This DCMI_MIS register is a read-only register. When read, it returns the current masked status value (depending on the value in DCMI_IER) of the corresponding interrupt. A bit in this register is set if the corresponding enable bit in DCMI_IER is set and the corresponding bit in DCMI_RIS is set.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_mis](dcmi_mis) module"] pub type DCMI_MIS = crate::Reg<u32, _DCMI_MIS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_MIS; #[doc = "`read()` method returns [dcmi_mis::R](dcmi_mis::R) reader structure"] impl crate::Readable for DCMI_MIS {} #[doc = "This DCMI_MIS register is a read-only register. When read, it returns the current masked status value (depending on the value in DCMI_IER) of the corresponding interrupt. A bit in this register is set if the corresponding enable bit in DCMI_IER is set and the corresponding bit in DCMI_RIS is set."] pub mod dcmi_mis; #[doc = "The DCMI_ICR register is write-only\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_icr](dcmi_icr) module"] pub type DCMI_ICR = crate::Reg<u32, _DCMI_ICR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_ICR; #[doc = "`read()` method returns [dcmi_icr::R](dcmi_icr::R) reader structure"] impl crate::Readable for DCMI_ICR {} #[doc = "`write(|w| ..)` method takes [dcmi_icr::W](dcmi_icr::W) writer structure"] impl crate::Writable for DCMI_ICR {} #[doc = "The DCMI_ICR register is write-only"] pub mod dcmi_icr; #[doc = "DCMI embedded synchronization code register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_escr](dcmi_escr) module"] pub type DCMI_ESCR = crate::Reg<u32, _DCMI_ESCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_ESCR; #[doc = "`read()` method returns [dcmi_escr::R](dcmi_escr::R) reader structure"] impl crate::Readable for DCMI_ESCR {} #[doc = "`write(|w| ..)` method takes [dcmi_escr::W](dcmi_escr::W) writer structure"] impl crate::Writable for DCMI_ESCR {} #[doc = "DCMI embedded synchronization code register"] pub mod dcmi_escr; #[doc = "DCMI embedded synchronization unmask register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_esur](dcmi_esur) module"] pub type DCMI_ESUR = crate::Reg<u32, _DCMI_ESUR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_ESUR; #[doc = "`read()` method returns [dcmi_esur::R](dcmi_esur::R) reader structure"] impl crate::Readable for DCMI_ESUR {} #[doc = "`write(|w| ..)` method takes [dcmi_esur::W](dcmi_esur::W) writer structure"] impl crate::Writable for DCMI_ESUR {} #[doc = "DCMI embedded synchronization unmask register"] pub mod dcmi_esur; #[doc = "DCMI crop window start\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_cwstrt](dcmi_cwstrt) module"] pub type DCMI_CWSTRT = crate::Reg<u32, _DCMI_CWSTRT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_CWSTRT; #[doc = "`read()` method returns [dcmi_cwstrt::R](dcmi_cwstrt::R) reader structure"] impl crate::Readable for DCMI_CWSTRT {} #[doc = "`write(|w| ..)` method takes [dcmi_cwstrt::W](dcmi_cwstrt::W) writer structure"] impl crate::Writable for DCMI_CWSTRT {} #[doc = "DCMI crop window start"] pub mod dcmi_cwstrt; #[doc = "DCMI crop window size\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_cwsize](dcmi_cwsize) module"] pub type DCMI_CWSIZE = crate::Reg<u32, _DCMI_CWSIZE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_CWSIZE; #[doc = "`read()` method returns [dcmi_cwsize::R](dcmi_cwsize::R) reader structure"] impl crate::Readable for DCMI_CWSIZE {} #[doc = "`write(|w| ..)` method takes [dcmi_cwsize::W](dcmi_cwsize::W) writer structure"] impl crate::Writable for DCMI_CWSIZE {} #[doc = "DCMI crop window size"] pub mod dcmi_cwsize; #[doc = "DCMI data register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcmi_dr](dcmi_dr) module"] pub type DCMI_DR = crate::Reg<u32, _DCMI_DR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DCMI_DR; #[doc = "`read()` method returns [dcmi_dr::R](dcmi_dr::R) reader structure"] impl crate::Readable for DCMI_DR {} #[doc = "DCMI data register"] pub mod dcmi_dr;
use std::io::Write; use std::collections::HashMap; use parser::html::Expression as Expr; use parser::html::Statement as Stmt; use parser::html::Statement::{Store}; use util::join; use super::Generator; use super::ast::{Statement, Param, Expression}; use super::ast::Expression as E; use super::ast::Statement as S; fn attr<'x, S: AsRef<str>>(e: Expression, v: S) -> Expression { E::Attr(Box::new(e), v.as_ref().to_string()) } impl<'a, W:Write+'a> Generator<'a, W> { fn compile_link(&self, expr: Expression, filter: &Option<Expr>, map: Option<&Expr>) -> Expression { let mut e = expr; if let Some(map) = map { let ev = Param { name: String::from("ev"), default_value: None }; let func = E::Function(None, vec![ev], vec![ S::Return(self.compile_expr(map))]); e = E::Call(Box::new(attr(e, "map")), vec![func]); } if let &Some(ref filt) = filter { let ev = Param { name: String::from("ev"), default_value: None }; let func = E::Function(None, vec![ev], vec![ S::Return(self.compile_expr(filt))]); e = E::Call(Box::new(attr(e, "filter")), vec![func]); } attr(e, "handle_event") } pub fn element(&self, name: &String, classes: &Vec<(String, Option<Expr>)>, attributes: &Vec<(String, Expr)>, key: Option<Expression>, body: &Vec<Stmt>) -> Expression { use parser::html::Link as L; use parser::html::LinkDest as D; let mut properties = vec![ (String::from("tag"), Expression::Str(name.clone())), ]; let mut statements = vec![]; let mut events = HashMap::new(); for item in body.iter() { match item { &Stmt::Let(ref name, ref value) => { statements.push(Statement::Var(name.clone(), self.compile_expr(value))); } &Store(ref name, ref value) => { let prop = String::from("store_") +name; statements.push(Statement::Var(name.clone(), E::Or( Box::new(E::And( Box::new(E::Name(String::from("old_node"))), Box::new(E::Attr(Box::new( E::Name(String::from("old_node"))), prop.clone())))), Box::new(self.compile_expr(value))))); properties.push((prop, E::Name(name.clone()))); events.entry(String::from("$destroyed")) .or_insert(vec!()).push( E::Ternary( Box::new(attr(E::Name(name.clone()), "owner_destroyed")), Box::new(attr( attr(E::Name(name.clone()), "owner_destroyed"), "handle_event")), Box::new(E::Function(None, vec![], vec![])), )); } &Stmt::Link(ref links) => { for lnk in links { match lnk { &L::One(ref s, ref f, D::Stream(ref expr)) => { events.entry(s.clone()).or_insert(vec!()).push( self.compile_link( self.compile_expr(expr), f, None)); } &L::Multi(ref names, D::Stream(ref expr)) => { let v = format!("_stream_{}", statements.len()); statements.push(Statement::Var( v.clone(), self.compile_expr(expr))); for &(ref aname, ref flt, ref ename) in names { let ev = ename.as_ref() .unwrap_or(aname).clone(); events.entry(ev.clone()).or_insert(vec!()) .push(self.compile_link( attr(E::Name(v.clone()), &aname), flt, None)); } } &L::One(ref s, ref f, D::Mapping(ref val, ref dst)) => { events.entry(s.clone()).or_insert(vec!()).push( self.compile_link( self.compile_expr(dst), f, Some(val))); } &L::Multi(ref names, D::Mapping(ref val, ref dest)) => { let v = format!("_stream_{}", statements.len()); statements.push(Statement::Var( v.clone(), self.compile_expr(dest))); for &(ref aname, ref flt, ref event) in names { let ename = event.as_ref() .unwrap_or(aname).clone(); events.entry(ename).or_insert(vec!()).push( self.compile_link( attr(E::Name(v.clone()), aname), flt, Some(val))); } } } } } _ => {} } } if classes.len() > 0 || attributes.len() > 0 { properties.push( (String::from("attrs"), self.attrs(name, classes, attributes))); } if body.len() > 0 { properties.push( (String::from("children"), self.fragment(&body, None))); } if events.len() > 0 { properties.push( (String::from("events"), Expression::Object( events.into_iter().map(|(k, mut v)| { if v.len() == 1 { (k, v.pop().unwrap()) } else { (k, Expression::List(v)) } }).collect() ))); } if statements.len() > 0 { statements.push( Statement::Return(Expression::Object(properties))); let func = Expression::Function(None, vec![Param { name: String::from("old_node"), default_value: None, }], statements); if let Some(key) = key { // If there is a key, we must turn function into fragment, // because it's impossible to find out old_node before knowing // the key return Expression::Object(vec![ ("key".to_string(), key), ("children".to_string(), func), ].into_iter().collect()) } else { return func } } else { if let Some(key) = key { properties.push((String::from("key"), key)); } return Expression::Object(properties); } } fn attrs(&self, name: &String, cls: &Vec<(String, Option<Expr>)>, attrs: &Vec<(String, Expr)>) -> Expression { let mut class_literals = vec!(); let mut class_expr = vec!(); if cls.len() > 0 || self.bare_element_names.contains(name) { class_literals.push(self.block_name.to_string()); } for &(ref cname, ref opt_cond) in cls { if let &Some(ref cond) = opt_cond { class_expr.push(Expression::Ternary( Box::new(self.compile_expr(cond)), Box::new(Expression::Str(cname.clone())), Box::new(Expression::Str(String::from(""))))); } else { class_literals.push(cname.clone()); } } let mut rattrs = vec!(); for &(ref name, ref value) in attrs { if &name[..] == "class" { class_expr.push(self.compile_expr(value)); } else { rattrs.push((name.clone(), self.compile_expr(value))); } } if class_literals.len() > 0 { class_expr.insert(0, Expression::Str(join(class_literals.iter(), " "))); } if class_expr.len() > 0 { let first = class_expr.remove(0); rattrs.push((String::from("class"), class_expr.into_iter() .fold(first, |acc, val| Expression::Add(Box::new( Expression::Add( Box::new(acc), Box::new(Expression::Str(String::from(" "))))), Box::new(val))))); } Expression::Object(rattrs) } }
use physics::{ElevatorState, MAX_JERK, MAX_ACCELERATION, MAX_VELOCITY}; use buildings::{Building, getCumulativeFloorHeight}; pub trait MotionController { fn init(&mut self, esp: Box<Building>, est: ElevatorState); fn adjust(&mut self, est: &ElevatorState, dst: u64) -> f64; } pub struct SmoothMotionController { pub esp: Box<Building>, pub timestamp: f64 } impl MotionController for SmoothMotionController { fn init(&mut self, esp: Box<Building>, est: ElevatorState) { self.esp = esp; self.timestamp = est.timestamp; } fn adjust(&mut self, est: &ElevatorState, dst: u64) -> f64 { //5.3. Adjust motor control to process next floor request //it will take t seconds to reach max from max let t_accel = MAX_ACCELERATION / MAX_JERK; let t_veloc = MAX_VELOCITY / MAX_ACCELERATION; //it may take up to d meters to decelerate from current let decel_t = if (est.velocity>0.0) == (est.acceleration>0.0) { //this case deliberately overestimates d to prevent "back up" (est.acceleration.abs() / MAX_JERK) + (est.velocity.abs() / (MAX_ACCELERATION / 2.0)) + 2.0 * (MAX_ACCELERATION / MAX_JERK) } else { //without the MAX_JERK, this approaches infinity and decelerates way too soon //MAX_JERK * 1s = acceleration in m/s^2 est.velocity.abs() / (MAX_JERK + est.acceleration.abs()) }; let d = est.velocity.abs() * decel_t; let dst_height = getCumulativeFloorHeight(self.esp.get_floor_heights(), dst); //l = distance to next floor let l = (est.location - dst_height).abs(); let target_acceleration = { //are we going up? let going_up = est.location < dst_height; //time elapsed since last poll let dt = est.timestamp - self.timestamp; self.timestamp = est.timestamp; //Do not exceed maximum acceleration if est.acceleration.abs() >= MAX_ACCELERATION { if est.acceleration > 0.0 { est.acceleration - (dt * MAX_JERK) } else { est.acceleration + (dt * MAX_JERK) } //Do not exceed maximum velocity } else if est.velocity.abs() >= MAX_VELOCITY || (est.velocity + est.acceleration * (est.acceleration.abs() / MAX_JERK)).abs() >= MAX_VELOCITY { if est.velocity > 0.0 { est.acceleration - (dt * MAX_JERK) } else { est.acceleration + (dt * MAX_JERK) } //if within comfortable deceleration range and moving in right direction, decelerate } else if l < d && (est.velocity>0.0) == going_up { if going_up { est.acceleration - (dt * MAX_JERK) } else { est.acceleration + (dt * MAX_JERK) } //else if not at peak velocity, accelerate smoothly } else { if going_up { est.acceleration + (dt * MAX_JERK) } else { est.acceleration - (dt * MAX_JERK) } } }; let gravity_adjusted_acceleration = target_acceleration + 9.8; let target_force = gravity_adjusted_acceleration * self.esp.get_carriage_weight(); if !target_force.is_finite() { //divide by zero etc. //may happen if time delta underflows 0.0 } else { target_force } } }
mod server; mod handler; pub use self::server::*; // ex: noet ts=4 filetype=rust
extern crate dbus; use dbus::{Connection, BusType, Message}; use dbus::arg::Array; use std::fmt::Write; fn main() { let c = Connection::get_private(BusType::Session).unwrap(); let m = Message::new_method_call("com.example.dbustest", "/hello", "com.example.dbustest", "Hello").expect("failed to create method") .append1::<&str>("the client"); let r = c.send_with_reply_and_block(m, 2000).expect("no reply"); let arr: &str = r.get1().expect("could not get reply arg"); println!("Greeting response: '{}'", arr); }
#[doc = "Register `TIM15_EGR` reader"] pub type R = crate::R<TIM15_EGR_SPEC>; #[doc = "Register `TIM15_EGR` writer"] pub type W = crate::W<TIM15_EGR_SPEC>; #[doc = "Field `UG` writer - Update generation This bit can be set by software, it is automatically cleared by hardware."] pub type UG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CC1G` writer - Capture/Compare 1 generation This bit is set by software in order to generate an event, it is automatically cleared by hardware. 1 A capture/compare event is generated on channel 1: If channel CC1 is configured as output: CC1IF flag is set, Corresponding interrupt or DMA request is sent if enabled. If channel CC1 is configured as input: The current value of the counter is captured in TIM15_CCR1 register. The CC1IF flag is set, the corresponding interrupt or DMA request is sent if enabled. The CC1OF flag is set if the CC1IF flag was already high."] pub type CC1G_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CC2G` writer - Capture/Compare 2 generation Refer to CC1G description"] pub type CC2G_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `COMG` reader - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] pub type COMG_R = crate::BitReader; #[doc = "Field `COMG` writer - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] pub type COMG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TG` writer - Trigger generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] pub type TG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BG` writer - Break generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] pub type BG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 5 - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] #[inline(always)] pub fn comg(&self) -> COMG_R { COMG_R::new(((self.bits >> 5) & 1) != 0) } } impl W { #[doc = "Bit 0 - Update generation This bit can be set by software, it is automatically cleared by hardware."] #[inline(always)] #[must_use] pub fn ug(&mut self) -> UG_W<TIM15_EGR_SPEC, 0> { UG_W::new(self) } #[doc = "Bit 1 - Capture/Compare 1 generation This bit is set by software in order to generate an event, it is automatically cleared by hardware. 1 A capture/compare event is generated on channel 1: If channel CC1 is configured as output: CC1IF flag is set, Corresponding interrupt or DMA request is sent if enabled. If channel CC1 is configured as input: The current value of the counter is captured in TIM15_CCR1 register. The CC1IF flag is set, the corresponding interrupt or DMA request is sent if enabled. The CC1OF flag is set if the CC1IF flag was already high."] #[inline(always)] #[must_use] pub fn cc1g(&mut self) -> CC1G_W<TIM15_EGR_SPEC, 1> { CC1G_W::new(self) } #[doc = "Bit 2 - Capture/Compare 2 generation Refer to CC1G description"] #[inline(always)] #[must_use] pub fn cc2g(&mut self) -> CC2G_W<TIM15_EGR_SPEC, 2> { CC2G_W::new(self) } #[doc = "Bit 5 - Capture/Compare control update generation This bit can be set by software, it is automatically cleared by hardware. Note: This bit acts only on channels that have a complementary output."] #[inline(always)] #[must_use] pub fn comg(&mut self) -> COMG_W<TIM15_EGR_SPEC, 5> { COMG_W::new(self) } #[doc = "Bit 6 - Trigger generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] #[inline(always)] #[must_use] pub fn tg(&mut self) -> TG_W<TIM15_EGR_SPEC, 6> { TG_W::new(self) } #[doc = "Bit 7 - Break generation This bit is set by software in order to generate an event, it is automatically cleared by hardware."] #[inline(always)] #[must_use] pub fn bg(&mut self) -> BG_W<TIM15_EGR_SPEC, 7> { BG_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u16) -> &mut Self { self.bits = bits; self } } #[doc = "TIM15 event generation register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim15_egr::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 [`tim15_egr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TIM15_EGR_SPEC; impl crate::RegisterSpec for TIM15_EGR_SPEC { type Ux = u16; } #[doc = "`read()` method returns [`tim15_egr::R`](R) reader structure"] impl crate::Readable for TIM15_EGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`tim15_egr::W`](W) writer structure"] impl crate::Writable for TIM15_EGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TIM15_EGR to value 0"] impl crate::Resettable for TIM15_EGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use core::u32; extern "C" { pub fn kReadCPUID( dwEAX: u32, pdwEAX: *mut u32, pdwEBX: *mut u32, pdwECX: *mut u32, pdwEDX: *mut u32, ); pub fn kSwitchAndExecute64BitKernel(); }
// This file is part of Substrate. // Copyright (C) 2018-2021 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/>. //! Substrate chain configurations. use sc_chain_spec::{ChainSpecExtension, ChainType, ChainSpec}; use sp_core::{Pair, Public, sr25519}; use serde::{Serialize, Deserialize}; pub use xxnetwork_runtime as xxnetwork; pub use protonet_runtime as protonet; pub use phoenixx_runtime as phoenixx; use phoenixx::constants::currency::*; use hex_literal::hex; use grandpa_primitives::{AuthorityId as GrandpaId}; use sp_consensus_babe::{AuthorityId as BabeId}; use pallet_im_online::sr25519::{AuthorityId as ImOnlineId}; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_runtime::{Perbill, traits::{Verify, IdentifyAccount}}; use pallet_staking::ValidatorPrefs; pub use node_primitives::{AccountId, Balance, Block, Signature}; type AccountPublic = <Signature as Verify>::Signer; /// Node `ChainSpec` extensions. /// /// Additional parameters for some Substrate core modules, /// customizable from the chain spec. #[derive(Default, Clone, Serialize, Deserialize, ChainSpecExtension)] #[serde(rename_all = "camelCase")] pub struct Extensions { /// Block numbers with known hashes. pub fork_blocks: sc_client_api::ForkBlocks<Block>, /// Known bad block hashes. pub bad_blocks: sc_client_api::BadBlocks<Block>, /// The light sync state extension used by the sync-state rpc. pub light_sync_state: sc_sync_state_rpc::LightSyncStateExtension, } /// The `ChainSpec` parameterized for the `xxnetwork` runtime. pub type XXNetworkChainSpec = sc_service::GenericChainSpec<xxnetwork::GenesisConfig, Extensions>; /// The `ChainSpec` parameterized for the `protonet` runtime. pub type ProtonetChainSpec = sc_service::GenericChainSpec<protonet::GenesisConfig, Extensions>; /// The `ChainSpec` parameterized for the `phoenixx` runtime. pub type PhoenixxChainSpec = sc_service::GenericChainSpec<phoenixx::GenesisConfig, Extensions>; /// Genesis config for `xxnetwork` mainnet pub fn xxnetwork_config() -> Result<XXNetworkChainSpec, String> { XXNetworkChainSpec::from_json_bytes(&include_bytes!("../res/xxnetwork.json")[..]) } /// Genesis config for `protonet` testnet pub fn protonet_config() -> Result<ProtonetChainSpec, String> { ProtonetChainSpec::from_json_bytes(&include_bytes!("../res/protonet.json")[..]) } /// Genesis config for `phoenixx` testnet pub fn phoenixx_config() -> Result<PhoenixxChainSpec, String> { PhoenixxChainSpec::from_json_bytes(&include_bytes!("../res/phoenixx.json")[..]) } /// Can be called for a `Configuration` to identify which network the configuration targets. pub trait IdentifyVariant { /// Returns if this is a configuration for the `xxnetwork` network. fn is_xxnetwork(&self) -> bool; /// Returns if this is a configuration for the `protonet` network. fn is_protonet(&self) -> bool; /// Returns if this is a configuration for the `phoenixx` network. fn is_phoenixx(&self) -> bool; } impl IdentifyVariant for Box<dyn ChainSpec> { fn is_xxnetwork(&self) -> bool { self.id().starts_with("xxnetwork") } fn is_protonet(&self) -> bool { self.id().starts_with("xxprotonet") } fn is_phoenixx(&self) -> bool { self.id().starts_with("phoenixx") } } fn xxnetwork_session_keys( grandpa: GrandpaId, babe: BabeId, im_online: ImOnlineId, authority_discovery: AuthorityDiscoveryId, ) -> xxnetwork::SessionKeys { xxnetwork::SessionKeys { grandpa, babe, im_online, authority_discovery } } fn protonet_session_keys( grandpa: GrandpaId, babe: BabeId, im_online: ImOnlineId, authority_discovery: AuthorityDiscoveryId, ) -> protonet::SessionKeys { protonet::SessionKeys { grandpa, babe, im_online, authority_discovery } } fn phoenixx_session_keys( grandpa: GrandpaId, babe: BabeId, im_online: ImOnlineId, authority_discovery: AuthorityDiscoveryId, ) -> phoenixx::SessionKeys { phoenixx::SessionKeys { grandpa, babe, im_online, authority_discovery } } /// Helper function to generate a crypto pair from seed pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public { TPublic::Pair::from_string(&format!("//{}", seed), None) .expect("static values are valid; qed") .public() } /// Helper function to generate an account ID from seed pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where AccountPublic: From<<TPublic::Pair as Pair>::Public> { AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() } /// Helper function to generate stash, controller and session key from seed pub fn authority_keys_from_seed(seed: &str) -> ( AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId, ) { ( get_account_id_from_seed::<sr25519::Public>(&format!("{}//stash", seed)), get_account_id_from_seed::<sr25519::Public>(seed), get_from_seed::<GrandpaId>(seed), get_from_seed::<BabeId>(seed), get_from_seed::<ImOnlineId>(seed), get_from_seed::<AuthorityDiscoveryId>(seed), ) } /// Helper function to create GenesisConfig for testing of the `phoenixx` network pub fn phoenixx_testnet_genesis( initial_authorities: Vec<( AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId, )>, initial_nominators: Vec<AccountId>, endowed_accounts: Option<Vec<AccountId>>, ) -> phoenixx::GenesisConfig { let mut endowed_accounts: Vec<AccountId> = endowed_accounts.unwrap_or_else(|| { vec![ get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), ] }); // endow all authorities and nominators. initial_authorities.iter().map(|x| &x.0).chain(initial_nominators.iter()).for_each(|x| { if !endowed_accounts.contains(&x) { endowed_accounts.push(x.clone()) } }); // stakers: all validators and nominators. let prefs = ValidatorPrefs::default(); let mut rng = rand::thread_rng(); let stakers = initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, phoenixx::StakerStatus::Validator(prefs.clone()))) .chain(initial_nominators.iter().map(|x| { use rand::{seq::SliceRandom, Rng}; let limit = (phoenixx::MAX_NOMINATIONS as usize).min(initial_authorities.len()); let count = rng.gen::<usize>() % limit; let nominations = initial_authorities .as_slice() .choose_multiple(&mut rng, count) .into_iter() .map(|choice| choice.0.clone()) .collect::<Vec<_>>(); (x.clone(), x.clone(), STASH, phoenixx::StakerStatus::Nominator(nominations)) })) .collect::<Vec<_>>(); let num_endowed_accounts = endowed_accounts.len(); const ENDOWMENT: Balance = 10_000_000 * UNITS; const STASH: Balance = ENDOWMENT / 1000; phoenixx::GenesisConfig { system: phoenixx::SystemConfig { code: phoenixx::wasm_binary_unwrap().to_vec(), changes_trie_config: Default::default(), }, balances: phoenixx::BalancesConfig { balances: endowed_accounts.iter().cloned() .map(|x| (x, ENDOWMENT)) .collect() }, session: phoenixx::SessionConfig { keys: initial_authorities.iter().map(|x| { (x.0.clone(), x.0.clone(), phoenixx_session_keys( x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone(), )) }).collect::<Vec<_>>(), }, staking: phoenixx::StakingConfig { validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32, invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), stakers, .. Default::default() }, democracy: phoenixx::DemocracyConfig::default(), elections: phoenixx::ElectionsConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .map(|member| (member, STASH)) .collect(), }, council: phoenixx::CouncilConfig::default(), technical_committee: phoenixx::TechnicalCommitteeConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .collect(), phantom: Default::default(), }, babe: phoenixx::BabeConfig { authorities: vec![], epoch_config: Some(xxnetwork_runtime::BABE_GENESIS_EPOCH_CONFIG), }, im_online: phoenixx::ImOnlineConfig { keys: vec![], }, authority_discovery: phoenixx::AuthorityDiscoveryConfig { keys: vec![], }, grandpa: phoenixx::GrandpaConfig { authorities: vec![], }, technical_membership: Default::default(), treasury: Default::default(), vesting: Default::default(), claims: Default::default(), swap: phoenixx::SwapConfig { swap_fee: 1 * UNITS, fee_destination: get_account_id_from_seed::<sr25519::Public>("Alice"), chains: vec![1], relayers: vec![get_account_id_from_seed::<sr25519::Public>("Alice")], resources: vec![ // SHA2_256("xx coin") [0:31] | 0x00 (hex!["26c3ecba0b7cea7c131a6aedf4774f96216318a2ae74926cd0e01832a0b0b500"], // Swap.transfer method hex!["537761702e7472616e73666572"].iter().cloned().collect()) ], threshold: 1, balance: 100 * UNITS, }, xx_cmix: phoenixx::XXCmixConfig { admin_permission: 0, cmix_address_space: 18, cmix_hashes: Default::default(), scheduling_account: get_account_id_from_seed::<sr25519::Public>("Alice"), cmix_variables: Default::default(), }, xx_economics: phoenixx::XXEconomicsConfig { balance: 10 * UNITS, inflation_params: Default::default(), interest_points: vec![Default::default()], ideal_stake_rewards: 10 * UNITS, liquidity_rewards: 100 * UNITS, }, xx_custody: phoenixx::XXCustodyConfig { team_allocations: vec![], custodians: vec![], } } } fn phoenixx_development_config_genesis() -> phoenixx::GenesisConfig { phoenixx_testnet_genesis( vec![ authority_keys_from_seed("Alice"), ], vec![], None, ) } /// `phoenixx` development config (single validator Alice) pub fn phoenixx_development_config() -> PhoenixxChainSpec { PhoenixxChainSpec::from_genesis( "phoenixx Development", "phoenixx_dev", ChainType::Development, phoenixx_development_config_genesis, vec![], None, None, None, Default::default(), ) } /// Helper function to create GenesisConfig for testing of the `protonet` network pub fn protonet_testnet_genesis( initial_authorities: Vec<( AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId, )>, initial_nominators: Vec<AccountId>, endowed_accounts: Option<Vec<AccountId>>, ) -> protonet::GenesisConfig { let mut endowed_accounts: Vec<AccountId> = endowed_accounts.unwrap_or_else(|| { vec![ get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), ] }); // endow all authorities and nominators. initial_authorities.iter().map(|x| &x.0).chain(initial_nominators.iter()).for_each(|x| { if !endowed_accounts.contains(&x) { endowed_accounts.push(x.clone()) } }); // stakers: all validators and nominators. let prefs = ValidatorPrefs::default(); let mut rng = rand::thread_rng(); let stakers = initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, protonet::StakerStatus::Validator(prefs.clone()))) .chain(initial_nominators.iter().map(|x| { use rand::{seq::SliceRandom, Rng}; let limit = (protonet::MAX_NOMINATIONS as usize).min(initial_authorities.len()); let count = rng.gen::<usize>() % limit; let nominations = initial_authorities .as_slice() .choose_multiple(&mut rng, count) .into_iter() .map(|choice| choice.0.clone()) .collect::<Vec<_>>(); (x.clone(), x.clone(), STASH, protonet::StakerStatus::Nominator(nominations)) })) .collect::<Vec<_>>(); let num_endowed_accounts = endowed_accounts.len(); const ENDOWMENT: Balance = 10_000_000 * UNITS; const STASH: Balance = ENDOWMENT / 1000; protonet::GenesisConfig { system: protonet::SystemConfig { code: protonet::wasm_binary_unwrap().to_vec(), changes_trie_config: Default::default(), }, balances: protonet::BalancesConfig { balances: endowed_accounts.iter().cloned() .map(|x| (x, ENDOWMENT)) .collect() }, session: protonet::SessionConfig { keys: initial_authorities.iter().map(|x| { (x.0.clone(), x.0.clone(), protonet_session_keys( x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone(), )) }).collect::<Vec<_>>(), }, staking: protonet::StakingConfig { validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32, invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), stakers, .. Default::default() }, democracy: protonet::DemocracyConfig::default(), elections: protonet::ElectionsConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .map(|member| (member, STASH)) .collect(), }, council: protonet::CouncilConfig::default(), technical_committee: protonet::TechnicalCommitteeConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .collect(), phantom: Default::default(), }, babe: protonet::BabeConfig { authorities: vec![], epoch_config: Some(xxnetwork_runtime::BABE_GENESIS_EPOCH_CONFIG), }, im_online: protonet::ImOnlineConfig { keys: vec![], }, authority_discovery: protonet::AuthorityDiscoveryConfig { keys: vec![], }, grandpa: protonet::GrandpaConfig { authorities: vec![], }, technical_membership: Default::default(), treasury: Default::default(), vesting: Default::default(), claims: Default::default(), swap: protonet::SwapConfig { swap_fee: 1 * UNITS, fee_destination: get_account_id_from_seed::<sr25519::Public>("Alice"), chains: vec![1], relayers: vec![get_account_id_from_seed::<sr25519::Public>("Alice")], resources: vec![ // SHA2_256("xx coin") [0:31] | 0x00 (hex!["26c3ecba0b7cea7c131a6aedf4774f96216318a2ae74926cd0e01832a0b0b500"], // Swap.transfer method hex!["537761702e7472616e73666572"].iter().cloned().collect()) ], threshold: 1, balance: 100 * UNITS, }, xx_cmix: protonet::XXCmixConfig { admin_permission: 0, cmix_address_space: 18, cmix_hashes: Default::default(), scheduling_account: get_account_id_from_seed::<sr25519::Public>("Alice"), cmix_variables: Default::default(), }, xx_economics: protonet::XXEconomicsConfig { balance: 10 * UNITS, inflation_params: Default::default(), interest_points: vec![Default::default()], ideal_stake_rewards: 10 * UNITS, liquidity_rewards: 100 * UNITS, }, xx_custody: protonet::XXCustodyConfig { team_allocations: vec![], custodians: vec![], } } } fn protonet_development_config_genesis() -> protonet::GenesisConfig { protonet_testnet_genesis( vec![ authority_keys_from_seed("Alice"), ], vec![], None, ) } /// `protonet` development config (single validator Alice) pub fn protonet_development_config() -> ProtonetChainSpec { ProtonetChainSpec::from_genesis( "xx protonet Development", "xxprotonet_dev", ChainType::Development, protonet_development_config_genesis, vec![], None, None, None, Default::default(), ) } /// Helper function to create GenesisConfig for testing of `xxnetwork` pub fn xxnetwork_testnet_genesis( initial_authorities: Vec<( AccountId, AccountId, GrandpaId, BabeId, ImOnlineId, AuthorityDiscoveryId, )>, initial_nominators: Vec<AccountId>, endowed_accounts: Option<Vec<AccountId>>, ) -> xxnetwork::GenesisConfig { let mut endowed_accounts: Vec<AccountId> = endowed_accounts.unwrap_or_else(|| { vec![ get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), ] }); // endow all authorities and nominators. initial_authorities.iter().map(|x| &x.0).chain(initial_nominators.iter()).for_each(|x| { if !endowed_accounts.contains(&x) { endowed_accounts.push(x.clone()) } }); // stakers: all validators and nominators. let prefs = ValidatorPrefs::default(); let mut rng = rand::thread_rng(); let stakers = initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, xxnetwork::StakerStatus::Validator(prefs.clone()))) .chain(initial_nominators.iter().map(|x| { use rand::{seq::SliceRandom, Rng}; let limit = (xxnetwork::MAX_NOMINATIONS as usize).min(initial_authorities.len()); let count = rng.gen::<usize>() % limit; let nominations = initial_authorities .as_slice() .choose_multiple(&mut rng, count) .into_iter() .map(|choice| choice.0.clone()) .collect::<Vec<_>>(); (x.clone(), x.clone(), STASH, xxnetwork::StakerStatus::Nominator(nominations)) })) .collect::<Vec<_>>(); let num_endowed_accounts = endowed_accounts.len(); const ENDOWMENT: Balance = 10_000_000 * UNITS; const STASH: Balance = ENDOWMENT / 1000; const TEAM_ALLOCATION: Balance = 10_000_000 * UNITS; xxnetwork::GenesisConfig { system: xxnetwork::SystemConfig { code: xxnetwork::wasm_binary_unwrap().to_vec(), changes_trie_config: Default::default(), }, balances: xxnetwork::BalancesConfig { balances: endowed_accounts.iter().cloned() .map(|x| (x, ENDOWMENT)) .collect() }, session: xxnetwork::SessionConfig { keys: initial_authorities.iter().map(|x| { (x.0.clone(), x.0.clone(), xxnetwork_session_keys( x.2.clone(), x.3.clone(), x.4.clone(), x.5.clone(), )) }).collect::<Vec<_>>(), }, staking: xxnetwork::StakingConfig { validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32, invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), stakers, .. Default::default() }, democracy: xxnetwork::DemocracyConfig::default(), elections: xxnetwork::ElectionsConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .map(|member| (member, STASH)) .collect(), }, council: xxnetwork::CouncilConfig::default(), technical_committee: xxnetwork::TechnicalCommitteeConfig { members: endowed_accounts.iter() .take((num_endowed_accounts + 1) / 2) .cloned() .collect(), phantom: Default::default(), }, babe: xxnetwork::BabeConfig { authorities: vec![], epoch_config: Some(xxnetwork_runtime::BABE_GENESIS_EPOCH_CONFIG), }, im_online: xxnetwork::ImOnlineConfig { keys: vec![], }, authority_discovery: xxnetwork::AuthorityDiscoveryConfig { keys: vec![], }, grandpa: xxnetwork::GrandpaConfig { authorities: vec![], }, technical_membership: Default::default(), treasury: Default::default(), vesting: Default::default(), claims: Default::default(), swap: xxnetwork::SwapConfig { swap_fee: 1 * UNITS, fee_destination: get_account_id_from_seed::<sr25519::Public>("Alice"), chains: vec![1], relayers: vec![get_account_id_from_seed::<sr25519::Public>("Alice")], resources: vec![ // SHA2_256("xx coin") [0:31] | 0x00 (hex!["26c3ecba0b7cea7c131a6aedf4774f96216318a2ae74926cd0e01832a0b0b500"], // Swap.transfer method hex!["537761702e7472616e73666572"].iter().cloned().collect()) ], threshold: 1, balance: 100 * UNITS, }, xx_cmix: xxnetwork::XXCmixConfig { admin_permission: 0, cmix_address_space: 18, cmix_hashes: Default::default(), scheduling_account: get_account_id_from_seed::<sr25519::Public>("Alice"), cmix_variables: Default::default(), }, xx_economics: xxnetwork::XXEconomicsConfig { balance: 10 * UNITS, inflation_params: Default::default(), interest_points: vec![Default::default()], ideal_stake_rewards: 10 * UNITS, liquidity_rewards: 100 * UNITS, }, xx_custody: xxnetwork::XXCustodyConfig { team_allocations: vec![ (get_account_id_from_seed::<sr25519::Public>("Alice"), TEAM_ALLOCATION), (get_account_id_from_seed::<sr25519::Public>("Bob"), TEAM_ALLOCATION), ], custodians: vec![ (get_account_id_from_seed::<sr25519::Public>("Charlie"), ()) ], } } } fn xxnetwork_development_config_genesis() -> xxnetwork::GenesisConfig { xxnetwork_testnet_genesis( vec![ authority_keys_from_seed("Alice"), ], vec![], None, ) } /// `xxnetwork` development config (single validator Alice) pub fn xxnetwork_development_config() -> XXNetworkChainSpec { XXNetworkChainSpec::from_genesis( "xx network Development", "xxnetwork_dev", ChainType::Development, xxnetwork_development_config_genesis, vec![], None, None, None, Default::default(), ) }
use crate::bits2d::Bits2D; use std::fmt; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Shape(Bits2D); impl fmt::Display for Shape { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = &self.0; for line in 1..=data.length2() { let y = data.length2() - line; for x in 0..data.length1() { write!(f, "{}", if data[(x, y)] { '*' } else { ' ' })? } writeln!(f, "")? } Ok(()) } } #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Grid(Bits2D); impl Grid { pub fn new(width: u32, height: u32) -> Self { Grid(Bits2D::new(width, height)) } pub fn try_place(&mut self, shape: &Shape, x_offset: u32, y_offset: u32) -> bool { // Bounds check if shape.0.length1() + x_offset > self.0.length1() { return false; } if shape.0.length2() + y_offset > self.0.length2() { return false; } // Check availability. Don't mutate anything here, allowing us to back out. for y in 0..shape.0.length2() { for x in 0..shape.0.length1() { // already occupied? if shape.0[(x, y)] && self.0[(x_offset + x, y_offset + y)] { return false; } } } // Make the change. for y in 0..shape.0.length2() { for x in 0..shape.0.length1() { self.0.assign(x_offset + x, y_offset + y, shape.0[(x, y)]); } } true } pub fn must_place(&mut self, shape: &Shape, x_offset: u32, y_offset: u32) { if !self.try_place(shape, x_offset, y_offset) { panic!("Tried to place on occupied field") } } } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = &self.0; write!(f, " ")?; for x in 0..data.length1() { write!(f, "-")? } writeln!(f, " ")?; for line in 1..=data.length2() { let y = data.length2() - line; write!(f, "|")?; for x in 0..data.length1() { write!(f, "{}", if data[(x, y)] { '*' } else { ' ' })? } writeln!(f, "|")? } write!(f, " ")?; for x in 0..data.length1() { write!(f, "-")? } writeln!(f, " ")?; Ok(()) } } pub mod shapes { use super::*; pub fn stair_step() -> Shape { let mut data = Bits2D::new(3, 2); data.set(0, 0); data.set(1, 0); data.set(1, 1); data.set(2, 1); Shape(data) } pub fn ell() -> Shape { let mut data = Bits2D::new(2, 3); data.set(0, 0); data.set(1, 0); data.set(0, 1); data.set(0, 2); Shape(data) } }
extern crate serde; use self::serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::vec::Vec; #[derive(Serialize, Deserialize, Debug)] pub struct KeyProviderInput { op: String, pub keywrapparams: KeyWrapParams, pub keyunwrapparams: KeyUnwrapParams, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyWrapParams { pub ec: Option<Ec>, pub optsdata: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct Ec { pub Parameters: HashMap<String, Vec<String>>, pub DecryptConfig: Dc, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyWrapOutput { pub keywrapresults: KeyWrapResults, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyWrapResults { pub annotation: Vec<u8>, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyUnwrapParams { pub dc: Option<Dc>, pub annotation: Option<String>, } #[derive(Serialize, Deserialize, Debug)] pub struct Dc { pub Parameters: HashMap<String, Vec<String>>, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyUnwrapOutput { pub keyunwrapresults: KeyUnwrapResults, } #[derive(Serialize, Deserialize, Debug)] pub struct KeyUnwrapResults { pub optsdata: Vec<u8>, }
use std::fs; #[derive(Copy, Clone)] struct PasswordTuple<'a> { min_occ: i32, max_occ: i32, letter: char, password: &'a str, } impl <'a>PasswordTuple<'a> { fn is_valid (&'a self) -> bool { let mut first_matched = false; let mut second_matched = false; for (position, character) in self.password.chars().enumerate() { if character == self.letter && (position + 1) as i32 == self.min_occ { first_matched = true; } if character == self.letter && (position + 1) as i32 == self.max_occ { second_matched = true; } } let is_valid = first_matched ^ second_matched; println!("{} ^ {} = {}: {}-{} {}: {} ", first_matched, second_matched, first_matched ^ second_matched, self.min_occ, self.max_occ, self.letter, self.password); is_valid } } // Example: 15-16 r: rrrrrrrrrrrrrrwr // Indices: ^0 ^1 ^2 fn build_password_tuple(input: &str) -> PasswordTuple { // Split by whitespace let mut parts = input.split_whitespace(); let min_max = parts.next().unwrap(); let letter_part = parts.next().unwrap(); let password = parts.next().unwrap(); let mut min_max_parts = min_max.split("-"); PasswordTuple { min_occ: min_max_parts.next().unwrap().parse::<i32>().unwrap(), max_occ: min_max_parts.next().unwrap().parse::<i32>().unwrap(), letter: letter_part.chars().next().unwrap(), password: password } } fn main() { let filename = "input.txt"; println!("In file {}", filename); // Read File let contents = fs::read_to_string(filename).expect("Something went wrong reading the file"); println!("{}", contents); // Parse into number collection let mut collection: Vec<PasswordTuple> = Vec::new(); for entry in contents.lines() { collection.push(build_password_tuple(entry)); } println!("\n"); println!("{}", collection.iter().count()); println!("\n"); let x = collection.iter() // .cloned() .filter(|t| t.is_valid()); println!("{}", x.cloned().count()); // OK(()) // x. // println!(x.) } #[test] fn test_build_password_tuple () { let tuple = build_password_tuple("15-16 r: rrrrrrrrrrrrrrwr"); assert_eq!(tuple.min_occ, 15); assert_eq!(tuple.max_occ, 16); assert_eq!(tuple.letter, 'r'); assert_eq!(tuple.password, "rrrrrrrrrrrrrrwr"); } #[test] fn test_build_password_tuple_2 () { let tuple = build_password_tuple("10-12 r: rrrrrrrrrrrrrrwr"); assert_eq!(tuple.min_occ, 10); assert_eq!(tuple.max_occ, 12); assert_eq!(tuple.letter, 'r'); assert_eq!(tuple.password, "rrrrrrrrrrrrrrwr"); } #[test] fn test_password_tuple_valid () { assert_eq!(build_password_tuple("1-3 a: abcde").is_valid(), true); assert_eq!(build_password_tuple("1-3 b: cdefg").is_valid(), false); assert_eq!(build_password_tuple("2-9 c: ccccccccc").is_valid(), false); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TZIC interrupt enable register 1"] pub ier1: IER1, #[doc = "0x04 - TZIC interrupt enable register 2"] pub ier2: IER2, #[doc = "0x08 - TZIC interrupt enable register 3"] pub ier3: IER3, _reserved3: [u8; 0x04], #[doc = "0x10 - TZIC interrupt status register 1"] pub sr1: SR1, #[doc = "0x14 - TZIC interrupt status register 2"] pub sr2: SR2, #[doc = "0x18 - TZIC interrupt status register 3"] pub sr3: SR3, _reserved6: [u8; 0x04], #[doc = "0x20 - TZIC interrupt clear register 1"] pub fcr1: FCR1, #[doc = "0x24 - TZIC interrupt clear register 2"] pub fcr2: FCR2, #[doc = "0x28 - TZIC interrupt clear register 3"] pub fcr3: FCR3, } #[doc = "IER1 (rw) register accessor: TZIC interrupt enable register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier1::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 [`ier1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier1`] module"] pub type IER1 = crate::Reg<ier1::IER1_SPEC>; #[doc = "TZIC interrupt enable register 1"] pub mod ier1; #[doc = "IER2 (rw) register accessor: TZIC interrupt enable register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier2::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 [`ier2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier2`] module"] pub type IER2 = crate::Reg<ier2::IER2_SPEC>; #[doc = "TZIC interrupt enable register 2"] pub mod ier2; #[doc = "IER3 (rw) register accessor: TZIC interrupt enable register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier3::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 [`ier3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ier3`] module"] pub type IER3 = crate::Reg<ier3::IER3_SPEC>; #[doc = "TZIC interrupt enable register 3"] pub mod ier3; #[doc = "SR1 (r) register accessor: TZIC interrupt status register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr1::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr1`] module"] pub type SR1 = crate::Reg<sr1::SR1_SPEC>; #[doc = "TZIC interrupt status register 1"] pub mod sr1; #[doc = "SR2 (rw) register accessor: TZIC interrupt status register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr2::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 [`sr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr2`] module"] pub type SR2 = crate::Reg<sr2::SR2_SPEC>; #[doc = "TZIC interrupt status register 2"] pub mod sr2; #[doc = "SR3 (rw) register accessor: TZIC interrupt status register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr3::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 [`sr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr3`] module"] pub type SR3 = crate::Reg<sr3::SR3_SPEC>; #[doc = "TZIC interrupt status register 3"] pub mod sr3; #[doc = "FCR1 (w) register accessor: TZIC interrupt clear register 1\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`fcr1::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fcr1`] module"] pub type FCR1 = crate::Reg<fcr1::FCR1_SPEC>; #[doc = "TZIC interrupt clear register 1"] pub mod fcr1; #[doc = "FCR2 (rw) register accessor: TZIC interrupt clear register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fcr2::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 [`fcr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fcr2`] module"] pub type FCR2 = crate::Reg<fcr2::FCR2_SPEC>; #[doc = "TZIC interrupt clear register 2"] pub mod fcr2; #[doc = "FCR3 (rw) register accessor: TZIC interrupt clear register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fcr3::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 [`fcr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`fcr3`] module"] pub type FCR3 = crate::Reg<fcr3::FCR3_SPEC>; #[doc = "TZIC interrupt clear register 3"] pub mod fcr3;
mod target; mod drawable; mod builder; use builder::WindowBuilder; pub use target::DrawTarget; pub use drawable::Drawable; #[derive(Copy, Clone)] pub struct Window(usize); impl Window { #[inline] pub fn new() -> WindowBuilder { WindowBuilder::default() } #[inline] pub fn draw(self) -> DrawTarget { DrawTarget::from(self.dpy()) } #[inline] pub fn id(self) -> usize { self.0 } }
// use std::io; // use std::io::prelude::*; // use regex::Regex; // fn main() { // let mut input = String::new(); // print!("Numbers to sort: "); // io::stdout().flush().unwrap(); // io::stdin().read_line(&mut input).ok().expect("failed to read line"); // let re = Regex::new(r"\s+").unwrap(); // let mut vec = Vec::<i32>::new(); // let numbers: Vec<&str> = re.split(input.trim()).collect(); // for n in numbers.iter() { // vec.push(n.parse().expect("Please enter numbers!")); // } // vec.sort(); // println!("sorted: {:?}", vec); // } // let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); // let text = "2012-03-14, 2013-01-01 and 2014-07-05"; // for cap in re.captures_iter(text) { // println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]); // } // let re = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})").unwrap(); // let before = "2012-03-14, 2013-01-01 and 2014-07-05"; // let after = re.replace_all(before, "$m/$d/$y"); // assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); use regex::Regex; #[derive(Debug)] struct MyRegex { year: u32, month: u32, day: u32 } fn to_u32(s: &str) -> u32 { s.parse::<u32>().unwrap() } fn main() { let text = "It was on 2019-03-14, almost after a year from 2018-02-11"; let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); for cap in re.captures_iter(text) { println!("{:?}", MyRegex { year: to_u32(&cap[1]), month: to_u32(&cap[2]), day: to_u32(&cap[3]) }); } }
//! MIPS CP0 ErrorEPC register register_rw!(30, 0);
use array2d::Array2D; use rand::Rng; use std::ops::Range; use std::collections::HashSet; use rand::distributions::Uniform; use std::fmt; struct Grid { grid: Array2D<bool> } // To achieve uniform distribution of grids fn random_indexes_in_range(range: Range<usize>, expected: usize) -> HashSet<usize> { let mut out = HashSet::with_capacity(expected); let uniform = Uniform::from(range); let mut rng = rand::thread_rng(); while out.len() < expected { let i = rng.sample(uniform); out.insert(i); } return out; } impl Grid { fn new(lx: usize, ly: usize, n: usize) -> Grid { let indexes = random_indexes_in_range(0..lx * ly, n); let mut counter: usize = 0; let gen = || { counter += 1; return indexes.contains(&(counter - 1)); }; Grid { grid: Array2D::filled_by_row_major(gen, ly, lx) } } } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for row in self.grid.rows_iter() { for cell in row { write!(f, "{}", if *cell { '+' } else { '.' })?; } write!(f, "\n")?; } Ok(()) } } pub fn main() { let lx = 6; let ly = 4; let n = 10; let g1 = Grid::new(lx, ly, n); let g2 = Grid::new(lx, ly, n); let g3 = Grid::new(lx, ly, n); println!("{}", g1); println!("{}", g2); println!("{}", g3); }
use websocket::sync::Client; use std::net::TcpStream; use std::thread; use std::sync::mpsc; use websocket::{Message, OwnedMessage}; pub struct WsClient { pub conn: Client<TcpStream>, } impl WsClient { pub fn run(self, receiver: mpsc::Receiver<Vec<u8>>) { let (mut rstream, mut sstream) = self.conn.split().unwrap(); let(tx, rx) = mpsc::channel::<OwnedMessage>(); let tx1 = mpsc::Sender::clone(&tx); let send_loop = thread::spawn(move || { loop { let message = match rx.recv() { Ok(m) => m, Err(e) => { warn!("Send Loop: {:?}", e); return; } }; match message { OwnedMessage::Close(_) => { debug!("Client disconnected"); return; }, OwnedMessage::Pong(ping) => { let message = OwnedMessage::Pong(ping); match sstream.send_message(&message) { Ok(()) => (), Err(e) => { warn!("Sending Pong messages to network error: {:?}", e); let _ = sstream.send_message(&Message::close()); return; } } }, _ => { match sstream.send_message(&message) { Ok(()) => (), Err(e) => { warn!("Sending messages to network error: {:?}", e); let _ = sstream.send_message(&Message::close()); return; } } }, } } }); let receive_loop = thread::spawn(move || { for message in rstream.incoming_messages() { let message = match message { Ok(m) => m, Err(e) => { warn!("Read error from network: {:?}", e); let _ = tx1.send(OwnedMessage::Close(None)); return; } }; match message { OwnedMessage::Close(_) => { match tx1.send(message) { Ok(()) => (), Err(e) => { warn!("Sending Close to sstream error: {:?}", e); return; } } debug!("Client disconnected"); return; } OwnedMessage::Ping(ping) => { let message = OwnedMessage::Pong(ping); match tx1.send(message) { Ok(()) => (), Err(e) => { warn!("Sending Ping to sstream error: {:?}", e); return; } } } _ => debug!("Received new message from client, drop it."), } } }); let _ = thread::spawn(move || { let mut iter = receiver.iter(); loop { match iter.next() { Some(message) => { let message = OwnedMessage::Binary(message); match tx.send(message) { Ok(()) => (), Err(e) => { debug!("Sending messages to sstream error: {:?}", e); return; } } }, None => break, } } }); let _ = send_loop.join(); let _ = receive_loop.join(); debug!("Client exited"); } }
fn main(){ struct Home { name: String, rooms: i32, sold: bool, } let mut home1 = Home { name: String::from("myhome"), rooms: 13, sold: false, }; home1.sold = true; println!("sold = {}", home1.sold); }
use crate::model::model_utils::{GridPosition, grid_to_position}; use cgmath; pub struct FoxHole<T> { pub entry: T, pub exit: T, pub used: bool, pub entry_sprite: i32, pub exit_sprite: i32, pub closed_sprite: i32, } impl<T> FoxHole<T> { pub fn new(entry: T, exit: T, used: Option<bool>) -> FoxHole<T> { FoxHole { entry: entry, exit: exit, used: used.unwrap_or(false), entry_sprite: 12, exit_sprite: 12, closed_sprite: 13, } } } impl FoxHole<GridPosition> { pub fn from(grid_hole: &FoxHole<GridPosition>, width: f32, height: f32) -> FoxHole<cgmath::Vector2<f32>> { let entry_pos = grid_to_position(&grid_hole.entry, width, height); let exit_pos = grid_to_position(&grid_hole.exit, width, height); FoxHole::new(entry_pos, exit_pos, None) } }
fn main() { let mut x: i32 = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); let _c = 'z'; let _z = 'Z'; let heart_eyed_cat = '😻'; println!("{}", heart_eyed_cat); }
pub mod command; pub mod commands { pub mod add; pub mod clear; pub mod delete; pub mod jump; pub mod list; pub mod ls; pub mod rename; } pub mod domain { pub mod command_line; pub mod model; pub mod repository; pub mod service; } pub mod infrastructure { pub mod command_line; pub mod db; pub mod error; pub mod repository; } pub mod interface { pub mod presenter; }
use super::*; #[test] fn traverse_at_root_dir() { assert_eq!(traverse_reduce("c:/").unwrap(), "c:/"); assert_eq!(traverse_reduce("D:/").unwrap(), "D:/"); assert_eq!(traverse_reduce("c:\\").unwrap(), "c:/"); assert_eq!(traverse_reduce("D:\\").unwrap(), "D:/"); assert_eq!(traverse_reduce("c:").unwrap(), "c:/"); assert_eq!(traverse_reduce("D:").unwrap(), "D:/"); } #[test] fn simple_at_root_dir() { assert_eq!(simple_reduce("c:/").unwrap(), "c:/"); assert_eq!(simple_reduce("D:/").unwrap(), "D:/"); assert_eq!(simple_reduce("c:\\").unwrap(), "c:/"); assert_eq!(simple_reduce("D:\\").unwrap(), "D:/"); assert_eq!(simple_reduce("c:").unwrap(), "c:/"); assert_eq!(simple_reduce("D:").unwrap(), "D:/"); } #[test] fn simple_nested() { let paths = &[ ("c:/", "c:/"), ("c:/dev/", "c:/dev/"), ("c:/dev", "c:/dev/"), ("c:/dev/foo", "c:/d/foo/"), ("c:/dev/foo/bar", "c:/d/f/bar/"), ("c:/dev/foo/bar/baz and", "c:/d/f/b/baz and/"), ("c:/dev/foo/bar/baz and/q u u x", "c:/d/f/b/b/q u u x/"), ]; for (path, expected) in paths { assert_eq!(simple_reduce(path).unwrap(), *expected); } } // TODO: need a temp fs to test the file traversal
use serenity::builder::CreateEmbed; use serenity::framework::standard::{Args, CommandError}; use serenity::model::channel::Message; use serenity::prelude::Context; use crate::commands::servers::lobby_details; use crate::commands::servers::*; use crate::db::{DbConnection, DbConnectionKey}; use crate::model::enums::{NationStatus, SubmissionStatus}; use crate::model::GameServerState; use crate::server::ServerConnection; pub fn details2<C: ServerConnection>( context: &mut Context, message: &Message, mut args: Args, ) -> Result<(), CommandError> { let data = context.data.lock(); let db_conn = data .get::<DbConnectionKey>() .ok_or("No DbConnection was created on startup. This is a bug.")?; let read_handle = data .get::<crate::DetailsReadHandleKey>() .ok_or("No ReadHandle was created on startup. This is a bug.")?; let alias = alias_from_arg_or_channel_name(&mut args, &message)?; if !args.is_empty() { return Err(CommandError::from( "Too many arguments. TIP: spaces in arguments need to be quoted \"like this\"", )); } let embed_response = details_helper(&alias, db_conn, read_handle)?; message .channel_id .send_message(|m| m.embed(|_| embed_response))?; Ok(()) } fn details_helper( alias: &str, db_conn: &DbConnection, read_handle: &crate::CacheReadHandle, ) -> Result<CreateEmbed, CommandError> { let server = db_conn.game_for_alias(&alias)?; match server.state { GameServerState::Lobby(ref lobby_state) => { let details: GameDetails = lobby_details(db_conn, lobby_state, alias)?; let embed: CreateEmbed = details_to_embed(details)?; Ok(embed) } GameServerState::StartedState(ref started_state, ref option_lobby_state) => { let option_option_game_cache = read_handle.get_clone(alias); match option_option_game_cache { Some(Some(cache)) => { let CacheEntry { game_data, option_snek_state, } = cache; let details: GameDetails = started_details_from_server( db_conn, started_state, option_lobby_state.as_ref(), alias, game_data, option_snek_state, )?; let embed: CreateEmbed = details_to_embed(details)?; Ok(embed) } Some(None) => Err("Got an error when trying to connect to the server".into()), None => Err("Not yet got a response from server, try again in 1 min".into()), } } } } fn details_to_embed(details: GameDetails) -> Result<CreateEmbed, CommandError> { let option_snek_state = details .cache_entry .and_then(|cache_entry| cache_entry.option_snek_state); let mut e = match details.nations { NationDetails::Started(started_details) => { match &started_details.state { StartedStateDetails::Playing(playing_state) => { let embed_title = format!( "{} ({}): turn {}, {}h {}m remaining", started_details.game_name, started_details.address, playing_state.turn, playing_state.hours_remaining, playing_state.mins_remaining ); // we can't have too many players per embed it's real annoying let mut embed_texts = vec![]; for (ix, potential_player) in playing_state.players.iter().enumerate() { let (option_user_id, player_details) = match potential_player { // If the game has started and they're not in it, too bad PotentialPlayer::RegisteredOnly(_, _) => continue, PotentialPlayer::RegisteredAndGame(user_id, player_details) => { (Some(user_id), player_details) } PotentialPlayer::GameOnly(player_details) => (None, player_details), }; let player_name = if let NationStatus::Human = player_details.player_status { match option_user_id { Some(user_id) => format!("**{}**", user_id.to_user()?), None => player_details.player_status.show().to_owned(), } } else { player_details.player_status.show().to_owned() }; let submission_symbol = if player_details.player_status.is_human() { player_details.submitted.show().to_owned() } else { SubmissionStatus::Submitted.show().to_owned() }; if ix % 20 == 0 { embed_texts.push(String::new()); } let new_len = embed_texts.len(); embed_texts[new_len - 1].push_str(&format!( "`{}` {}: {}\n", submission_symbol, player_details .nation_identifier .name(option_snek_state.as_ref()), player_name, )); } // This is pretty hacky let mut e = CreateEmbed::default().title("Details").field( embed_title, embed_texts[0].clone(), false, ); for embed_text in &embed_texts[1..] { e = e.field("-----", embed_text, false); } e } StartedStateDetails::Uploading(uploading_state) => { let embed_title = format!( "{} ({}): Pretender uploading", started_details.game_name, started_details.address, ); let mut embed_texts = vec![]; for (ix, uploading_player) in uploading_state.uploading_players.iter().enumerate() { let player_name = match uploading_player.option_player_id() { Some(user_id) => format!("**{}**", user_id.to_user()?), None => NationStatus::Human.show().to_owned(), }; let player_submitted_status = if uploading_player.uploaded { SubmissionStatus::Submitted.show() } else { SubmissionStatus::NotSubmitted.show() }; if ix % 20 == 0 { embed_texts.push(String::new()); } let new_len = embed_texts.len(); embed_texts[new_len - 1].push_str(&format!( "`{}` {}: {}\n", player_submitted_status, uploading_player.nation_name(option_snek_state.as_ref()), player_name, )); } // This is pretty hacky let mut e = CreateEmbed::default().title("Details").field( embed_title, embed_texts[0].clone(), false, ); for embed_text in &embed_texts[1..] { e = e.field("-----", embed_text, false); } e } } } NationDetails::Lobby(lobby_details) => { let embed_title = match lobby_details.era { Some(era) => format!("{} ({} Lobby)", details.alias, era), None => format!("{} (Lobby)", details.alias), }; let mut embed_texts = vec![]; if lobby_details.players.len() != 0 { for (ix, lobby_player) in lobby_details.players.iter().enumerate() { let discord_user = lobby_player.player_id.to_user()?; if ix % 20 == 0 { embed_texts.push(String::new()); } let new_len = embed_texts.len(); embed_texts[new_len - 1] .push_str(&format!("{}: {}\n", lobby_player.cached_name, discord_user,)); } } else { embed_texts.push(String::new()); } // We don't increase the number of fields any more let new_len = embed_texts.len(); for _ in 0..lobby_details.remaining_slots { embed_texts[new_len - 1].push_str("OPEN\n"); } // This is pretty hacky let mut e = CreateEmbed::default().title("Details").field( embed_title, embed_texts[0].clone(), false, ); for embed_text in &embed_texts[1..] { e = e.field("-----", embed_text, false); } e } }; for owner in details.owner { e = e.field("Owner", owner.to_user()?.to_string(), false); } for description in details.description { if !description.is_empty() { e = e.field("Description", description, false); } } Ok(e) }
use crate::{execute::ExecuteArgs, Client, ClientFactory, Execute, Parameter, QueryRows, ToSql}; use futures::{Stream, StreamExt, TryStreamExt}; use std::{ borrow::Cow, fmt::Debug, pin::Pin, sync::{ atomic::{AtomicBool, Ordering::Relaxed}, Arc, }, task::{Context, Poll}, }; use storm::{provider, BoxFuture, Error, InstrumentErr, Result}; use tiberius::Row; use tokio::sync::{Mutex, MutexGuard}; use tracing::{debug_span, instrument, Instrument, Span}; pub struct MssqlProvider(Arc<Inner>); impl MssqlProvider { pub fn new<F: ClientFactory>(client_factory: F) -> Self { (Box::new(client_factory) as Box<dyn ClientFactory>).into() } async fn state(&self) -> MutexGuard<'_, State> { let mut guard = self.0.state.lock().await; if self.0.cancel_transaction.swap(false, Relaxed) { let _ = guard.cancel().await; } guard } /// Creates a new [Client](Client) instance. /// # Safety /// This operation is safe but the returning client is not constrained by the lock and can modify the database without storm's knowledge. pub async unsafe fn create_client(&self) -> Result<Client> { self.0.state.lock().await.create_client().await } } impl Execute for MssqlProvider { #[instrument( level = "debug", name = "MssqlProvider::execute", skip(self, params), err )] fn execute_with_args<'a, S>( &'a self, statement: S, params: &'a [&'a (dyn ToSql)], args: ExecuteArgs, ) -> BoxFuture<'a, Result<u64>> where S: ?Sized + Debug + Into<Cow<'a, str>> + Send + 'a, { Box::pin(async move { let mut intermediate = Vec::new(); let mut output = Vec::new(); adapt_params(params, &mut intermediate, &mut output); let mut client; let client_ref; let mut guard = self.state().await; if args.use_transaction { client = guard.transaction().await?; client_ref = &mut guard.transaction; } else { client = guard.client().await?; client_ref = &mut guard.client; }; let count = client.execute(statement, &output).await?.total(); *client_ref = Some(client); Ok(count) }) } } struct Inner { cancel_transaction: AtomicBool, state: Mutex<State>, } impl From<Box<dyn ClientFactory>> for MssqlProvider { fn from(factory: Box<dyn ClientFactory>) -> Self { Self(Arc::new(Inner { cancel_transaction: Default::default(), state: Mutex::new(State::new(factory)), })) } } impl provider::Provider for MssqlProvider { fn cancel(&self) { self.0.cancel_transaction.store(true, Relaxed); let span = tracing::Span::current(); let p = Self(Arc::clone(&self.0)); tokio::spawn( async move { let _ = p.state().await; } .instrument(debug_span!(parent: span, "rollback_transaction")), ); } fn commit(&self) -> BoxFuture<'_, Result<()>> { Box::pin(async move { self.state().await.commit().await }) } } impl QueryRows for MssqlProvider { fn query_rows<'a, S, M, R, C>( &'a self, statement: S, params: &'a [&'a (dyn ToSql)], mut mapper: M, use_transaction: bool, ) -> BoxFuture<'a, Result<C>> where C: Default + Extend<R> + Send, M: FnMut(Row) -> Result<R> + Send + 'a, R: Send, S: ?Sized + Debug + for<'b> Into<Cow<'b, str>> + Send + 'a, { let sql = statement.into(); let span = instrument_query_rows(&sql); Box::pin( async move { let mut conn = QueryConn::new(self, use_transaction).await?; let mut query = conn.query(sql, params).await?; let mut vec = Vec::with_capacity(10); let mut coll = C::default(); while let Some(row) = query.try_next().await? { vec.push(mapper(row)?); if vec.len() == 10 { #[allow(clippy::iter_with_drain)] coll.extend(vec.drain(..)); } } if !vec.is_empty() { coll.extend(vec); } query.complete().await?; conn.complete(); Ok(coll) } .instrument_err(span), ) } } fn instrument_query_rows(sql: &str) -> Span { debug_span!( "MssqlProvider::query_rows", sql, err = tracing::field::Empty ) } struct QueryConn<'a> { client: Client, guard: MutexGuard<'a, State>, use_transaction: bool, } impl<'a> QueryConn<'a> { async fn new(provider: &'a MssqlProvider, use_transaction: bool) -> Result<QueryConn<'a>> { let mut guard = provider.state().await; let client = match use_transaction { true => guard.transaction().await, false => guard.client().await, }?; Ok(Self { client, guard, use_transaction, }) } fn complete(mut self) { match self.use_transaction { true => self.guard.transaction = Some(self.client), false => self.guard.client = Some(self.client), } } async fn query<'b>( &'b mut self, sql: Cow<'b, str>, params: &'b [&'b (dyn ToSql)], ) -> Result<QueryStream<'b>> { let mut intermediate = Vec::new(); let mut output = Vec::new(); adapt_params(params, &mut intermediate, &mut output); let stream = self.client.query(sql, &output[..]).await?; Ok(QueryStream(stream)) } } struct QueryStream<'a>(tiberius::QueryStream<'a>); impl<'a> QueryStream<'a> { async fn complete(self) -> Result<()> { self.0.into_results().await?; Ok(()) } } impl<'a> Stream for QueryStream<'a> { type Item = Result<tiberius::Row>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { loop { return match self.0.poll_next_unpin(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Some(Ok(tiberius::QueryItem::Metadata(_)))) => continue, Poll::Ready(Some(Ok(tiberius::QueryItem::Row(r)))) => Poll::Ready(Some(Ok(r))), Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e.into()))), Poll::Ready(None) => Poll::Ready(None), }; } } } struct State { client: Option<Client>, factory: Box<dyn ClientFactory>, transaction: Option<Client>, } impl State { fn new(factory: Box<dyn ClientFactory>) -> Self { Self { client: None, factory, transaction: None, } } async fn cancel(&mut self) -> Result<()> { self.cancel_or_commit("ROLLBACK").await } async fn cancel_or_commit(&mut self, statement: &'static str) -> Result<()> { if let Some(mut client) = self.transaction.take() { client.simple_query(statement).await.map_err(Error::Mssql)?; if self.client.is_none() { self.client = Some(client); } } Ok(()) } async fn client(&mut self) -> Result<Client> { match self.client.take() { Some(c) => Ok(c), None => { if let Some(client) = self .factory .under_transaction() .then(|| self.transaction.take()) .flatten() { return Ok(client); } self.create_client().await } } } async fn commit(&mut self) -> Result<()> { self.cancel_or_commit("COMMIT").await } async fn create_client(&self) -> Result<Client> { self.factory.create_client().await } async fn transaction(&mut self) -> Result<Client> { match self.transaction.take() { Some(t) => Ok(t), None => { let mut client = self.client().await?; client .simple_query("BEGIN TRAN") .await .map_err(Error::Mssql)?; Ok(client) } } } } fn adapt_params<'a>( input: &'a [&dyn ToSql], intermediate: &'a mut Vec<Parameter<'a>>, output: &mut Vec<&'a dyn tiberius::ToSql>, ) { intermediate.extend(input.iter().map(|p| Parameter(p.to_sql()))); output.extend(intermediate.iter().map(|p| p as &dyn tiberius::ToSql)); }
pub mod data; mod query; #[cfg(test)] mod test; use hyper::{body::HttpBody as _, client::HttpConnector, Client}; use hyper_tls::HttpsConnector; use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; use data::{MVGError}; use data::location::{Location, Locations}; use data::departure::{Departure, DepartureInfo}; use data::connection::{ConnectionList, Connection}; pub struct MVG { client: Client<HttpsConnector<HttpConnector>>, } impl MVG { pub fn new() -> Self { let https = HttpsConnector::new(); let client = Client::builder().build::<_, hyper::Body>(https); MVG { client: client } } pub async fn stations_by_name(&self, search: &str) -> Result<Vec<Location>, MVGError> { let search = utf8_percent_encode(search, NON_ALPHANUMERIC).to_string(); let url = query::query_url_name(&search); let url = url.parse::<hyper::Uri>()?; let mut res = self.client.get(url).await?; if res.status() != http::status::StatusCode::OK { return Err(MVGError::ArgumentError("No response".to_string())); } let mut json = String::new(); while let Some(next) = res.data().await { let chunk = next?; json += &String::from_utf8_lossy(&chunk); } let locations_raw: Locations = serde_json::from_str(&json)?; Ok(locations_raw.locations) } pub async fn stations_by_id(&self, id: &str) -> Result<Vec<Location>, MVGError> { let url = query::query_url_id(id); let url = url.parse::<hyper::Uri>()?; let mut res = self.client.get(url).await?; if res.status() != http::status::StatusCode::OK { return Err(MVGError::ArgumentError("No response".to_string())); } let mut json = String::new(); while let Some(next) = res.data().await { let chunk = next?; json += &String::from_utf8_lossy(&chunk); } let locations_raw: Locations = serde_json::from_str(&json)?; Ok(locations_raw.locations) } pub async fn departures_by_id(&self, station_id: &str) -> Result<Vec<Departure>, MVGError> { let url: String = query::departure_url(station_id); let url = url.parse::<hyper::Uri>()?; let mut res = self.client.get(url).await?; if res.status() != http::status::StatusCode::OK { return Err(MVGError::ArgumentError( format!("No valid station id: {}", station_id) )); } let mut json = String::new(); while let Some(next) = res.data().await { let chunk = next?; json += &String::from_utf8_lossy(&chunk); } let departure_info: DepartureInfo = serde_json::from_str(&json)?; Ok(departure_info.departures) } pub async fn connections(&self, from_id: &str, to_id: &str) -> Result<Vec<Connection>, MVGError>{ let url = query::routing_url(from_id, to_id); let url = url.parse::<hyper::Uri>()?; let mut res = self.client.get(url).await?; if res.status() != http::status::StatusCode::OK { return Err(MVGError::ArgumentError( format!("No valid station ids: {} - {}", from_id, to_id) )); } let mut json = String::new(); while let Some(next) = res.data().await { let chunk = next?; json += &String::from_utf8_lossy(&chunk); } let connections: ConnectionList = serde_json::from_str(&json)?; let connections = connections.connection_list; Ok(connections) } }
const AVERAGE_EARTH_RADIUS: f64 = 6371000.0; #[no_mangle] pub unsafe extern "C" fn haversine(lat1:f64, lon1:f64, lat2:f64, lon2:f64) -> f64 { let d_lat = (lat2 - lat1).to_radians(); let d_lon = (lon2 - lon1).to_radians(); let l1 = (lat1).to_radians(); let l2 = (lat2).to_radians(); let a = ((d_lat/2.0).sin()) * ((d_lat/2.0).sin()) + ((d_lon/2.0).sin()) * ((d_lon/2.0).sin()) * (l1.cos()) * (l2.cos()); let c = 2.0 * ((a.sqrt()).atan2((1.0-a).sqrt())); return AVERAGE_EARTH_RADIUS * c; }
use crate::{definitions::*, packet::*}; use bytes::{BufMut, Bytes, BytesMut}; use num_traits::ToPrimitive; pub fn encode_fix_header(src: FixHeader, bytes: &mut BytesMut) { bytes.put_u8((src.control_packet_type.to_u8().unwrap() << 4) | src.flags.0 | (src.flags.1 << 1) | (src.flags.2 << 2) | (src.flags.3 << 3)); } pub fn encode_conn_ack_packet(src: ConnAckControlPacket, bytes: &mut BytesMut) { bytes.put_u8(src.variable_header.conn_ack_flag.session_present_flag as u8); bytes.put_u8(src.variable_header.reason_code.to_u8().unwrap()); encode_properties(src.variable_header.properties, bytes); } pub fn encode_pub_ack_packet(src: PubAckControlPacket, bytes: &mut BytesMut) { bytes.put_u16(src.variable_header.packet_identifier); bytes.put_u8(src.variable_header.reason_code.to_u8().unwrap()); encode_properties(src.variable_header.get_properties(), bytes); } pub fn encode_pub_rec_packet(src: PubRecControlPacket, bytes: &mut BytesMut) { bytes.put_u16(src.variable_header.packet_identifier); bytes.put_u8(src.variable_header.reason_code.to_u8().unwrap()); encode_properties(src.variable_header.get_properties(), bytes); } pub fn encode_pub_comp_packet(src: PubCompControlPacket, bytes: &mut BytesMut) { bytes.put_u16(src.variable_header.packet_identifier); bytes.put_u8(src.variable_header.reason_code.to_u8().unwrap()); encode_properties(src.variable_header.get_properties(), bytes); } pub fn encode_sub_ack_packet(src: SubAckControlPacket, bytes: &mut BytesMut) { bytes.put_u16(src.variable_header.packet_identifier); encode_properties(src.variable_header.get_properties(), bytes); encode_sub_ack_payload(src.variable_header.sub_ack_payload, bytes); } pub fn encode_sub_ack_payload(src: SubAckPayload, bytes: &mut BytesMut) { for iter in src.sub_ack_reason_codes { bytes.put_u8(iter.to_u8().unwrap()); } } pub fn encode_properties(src: Vec<Option<Property>>, bytes: &mut BytesMut) { let mut data: BytesMut = BytesMut::new(); for elem in src.iter() { match elem { Some(property) => encode_property(property, &mut data), None => (), } } bytes.extend(VariableByteInteger::encode_u32(data.len() as u32)); bytes.extend(data); } pub fn encode_property(src: &Property, bytes: &mut BytesMut) { match src { Property::PayloadFormatIndicator(p_data) => { bytes.put_u8(1); bytes.put_u8(*p_data); } Property::MessageExpiryInterval(p_data) => { bytes.put_u8(2); bytes.put_slice(&p_data.to_be_bytes()); } Property::ContentType(p_data) => { bytes.put_u8(3); encode_string(p_data, bytes); } Property::ResponseTopic(p_data) => { bytes.put_u8(8); encode_string(p_data, bytes); } Property::CorrelationData(p_data) => { bytes.put_u8(9); encode_binary_data(p_data, bytes); } Property::SubscriptionIdentifier(p_data) => { bytes.put_u8(11); bytes.put_slice(&p_data.encode()); } Property::SessionExpiryInterval(p_data) => { bytes.put_u8(17); bytes.put_slice(&p_data.to_be_bytes()); } Property::AssignedClientIdentifier(p_data) => { bytes.put_u8(18); encode_string(p_data, bytes); } Property::ServerKeepAlive(p_data) => { bytes.put_u8(19); bytes.put_u16(*p_data); } Property::AuthenticationMethod(p_data) => { bytes.put_u8(21); encode_string(p_data, bytes); } Property::AuthenticationData(p_data) => { bytes.put_u8(22); encode_binary_data(p_data, bytes); } Property::RequestProblemInformation(p_data) => { bytes.put_u8(23); bytes.put_u8(*p_data); } Property::WillDelayInterval(p_data) => { bytes.put_u8(24); bytes.put_u32(*p_data); } Property::RequestResponseInformation(p_data) => { bytes.put_u8(25); bytes.put_u8(*p_data); } Property::ResponseInformation(p_data) => { bytes.put_u8(26); encode_string(p_data, bytes); } Property::ServerReference(p_data) => { bytes.put_u8(28); encode_string(p_data, bytes); } Property::ReasonString(p_data) => { bytes.put_u8(31); encode_string(p_data, bytes); } Property::ReceiveMaximum(p_data) => { bytes.put_u8(33); bytes.put_u16(*p_data); } Property::TopicAliasMaximum(p_data) => { bytes.put_u8(34); bytes.put_u16(*p_data); } Property::TopicAlias(p_data) => { bytes.put_u8(35); bytes.put_u16(*p_data); } Property::MaximumQoS(p_data) => { bytes.put_u8(36); bytes.put_u8(p_data.to_u8().unwrap()); } Property::RetainAvailable(p_data) => { bytes.put_u8(37); bytes.put_u8(*p_data); } Property::UserProperty(p_data) => { bytes.put_u8(38); encode_string(p_data, bytes); } Property::MaximumPacketSize(p_data) => { bytes.put_u8(39); bytes.put_u32(*p_data); } Property::WildcardSubscriptionAvailable(p_data) => { bytes.put_u8(40); bytes.put_u8(*p_data); } Property::SubscriptionIdentifierAvailable(p_data) => { bytes.put_u8(41); bytes.put_u8(*p_data); } Property::SharedSubscriptionAvailable(p_data) => { bytes.put_u8(42); bytes.put_u8(*p_data); } }; } pub fn encode_string(src: &str, bytes: &mut BytesMut) { bytes.put_u16(src.len() as u16); bytes.put_slice(src.as_bytes()); } pub fn encode_binary_data(src: &Bytes, bytes: &mut BytesMut) { bytes.put_u16(src.len() as u16); bytes.put_slice(src.as_ref()); }
/// Compare two errors /// /// Used for testing only #[macro_export] macro_rules! assert_error_eq { ($left:expr, $right:expr) => { assert_eq!( Into::<$crate::Error>::into($left).to_string(), Into::<$crate::Error>::into($right).to_string(), ); }; ($left:expr, $right:expr,) => { $crate::assert_error_eq!($left, $right); }; ($left:expr, $right:expr, $($arg:tt)+) => { assert_eq!( Into::<$crate::Error>::into($left).to_string(), Into::<$crate::Error>::into($right).to_string(), $($arg)+ ); } } #[macro_export] macro_rules! impl_error_conversion_with_kind { ($source:ty, $kind:expr, $target:ty) => { impl ::std::convert::From<$source> for $target { fn from(error: $source) -> Self { error.context($kind).into() } } }; } #[macro_export] macro_rules! impl_error_conversion_with_adaptor { ($source:ty, $adaptor:ty, $target:ty) => { impl ::std::convert::From<$source> for $target { fn from(error: $source) -> Self { ::std::convert::Into::<$adaptor>::into(error).into() } } }; }
use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; // use solana_program::{borsh}; use borsh::{BorshDeserialize, BorshSerialize}; pub trait Serdes: Sized + BorshSerialize + BorshDeserialize { fn pack(&self, dst: &mut [u8]) { let encoded = self.try_to_vec().unwrap(); dst[..encoded.len()].copy_from_slice(&encoded); } fn unpack(src: &[u8]) -> Result<Self, ProgramError> { Self::try_from_slice(src).map_err(|_| ProgramError::InvalidAccountData) } } #[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)] pub struct Message { pub txt: String } impl Message { pub fn new(txt: String ) -> Message { Message { txt } } } impl Serdes for Message {} pub struct Processor; impl Processor { pub fn process( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> ProgramResult { let accounts_iter = &mut accounts.iter(); let state_account = next_account_info(accounts_iter)?; let payer_account = next_account_info(accounts_iter)?; // make sure the user has control of the private key used to authorize changes if !payer_account.is_signer { msg!("Record authority signature missing"); return Err(ProgramError::MissingRequiredSignature); } // Authorize State Account changes: check that seed + payer derives to state_account // since you can only pay if you have the private keys, // that means the payer has the private keys // PAYER + SEED + thisProgramID = STATE_ACCOUNT // seed can be public/same since payer private key is secret, and only one secret is needed // need the same derivation code in JS and Rust to generate (in client code) and check (here) // let _state_data = Message::try_from_slice(*state_account.data.borrow())?; let mut msg = Message::new("new".to_string() // , "seed".to_string() ); let base = payer_account.key; let seed = "same seed in rust & javascript"; let owner = program_id; let maybe_state_account = Pubkey::create_with_seed(base, seed, owner)?; if maybe_state_account != *state_account.key // throw error, not authorized { msg!("Payer account is not the generator for this state account"); return Err(ProgramError::InvalidAccountData); } let mut data = state_account.try_borrow_mut_data()?; let memo = String::from_utf8(instruction_data.to_vec()).map_err(|_| { msg!("Invalid UTF-8, from byte {}"); ProgramError::InvalidInstructionData })?; let iter = memo.chars(); let slice = iter.as_str(); let mut txt_final = String::from(slice); txt_final.truncate(76); msg.txt = txt_final; msg.pack(&mut data); Ok(()) } }
use crate::config::QTableProps; use crate::data::DataTable; use crate::data::DataTableExt; use crate::group::Groups; use crate::limits::LimitsTableExt; use crate::limits::{Limits, LimitsExt, LimitsTable, YieldOk}; use crate::numbers::{F64Ext, Numbers}; use crate::pdf::{tint, Pdf, Pos, Tint}; use crate::table::{CellContent, Table}; use crate::{limits, numbers}; use enumflags2::BitFlags; use printpdf::{Color, Rgb}; pub struct QTable<'a> { pub table: Table<'a>, pub qtableprops: &'a QTableProps, pub groups: &'a Groups, } impl QTable<'_> { /// Adds a Qtable(aka quality table) /// /// # Arguments /// /// * `datpath` - path to .csv data file. /// * `limpath` - path to .csv limits file. /// * `mar` - top margin in mm. /// * `fnt` - font size in points. /// * `hea` - column headers as `&mut Vec<String>`. /// * `col` - column widths in mm as `&Vec<f64>`. /// * `col` - column widths in mm as `&Vec<f64>`. /// /// # Remarks /// /// This function adds a statistical table to the PDF file`. /// /// *Note*: the path to the .csv limits file is optional. /// If missing, only simple stats are inserted into the table. pub fn new<'a>( pdf: &mut Pdf, datpath: &String, limpath: &String, columns_in: &'a Vec<Column>, qtableprops: &QTableProps, ) -> Result<(), String> { if columns_in.len() < 1 { return Err(format!("no columns defined for Qtable::new(...).")); } let mut columns = vec![ Column::Number("num".to_string(), 5.), Column::Parameter("parameter".to_string(), 10.), ]; for c in columns_in { match c { Column::Number(_, _) => columns[0] = c.clone(), Column::Parameter(_, _) => columns[1] = c.clone(), _ => { if !columns.contains(c) { columns.push(c.clone()) } } } } let column_headers: Vec<String> = columns .iter() .map(|x| x.column_name().to_string()) .collect(); let column_widths = columns.iter().map(|x| *(x.column_width())).collect(); let limitstable = &mut LimitsTable::new(); limitstable.read_limits(&limpath)?; let mut datatable = DataTable::new(); datatable.add_data(&datpath, &limitstable, &qtableprops.filter)?; pdf.pos.y += qtableprops.margin; let groups = Groups::new(&datatable, &qtableprops)?; let mut qcaption = qtableprops.caption.clone(); for (i, g) in groups.groups.iter().enumerate() { if i == 0 { qcaption = format!["{}: {} {} |", qcaption, g.name, g.group]; } else { qcaption = format!["{} {} {} |", qcaption, g.name, g.group]; } } let mut qtable = QTable { table: Table::new( pdf, qtableprops.fontsize, &column_widths, &column_headers, qcaption.as_ref(), ), qtableprops: qtableprops, groups: &groups, }; let mut badspec: Vec<Par> = vec![]; let mut badctrl: Vec<Par> = vec![]; let mut badcpk: Vec<Par> = vec![]; let mut good: Vec<Par> = vec![]; let mut nolimits: Vec<Par> = vec![]; let numwidth = (datatable.len() as f64).log10().abs() as usize + 1; for (k, v) in datatable.iter() { let numbers = numbers::Numbers::new(&v.vals, qtableprops.float_limit, &v.filt); let (limok, limits) = limitstable.check_limits( &v.name, &numbers, qtable.qtableprops.spec_yield_limit, qtable.qtableprops.ctrl_yield_limit, qtable.qtableprops.cpk_limit, qtable.qtableprops.mark, ); let par = Par { number: *k, group: "".to_string(), name: v.name.clone(), limitsok: limok, numbers, limits, }; if qtableprops.order == Order::ByBadGood && limitstable.len() > 0 && limok != YieldOk::Yes { match limok { YieldOk::SpecYieldNot => badspec.push(par), YieldOk::CtrlYieldNot => badctrl.push(par), YieldOk::CpkNot => badcpk.push(par), _ => nolimits.push(par), } } else { good.push(par); } } //badspec for par in &badspec { qtable.group_ruler(&groups); let (mut line, rowcolor) = qtable.qtable_line(par, &columns, numwidth); qtable .table .row(&mut line, &rowcolor, false, qtableprops.captioneverypage); qtable.group_lines(par, &datatable, &groups, &limitstable, &columns); } //badctrl for par in &badctrl { qtable.group_ruler(&groups); let (mut line, rowcolor) = qtable.qtable_line(par, &columns, numwidth); qtable .table .row(&mut line, &rowcolor, false, qtableprops.captioneverypage); qtable.group_lines(par, &datatable, &groups, &limitstable, &columns); } //badcpk for par in &badcpk { qtable.group_ruler(&groups); let (mut line, rowcolor) = qtable.qtable_line(par, &columns, numwidth); qtable .table .row(&mut line, &rowcolor, false, qtableprops.captioneverypage); qtable.group_lines(par, &datatable, &groups, &limitstable, &columns); } //good for par in &good { qtable.group_ruler(&groups); let (mut line, rowcolor) = qtable.qtable_line(par, &columns, numwidth); qtable .table .row(&mut line, &rowcolor, false, qtableprops.captioneverypage); qtable.group_lines(par, &datatable, &groups, &limitstable, &columns); } //nolimits for par in &nolimits { qtable.group_ruler(&groups); let (mut line, rowcolor) = qtable.qtable_line(par, &columns, numwidth); qtable .table .row(&mut line, &rowcolor, false, qtableprops.captioneverypage); qtable.group_lines(par, &datatable, &groups, &limitstable, &columns); } //last line of table qtable.table.table_full_line(); Ok(()) } pub fn group_ruler(&self, groups: &Groups) { if groups.groups.len() > 0 { self.table.pdf.lay.set_outline_color(tint(&Tint::Blue)); self.table.table_full_line(); } } pub fn group_lines<'a>( &mut self, par: &Par, datatable: &DataTable, by_groups: &Groups, limitstable: &LimitsTable, columns: &'a Vec<Column>, ) { if par.numbers.cnt() == 0.0 { return; } if by_groups.groups.len() == 0 { return; } let mut numwid = 0.0; let mut parwid = 0.0; let mut nummax = 0; if by_groups.groups.len() > 1 && self.qtableprops.longgroupnames && columns.len() > 1 { numwid = self.table.wid[0]; parwid = self.table.wid[1]; nummax = self.table.max[0]; let parmax = self.table.max[1]; self.table.wid[0] = numwid + parwid; self.table.max[0] = nummax + parmax; self.table.wid[1] = 0.0; } let data = &datatable.get(&par.number).unwrap().vals; let filt = &datatable.get(&par.number).unwrap().filt; for g in by_groups.groups.iter() { let gvals = g .indices .iter() .map(|i| data[*i].clone()) .collect::<Vec<_>>(); let numbers = numbers::Numbers::new(&gvals, self.qtableprops.float_limit, &filt); let (limitsok, limits) = limitstable.check_limits( &par.name, &numbers, self.qtableprops.spec_yield_limit, self.qtableprops.ctrl_yield_limit, self.qtableprops.cpk_limit, self.qtableprops.mark, ); let groupname = match self.qtableprops.longgroupnames { true => format!("{} {}", g.name, g.group), false => format!("{}", g.name), }; let par = Par { number: par.number.clone(), group: groupname, name: par.name.clone(), limitsok, numbers, limits, }; let (mut line, rowcolor) = self.qtable_line(&par, columns, 0); let groupcolor = self.dimm_color(&rowcolor); self.table.row( &mut line, &groupcolor, true, self.qtableprops.captioneverypage, ); } if by_groups.groups.len() > 1 && self.qtableprops.longgroupnames && columns.len() > 1 { self.table.wid[0] = numwid; self.table.max[0] = nummax; self.table.wid[1] = parwid; } } pub fn dimm_color(&self, color: &Color) -> Color { let mut color_vec = color.clone().into_vec(); if color_vec[0] == 1.0 { color_vec[0] -= 0.1; } else { color_vec[0] += 0.5; } if color_vec[1] == 1.0 { color_vec[1] -= 0.1; } else { color_vec[1] += 0.5; } if color_vec[2] == 1.0 { color_vec[2] -= 0.1; } else { color_vec[2] += 0.5; } Color::Rgb(Rgb::new(color_vec[0], color_vec[1], color_vec[2], None)) } pub fn qtable_line<'a>( &mut self, par: &'a Par, columns: &'a Vec<Column>, numwidth: usize, ) -> (Vec<CellContent<'a>>, Color) { let k = par.number; let name = &par.name; let group = &par.group; let limok = par.limitsok; let param = name.clone(); let numbers = &par.numbers; let limits = &par.limits; let mut rowcolor = self.color_by_limits(&limok); if numbers.data.len() < 1 { rowcolor = tint(&Tint::White); } let line: Vec<CellContent> = columns .iter() .map(|x| { x.column_value( &k, &group, &param, &numbers, &limits, &self.qtableprops, numwidth, ) }) .collect(); (line, rowcolor) } pub fn color_by_limits(&mut self, limok: &YieldOk) -> Color { match limok { YieldOk::Yes => tint(&Tint::Green), YieldOk::SpecYieldNot => tint(&Tint::Red), YieldOk::CtrlYieldNot => tint(&Tint::YellowOrange), YieldOk::CpkNot => tint(&Tint::Fuchsia), YieldOk::NoLimits => tint(&Tint::White), } } } #[derive(Debug, Clone, PartialEq)] pub struct Par { number: usize, group: String, name: std::string::String, limitsok: limits::YieldOk, numbers: numbers::Numbers, limits: std::collections::BTreeMap<std::string::String, f64>, } #[derive(Debug, Clone, PartialEq)] pub enum Order { ByNumber, ByBadGood, } #[derive(Debug, Clone, PartialEq)] pub enum Filter { None, IQR(f64), ZScore(f64), Lower(f64), Upper(f64), Between(f64, f64), } #[derive(Debug, Clone, PartialEq)] pub enum Align { SpecLimits, ControlLimits, Targets, FitValues, } #[derive(BitFlags, Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum Show { SpecLimits = 0b0001, ControlLimits = 0b0010, Targets = 0b0100, } #[derive(BitFlags, Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum Mark { SpecYield = 0b0001, ControlYield = 0b0010, Cpk = 0b0100, } #[derive(Debug, Clone, PartialEq)] pub enum Column { Number(String, f64), Parameter(String, f64), Count(String, f64), Mean(String, f64), Median(String, f64), Variance(String, f64), Sdev(String, f64), Min(String, f64), Max(String, f64), Range(String, f64), SpecYield(String, f64), CtrlYield(String, f64), K(String, f64), Cpk(String, f64), Cp(String, f64), Percentile(String, f64, f64), P25(String, f64), P75(String, f64), LSL(String, f64), TGT(String, f64), USL(String, f64), LCL(String, f64), UCL(String, f64), Boxplot(String, f64), Histogram(String, f64), Cpkplot(String, f64), } pub trait ColumnsExt<T> { fn delete(&mut self, elem: usize) -> Result<(), String>; fn replace(&mut self, elem: usize, column: Column) -> Result<(), String>; } impl ColumnsExt<Vec<Column>> for Vec<Column> { fn delete(&mut self, elem: usize) -> Result<(), String> { match elem > self.len() - 1 { true => Err(format!( "canot delete column '{}', because it is > {}.", elem, self.len() - 1 )), false => { self.remove(elem); Ok(()) } } } fn replace(&mut self, elem: usize, column: Column) -> Result<(), String> { match elem > self.len() - 1 { true => Err(format!( "canot replace column '{}', because it is > {}.", elem, self.len() - 1 )), false => { self[elem] = column; Ok(()) } } } } pub fn default_columns() -> Vec<Column> { vec![ Column::Number("num".to_string(), 4.), Column::Parameter("parameter".to_string(), 10.), Column::LSL("lsl".to_string(), 6.), Column::TGT("tgt".to_string(), 6.), Column::USL("usl".to_string(), 6.), Column::LCL("lcl".to_string(), 6.), Column::UCL("ucl".to_string(), 6.), Column::Count("cnt".to_string(), 3.), Column::Min("min".to_string(), 6.), Column::Mean("mea".to_string(), 6.), Column::Max("max".to_string(), 6.), Column::CtrlYield("ctrl yld".to_string(), 3.), Column::SpecYield("spec yld".to_string(), 3.), Column::Cpk("cpk".to_string(), 3.), Column::Histogram("histogram".to_string(), 10.), Column::Boxplot("boxplot".to_string(), 10.), Column::Cpkplot("cpkchart".to_string(), 6.), ] } impl Column { pub fn column_name_width(&self) -> (&str, &f64) { match &self { Column::Number(name, width) => (name, width), Column::Parameter(name, width) => (name, width), Column::Count(name, width) => (name, width), Column::Mean(name, width) => (name, width), Column::Median(name, width) => (name, width), Column::Variance(name, width) => (name, width), Column::Sdev(name, width) => (name, width), Column::Min(name, width) => (name, width), Column::Max(name, width) => (name, width), Column::Range(name, width) => (name, width), Column::SpecYield(name, width) => (name, width), Column::CtrlYield(name, width) => (name, width), Column::K(name, width) => (name, width), Column::Cpk(name, width) => (name, width), Column::Cp(name, width) => (name, width), Column::LSL(name, width) => (name, width), Column::TGT(name, width) => (name, width), Column::USL(name, width) => (name, width), Column::LCL(name, width) => (name, width), Column::UCL(name, width) => (name, width), Column::Percentile(name, width, _) => (name, width), Column::P25(name, width) => (name, width), Column::P75(name, width) => (name, width), Column::Boxplot(name, width) => (name, width), Column::Histogram(name, width) => (name, width), Column::Cpkplot(name, width) => (name, width), } } pub fn column_name(&self) -> &str { self.column_name_width().0 } pub fn column_width(&self) -> &f64 { self.column_name_width().1 } pub fn column_value<'a>( &self, num: &usize, group: &String, par: &String, numbers: &'a Numbers, limits: &'a Limits, qtableprops: &QTableProps, numwidth: usize, ) -> CellContent<'a> { match &self { Column::Number(_, _) => match *group != "".to_string() { false => CellContent::String(format!("{:0width$}", num + 1, width = numwidth)), true => CellContent::String(format!("{:}", group)), }, Column::Parameter(_, _) => CellContent::String(format!("{:}", par)), Column::Count(_, _) => { CellContent::String(numbers.cnt().frmtint(&qtableprops.nanstring)) } Column::Mean(_, _) => CellContent::String( numbers .mea() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Median(_, _) => CellContent::String( numbers .med() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Variance(_, _) => CellContent::String( numbers .var() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Sdev(_, _) => CellContent::String( numbers .std() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Min(_, _) => CellContent::String( numbers .min() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Max(_, _) => CellContent::String( numbers .max() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::Range(_, _) => { let min = numbers .min() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring); let max = numbers .max() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring); CellContent::String(format!("{}...{}", min, max)) } Column::SpecYield(_, _) => { let lsl = limits.getnum("lsl"); let usl = limits.getnum("usl"); CellContent::String( numbers .yld(&lsl, &usl) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ) } Column::CtrlYield(_, _) => { let lcl = limits.getnum("lcl"); let ucl = limits.getnum("ucl"); CellContent::String( numbers .yld(&lcl, &ucl) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ) } Column::K(_, _) => { let lsl = limits.getnum("lsl"); let tgt = limits.getnum("tgt"); let usl = limits.getnum("usl"); CellContent::String( numbers .k(&lsl, &tgt, &usl) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ) } Column::Cpk(_, _) => { let lsl = limits.getnum("lsl"); let usl = limits.getnum("usl"); CellContent::String( numbers .cpk(&lsl, &usl) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ) } Column::Cp(_, _) => { let lsl = limits.getnum("lsl"); let usl = limits.getnum("usl"); CellContent::String( numbers .cp(&lsl, &usl) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ) } Column::Percentile(_, _, perc) => CellContent::String( numbers .prc(*perc) .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::P25(_, _) => CellContent::String( numbers .p25() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::P75(_, _) => CellContent::String( numbers .p75() .frmtf64(qtableprops.sig_digits, &qtableprops.nanstring), ), Column::LSL(_, _) => CellContent::String(limits.getstr( "lsl", qtableprops.sig_digits, &qtableprops.nanstring, )), Column::TGT(_, _) => CellContent::String(limits.getstr( "tgt", qtableprops.sig_digits, &qtableprops.nanstring, )), Column::USL(_, _) => CellContent::String(limits.getstr( "usl", qtableprops.sig_digits, &qtableprops.nanstring, )), Column::LCL(_, _) => CellContent::String(limits.getstr( "lcl", qtableprops.sig_digits, &qtableprops.nanstring, )), Column::UCL(_, _) => CellContent::String(limits.getstr( "ucl", qtableprops.sig_digits, &qtableprops.nanstring, )), Column::Boxplot(_, _) => { CellContent::Chart(boxplot, numbers, limits, qtableprops.clone()) } Column::Histogram(_, _) => { CellContent::Chart(histogram, numbers, limits, qtableprops.clone()) } Column::Cpkplot(_, _) => { CellContent::Chart(cpkplot, numbers, limits, qtableprops.clone()) } } } } pub fn reset_color_and_thickness(table: &Table) { table.pdf.lay.set_outline_thickness(table.pdf.thk); table .pdf .lay .set_outline_color(tint(&table.col.outline_color)); table.pdf.lay.set_fill_color(tint(&table.col.fill_color)); } pub fn add_limits<F>( table: &Table, numbers: &Numbers, limits: &Limits, qtableprops: &QTableProps, x: F, pos: &Pos, wid: f64, ) where F: Fn(f64) -> f64, { if numbers.data.len() < 1 { return; } let lsl = limits.getnum("lsl"); let tgt = limits.getnum("tgt"); let usl = limits.getnum("usl"); let lcl = limits.getnum("lcl"); let ucl = limits.getnum("ucl"); table.pdf.lay.set_outline_thickness(2.0); // ctrl_limits if qtableprops.show.contains(Show::ControlLimits) { if !lcl.is_nan() { if numbers.min() >= lcl { table.pdf.lay.set_outline_color(tint(&Tint::LightBlue)); } else { table.pdf.lay.set_outline_color(tint(&Tint::YellowOrange)); } let xlcl = x(lcl); if xlcl > pos.x && xlcl < pos.x + wid { table.pdf.line( Pos { x: xlcl + 0.5, y: pos.y + 0.4 * table.hei, }, Pos { x: xlcl + 0.5, y: pos.y + 0.6 * table.hei, }, ); table.pdf.line( Pos { x: xlcl, y: pos.y }, Pos { x: xlcl, y: pos.y + table.hei, }, ); } } if !ucl.is_nan() { if numbers.max() <= ucl { table.pdf.lay.set_outline_color(tint(&Tint::LightBlue)); } else { table.pdf.lay.set_outline_color(tint(&Tint::YellowOrange)); } let xucl = x(ucl); if xucl > pos.x && xucl < pos.x + wid { table.pdf.line( Pos { x: xucl - 0.5, y: pos.y + 0.4 * table.hei, }, Pos { x: xucl - 0.5, y: pos.y + 0.6 * table.hei, }, ); table.pdf.line( Pos { x: xucl, y: pos.y }, Pos { x: xucl, y: pos.y + table.hei, }, ); } } } //spec_limits if qtableprops.show.contains(Show::SpecLimits) { if !lsl.is_nan() { if numbers.min() >= lsl { table.pdf.lay.set_outline_color(tint(&Tint::Blue)); } else { table.pdf.lay.set_outline_color(tint(&Tint::Red)); } let xlsl = x(lsl); if xlsl > pos.x && xlsl < pos.x + wid { table.pdf.line( Pos { x: xlsl + 0.5, y: pos.y + 0.4 * table.hei, }, Pos { x: xlsl + 0.5, y: pos.y + 0.6 * table.hei, }, ); table.pdf.line( Pos { x: xlsl, y: pos.y }, Pos { x: xlsl, y: pos.y + table.hei, }, ); } } if !usl.is_nan() { if numbers.max() <= usl { table.pdf.lay.set_outline_color(tint(&Tint::Blue)); } else { table.pdf.lay.set_outline_color(tint(&Tint::Red)); } let xusl = x(usl); if xusl > pos.x && xusl < pos.x + wid { table.pdf.line( Pos { x: xusl - 0.5, y: pos.y + 0.4 * table.hei, }, Pos { x: xusl - 0.5, y: pos.y + 0.6 * table.hei, }, ); table.pdf.line( Pos { x: xusl, y: pos.y }, Pos { x: xusl, y: pos.y + table.hei, }, ); } } } // targets if qtableprops.show.contains(Show::Targets) { let xtgt = x(tgt); if xtgt > pos.x && xtgt < pos.x + wid { if !tgt.is_nan() { table.pdf.lay.set_outline_color(tint(&Tint::Green)); table.pdf.line( Pos { x: xtgt, y: pos.y }, Pos { x: xtgt, y: pos.y + table.hei, }, ); } } } reset_color_and_thickness(table); } pub fn compute_lef_rig_x( numbers: &Numbers, limits: &Limits, qtableprops: &QTableProps, posx: f64, wid: f64, ) -> (f64, f64, Box<dyn Fn(f64) -> f64>) { let min = numbers.min(); let max = numbers.max(); let lsl = limits.getnum("lsl"); let tgt = limits.getnum("tgt"); let usl = limits.getnum("usl"); let lcl = limits.getnum("lcl"); let ucl = limits.getnum("ucl"); let mut lef = min; let mut rig = max; match qtableprops.align { Align::SpecLimits => { if !lsl.is_nan() { lef = lsl; } if !usl.is_nan() { rig = usl; } } Align::ControlLimits => { if !lcl.is_nan() { lef = lcl; } if !ucl.is_nan() { rig = ucl; } } Align::FitValues | Align::Targets => { let mut v = vec![min, max]; if qtableprops.show.contains(Show::SpecLimits) { v.push(lsl); v.push(usl); } if qtableprops.show.contains(Show::ControlLimits) { v.push(lcl); v.push(ucl); } if qtableprops.show.contains(Show::Targets) { v.push(tgt); } // n contains data plus limits, target let n = Numbers::from_f64(v); lef = n.min(); rig = n.max(); if qtableprops.align == Align::Targets && !tgt.is_nan() && !lef.is_nan() && !rig.is_nan() { let dlef = tgt - lef; let drig = rig - tgt; let d = vec![dlef, drig]; let dmax = Numbers::from_f64(d).max(); lef = tgt - dmax; rig = tgt + dmax; } } } let x = move |mut x: f64| -> f64 { x = posx + 0.05 * wid + 0.9 * wid * (x - lef) / (rig - lef); if x < posx { x = posx; } if x > posx + wid { x = posx + wid; } x }; (lef, rig, Box::new(x)) } pub fn plot_borders_and_check_empty( table: &Table, numbers: &Numbers, pos: &Pos, wid: f64, nls: f64, ) -> bool { // cell borders left, right table.pdf.lay.set_outline_color(tint(&Tint::Black)); table.pdf.line( Pos { x: pos.x, y: pos.y }, Pos { x: pos.x, y: pos.y + nls * table.hei, }, ); table.pdf.line( Pos { x: pos.x + wid, y: pos.y, }, Pos { x: pos.x + wid, y: pos.y + nls * table.hei, }, ); // cell is empty if numbers.data.iter().any(|x| x.is_nan()) { return true; } false } pub fn boxplot( table: &Table, numbers: &Numbers, limits: &Limits, qtableprops: &QTableProps, pos: &Pos, wid: f64, nls: f64, ) -> () { if plot_borders_and_check_empty(table, numbers, pos, wid, nls) { return; } let min = numbers.min(); let p25 = numbers.p25(); let med = numbers.med(); let mea = numbers.mea(); let p75 = numbers.p75(); let max = numbers.max(); // x -> compute x-position inside cell let (lef, rig, x) = compute_lef_rig_x(numbers, limits, qtableprops, pos.x, wid); table.pdf.lay.set_fill_color(tint(&Tint::Grey)); let boxy = pos.y + table.hei * 0.2; let boxh = table.hei * 0.6; let mima = wid; let boxw = mima * (p75 - p25) / (rig - lef); if boxw.is_nan() { return; } // whiskers table.pdf.lay.set_outline_thickness(0.6); let minx = x(min); let maxx = x(max); table.pdf.line( Pos { x: minx, y: boxy }, Pos { x: minx, y: boxy + boxh, }, ); table.pdf.line( Pos { x: minx, y: boxy + boxh / 2.0, }, Pos { x: maxx, y: boxy + boxh / 2.0, }, ); table.pdf.line( Pos { x: maxx, y: boxy }, Pos { x: maxx, y: boxy + boxh, }, ); let p25x = x(p25); let p75x = x(p75); table.pdf.rect( true, Pos { x: p25x, y: boxy }, Pos { x: p75x, y: boxy }, Pos { x: p75x, y: boxy + boxh, }, Pos { x: p25x, y: boxy + boxh, }, ); let medx = x(med); let meax = x(mea); table.pdf.lay.set_outline_thickness(2.0); table.pdf.lay.set_outline_color(tint(&Tint::Black)); table.pdf.line( Pos { x: medx, y: boxy }, Pos { x: medx, y: boxy + boxh, }, ); table.pdf.lay.set_outline_thickness(0.6); table.pdf.lay.set_fill_color(tint(&Tint::White)); table.pdf.lay.set_outline_color(tint(&Tint::Black)); table.pdf.rect( true, Pos { x: meax - 0.2 * boxh, y: boxy + 0.3 * boxh, }, Pos { x: meax + 0.2 * boxh, y: boxy + 0.3 * boxh, }, Pos { x: meax + 0.2 * boxh, y: boxy + 0.7 * boxh, }, Pos { x: meax - 0.2 * boxh, y: boxy + 0.7 * boxh, }, ); // limits add_limits(table, numbers, limits, qtableprops, x, pos, wid); reset_color_and_thickness(table); } pub fn histogram( table: &Table, numbers: &Numbers, limits: &Limits, qtableprops: &QTableProps, pos: &Pos, wid: f64, nls: f64, ) -> () { if plot_borders_and_check_empty(table, numbers, pos, wid, nls) { return; } let (bins, d) = numbers.bins_delta(qtableprops.histogram_bins); // x -> compute x-position inside cell let (_lef, _rig, x) = compute_lef_rig_x(numbers, limits, qtableprops, pos.x, wid); table.pdf.lay.set_fill_color(tint(&Tint::Grey)); let vbins = Numbers::from_f64(bins.iter().map(|x| *x as f64).collect()); let min = numbers.min(); for (i, v) in bins.iter().enumerate() { let boxy = pos.y; let boxh = table.hei; let j = i as f64; let xl = x(min + j * d); let xr = x(min + (j + 1.0) * d); let ytop = boxh - ((*v as f64) / vbins.max()) * boxh; table.pdf.lay.set_outline_thickness(0.6); table.pdf.rect( true, Pos { x: xl, y: boxy + ytop, }, Pos { x: xr, y: boxy + ytop, }, Pos { x: xr, y: boxy + boxh, }, Pos { x: xl, y: boxy + boxh, }, ); } // limits add_limits(table, numbers, limits, qtableprops, x, pos, wid); reset_color_and_thickness(table); } pub fn cpkplot( table: &Table, numbers: &Numbers, limits: &Limits, qtableprops: &QTableProps, pos: &Pos, wid: f64, nls: f64, ) -> () { if plot_borders_and_check_empty(table, numbers, pos, wid, nls) { return; } let lef = 0.0; let rig = 5.0; let posx = pos.x; let x = move |mut x: f64| -> f64 { x = posx + 0.05 * wid + 0.9 * wid * (x - lef) / (rig - lef); if x < posx { x = posx; } if x > posx + wid { x = posx + wid; } x }; let cpklim = x(qtableprops.cpk_limit); table.pdf.lay.set_outline_thickness(0.0); table.pdf.lay.set_fill_color(tint(&Tint::Plum)); table.pdf.lay.set_outline_color(tint(&Tint::Plum)); table.pdf.rect( true, Pos { x: pos.x, y: pos.y }, Pos { x: cpklim, y: pos.y, }, Pos { x: cpklim, y: pos.y + nls * table.hei, }, Pos { x: pos.x, y: pos.y + nls * table.hei, }, ); table.pdf.lay.set_fill_color(tint(&Tint::PaleGreen)); table.pdf.lay.set_outline_color(tint(&Tint::PaleGreen)); table.pdf.rect( true, Pos { x: cpklim, y: pos.y, }, Pos { x: posx + wid, y: pos.y, }, Pos { x: posx + wid, y: pos.y + nls * table.hei, }, Pos { x: cpklim, y: pos.y + nls * table.hei, }, ); table.pdf.lay.set_outline_thickness(2.0); table.pdf.lay.set_fill_color(tint(&Tint::Green)); table.pdf.line( Pos { x: cpklim, y: pos.y, }, Pos { x: cpklim, y: pos.y + nls * table.hei, }, ); let lsl = limits.getnum("lsl"); let usl = limits.getnum("usl"); let cpk = numbers.cpk(&lsl, &usl); if cpk < qtableprops.cpk_limit { table.pdf.lay.set_outline_color(tint(&Tint::Fuchsia)); } else { table.pdf.lay.set_outline_color(tint(&Tint::DarkGreen)); } let xcpk = x(cpk); if !cpk.is_nan() { table.pdf.line( Pos { x: xcpk, y: pos.y }, Pos { x: xcpk, y: pos.y + nls * table.hei, }, ); } reset_color_and_thickness(table); }
use std::env; use std::fs; fn main(){ let args : Vec<String> = env::args().collect(); if args.len() < 2 { return; } let input = fs::read_to_string(&args[1]).unwrap() .strip_suffix('\n').unwrap() .parse::<i32>().unwrap(); let mut elves = Vec::<i32>::new(); for i in 1..input+1 { elves.push(i); } while elves.len() > 1 { let mut newelves = Vec::new(); let mut i = 0; while i < elves.len() { newelves.push(elves[i]); i += 2; } if i == elves.len()+1 { newelves.remove(0); } elves = newelves; } println!("{}", elves[0]); }
#![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 EhNamespaceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EhNamespace>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EhNamespace { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<Identity>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<eh_namespace::Properties>, } pub mod eh_namespace { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, #[serde(rename = "serviceBusEndpoint", default, skip_serializing_if = "Option::is_none")] pub service_bus_endpoint: Option<String>, #[serde(rename = "clusterArmId", default, skip_serializing_if = "Option::is_none")] pub cluster_arm_id: Option<String>, #[serde(rename = "metricId", default, skip_serializing_if = "Option::is_none")] pub metric_id: Option<String>, #[serde(rename = "isAutoInflateEnabled", default, skip_serializing_if = "Option::is_none")] pub is_auto_inflate_enabled: Option<bool>, #[serde(rename = "maximumThroughputUnits", default, skip_serializing_if = "Option::is_none")] pub maximum_throughput_units: Option<i32>, #[serde(rename = "kafkaEnabled", default, skip_serializing_if = "Option::is_none")] pub kafka_enabled: Option<bool>, #[serde(rename = "zoneRedundant", default, skip_serializing_if = "Option::is_none")] pub zone_redundant: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encryption: Option<Encryption>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<PrivateEndpointConnection>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub name: sku::Name, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<sku::Tier>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i32>, } pub mod sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { Basic, Standard, Premium, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tier { Basic, Standard, Premium, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<identity::Type>, #[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identities: Option<serde_json::Value>, } pub mod identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, UserAssigned, #[serde(rename = "SystemAssigned, UserAssigned")] SystemAssignedUserAssigned, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Encryption { #[serde(rename = "keyVaultProperties", default, skip_serializing_if = "Vec::is_empty")] pub key_vault_properties: Vec<KeyVaultProperties>, #[serde(rename = "keySource", default, skip_serializing_if = "Option::is_none")] pub key_source: Option<encryption::KeySource>, #[serde(rename = "requireInfrastructureEncryption", default, skip_serializing_if = "Option::is_none")] pub require_infrastructure_encryption: Option<bool>, } pub mod encryption { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeySource { #[serde(rename = "Microsoft.KeyVault")] MicrosoftKeyVault, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyVaultProperties { #[serde(rename = "keyName", default, skip_serializing_if = "Option::is_none")] pub key_name: Option<String>, #[serde(rename = "keyVaultUri", default, skip_serializing_if = "Option::is_none")] pub key_vault_uri: Option<String>, #[serde(rename = "keyVersion", default, skip_serializing_if = "Option::is_none")] pub key_version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<UserAssignedIdentityProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnection { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateEndpointConnectionProperties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionProperties { #[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")] pub private_endpoint: Option<PrivateEndpoint>, #[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")] pub private_link_service_connection_state: Option<ConnectionState>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<private_endpoint_connection_properties::ProvisioningState>, } pub mod private_endpoint_connection_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Canceled, Failed, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpoint { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectionState { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<connection_state::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } pub mod connection_state { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Pending, Approved, Rejected, Disconnected, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateEndpointConnection>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateLinkResourceProperties>, #[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>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceProperties { #[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")] pub group_id: Option<String>, #[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")] pub required_members: Vec<String>, #[serde(rename = "requiredZoneNames", default, skip_serializing_if = "Vec::is_empty")] pub required_zone_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourcesListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateLinkResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserAssignedIdentityProperties { #[serde(rename = "userAssignedIdentity", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identity: 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 CaptureDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encoding: Option<capture_description::Encoding>, #[serde(rename = "intervalInSeconds", default, skip_serializing_if = "Option::is_none")] pub interval_in_seconds: Option<i32>, #[serde(rename = "sizeLimitInBytes", default, skip_serializing_if = "Option::is_none")] pub size_limit_in_bytes: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub destination: Option<Destination>, #[serde(rename = "skipEmptyArchives", default, skip_serializing_if = "Option::is_none")] pub skip_empty_archives: Option<bool>, } pub mod capture_description { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Encoding { Avro, AvroDeflate, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Eventhub { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<eventhub::Properties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } pub mod eventhub { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "partitionIds", default, skip_serializing_if = "Vec::is_empty")] pub partition_ids: Vec<String>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, #[serde(rename = "messageRetentionInDays", default, skip_serializing_if = "Option::is_none")] pub message_retention_in_days: Option<i64>, #[serde(rename = "partitionCount", default, skip_serializing_if = "Option::is_none")] pub partition_count: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "captureDescription", default, skip_serializing_if = "Option::is_none")] pub capture_description: Option<CaptureDescription>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Active, Disabled, Restoring, SendDisabled, ReceiveDisabled, Creating, Deleting, Renaming, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Eventhub>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Destination { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<destination::Properties>, } pub mod destination { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "storageAccountResourceId", default, skip_serializing_if = "Option::is_none")] pub storage_account_resource_id: Option<String>, #[serde(rename = "blobContainer", default, skip_serializing_if = "Option::is_none")] pub blob_container: Option<String>, #[serde(rename = "archiveNameFormat", default, skip_serializing_if = "Option::is_none")] pub archive_name_format: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UnavailableReason { None, InvalidName, SubscriptionIsDisabled, NameInUse, NameInLockdown, TooManyNamespaceInCurrentSubscription, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckNameAvailabilityParameter { pub name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckNameAvailabilityResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<UnavailableReason>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ArmDisasterRecovery { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<arm_disaster_recovery::Properties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } pub mod arm_disaster_recovery { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "partnerNamespace", default, skip_serializing_if = "Option::is_none")] pub partner_namespace: Option<String>, #[serde(rename = "alternateName", default, skip_serializing_if = "Option::is_none")] pub alternate_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub role: Option<properties::Role>, #[serde(rename = "pendingReplicationOperationsCount", default, skip_serializing_if = "Option::is_none")] pub pending_replication_operations_count: Option<i64>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Accepted, Succeeded, Failed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Role { Primary, PrimaryNotReplicating, Secondary, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ArmDisasterRecoveryListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ArmDisasterRecovery>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Subnet { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NwRuleSetIpRules { #[serde(rename = "ipMask", default, skip_serializing_if = "Option::is_none")] pub ip_mask: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<nw_rule_set_ip_rules::Action>, } pub mod nw_rule_set_ip_rules { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NwRuleSetVirtualNetworkRules { #[serde(default, skip_serializing_if = "Option::is_none")] pub subnet: Option<Subnet>, #[serde(rename = "ignoreMissingVnetServiceEndpoint", default, skip_serializing_if = "Option::is_none")] pub ignore_missing_vnet_service_endpoint: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkRuleSet { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<network_rule_set::Properties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } pub mod network_rule_set { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "trustedServiceAccessEnabled", default, skip_serializing_if = "Option::is_none")] pub trusted_service_access_enabled: Option<bool>, #[serde(rename = "defaultAction", default, skip_serializing_if = "Option::is_none")] pub default_action: Option<properties::DefaultAction>, #[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")] pub virtual_network_rules: Vec<NwRuleSetVirtualNetworkRules>, #[serde(rename = "ipRules", default, skip_serializing_if = "Vec::is_empty")] pub ip_rules: Vec<NwRuleSetIpRules>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DefaultAction { Allow, Deny, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthorizationRuleListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<AuthorizationRule>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthorizationRule { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<authorization_rule::Properties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } pub mod authorization_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { pub rights: Vec<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessKeys { #[serde(rename = "primaryConnectionString", default, skip_serializing_if = "Option::is_none")] pub primary_connection_string: Option<String>, #[serde(rename = "secondaryConnectionString", default, skip_serializing_if = "Option::is_none")] pub secondary_connection_string: Option<String>, #[serde(rename = "aliasPrimaryConnectionString", default, skip_serializing_if = "Option::is_none")] pub alias_primary_connection_string: Option<String>, #[serde(rename = "aliasSecondaryConnectionString", default, skip_serializing_if = "Option::is_none")] pub alias_secondary_connection_string: Option<String>, #[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")] pub primary_key: Option<String>, #[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")] pub secondary_key: Option<String>, #[serde(rename = "keyName", default, skip_serializing_if = "Option::is_none")] pub key_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegenerateAccessKeyParameters { #[serde(rename = "keyType")] pub key_type: regenerate_access_key_parameters::KeyType, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, } pub mod regenerate_access_key_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeyType { PrimaryKey, SecondaryKey, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConsumerGroup { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<consumer_group::Properties>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } pub mod consumer_group { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "updatedAt", default, skip_serializing_if = "Option::is_none")] pub updated_at: Option<String>, #[serde(rename = "userMetadata", default, skip_serializing_if = "Option::is_none")] pub user_metadata: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConsumerGroupListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ConsumerGroup>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[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 SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct 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>, }
extern crate sack; use sack::data_store::kv_store::{KVSack, WriteableKVSack}; fn main() { let mut s: KVSack<i32, i32> = KVSack::default(); let foo = s.insert(1, 2); println!("s: {:?}", foo); } // impl<C,D> SackBacker for BTreeMap<C,D>{} // #[derive(Clone,Ord,Eq,PartialOrd,PartialEq,Debug)] // pub struct BTreeBackedSack<C, D, T> { // t: T, // b: BTreeMap<C, D>, // } // // impl<C, D, T> SackBacker for BTreeBackedSack<C, D, T> // where C: Clone+Debug, // D: Clone+Debug, // T: Clone // { // } // impl<C, D, T> Default for BTreeBackedSack<C, D, T> // where C: Clone + Ord, // D: Clone, // T: Clone + Default // { // fn default() -> Self { // BTreeBackedSack { // t: T::default(), // b: BTreeMap::default(), // } // } // }
use diesel::ExpressionMethods; use diesel::pg::PgConnection; use diesel::query_builder::SqlQuery; use diesel::query_dsl::QueryDsl; use diesel::RunQueryDsl; use diesel::sql_query; use std::slice::SliceConcatExt; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; use epoch; use epoch::*; use models::*; //use super::schema::transactions; use super::schema::transactions::dsl::*; use serde_json; use r2d2::Pool; use r2d2_diesel::ConnectionManager; pub struct BlockLoader { epoch: Epoch, pub connection: Arc<Pool<ConnectionManager<PgConnection>>>, // DB connection rx: std::sync::mpsc::Receiver<i64>, pub tx: std::sync::mpsc::Sender<i64>, } impl BlockLoader { pub fn new( connection: Arc<Pool<ConnectionManager<PgConnection>>>, epoch_url: String, ) -> BlockLoader { let (_tx, rx): (Sender<i64>, Receiver<i64>) = mpsc::channel(); let epoch = Epoch::new(epoch_url.clone()); BlockLoader { epoch, connection, rx, tx: _tx, } } pub fn in_fork(height: i64) { let connection = epoch::establish_sql_connection(); connection.execute("DELETE FROM key_blocks where height >= $1", &[&height]); } pub fn load_mempool(&self, epoch: &Epoch) { let conn = epoch::establish_connection().get().unwrap(); let trans: JsonTransactionList = serde_json::from_value(self.epoch.get_pending_transaction_list().unwrap()).unwrap(); let mut hashes_in_mempool = vec!(); for i in 0..trans.transactions.len() { self.store_or_update_transaction(&conn, &trans.transactions[i], None); hashes_in_mempool.push(format!("'{}'", trans.transactions[i].hash)); } let sql = format!( "UPDATE transactions SET VALID=FALSE WHERE \ micro_block_id IS NULL AND \ hash NOT IN ({})", hashes_in_mempool.join(", ")); epoch::establish_sql_connection.execute(sql); } pub fn scan(epoch: &Epoch, _tx: &std::sync::mpsc::Sender<i64>) { let connection = epoch::establish_connection(); let top_block_chain = key_block_from_json(epoch.latest_key_block().unwrap()).unwrap(); let top_block_db = KeyBlock::top_height(&connection.get().unwrap()).unwrap(); if top_block_chain.height == top_block_db { println!("Up-to-date"); return; } if top_block_chain.height < top_block_db { println!("Fork detected"); //in_fork(); return; } println!( "Reading blocks {} to {}", top_block_db+1, top_block_chain.height ); let mut height = top_block_chain.height; loop { if height <= top_block_db { break; } if !KeyBlock::height_exists(&connection.get().unwrap(), height) { println!("Fetching block {}", height); match _tx.send(height) { Ok(x) => println!("Success: {:?}", x), Err(e) => println!("Error: {:?}", e), }; } else { println!("Block already in DB at height {}", height); } height -= 1; } } fn load_blocks(&self, height: i64) -> Result<String, Box<std::error::Error>> { let connection = self.connection.get()?; let mut kb = self.epoch.get_key_block_by_height(height)?; let newblock = key_block_from_json(kb)?; let ib: InsertableKeyBlock = InsertableKeyBlock::from_json_key_block(&newblock)?; let key_block_id = ib.save(&connection)? as i32; let mut prev = newblock.prev_hash; // we're currently (naively) getting transactions working back from the latest mined keyblock // so this is necessary in order to get the keyblock to which these microblocks relate let last_key_block = match KeyBlock::load_at_height(&connection, height-1) { Some(x) => x, None => { let err = format!("Didn't load key block at height {}", height-1); println!("{}", err); return Ok(err); }, }; while str::eq(&prev[0..1], "m") { // loop until we run out of microblocks let mut mb = micro_block_from_json(self.epoch.get_micro_block_by_hash(&prev)?)?; mb.key_block_id = last_key_block.id; println!("Inserting micro w. key_block_id={}", key_block_id); let _micro_block_id = mb.save(&connection).unwrap() as i32; let trans: JsonTransactionList = serde_json::from_value(self.epoch.get_transaction_list_by_micro_block(&prev)?)?; for i in 0..trans.transactions.len() { self.store_or_update_transaction(&connection, &trans.transactions[i], Some(_micro_block_id)).unwrap(); } prev = mb.prev_hash; } Ok(String::from("foo")) } pub fn store_or_update_transaction(&self, conn: &PgConnection, trans: &JsonTransaction, _micro_block_id: Option<i32> ) -> Result<i32, Box<std::error::Error>> { let mut results: Vec<Transaction> = sql_query( "select * from transactions where hash = '?' limit 1"). bind::<diesel::sql_types::Text, _>(trans.hash.clone()). get_results(conn)?; match results.pop() { Some(x) => { println!("Found {}", &trans.hash); diesel::update(&x).set(micro_block_id.eq(_micro_block_id)); Ok(x.id) }, None => { println!("Not found {}", &trans.hash); let _tx_type: String = from_json(&serde_json::to_string(&trans.tx["type"])?); let _tx: InsertableTransaction = InsertableTransaction::from_json_transaction(&trans, _tx_type, _micro_block_id)?; _tx.save(conn) }, } } pub fn start(&self) { for b in &self.rx { self.load_blocks(b); } } }
use connection::Connection; use key_exchange::{KexResult, KeyExchange}; use message::MessageType; use num_bigint::{BigInt, RandBigInt, ToBigInt}; use packet::{Packet, ReadPacketExt, WritePacketExt}; use rand; const DH_GEX_GROUP: u8 = 31; const DH_GEX_INIT: u8 = 32; const DH_GEX_REPLY: u8 = 33; const DH_GEX_REQUEST: u8 = 34; /// Second Oakley Group /// Source: https://tools.ietf.org/html/rfc2409#section-6.2 #[cfg_attr(rustfmt, rustfmt_skip)] static OAKLEY_GROUP_2: &[u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE65381, 0xFFFFFFFF, 0xFFFFFFFF ]; pub struct DhGroupSha1 { g: Option<BigInt>, p: Option<BigInt>, e: Option<BigInt>, } impl DhGroupSha1 { pub fn new() -> DhGroupSha1 { DhGroupSha1 { g: None, p: None, e: None, } } } impl KeyExchange for DhGroupSha1 { fn shared_secret<'a>(&'a self) -> Option<&'a [u8]> { Some(&[]) } fn exchange_hash<'a>(&'a self) -> Option<&'a [u8]> { Some(&[]) } fn hash(&self, data: &[&[u8]]) -> Vec<u8> { vec![] } fn process(&mut self, conn: &mut Connection, packet: Packet) -> KexResult { match packet.msg_type() { MessageType::KeyExchange(DH_GEX_REQUEST) => { let mut reader = packet.reader(); let min = reader.read_uint32().unwrap(); let opt = reader.read_uint32().unwrap(); let max = reader.read_uint32().unwrap(); println!("Key Sizes: Min {}, Opt {}, Max {}", min, opt, max); let mut rng = rand::thread_rng(); let g = rng.gen_biguint(opt as usize).to_bigint().unwrap(); let p = rng.gen_biguint(opt as usize).to_bigint().unwrap(); let mut packet = Packet::new(MessageType::KeyExchange(DH_GEX_GROUP)); packet.with_writer(&|w| { w.write_mpint(g.clone())?; w.write_mpint(p.clone())?; Ok(()) }); self.g = Some(g); self.p = Some(p); KexResult::Ok(packet) } MessageType::KeyExchange(DH_GEX_INIT) => { let mut reader = packet.reader(); let e = reader.read_mpint().unwrap(); println!("Received e: {:?}", e); let mut packet = Packet::new(MessageType::KeyExchange(DH_GEX_REPLY)); packet.with_writer(&|w| { w.write_string("HELLO WORLD")?; w.write_mpint(e.clone())?; w.write_string("HELLO WORLD")?; Ok(()) }); self.e = Some(e); KexResult::Done(packet) } _ => { debug!("Unhandled key exchange packet: {:?}", packet); KexResult::Error } } } }
use std::env; use std::fs::*; use clap::*; use serde::{Serialize, Deserialize}; use std::io::prelude::*; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ProgramArgs { pub input_file: String, pub output_file: String, pub pixel_size: u32, pub thread_count: u8, pub create_joined: bool, pub outline_quadrants: bool, pub render_all_points: bool } impl ProgramArgs { pub fn new() -> Option<Self> { if env::args().len() == 1 { let raw_config = read_to_string("config"); let config: ProgramArgs; match raw_config { Ok(val) => config = serde_json::from_str(&val).unwrap(), _ => return None } return Some(config); } else { let run_arguments = App::new("GCode Rendering") .version("0.1.0") .author("Austin Haskell") .about("Debugging tool to view what a given gcode snippet will look like") .arg(Arg::with_name("file") .short("f") .long("file") .takes_value(true) .required(true) .help("File to generate images from")) .arg(Arg::with_name("output") .short("o") .long("output") .takes_value(true) .required(true) .help("Base output filename, this filename will have the quadrant rendered appended")) .arg(Arg::with_name("pixels_per_mm") .short("p") .long("pixel") .takes_value(true) .required(true) .help("Number of pixels to use per mm, default is 1")) .arg(Arg::with_name("thread_count") .short("t") .long("threads") .takes_value(true) .required(true) .help("Number of threads to use to speed up rendering")) .arg(Arg::with_name("create_joined_image") .short("j") .long("joined") .takes_value(false) .help("Additionally create joined image that is combined result of all quadrant images")) .arg(Arg::with_name("outline_quadrants_in_master") .short("l") .long("outline") .takes_value(false) .help("Used in conjunction with the -j command, outlines each quadrant in red. Ignored if -j is not defined. ")) .arg(Arg::with_name("always_render_points") .short("r") .long("points") .takes_value(false) .help("If present, will render points that have no connections. ")) .get_matches(); let input_file: &str = run_arguments.value_of("file").unwrap_or("input.gcode"); let output_base: &str = run_arguments.value_of("output").unwrap_or("quadrant"); let pixel_scalar: u32 = run_arguments.value_of("pixels_per_mm").unwrap_or("1").parse().unwrap_or(1); let thread_count: u8 = run_arguments.value_of("thread_count").unwrap_or("4").parse().unwrap_or(4); let create_joined: bool = run_arguments.is_present("create_joined_image"); let outline_quadrants: bool = run_arguments.is_present("outline_quadrants_in_master"); let render_all_points: bool = run_arguments.is_present("always_render_points"); Some( ProgramArgs { input_file: String::from(input_file), output_file: String::from(output_base), pixel_size: pixel_scalar, thread_count: thread_count, create_joined: create_joined, outline_quadrants: outline_quadrants, render_all_points: render_all_points } ) } } pub fn dump(&self, path: &str) { let arg_dump = serde_json::to_string(&self); match arg_dump { Err(e) => { println!("Error: Failed to dump arguments to file. {:?}", e); return; }, _ => { } } let raw_arg_file = File::create(path); let mut arg_file; match raw_arg_file { Err(e) => { println!("Failed to create/open argument file: {:?}:{:?}", path, e); return; }, Ok(val) => arg_file = val } arg_file.write_all(arg_dump.unwrap().as_bytes()).unwrap(); } }
use crate::grandpa::GrandpaJustification; use crate::{Config, EncodedBlockHash, EncodedBlockNumber, Error}; use codec::Decode; use frame_support::Parameter; use num_traits::AsPrimitive; use sp_runtime::generic; use sp_runtime::traits::{ AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay, MaybeSerializeDeserialize, Member, Saturating, SimpleBitOps, }; use sp_std::hash::Hash; use sp_std::str::FromStr; use sp_std::vec::Vec; pub(crate) type OpaqueExtrinsic = Vec<u8>; pub type SignedBlock<Header> = generic::SignedBlock<generic::Block<Header, OpaqueExtrinsic>>; /// Minimal Substrate-based chain representation that may be used from no_std environment. pub trait Chain { /// A type that fulfills the abstract idea of what a Substrate block number is. // Constraints come from the associated Number type of `sp_runtime::traits::Header` // See here for more info: // https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Number // // Note that the `AsPrimitive<usize>` trait is required by the GRANDPA justification // verifier, and is not usually part of a Substrate Header's Number type. type BlockNumber: Parameter + Member + MaybeSerializeDeserialize + Hash + Copy + Default + MaybeDisplay + AtLeast32BitUnsigned + FromStr + AsPrimitive<usize> + Default + Saturating; /// A type that fulfills the abstract idea of what a Substrate hash is. // Constraints come from the associated Hash type of `sp_runtime::traits::Header` // See here for more info: // https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hash type Hash: Parameter + Member + MaybeSerializeDeserialize + Hash + Ord + Copy + MaybeDisplay + Default + SimpleBitOps + AsRef<[u8]> + AsMut<[u8]>; /// A type that fulfills the abstract idea of what a Substrate header is. // See here for more info: // https://crates.parity.io/sp_runtime/traits/trait.Header.html type Header: Parameter + HeaderT<Number = Self::BlockNumber, Hash = Self::Hash> + MaybeSerializeDeserialize; /// A type that fulfills the abstract idea of what a Substrate hasher (a type /// that produces hashes) is. // Constraints come from the associated Hashing type of `sp_runtime::traits::Header` // See here for more info: // https://crates.parity.io/sp_runtime/traits/trait.Header.html#associatedtype.Hashing type Hasher: HashT<Output = Self::Hash>; fn decode_block<T: Config>(block: &[u8]) -> Result<SignedBlock<Self::Header>, Error<T>> { SignedBlock::<Self::Header>::decode(&mut &*block).map_err(|error| { log::error!("Cannot decode block, error: {:?}", error); Error::<T>::FailedDecodingBlock }) } fn decode_header<T: Config>(header: &[u8]) -> Result<Self::Header, Error<T>> { Self::Header::decode(&mut &*header).map_err(|error| { log::error!("Cannot decode header, error: {:?}", error); Error::<T>::FailedDecodingHeader }) } fn decode_grandpa_justifications<T: Config>( justifications: &[u8], ) -> Result<GrandpaJustification<Self::Header>, Error<T>> { GrandpaJustification::<Self::Header>::decode(&mut &*justifications).map_err(|error| { log::error!("Cannot decode justifications, error: {:?}", error); Error::<T>::FailedDecodingJustifications }) } fn decode_block_number_and_hash<T: Config>( pair: (EncodedBlockNumber, EncodedBlockHash), ) -> Result<(Self::BlockNumber, Self::Hash), Error<T>> { let number = Self::decode_block_number::<T>(pair.0.as_slice())?; let hash = Self::decode_block_hash::<T>(pair.1.as_slice())?; Ok((number, hash)) } fn decode_block_number<T: Config>(number: &[u8]) -> Result<Self::BlockNumber, Error<T>> { Self::BlockNumber::decode(&mut &*number).map_err(|error| { log::error!("Cannot decode block number, error: {:?}", error); Error::<T>::FailedDecodingBlockNumber }) } fn decode_block_hash<T: Config>(hash: &[u8]) -> Result<Self::Hash, Error<T>> { Self::Hash::decode(&mut &*hash).map_err(|error| { log::error!("Cannot decode block hash, error: {:?}", error); Error::<T>::FailedDecodingBlockHash }) } }
#[derive(Debug, PartialEq)] pub struct Error<T> { msg: T, } // brute force fn __is_prime(n: i32) -> bool { if n < 2 { return false; } for y in (2..n).rev() { if n % y == 0 { return false; } } return true; } // AKS (?) fn is_prime(n: i32) -> bool { if n < 2 { return false; } if (n == 2) || (n == 3) { return true; } if (n % 2 == 0) || (n % 3 == 0) { return false; } let mut i = 5; let mut w = 2; while i < n { if n % i == 0 { return false; } i += w; w = 6 - w; // either 4 or 2 } return true; } pub fn nth(n: i32) -> Result<i32, Error<String>> { match n { 0 => Err(Error { msg: format!("zeroth prime") }), _ => { let mut count = 0; for x in 1.. { if is_prime(x) { count += 1; } if count == n { return Ok(x); } } Err(Error { msg: format!("did not find any prime for {}", n) }) } } }
pub use self::platform::*; #[cfg(target_os = "linux")] #[path = "linux/mod.rs"] mod platform; #[cfg(target_os = "windows")] #[path = "windows/mod.rs"] mod platform;
use super::{check_dtype, HasPandasColumn, PandasColumn, PandasColumnObject}; use crate::errors::ConnectorXPythonError; use anyhow::anyhow; use chrono::{DateTime, Utc}; use fehler::throws; use ndarray::{ArrayViewMut2, Axis, Ix2}; use numpy::PyArray; use pyo3::{FromPyObject, PyAny, PyResult}; use std::any::TypeId; // datetime64 is represented in int64 in numpy // https://github.com/numpy/numpy/blob/master/numpy/core/include/numpy/npy_common.h#L1104 pub struct DateTimeBlock<'a> { data: ArrayViewMut2<'a, i64>, } impl<'a> FromPyObject<'a> for DateTimeBlock<'a> { fn extract(ob: &'a PyAny) -> PyResult<Self> { check_dtype(ob, "int64")?; let array = ob.downcast::<PyArray<i64, Ix2>>()?; let data = unsafe { array.as_array_mut() }; Ok(DateTimeBlock { data }) } } impl<'a> DateTimeBlock<'a> { #[throws(ConnectorXPythonError)] pub fn split(self) -> Vec<DateTimeColumn> { let mut ret = vec![]; let mut view = self.data; let nrows = view.ncols(); while view.nrows() > 0 { let (col, rest) = view.split_at(Axis(0), 1); view = rest; ret.push(DateTimeColumn { data: col .into_shape(nrows)? .into_slice() .ok_or_else(|| anyhow!("get None for splitted DateTime data"))? .as_mut_ptr(), }) } ret } } pub struct DateTimeColumn { data: *mut i64, } unsafe impl Send for DateTimeColumn {} unsafe impl Sync for DateTimeColumn {} impl PandasColumnObject for DateTimeColumn { fn typecheck(&self, id: TypeId) -> bool { id == TypeId::of::<DateTime<Utc>>() || id == TypeId::of::<Option<DateTime<Utc>>>() } fn typename(&self) -> &'static str { std::any::type_name::<DateTime<Utc>>() } } impl PandasColumn<DateTime<Utc>> for DateTimeColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: DateTime<Utc>, row: usize) { unsafe { *self.data.add(row) = val.timestamp_nanos() }; } } impl PandasColumn<Option<DateTime<Utc>>> for DateTimeColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Option<DateTime<Utc>>, row: usize) { // numpy use i64::MIN as NaT unsafe { *self.data.add(row) = val.map(|t| t.timestamp_nanos()).unwrap_or(i64::MIN); }; } } impl HasPandasColumn for DateTime<Utc> { type PandasColumn<'a> = DateTimeColumn; } impl HasPandasColumn for Option<DateTime<Utc>> { type PandasColumn<'a> = DateTimeColumn; } impl DateTimeColumn { pub fn partition(self, counts: usize) -> Vec<DateTimeColumn> { let mut partitions = vec![]; for _ in 0..counts { partitions.push(DateTimeColumn { data: self.data }); } partitions } }
#[doc = "Register `FMC_PCR` reader"] pub type R = crate::R<FMC_PCR_SPEC>; #[doc = "Register `FMC_PCR` writer"] pub type W = crate::W<FMC_PCR_SPEC>; #[doc = "Field `PWAITEN` reader - PWAITEN"] pub type PWAITEN_R = crate::BitReader; #[doc = "Field `PWAITEN` writer - PWAITEN"] pub type PWAITEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PBKEN` reader - PBKEN"] pub type PBKEN_R = crate::BitReader; #[doc = "Field `PBKEN` writer - PBKEN"] pub type PBKEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PWID` reader - PWID"] pub type PWID_R = crate::FieldReader; #[doc = "Field `PWID` writer - PWID"] pub type PWID_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `ECCEN` reader - ECCEN"] pub type ECCEN_R = crate::BitReader; #[doc = "Field `ECCEN` writer - ECCEN"] pub type ECCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ECCALG` reader - ECCALG"] pub type ECCALG_R = crate::BitReader; #[doc = "Field `ECCALG` writer - ECCALG"] pub type ECCALG_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCLR` reader - TCLR"] pub type TCLR_R = crate::FieldReader; #[doc = "Field `TCLR` writer - TCLR"] pub type TCLR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TAR` reader - TAR"] pub type TAR_R = crate::FieldReader; #[doc = "Field `TAR` writer - TAR"] pub type TAR_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `ECCSS` reader - ECCSS"] pub type ECCSS_R = crate::FieldReader; #[doc = "Field `ECCSS` writer - ECCSS"] pub type ECCSS_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `TCEH` reader - TCEH"] pub type TCEH_R = crate::FieldReader; #[doc = "Field `TCEH` writer - TCEH"] pub type TCEH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `BCHECC` reader - BCHECC"] pub type BCHECC_R = crate::BitReader; #[doc = "Field `BCHECC` writer - BCHECC"] pub type BCHECC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WEN` reader - WEN"] pub type WEN_R = crate::BitReader; #[doc = "Field `WEN` writer - WEN"] pub type WEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 1 - PWAITEN"] #[inline(always)] pub fn pwaiten(&self) -> PWAITEN_R { PWAITEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - PBKEN"] #[inline(always)] pub fn pbken(&self) -> PBKEN_R { PBKEN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 4:5 - PWID"] #[inline(always)] pub fn pwid(&self) -> PWID_R { PWID_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bit 6 - ECCEN"] #[inline(always)] pub fn eccen(&self) -> ECCEN_R { ECCEN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 8 - ECCALG"] #[inline(always)] pub fn eccalg(&self) -> ECCALG_R { ECCALG_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bits 9:12 - TCLR"] #[inline(always)] pub fn tclr(&self) -> TCLR_R { TCLR_R::new(((self.bits >> 9) & 0x0f) as u8) } #[doc = "Bits 13:16 - TAR"] #[inline(always)] pub fn tar(&self) -> TAR_R { TAR_R::new(((self.bits >> 13) & 0x0f) as u8) } #[doc = "Bits 17:19 - ECCSS"] #[inline(always)] pub fn eccss(&self) -> ECCSS_R { ECCSS_R::new(((self.bits >> 17) & 7) as u8) } #[doc = "Bits 20:23 - TCEH"] #[inline(always)] pub fn tceh(&self) -> TCEH_R { TCEH_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bit 24 - BCHECC"] #[inline(always)] pub fn bchecc(&self) -> BCHECC_R { BCHECC_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - WEN"] #[inline(always)] pub fn wen(&self) -> WEN_R { WEN_R::new(((self.bits >> 25) & 1) != 0) } } impl W { #[doc = "Bit 1 - PWAITEN"] #[inline(always)] #[must_use] pub fn pwaiten(&mut self) -> PWAITEN_W<FMC_PCR_SPEC, 1> { PWAITEN_W::new(self) } #[doc = "Bit 2 - PBKEN"] #[inline(always)] #[must_use] pub fn pbken(&mut self) -> PBKEN_W<FMC_PCR_SPEC, 2> { PBKEN_W::new(self) } #[doc = "Bits 4:5 - PWID"] #[inline(always)] #[must_use] pub fn pwid(&mut self) -> PWID_W<FMC_PCR_SPEC, 4> { PWID_W::new(self) } #[doc = "Bit 6 - ECCEN"] #[inline(always)] #[must_use] pub fn eccen(&mut self) -> ECCEN_W<FMC_PCR_SPEC, 6> { ECCEN_W::new(self) } #[doc = "Bit 8 - ECCALG"] #[inline(always)] #[must_use] pub fn eccalg(&mut self) -> ECCALG_W<FMC_PCR_SPEC, 8> { ECCALG_W::new(self) } #[doc = "Bits 9:12 - TCLR"] #[inline(always)] #[must_use] pub fn tclr(&mut self) -> TCLR_W<FMC_PCR_SPEC, 9> { TCLR_W::new(self) } #[doc = "Bits 13:16 - TAR"] #[inline(always)] #[must_use] pub fn tar(&mut self) -> TAR_W<FMC_PCR_SPEC, 13> { TAR_W::new(self) } #[doc = "Bits 17:19 - ECCSS"] #[inline(always)] #[must_use] pub fn eccss(&mut self) -> ECCSS_W<FMC_PCR_SPEC, 17> { ECCSS_W::new(self) } #[doc = "Bits 20:23 - TCEH"] #[inline(always)] #[must_use] pub fn tceh(&mut self) -> TCEH_W<FMC_PCR_SPEC, 20> { TCEH_W::new(self) } #[doc = "Bit 24 - BCHECC"] #[inline(always)] #[must_use] pub fn bchecc(&mut self) -> BCHECC_W<FMC_PCR_SPEC, 24> { BCHECC_W::new(self) } #[doc = "Bit 25 - WEN"] #[inline(always)] #[must_use] pub fn wen(&mut self) -> WEN_W<FMC_PCR_SPEC, 25> { WEN_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 = "NAND Flash Programmable control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_pcr::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 [`fmc_pcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FMC_PCR_SPEC; impl crate::RegisterSpec for FMC_PCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fmc_pcr::R`](R) reader structure"] impl crate::Readable for FMC_PCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`fmc_pcr::W`](W) writer structure"] impl crate::Writable for FMC_PCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FMC_PCR to value 0x0007_fe08"] impl crate::Resettable for FMC_PCR_SPEC { const RESET_VALUE: Self::Ux = 0x0007_fe08; }
use crate::config; use std::fs; pub fn get_file_list(storage: &str) -> String { let mut msg = String::new(); for entry in fs::read_dir(storage).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if !path.is_dir() { let fullpath = String::from(entry.path().to_string_lossy()); let filename = String::from(str::replace(&fullpath, storage, "")); let file_name = &filename[1..]; let file = fs::File::open(fullpath).unwrap(); let file_size = file.metadata().unwrap().len(); let file_info = format!("{} [{} bytes]", file_name, file_size); msg.push_str(&file_info); msg.push('\n'); } } msg } pub fn check_file(file_name: &str, storage: &str) -> config::ServerFile { let mut f = config::ServerFile::new(); for entry in fs::read_dir(storage).unwrap() { let entry = entry.unwrap(); let path = entry.path(); if !path.is_dir() { let fullpath = String::from(entry.path().to_string_lossy()); let filename = String::from(str::replace(&fullpath, storage, "")); if &filename[1..] == file_name { let file = fs::File::open(&fullpath).unwrap(); f.size = file.metadata().unwrap().len(); f.name = file_name.to_string(); f.fullpath = fullpath; break; } } } f }
#![feature(alloc)] extern crate byteorder; #[macro_use] extern crate enum_primitive; extern crate num; pub mod bytecode; pub mod context; pub mod cst; pub mod environment; pub mod function; pub mod io; pub mod scribe;
// cargo-deps: maze="^0.1.2" // A demonstration of the A* algorithm in Rust. extern crate maze; macro_rules! impl_ord_supertraits { ( $name:tt, $( $params:tt ),* ) => { impl< $( $params ),* > PartialEq for $name < $( $params ),* > { fn eq(&self, other: &$name < $( $params ),* >) -> bool { self.partial_cmp(other) == Some(::std::cmp::Ordering::Equal) } } impl< $( $params ),* > Eq for $name < $( $params ),* > {} impl< $( $params ),* > PartialOrd for $name < $( $params ),* > { fn partial_cmp(&self, other: &$name < $( $params ),* >) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } } } /// A* path-finding algorithm. pub fn a_star<Node, Heuristic, Neighbors>( start: Node, goal: Node, mut neighbors: Neighbors, mut heuristic: Heuristic, ) -> Option<Vec<Node>> where Node: std::hash::Hash + Eq + Clone, Neighbors: FnMut(&Node, &mut Vec<(f64, Node)>), Heuristic: FnMut(&Node) -> f64, { use std::collections::{BinaryHeap, HashMap, HashSet}; use std::collections::hash_map::Entry; struct OpenNode<T>(f64, T); impl_ord_supertraits!(OpenNode, T); impl<T> Ord for OpenNode<T> { fn cmp(&self, other: &OpenNode<T>) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap().reverse() } } let mut cost = HashMap::new(); let mut came_from = HashMap::<Node, Node>::new(); let mut closed_set = HashSet::new(); let mut open_set = BinaryHeap::new(); let mut neighbors_buf = Vec::new(); cost.insert(start.clone(), 0.0); open_set.push(OpenNode(heuristic(&start), start)); while let Some(OpenNode(_, current)) = open_set.pop() { if &current == &goal { let mut path = Vec::new(); path.push(current); while let Some(c) = came_from.get(path.last().unwrap()) { path.push(c.clone()); } path.reverse(); return Some(path); } closed_set.insert(current.clone()); let current_cost = cost.get(&current).unwrap().clone(); neighbors(&current, &mut neighbors_buf); for &(dist, ref neighbor) in &neighbors_buf { if closed_set.contains(&neighbor) { continue; } let new_cost = current_cost + dist; match cost.entry(neighbor.clone()) { Entry::Occupied(ref e) if &new_cost >= e.get() => continue, e => e, }.or_insert(new_cost); came_from.insert(neighbor.clone(), current.clone()); let est_cost = new_cost + heuristic(&neighbor); open_set.push(OpenNode(est_cost, neighbor.clone())); } } None } fn main() { use std::collections::HashSet; const DIM: usize = 39; const FPS: u32 = 60; const EMPTY: &'static str = " "; const WALL: &'static str = "\x1b[41m \x1b[0m"; const PATH: &'static str = "\x1b[42m \x1b[0m"; const TRY: &'static str = "\x1b[44m \x1b[0m"; fn render_cells(cells: &[&str], dim: usize) { print!("\x1b[1;1H"); for y in 0 .. dim { for x in 0 .. dim { print!("{}", cells[x + y * dim]); } print!("\n"); } } assert!(DIM % 2 == 1); let mut wall = HashSet::new(); let mut grid = maze::types::grid::Grid::<maze::types::cell::BaseCell>::new( DIM / 2 + 1, DIM / 2 + 1); grid.generate_aldous_broder(); for y in 0 .. DIM { for x in 0 .. DIM { if x % 2 == 1 && y % 2 == 0 { if !grid.is_linked_indices(x / 2, y / 2, x / 2 + 1, y / 2) { wall.insert((x, y)); } if y > 0 && (wall.contains(&(x, y)) || wall.contains(&(x, y - 2)) || wall.contains(&(x - 1, y - 1)) || wall.contains(&(x + 1, y - 1))) { wall.insert((x, y - 1)); } } else if x % 2 == 0 && y % 2 == 1 && !grid.is_linked_indices(x / 2, y / 2, x / 2, y / 2 + 1) { wall.insert((x, y)); } } } print!("\x1b[2J"); // clear screen let mut cells = vec![EMPTY; DIM * DIM]; for &(x, y) in &wall { cells[x + y * DIM] = WALL; } let goal = (DIM - 1, DIM - 1); let result = a_star( (0, 0), goal, |&(x, y), neighbors| { cells[x + y * DIM] = TRY; render_cells(&cells, DIM); let ten_millis = std::time::Duration::from_secs(1) / FPS; std::thread::sleep(ten_millis); neighbors.clear(); neighbors.extend([ (1.0, (x + 1, y)), (1.0, (x, y + 1)), (1.0, ((x as isize - 1) as usize, y)), (1.0, (x, (y as isize - 1) as usize)), ].iter().cloned().filter(|&(_, (x, y))| { x < DIM && y < DIM && !wall.contains(&(x, y)) })); }, |&(x, y)| { let dx = x as f64 - goal.0 as f64; let dy = y as f64 - goal.1 as f64; dx * dx + dy * dy }, ); if let Some(r) = result { for &(x, y) in &r { cells[x + y * DIM] = PATH; } } render_cells(&cells, DIM); }
//! Module with hardware key port\masks /// Struct, which contains mast and port of key #[rustfmt::skip] #[cfg_attr(feature = "strum", derive(strum::EnumIter))] #[derive(Debug, Clone, Copy)] pub enum ZXKey { // Port 0xFEFE Shift, Z, X, C, V, // Port 0xFDFE A, S, D, F, G, // Port 0xFBFE Q, W, E, R, T, // Port 0xF7FE N1, N2, N3, N4, N5, // Port 0xEFFE N0, N9, N8, N7, N6, // Port 0xDFFE P, O, I, U, Y, // Port 0xBFFE Enter, L, K, J, H, // Port 0x7FFE Space, SymShift, M, N, B, } #[cfg_attr(feature = "strum", derive(strum::EnumIter))] #[derive(Debug, Clone, Copy)] pub enum CompoundKey { ArrowLeft, ArrowRight, ArrowUp, ArrowDown, CapsLock, Delete, Break, } impl CompoundKey { /// This mask is required to implement logic to keep /// modifier key pressed while one of the compound /// keys were released, but one of them is still /// pressed, therefore modifier should be unchanged pub(crate) fn modifier_mask(self) -> u32 { match self { CompoundKey::ArrowLeft => 0x00000001, CompoundKey::ArrowRight => 0x00000002, CompoundKey::ArrowUp => 0x00000004, CompoundKey::ArrowDown => 0x00000008, CompoundKey::CapsLock => 0x00000010, CompoundKey::Delete => 0x00000020, CompoundKey::Break => 0x00000040, } } pub(crate) fn modifier_key(self) -> ZXKey { ZXKey::Shift } pub(crate) fn primary_key(self) -> ZXKey { match self { CompoundKey::ArrowLeft => ZXKey::N5, CompoundKey::ArrowRight => ZXKey::N8, CompoundKey::ArrowUp => ZXKey::N7, CompoundKey::ArrowDown => ZXKey::N6, CompoundKey::CapsLock => ZXKey::N2, CompoundKey::Delete => ZXKey::N0, CompoundKey::Break => ZXKey::Space, } } } impl ZXKey { pub(crate) fn row_id(self) -> usize { match self.half_port() { 0xFE => 0, 0xFD => 1, 0xFB => 2, 0xF7 => 3, 0xEF => 4, 0xDF => 5, 0xBF => 6, 0x7F => 7, _ => unreachable!(), } } pub(crate) fn mask(&self) -> u8 { use ZXKey::*; match self { Shift | A | Q | N1 | N0 | P | Enter | Space => 0x01, Z | S | W | N2 | N9 | O | L | SymShift => 0x02, X | D | E | N3 | N8 | I | K | M => 0x04, C | F | R | N4 | N7 | U | J | N => 0x08, V | G | T | N5 | N6 | Y | H | B => 0x10, } } fn half_port(self) -> u8 { use ZXKey::*; match self { Shift | Z | X | C | V => 0xFE, A | S | D | F | G => 0xFD, Q | W | E | R | T => 0xFB, N1 | N2 | N3 | N4 | N5 => 0xF7, N0 | N9 | N8 | N7 | N6 => 0xEF, P | O | I | U | Y => 0xDF, Enter | L | K | J | H => 0xBF, Space | SymShift | M | N | B => 0x7F, } } }
extern crate day_01_inverse_captcha; extern crate utils; use day_01_inverse_captcha::inv_captcha; use utils::{file2str, str2vec_u32}; fn main() { let puzzle_string = file2str("puzzle.txt"); let puzzle_vec = str2vec_u32(&puzzle_string); let sum = inv_captcha(puzzle_vec); println!("The sum is: {}", sum); }
use crate::{ components::{Human, MovementState, Player}, utils, }; use amethyst::{ derive::SystemDesc, ecs::{Join, Read, ReadStorage, System, SystemData, WriteStorage}, input::{InputHandler, StringBindings}, }; #[derive(SystemDesc)] pub struct InputMovement; fn movement_multiplier(raw_movement_x: f32, raw_movement_y: f32, speed: f32) -> f32 { // We compute what's the right multiplier for the individual axis movement if // we want the euclidean distance moved in a second to be a maximum of "speed". // Assuming raw movements go from -1 to 1. let max_movement = f32::max(raw_movement_x.abs(), raw_movement_y.abs()); let target_speed = (speed * max_movement).powi(2); let actual_speed = raw_movement_x.powi(2) + raw_movement_y.powi(2); if actual_speed == 0.0 { 0.0 } else { (target_speed / actual_speed).sqrt() } } impl<'s> System<'s> for InputMovement { type SystemData = ( ReadStorage<'s, Player>, ReadStorage<'s, Human>, WriteStorage<'s, MovementState>, Read<'s, InputHandler<StringBindings>>, ); fn run(&mut self, (players, humans, mut movement_states, input): Self::SystemData) { for (player, _human, movement_state) in (&players, &humans, &mut movement_states).join() { let (raw_movement_x, raw_movement_y) = utils::input_movement(&input); let speed = player.speed; let move_multiplier = movement_multiplier(raw_movement_x, raw_movement_y, speed); let (movement_x, movement_y) = ( raw_movement_x * move_multiplier, raw_movement_y * move_multiplier, ); movement_state.velocity.x += movement_x; movement_state.velocity.y += movement_y; } } }
extern crate patronus; extern crate patronus_provider; pub use patronus_provider::{Annotation, AnnotationArray, Properties, Suggestion}; use std::ffi::{CStr, CString}; use std::os::raw::c_char; /// Opaque wrapper for `Patronus` struct. pub enum Patronus {} /// Creates an instance of `Patronus` checker. /// The returned value should be cleaned using `patronus_free` after use. #[no_mangle] pub extern "C" fn patronus_create() -> *mut Patronus { Box::into_raw(Box::new(patronus::Patronus::new())) as *mut Patronus } /// Cleans up the `Patronus` object returned by `patronus_create`. #[no_mangle] pub unsafe extern "C" fn patronus_free(ptr: *mut Patronus) { assert!(!ptr.is_null(), "Trying to free a NULL pointer."); Box::from_raw(ptr as *mut patronus::Patronus); } /// Checks provided text for mistakes. /// The returned value should be cleaned using `patronus_free_annotations` after use. #[no_mangle] pub unsafe extern "C" fn patronus_check( ptr: *mut Patronus, props: *const Properties, text: *const std::os::raw::c_char, ) -> *mut AnnotationArray { assert!(!ptr.is_null(), "Trying to use a NULL pointer."); assert!(!props.is_null(), "Trying to use a NULL pointer."); let patronus = &(*(ptr as *mut patronus::Patronus)); let properties = { let Properties { primary_language } = *props; patronus::Properties { primary_language: CStr::from_ptr(primary_language) .to_string_lossy() .into_owned(), } }; let anns = patronus .check(&properties, &CStr::from_ptr(text).to_string_lossy()) .iter() .map(|&patronus::Annotation { offset, length, ref message, kind, ref suggestions, }| { let msg = CString::new(message.clone()) .expect("cannot create C string") .into_raw() as *const c_char; let suggestions: Vec<Suggestion> = suggestions .into_iter() .map(|sugg| { CString::new((*sugg).clone()) .expect("cannot create C string") .into_raw() as *const c_char }) .collect(); Annotation { offset: offset, length: length, message: msg, kind: kind, suggestions: Box::into_raw(Box::new(suggestions.into())), } }) .collect::<Vec<Annotation>>() .into(); Box::into_raw(Box::new(anns)) } /// Cleans up the `AnnotationArray` returned by `patronus_check`. #[no_mangle] pub unsafe extern "C" fn patronus_free_annotations(ptr: *mut AnnotationArray) { assert!(!ptr.is_null(), "Trying to use a NULL pointer."); let anns = Box::from_raw(ptr); for i in 0..anns.len { let ann = &*anns.data.offset(i as isize); let suggs = Box::from_raw(ann.suggestions); for i in 0..suggs.len { let sugg = *suggs.data.offset(i as isize); CString::from_raw(sugg as *mut c_char); } CString::from_raw(ann.message as *mut c_char); } }
use amethyst::{ core::bundle::{Result, SystemBundle}, ecs::DispatcherBuilder, prelude::*, }; use crate::level; use crate::system; #[derive(Default)] pub struct LevelBundle; impl<'a, 'b> SystemBundle<'a, 'b> for LevelBundle { fn build(self, builder: &mut DispatcherBuilder<'a, 'b>) -> Result<()> { builder.add( system::PaddleSystem.pausable(level::GameState::Running), "paddle_system", &[], ); builder.add( system::Bounce.pausable(level::GameState::Running), "bounce", &["paddle_system"], ); builder.add( system::BouncedBlock.pausable(level::GameState::Running), "bounced_block", &["bounce"], ); builder.add( system::BelowZero.pausable(level::GameState::Running), "below_zero", &["bounce"], ); Ok(()) } }
use super::{ActivationFrame, CodePointer}; use crate::vm::VirtualMachine; #[derive(Debug, Copy, Clone)] pub struct Closure { code: CodePointer, closed_environment: &'static ActivationFrame, } impl Closure { pub fn new(code: CodePointer, env: &'static ActivationFrame) -> Self { Closure { code, closed_environment: env, } } pub fn allocate(code: CodePointer, env: &'static ActivationFrame) -> &'static Self { Box::leak(Box::new(Self::new(code, env))) } pub fn invoke(&self, vm: &mut VirtualMachine) { vm.env = self.closed_environment; vm.pc = self.code; } pub fn code(&self) -> &CodePointer { &self.code } pub fn env(&self) -> &ActivationFrame { self.closed_environment } }
#[doc = "Register `DDRPERFM_CNT2` reader"] pub type R = crate::R<DDRPERFM_CNT2_SPEC>; #[doc = "Field `CNT` reader - CNT"] pub type CNT_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - CNT"] #[inline(always)] pub fn cnt(&self) -> CNT_R { CNT_R::new(self.bits) } } #[doc = "DDRPERFM event counter 2 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ddrperfm_cnt2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DDRPERFM_CNT2_SPEC; impl crate::RegisterSpec for DDRPERFM_CNT2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ddrperfm_cnt2::R`](R) reader structure"] impl crate::Readable for DDRPERFM_CNT2_SPEC {} #[doc = "`reset()` method sets DDRPERFM_CNT2 to value 0"] impl crate::Resettable for DDRPERFM_CNT2_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `BMCR` reader"] pub type R = crate::R<BMCR_SPEC>; #[doc = "Register `BMCR` writer"] pub type W = crate::W<BMCR_SPEC>; #[doc = "Field `BME` reader - Burst Mode enable"] pub type BME_R = crate::BitReader<BME_A>; #[doc = "Burst Mode enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BME_A { #[doc = "0: Burst mode disabled"] Disabled = 0, #[doc = "1: Burst mode enabled"] Enabled = 1, } impl From<BME_A> for bool { #[inline(always)] fn from(variant: BME_A) -> Self { variant as u8 != 0 } } impl BME_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BME_A { match self.bits { false => BME_A::Disabled, true => BME_A::Enabled, } } #[doc = "Burst mode disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == BME_A::Disabled } #[doc = "Burst mode enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == BME_A::Enabled } } #[doc = "Field `BME` writer - Burst Mode enable"] pub type BME_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BME_A>; impl<'a, REG, const O: u8> BME_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Burst mode disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(BME_A::Disabled) } #[doc = "Burst mode enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(BME_A::Enabled) } } #[doc = "Field `BMOM` reader - Burst Mode operating mode"] pub type BMOM_R = crate::BitReader<BMOM_A>; #[doc = "Burst Mode operating mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BMOM_A { #[doc = "0: Single-shot mode"] SingleShot = 0, #[doc = "1: Continuous operation"] Continuous = 1, } impl From<BMOM_A> for bool { #[inline(always)] fn from(variant: BMOM_A) -> Self { variant as u8 != 0 } } impl BMOM_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BMOM_A { match self.bits { false => BMOM_A::SingleShot, true => BMOM_A::Continuous, } } #[doc = "Single-shot mode"] #[inline(always)] pub fn is_single_shot(&self) -> bool { *self == BMOM_A::SingleShot } #[doc = "Continuous operation"] #[inline(always)] pub fn is_continuous(&self) -> bool { *self == BMOM_A::Continuous } } #[doc = "Field `BMOM` writer - Burst Mode operating mode"] pub type BMOM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BMOM_A>; impl<'a, REG, const O: u8> BMOM_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Single-shot mode"] #[inline(always)] pub fn single_shot(self) -> &'a mut crate::W<REG> { self.variant(BMOM_A::SingleShot) } #[doc = "Continuous operation"] #[inline(always)] pub fn continuous(self) -> &'a mut crate::W<REG> { self.variant(BMOM_A::Continuous) } } #[doc = "Field `BMCLK` reader - Burst Mode Clock source"] pub type BMCLK_R = crate::FieldReader<BMCLK_A>; #[doc = "Burst Mode Clock source\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum BMCLK_A { #[doc = "0: Master timer reset/roll-over"] Master = 0, #[doc = "1: Timer A counter reset/roll-over"] TimerA = 1, #[doc = "2: Timer B counter reset/roll-over"] TimerB = 2, #[doc = "3: Timer C counter reset/roll-over"] TimerC = 3, #[doc = "4: Timer D counter reset/roll-over"] TimerD = 4, #[doc = "5: Timer E counter reset/roll-over"] TimerE = 5, #[doc = "6: On-chip Event 1 (BMClk\\[1\\]), acting as a burst mode counter clock"] Event1 = 6, #[doc = "7: On-chip Event 2 (BMClk\\[2\\]), acting as a burst mode counter clock"] Event2 = 7, #[doc = "8: On-chip Event 3 (BMClk\\[3\\]), acting as a burst mode counter clock"] Event3 = 8, #[doc = "9: On-chip Event 4 (BMClk\\[4\\]), acting as a burst mode counter clock"] Event4 = 9, #[doc = "10: Prescaled f_HRTIM clock (as per BMPRSC\\[3:0\\] setting"] Clock = 10, } impl From<BMCLK_A> for u8 { #[inline(always)] fn from(variant: BMCLK_A) -> Self { variant as _ } } impl crate::FieldSpec for BMCLK_A { type Ux = u8; } impl BMCLK_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<BMCLK_A> { match self.bits { 0 => Some(BMCLK_A::Master), 1 => Some(BMCLK_A::TimerA), 2 => Some(BMCLK_A::TimerB), 3 => Some(BMCLK_A::TimerC), 4 => Some(BMCLK_A::TimerD), 5 => Some(BMCLK_A::TimerE), 6 => Some(BMCLK_A::Event1), 7 => Some(BMCLK_A::Event2), 8 => Some(BMCLK_A::Event3), 9 => Some(BMCLK_A::Event4), 10 => Some(BMCLK_A::Clock), _ => None, } } #[doc = "Master timer reset/roll-over"] #[inline(always)] pub fn is_master(&self) -> bool { *self == BMCLK_A::Master } #[doc = "Timer A counter reset/roll-over"] #[inline(always)] pub fn is_timer_a(&self) -> bool { *self == BMCLK_A::TimerA } #[doc = "Timer B counter reset/roll-over"] #[inline(always)] pub fn is_timer_b(&self) -> bool { *self == BMCLK_A::TimerB } #[doc = "Timer C counter reset/roll-over"] #[inline(always)] pub fn is_timer_c(&self) -> bool { *self == BMCLK_A::TimerC } #[doc = "Timer D counter reset/roll-over"] #[inline(always)] pub fn is_timer_d(&self) -> bool { *self == BMCLK_A::TimerD } #[doc = "Timer E counter reset/roll-over"] #[inline(always)] pub fn is_timer_e(&self) -> bool { *self == BMCLK_A::TimerE } #[doc = "On-chip Event 1 (BMClk\\[1\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn is_event1(&self) -> bool { *self == BMCLK_A::Event1 } #[doc = "On-chip Event 2 (BMClk\\[2\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn is_event2(&self) -> bool { *self == BMCLK_A::Event2 } #[doc = "On-chip Event 3 (BMClk\\[3\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn is_event3(&self) -> bool { *self == BMCLK_A::Event3 } #[doc = "On-chip Event 4 (BMClk\\[4\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn is_event4(&self) -> bool { *self == BMCLK_A::Event4 } #[doc = "Prescaled f_HRTIM clock (as per BMPRSC\\[3:0\\] setting"] #[inline(always)] pub fn is_clock(&self) -> bool { *self == BMCLK_A::Clock } } #[doc = "Field `BMCLK` writer - Burst Mode Clock source"] pub type BMCLK_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O, BMCLK_A>; impl<'a, REG, const O: u8> BMCLK_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "Master timer reset/roll-over"] #[inline(always)] pub fn master(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Master) } #[doc = "Timer A counter reset/roll-over"] #[inline(always)] pub fn timer_a(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::TimerA) } #[doc = "Timer B counter reset/roll-over"] #[inline(always)] pub fn timer_b(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::TimerB) } #[doc = "Timer C counter reset/roll-over"] #[inline(always)] pub fn timer_c(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::TimerC) } #[doc = "Timer D counter reset/roll-over"] #[inline(always)] pub fn timer_d(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::TimerD) } #[doc = "Timer E counter reset/roll-over"] #[inline(always)] pub fn timer_e(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::TimerE) } #[doc = "On-chip Event 1 (BMClk\\[1\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn event1(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Event1) } #[doc = "On-chip Event 2 (BMClk\\[2\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn event2(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Event2) } #[doc = "On-chip Event 3 (BMClk\\[3\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn event3(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Event3) } #[doc = "On-chip Event 4 (BMClk\\[4\\]), acting as a burst mode counter clock"] #[inline(always)] pub fn event4(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Event4) } #[doc = "Prescaled f_HRTIM clock (as per BMPRSC\\[3:0\\] setting"] #[inline(always)] pub fn clock(self) -> &'a mut crate::W<REG> { self.variant(BMCLK_A::Clock) } } #[doc = "Field `BMPRSC` reader - Burst Mode Prescaler"] pub type BMPRSC_R = crate::FieldReader<BMPRSC_A>; #[doc = "Burst Mode Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum BMPRSC_A { #[doc = "0: Clock not divided"] Div1 = 0, #[doc = "1: Division by 2"] Div2 = 1, #[doc = "2: Division by 4"] Div4 = 2, #[doc = "3: Division by 8"] Div8 = 3, #[doc = "4: Division by 16"] Div16 = 4, #[doc = "5: Division by 32"] Div32 = 5, #[doc = "6: Division by 64"] Div64 = 6, #[doc = "7: Division by 128"] Div128 = 7, #[doc = "8: Division by 256"] Div256 = 8, #[doc = "9: Division by 512"] Div512 = 9, #[doc = "10: Division by 1024"] Div1024 = 10, #[doc = "11: Division by 2048"] Div2048 = 11, #[doc = "12: Division by 4096"] Div4096 = 12, #[doc = "13: Division by 8192"] Div8192 = 13, #[doc = "14: Division by 16384"] Div16384 = 14, #[doc = "15: Division by 32768"] Div32768 = 15, } impl From<BMPRSC_A> for u8 { #[inline(always)] fn from(variant: BMPRSC_A) -> Self { variant as _ } } impl crate::FieldSpec for BMPRSC_A { type Ux = u8; } impl BMPRSC_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BMPRSC_A { match self.bits { 0 => BMPRSC_A::Div1, 1 => BMPRSC_A::Div2, 2 => BMPRSC_A::Div4, 3 => BMPRSC_A::Div8, 4 => BMPRSC_A::Div16, 5 => BMPRSC_A::Div32, 6 => BMPRSC_A::Div64, 7 => BMPRSC_A::Div128, 8 => BMPRSC_A::Div256, 9 => BMPRSC_A::Div512, 10 => BMPRSC_A::Div1024, 11 => BMPRSC_A::Div2048, 12 => BMPRSC_A::Div4096, 13 => BMPRSC_A::Div8192, 14 => BMPRSC_A::Div16384, 15 => BMPRSC_A::Div32768, _ => unreachable!(), } } #[doc = "Clock not divided"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == BMPRSC_A::Div1 } #[doc = "Division by 2"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == BMPRSC_A::Div2 } #[doc = "Division by 4"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == BMPRSC_A::Div4 } #[doc = "Division by 8"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == BMPRSC_A::Div8 } #[doc = "Division by 16"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == BMPRSC_A::Div16 } #[doc = "Division by 32"] #[inline(always)] pub fn is_div32(&self) -> bool { *self == BMPRSC_A::Div32 } #[doc = "Division by 64"] #[inline(always)] pub fn is_div64(&self) -> bool { *self == BMPRSC_A::Div64 } #[doc = "Division by 128"] #[inline(always)] pub fn is_div128(&self) -> bool { *self == BMPRSC_A::Div128 } #[doc = "Division by 256"] #[inline(always)] pub fn is_div256(&self) -> bool { *self == BMPRSC_A::Div256 } #[doc = "Division by 512"] #[inline(always)] pub fn is_div512(&self) -> bool { *self == BMPRSC_A::Div512 } #[doc = "Division by 1024"] #[inline(always)] pub fn is_div1024(&self) -> bool { *self == BMPRSC_A::Div1024 } #[doc = "Division by 2048"] #[inline(always)] pub fn is_div2048(&self) -> bool { *self == BMPRSC_A::Div2048 } #[doc = "Division by 4096"] #[inline(always)] pub fn is_div4096(&self) -> bool { *self == BMPRSC_A::Div4096 } #[doc = "Division by 8192"] #[inline(always)] pub fn is_div8192(&self) -> bool { *self == BMPRSC_A::Div8192 } #[doc = "Division by 16384"] #[inline(always)] pub fn is_div16384(&self) -> bool { *self == BMPRSC_A::Div16384 } #[doc = "Division by 32768"] #[inline(always)] pub fn is_div32768(&self) -> bool { *self == BMPRSC_A::Div32768 } } #[doc = "Field `BMPRSC` writer - Burst Mode Prescaler"] pub type BMPRSC_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O, BMPRSC_A>; impl<'a, REG, const O: u8> BMPRSC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "Clock not divided"] #[inline(always)] pub fn div1(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div1) } #[doc = "Division by 2"] #[inline(always)] pub fn div2(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div2) } #[doc = "Division by 4"] #[inline(always)] pub fn div4(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div4) } #[doc = "Division by 8"] #[inline(always)] pub fn div8(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div8) } #[doc = "Division by 16"] #[inline(always)] pub fn div16(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div16) } #[doc = "Division by 32"] #[inline(always)] pub fn div32(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div32) } #[doc = "Division by 64"] #[inline(always)] pub fn div64(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div64) } #[doc = "Division by 128"] #[inline(always)] pub fn div128(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div128) } #[doc = "Division by 256"] #[inline(always)] pub fn div256(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div256) } #[doc = "Division by 512"] #[inline(always)] pub fn div512(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div512) } #[doc = "Division by 1024"] #[inline(always)] pub fn div1024(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div1024) } #[doc = "Division by 2048"] #[inline(always)] pub fn div2048(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div2048) } #[doc = "Division by 4096"] #[inline(always)] pub fn div4096(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div4096) } #[doc = "Division by 8192"] #[inline(always)] pub fn div8192(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div8192) } #[doc = "Division by 16384"] #[inline(always)] pub fn div16384(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div16384) } #[doc = "Division by 32768"] #[inline(always)] pub fn div32768(self) -> &'a mut crate::W<REG> { self.variant(BMPRSC_A::Div32768) } } #[doc = "Field `BMPREN` reader - Burst Mode Preload Enable"] pub type BMPREN_R = crate::BitReader<BMPREN_A>; #[doc = "Burst Mode Preload Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BMPREN_A { #[doc = "0: Preload disabled: the write access is directly done into active registers"] Disabled = 0, #[doc = "1: Preload enabled: the write access is done into preload registers"] Enabled = 1, } impl From<BMPREN_A> for bool { #[inline(always)] fn from(variant: BMPREN_A) -> Self { variant as u8 != 0 } } impl BMPREN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BMPREN_A { match self.bits { false => BMPREN_A::Disabled, true => BMPREN_A::Enabled, } } #[doc = "Preload disabled: the write access is directly done into active registers"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == BMPREN_A::Disabled } #[doc = "Preload enabled: the write access is done into preload registers"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == BMPREN_A::Enabled } } #[doc = "Field `BMPREN` writer - Burst Mode Preload Enable"] pub type BMPREN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BMPREN_A>; impl<'a, REG, const O: u8> BMPREN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Preload disabled: the write access is directly done into active registers"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(BMPREN_A::Disabled) } #[doc = "Preload enabled: the write access is done into preload registers"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(BMPREN_A::Enabled) } } #[doc = "Field `MTBM` reader - Master Timer Burst Mode"] pub type MTBM_R = crate::BitReader<MTBM_A>; #[doc = "Master Timer Burst Mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MTBM_A { #[doc = "0: Counter clock is maintained and timer operates normally"] Normal = 0, #[doc = "1: Counter clock is stopped and counter is reset"] Stopped = 1, } impl From<MTBM_A> for bool { #[inline(always)] fn from(variant: MTBM_A) -> Self { variant as u8 != 0 } } impl MTBM_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MTBM_A { match self.bits { false => MTBM_A::Normal, true => MTBM_A::Stopped, } } #[doc = "Counter clock is maintained and timer operates normally"] #[inline(always)] pub fn is_normal(&self) -> bool { *self == MTBM_A::Normal } #[doc = "Counter clock is stopped and counter is reset"] #[inline(always)] pub fn is_stopped(&self) -> bool { *self == MTBM_A::Stopped } } #[doc = "Field `MTBM` writer - Master Timer Burst Mode"] pub type MTBM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MTBM_A>; impl<'a, REG, const O: u8> MTBM_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Counter clock is maintained and timer operates normally"] #[inline(always)] pub fn normal(self) -> &'a mut crate::W<REG> { self.variant(MTBM_A::Normal) } #[doc = "Counter clock is stopped and counter is reset"] #[inline(always)] pub fn stopped(self) -> &'a mut crate::W<REG> { self.variant(MTBM_A::Stopped) } } #[doc = "Field `TABM` reader - Timer A Burst Mode"] pub use MTBM_R as TABM_R; #[doc = "Field `TBBM` reader - Timer B Burst Mode"] pub use MTBM_R as TBBM_R; #[doc = "Field `TCBM` reader - Timer C Burst Mode"] pub use MTBM_R as TCBM_R; #[doc = "Field `TDBM` reader - Timer D Burst Mode"] pub use MTBM_R as TDBM_R; #[doc = "Field `TEBM` reader - Timer E Burst Mode"] pub use MTBM_R as TEBM_R; #[doc = "Field `TABM` writer - Timer A Burst Mode"] pub use MTBM_W as TABM_W; #[doc = "Field `TBBM` writer - Timer B Burst Mode"] pub use MTBM_W as TBBM_W; #[doc = "Field `TCBM` writer - Timer C Burst Mode"] pub use MTBM_W as TCBM_W; #[doc = "Field `TDBM` writer - Timer D Burst Mode"] pub use MTBM_W as TDBM_W; #[doc = "Field `TEBM` writer - Timer E Burst Mode"] pub use MTBM_W as TEBM_W; #[doc = "Field `BMSTAT` reader - Burst Mode Status"] pub type BMSTAT_R = crate::BitReader<BMSTATR_A>; #[doc = "Burst Mode Status\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BMSTATR_A { #[doc = "0: Normal operation"] Normal = 0, #[doc = "1: Burst operation ongoing"] Burst = 1, } impl From<BMSTATR_A> for bool { #[inline(always)] fn from(variant: BMSTATR_A) -> Self { variant as u8 != 0 } } impl BMSTAT_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BMSTATR_A { match self.bits { false => BMSTATR_A::Normal, true => BMSTATR_A::Burst, } } #[doc = "Normal operation"] #[inline(always)] pub fn is_normal(&self) -> bool { *self == BMSTATR_A::Normal } #[doc = "Burst operation ongoing"] #[inline(always)] pub fn is_burst(&self) -> bool { *self == BMSTATR_A::Burst } } #[doc = "Burst Mode Status\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BMSTATW_AW { #[doc = "0: Terminate burst mode"] Cancel = 0, } impl From<BMSTATW_AW> for bool { #[inline(always)] fn from(variant: BMSTATW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `BMSTAT` writer - Burst Mode Status"] pub type BMSTAT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, BMSTATW_AW>; impl<'a, REG, const O: u8> BMSTAT_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Terminate burst mode"] #[inline(always)] pub fn cancel(self) -> &'a mut crate::W<REG> { self.variant(BMSTATW_AW::Cancel) } } impl R { #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] pub fn bme(&self) -> BME_R { BME_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] pub fn bmom(&self) -> BMOM_R { BMOM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] pub fn bmclk(&self) -> BMCLK_R { BMCLK_R::new(((self.bits >> 2) & 0x0f) as u8) } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] pub fn bmprsc(&self) -> BMPRSC_R { BMPRSC_R::new(((self.bits >> 6) & 0x0f) as u8) } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] pub fn bmpren(&self) -> BMPREN_R { BMPREN_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] pub fn mtbm(&self) -> MTBM_R { MTBM_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] pub fn tabm(&self) -> TABM_R { TABM_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] pub fn tbbm(&self) -> TBBM_R { TBBM_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] pub fn tcbm(&self) -> TCBM_R { TCBM_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] pub fn tdbm(&self) -> TDBM_R { TDBM_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] pub fn tebm(&self) -> TEBM_R { TEBM_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] pub fn bmstat(&self) -> BMSTAT_R { BMSTAT_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - Burst Mode enable"] #[inline(always)] #[must_use] pub fn bme(&mut self) -> BME_W<BMCR_SPEC, 0> { BME_W::new(self) } #[doc = "Bit 1 - Burst Mode operating mode"] #[inline(always)] #[must_use] pub fn bmom(&mut self) -> BMOM_W<BMCR_SPEC, 1> { BMOM_W::new(self) } #[doc = "Bits 2:5 - Burst Mode Clock source"] #[inline(always)] #[must_use] pub fn bmclk(&mut self) -> BMCLK_W<BMCR_SPEC, 2> { BMCLK_W::new(self) } #[doc = "Bits 6:9 - Burst Mode Prescaler"] #[inline(always)] #[must_use] pub fn bmprsc(&mut self) -> BMPRSC_W<BMCR_SPEC, 6> { BMPRSC_W::new(self) } #[doc = "Bit 10 - Burst Mode Preload Enable"] #[inline(always)] #[must_use] pub fn bmpren(&mut self) -> BMPREN_W<BMCR_SPEC, 10> { BMPREN_W::new(self) } #[doc = "Bit 16 - Master Timer Burst Mode"] #[inline(always)] #[must_use] pub fn mtbm(&mut self) -> MTBM_W<BMCR_SPEC, 16> { MTBM_W::new(self) } #[doc = "Bit 17 - Timer A Burst Mode"] #[inline(always)] #[must_use] pub fn tabm(&mut self) -> TABM_W<BMCR_SPEC, 17> { TABM_W::new(self) } #[doc = "Bit 18 - Timer B Burst Mode"] #[inline(always)] #[must_use] pub fn tbbm(&mut self) -> TBBM_W<BMCR_SPEC, 18> { TBBM_W::new(self) } #[doc = "Bit 19 - Timer C Burst Mode"] #[inline(always)] #[must_use] pub fn tcbm(&mut self) -> TCBM_W<BMCR_SPEC, 19> { TCBM_W::new(self) } #[doc = "Bit 20 - Timer D Burst Mode"] #[inline(always)] #[must_use] pub fn tdbm(&mut self) -> TDBM_W<BMCR_SPEC, 20> { TDBM_W::new(self) } #[doc = "Bit 21 - Timer E Burst Mode"] #[inline(always)] #[must_use] pub fn tebm(&mut self) -> TEBM_W<BMCR_SPEC, 21> { TEBM_W::new(self) } #[doc = "Bit 31 - Burst Mode Status"] #[inline(always)] #[must_use] pub fn bmstat(&mut self) -> BMSTAT_W<BMCR_SPEC, 31> { BMSTAT_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Burst Mode Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bmcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`bmcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct BMCR_SPEC; impl crate::RegisterSpec for BMCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`bmcr::R`](R) reader structure"] impl crate::Readable for BMCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`bmcr::W`](W) writer structure"] impl crate::Writable for BMCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets BMCR to value 0"] impl crate::Resettable for BMCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::collections::{HashMap, HashSet}; use rand::distributions::Distribution; use rand::Rng; use crate::topology::{PixelLoc, Topology}; pub struct PointTracker { frontier: Vec<PixelLoc>, frontier_map: HashMap<PixelLoc, usize>, used: Vec<bool>, topology: Topology, } impl PointTracker { pub fn new(topology: Topology) -> Self { Self { used: vec![false; topology.len()], topology, frontier: Vec::new(), frontier_map: HashMap::new(), } } pub fn add_to_frontier(&mut self, loc: PixelLoc) { let index = self.topology.get_index(loc); if let Some(index) = index { PointTracker::_add_to_frontier( &mut self.frontier, &mut self.frontier_map, &mut self.used, index, loc, ); } } pub fn add_random_to_frontier( &mut self, num_random: usize, rng: &mut impl Rng, ) { let num_unused = self.used.iter().filter(|&x| !x).count(); let num_random = usize::min(num_unused, num_random); if num_random == 0 { return; } let mut indices = HashSet::new(); let distribution = rand::distributions::Uniform::from(0..num_unused); while indices.len() < num_random { indices.insert(distribution.sample(rng)); } self.used .iter() .enumerate() .filter(|(_i, &b)| !b) .map(|(i, _b)| i) .enumerate() .filter(|(i_unused, _i_arr)| indices.contains(i_unused)) .map(|(_i_unused, i_arr)| { (i_arr, self.topology.get_loc(i_arr).unwrap()) }) .collect::<Vec<_>>() .iter() .for_each(|&(i_arr, loc)| { PointTracker::_add_to_frontier( &mut self.frontier, &mut self.frontier_map, &mut self.used, i_arr, loc, ) }); } fn _add_to_frontier( frontier: &mut Vec<PixelLoc>, frontier_map: &mut HashMap<PixelLoc, usize>, used: &mut Vec<bool>, index: usize, loc: PixelLoc, ) { if !used[index] { frontier_map.insert(loc, frontier.len()); frontier.push(loc); used[index] = true; } } pub fn mark_as_used(&mut self, loc: PixelLoc) { self._mark_used_unused_state(loc, true); } pub fn mark_as_unused(&mut self, loc: PixelLoc) { self._mark_used_unused_state(loc, false); } fn _mark_used_unused_state(&mut self, loc: PixelLoc, val: bool) { let index = self.topology.get_index(loc); if let Some(index) = index { self.used[index] = val; } } pub fn mark_all_as_used(&mut self) { self.used.iter_mut().for_each(|x| *x = true); } pub fn is_done(&self) -> bool { return self.frontier.len() == 0; } pub fn frontier_size(&self) -> usize { self.frontier.len() } pub fn get_frontier_point(&self, index: usize) -> PixelLoc { self.frontier[index] } pub fn fill(&mut self, loc: PixelLoc) { let topology = &self.topology; let mut frontier = &mut self.frontier; let mut frontier_map = &mut self.frontier_map; let mut used = &mut self.used; topology.iter_adjacent(loc).for_each(|adjacent| { let index = topology.get_index(adjacent); if let Some(index) = index { PointTracker::_add_to_frontier( &mut frontier, &mut frontier_map, &mut used, index, adjacent, ); } }); self.remove_from_frontier(loc); } fn remove_from_frontier(&mut self, loc: PixelLoc) { let index = self.frontier_map.get(&loc).map(|i| *i); if let Some(index) = index { let last_point = *self.frontier.last().unwrap(); self.frontier_map.insert(last_point, index); self.frontier.swap_remove(index); self.frontier_map.remove(&loc); } } }
// Generated by `scripts/generate.js` pub type VkRayTracingShaderGroupType = super::super::khr::VkRayTracingShaderGroupType; #[doc(hidden)] pub type RawVkRayTracingShaderGroupType = super::super::khr::RawVkRayTracingShaderGroupType;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::{env, near_bindgen, AccountId, PanicOnDefault, assert_one_yocto, Promise, log}; use near_sdk::json_types::{ValidAccountId, U128}; use near_sdk::collections::{LookupMap}; near_sdk::setup_alloc!(); use crate::utils::{ext_fungible_token, GAS_FOR_FT_TRANSFER}; use crate::rewards::{Rewards, Reward, WrappedReward}; mod utils; mod rewards; mod token_receiver; /* Implementation of claim rewards. */ #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Contract { owner: AccountId, token: AccountId, records: LookupMap<AccountId, Rewards>, deposited_amount: u128, } #[near_bindgen] impl Contract{ #[init] pub fn new( owner: ValidAccountId, token: ValidAccountId, ) -> Self { assert!(!env::state_exists(), "ERR_CONTRACT_ALREADY_INTIALIZED"); let this = Self { owner: owner.into(), token: token.into(), records: LookupMap::new(b"t".to_vec()), deposited_amount: 0, }; this } fn internal_deposit(&mut self, amount: u128) { self.deposited_amount = self.deposited_amount.checked_add(amount).expect("ERR_INTEGER_OVERFLOW"); } pub fn get_rewards(&self, from_index: u64, limit: u64, account_id: ValidAccountId) -> Vec<WrappedReward> { let user_rewards = self.records.get(account_id.as_ref()).unwrap(); let end_index = user_rewards.get_rewards_len().saturating_sub(from_index); (end_index.saturating_sub(limit)..end_index).rev() .map(|index| user_rewards.get_reward(index).to_wreward()) .collect() } pub fn get_reward_amount(&self, account_id: ValidAccountId) -> U128 { let current_rewards = self.records.get(account_id.as_ref()).unwrap(); current_rewards.internal_reward_amount().into() } #[payable] pub fn claim_reward(&mut self, amount: U128) -> Promise { assert_one_yocto(); let mut current_rewards = self.records.get(&env::predecessor_account_id()).unwrap(); let current_amount = current_rewards.internal_reward_amount(); let amount: u128 = amount.into(); assert!(amount <= current_amount, "ERR_AMOUNT_TOO_HIGH"); log!("Claiming reward : {} PARAS", (amount as f64 / 1e24)); current_rewards.internal_set_reward_amount(current_amount.checked_sub(amount).expect("ERR_INTEGER_OVERFLOW")); self.records.insert(&env::predecessor_account_id(), &current_rewards); ext_fungible_token::ft_transfer( env::predecessor_account_id().into(), amount.into(), None, &self.token, 1, GAS_FOR_FT_TRANSFER ) } #[payable] pub fn push_reward(&mut self, account_id: ValidAccountId, amount: U128, memo: String) { assert_eq!(self.owner, env::predecessor_account_id(), "ERR_NOT_OWNER"); assert_one_yocto(); assert!(self.deposited_amount >= amount.into(), "ERR_DEPOSITED_AMOUNT_NOT_ENOUGH"); let mut current_rewards = self.records.get(account_id.as_ref()).unwrap_or(Rewards::new(account_id.clone().into())); let new_reward: Reward = Reward::new( amount.into(), memo, ); self.deposited_amount = self.deposited_amount.checked_sub(amount.into()).expect("ERR_INTEGER_OVERFLOW"); // insert new record to current_record and set reward amount let current_amount = current_rewards.internal_reward_amount(); current_rewards.internal_add_new_reward(new_reward); current_rewards.internal_set_reward_amount(current_amount.checked_add(amount.into()).expect("ERR_INTEGER_OVERFLOW")); self.records.insert(account_id.as_ref(), &current_rewards); log!("Current reward for {} : {} PARAS", account_id.to_string(), current_rewards.internal_reward_amount() as f64 / 1e24); } } #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use super::*; use near_contract_standards::fungible_token::receiver::FungibleTokenReceiver; use near_sdk::test_utils::{accounts, VMContextBuilder}; use near_sdk::MockedBlockchain; use near_sdk::{testing_env}; const TEN_PARAS_TOKEN: U128 = U128(10_000_000_000_000_000_000_000_000); fn get_context(predecessor_account_id: ValidAccountId) -> VMContextBuilder { let mut builder = VMContextBuilder::new(); builder .current_account_id(accounts(0)) .signer_account_id(predecessor_account_id.clone()) .predecessor_account_id(predecessor_account_id); builder } fn setup_contract() -> (VMContextBuilder, Contract) { let mut context = VMContextBuilder::new(); testing_env!(context.predecessor_account_id(accounts(0)).build()); let contract = Contract::new(accounts(1).into(), accounts(2).into()); (context, contract) } #[test] fn test_new() { let mut context = get_context(accounts(1)); testing_env!(context.build()); let contract = Contract::new(accounts(1).into(), accounts(2).into()); testing_env!(context.is_view(true).build()); assert_eq!(contract.deposited_amount, 0); assert_eq!(contract.owner, accounts(1).to_string()); assert_eq!(contract.token, accounts(2).to_string()); } #[test] #[should_panic(expected = "The contract is not initialized")] fn test_default() { let context = get_context(accounts(1)); testing_env!(context.build()); let _contract = Contract::default(); } #[test] fn test_internal_deposit() { let (mut context, mut contract) = setup_contract(); testing_env!(context .predecessor_account_id(accounts(2)) .attached_deposit(1) .build()); contract.ft_on_transfer(accounts(3), U128(10), "".to_string()); assert_eq!(contract.deposited_amount, 10); } #[test] fn test_push_reward() { let (mut context, mut contract) = setup_contract(); testing_env!(context .predecessor_account_id(accounts(2)) .attached_deposit(1) .build()); contract.ft_on_transfer(accounts(3), TEN_PARAS_TOKEN, "".to_string()); testing_env!(context .predecessor_account_id(accounts(1)) .attached_deposit(1) .build()); contract.push_reward(accounts(3), TEN_PARAS_TOKEN, "first reward".to_string()); assert_eq!(contract.deposited_amount, 0); assert_eq!(contract.get_reward_amount(accounts(3)), TEN_PARAS_TOKEN.into()); assert_eq!(contract.records.get(accounts(3).as_ref()).unwrap().get_reward(0).get_amount(), TEN_PARAS_TOKEN.into()); assert_eq!(contract.records.get(accounts(3).as_ref()).unwrap().get_reward(0).get_memo(), "first reward"); } #[test] fn test_claim_reward() { let (mut context, mut contract) = setup_contract(); testing_env!(context .predecessor_account_id(accounts(2)) .attached_deposit(1) .build()); contract.ft_on_transfer(accounts(3), TEN_PARAS_TOKEN, "".to_string()); testing_env!(context .predecessor_account_id(accounts(1)) .attached_deposit(1) .build()); contract.push_reward(accounts(3), TEN_PARAS_TOKEN, "first reward".to_string()); testing_env!(context .predecessor_account_id(accounts(3)) .attached_deposit(1) .build()); contract.claim_reward(TEN_PARAS_TOKEN); assert_eq!(contract.get_reward_amount(accounts(3)), U128(0)); } #[test] #[should_panic(expected = "ERR_DEPOSITED_AMOUNT_NOT_ENOUGH")] fn test_not_enough_push_reward() { let (mut context, mut contract) = setup_contract(); testing_env!(context .predecessor_account_id(accounts(1)) .attached_deposit(1) .build()); contract.push_reward(accounts(3).into(), TEN_PARAS_TOKEN, "".to_string()); } }
use num_derive::FromPrimitive; use num_enum::IntoPrimitive; pub mod dataframe; #[derive(FromPrimitive, IntoPrimitive)] #[repr(u8)] pub enum Type { ACK = 0x6, NAK = 0x15, CAN = 0x18, DATAFRAME = 0x01, } #[derive(Debug, PartialEq)] pub enum Message { Ack, Nak, Can, DataFrame(dataframe::DataFrame), }
use std::process::Command; pub enum Align { Left, Center, Right, None, } #[derive(Debug)] pub enum WindowManagers { Bspwm, I3, } pub fn run_command<T: Into<String>>(cmd: T) -> String { let command = Command::new("bash") .arg("-c") .arg(cmd.into()) .output().unwrap_or_else(|e| { panic!("Failed to execute process: {}", e); }); let cmd_cow = String::from_utf8_lossy(&command.stdout); let mut out = cmd_cow.to_string(); let len = out.len(); // Remove newline if len > 0 { out.truncate(len - 1); } out } pub fn run_i32<T: Into<String>>(cmd: T) -> i32 { let result = run_command(cmd.into()); result.parse::<i32>().unwrap_or_else(|e| { panic!("Parsing error: {}", e); }) } pub fn run_bg<T: Into<String>>(cmd: T) -> u32 { let process = Command::new("bash") .arg("-c") .arg(cmd.into()) .spawn(); match process { Ok(p) => { p.id() }, Err(e) => panic!("Could not start background process! Err: {}", e), } } pub fn opacity_to_hex(opacity: u32) -> String { let alpha = (2.55 * opacity as f32) as u32; let mut alpha_hex = format!("{:x}", alpha); if alpha_hex.len() == 1 { alpha_hex = String::from("0") + &alpha_hex; } alpha_hex }
use std::ffi::CString; use std::os::raw::c_char; #[no_mangle] pub fn get_message() -> *mut c_char { CString::new(String::from("hello world")).unwrap().into_raw() }
use serde_derive::{Deserialize, Serialize}; use crate::{ entity::{Item, Room}, player::Player, types::{CmdResult, ItemMap, RoomMap}, util::dont_have, }; // Represents a world for the player to explore that consists of a grid of Rooms. // A World is a graph data structure that encapsulates a collection of Room nodes. #[derive(Debug, Serialize, Deserialize)] pub struct World { curr_room: String, rooms: RoomMap, } impl World { pub fn get_curr_room(&self) -> &Room { match self.rooms.get(&self.curr_room) { Some(room) => room, None => panic!("ERROR: You are not in a valid room (The world should be fixed)."), } } pub fn get_curr_room_mut(&mut self) -> &mut Room { match self.rooms.get_mut(&self.curr_room) { Some(room) => room, None => panic!("ERROR: You are not in a valid room (The world should be fixed)."), } } // displays description of the current Room pub fn look(&self) -> CmdResult { CmdResult::new(true, self.get_curr_room().desc()) } pub fn inspect(&self, name: &str) -> Option<CmdResult> { if let Some(item) = self.get_curr_room().items().get(name) { Some(CmdResult::new(true, item.inspection().to_owned())) } else if let Some(item) = self.get_curr_room().paths().get(name) { Some(CmdResult::new(true, item.inspection().to_owned())) } else if let Some(enemy) = self.get_curr_room().enemies().get(name) { Some(CmdResult::new(true, enemy.inspection().to_owned())) } else if let Some(ally) = self.get_curr_room().allies().get(name) { Some(CmdResult::new(true, ally.inspection().to_owned())) } else { None } } // changes the current Room to the target of the current Room's chosen path pub fn move_room(&mut self, direction: &str) -> CmdResult { if let Some(new_room) = self.get_curr_room().paths().get(direction) { if new_room.is_locked() == Some(true) { CmdResult::new(true, "The way is locked.".to_owned()) } else if new_room.is_closed() == Some(true) { CmdResult::new(true, "The way is shut.".to_owned()) } else { for e in self.get_curr_room().enemies().values() { if e.is_angry() { return CmdResult::new(false, "Enemies bar your way.".to_owned()); } } self.curr_room = new_room.target().to_owned(); self.look() } } else { CmdResult::new(false, "You cannot go that way.".to_owned()) } } pub fn open(&mut self, name: &str) -> CmdResult { if let Some(path) = self.get_curr_room_mut().paths_mut().get_mut(name) { if path.is_closed() == Some(true) { path.open(); CmdResult::new(true, "Opened.".to_owned()) } else { CmdResult::new(false, format!("The {} is already opened.", name)) } } else if let Some(item) = self.get_curr_room_mut().items_mut().get_mut(name) { if item.is_closed() == Some(true) { item.open(); CmdResult::new(true, "Opened.".to_owned()) } else { CmdResult::new(false, format!("The {} is already opened.", name)) } } else { CmdResult::new(false, format!("There is no \"{}\".", name)) } } pub fn close(&mut self, name: &str) -> CmdResult { if let Some(path) = self.get_curr_room_mut().paths_mut().get_mut(name) { if path.is_closed() == Some(true) { CmdResult::new(false, format!("The {} is already closed.", name)) } else { path.close(); CmdResult::new(true, "Closed.".to_owned()) } } else if let Some(item) = self.get_curr_room_mut().items_mut().get_mut(name) { if item.is_closed() == Some(true) { CmdResult::new(false, format!("The {} is already closed.", name)) } else { item.close(); CmdResult::new(true, "Closed.".to_owned()) } } else { CmdResult::new(false, format!("There is no \"{}\".", name)) } } // let an Enemy in the current Room take damage pub fn harm_enemy(&mut self, damage: Option<u32>, enemy_name: &str, weapon: &str) -> CmdResult { if let Some(enemy) = self.get_curr_room_mut().enemies_mut().get_mut(enemy_name) { if let Some(damage) = damage { enemy.get_hit(damage); if enemy.is_alive() { CmdResult::new( true, format!( "You hit the {} with your {} for {} damage.", enemy_name, weapon, damage, ), ) } else { let mut res = format!( "You hit the {} with your {} for {} damage. It is dead.\n", enemy_name, weapon, damage ); if !enemy.loot().is_empty() { res.push_str("It dropped:\n"); for x in enemy.loot().iter() { res.push_str(&format!(" {},", x.1.name())); } } CmdResult::new(true, res) } } else { dont_have(weapon) } } else { CmdResult::new(false, format!("There is no \"{}\" here.", enemy_name)) } } // move an Item out of the current Room pub fn give(&mut self, name: &str) -> Option<Box<Item>> { if let Some(item) = self.get_curr_room_mut().items_mut().remove(name) { Some(item) } else { let similar_name = if let Some(similar_name) = self.get_curr_room_mut().items().keys().find(|k| { k.contains(&format!("{} ", name)) || k.contains(&format!(" {}", name)) }) { similar_name.clone() } else { return None; }; self.get_curr_room_mut() .items_mut() .remove(similar_name.as_str()) } } // take an Item from a container Item in the current Room pub fn give_from( &mut self, player: &mut Player, item_name: &str, container_name: &str, ) -> CmdResult { let is_closed = if let Some(container) = self.get_curr_room().items().get(container_name) { container.is_closed() } else { return dont_have(container_name); }; if is_closed == Some(true) { CmdResult::new(false, format!("The {} is closed.", container_name)) } else if let Some(container) = self.get_curr_room_mut().items_mut().get_mut(container_name) { if let Some(ref mut contents) = container.contents_mut() { if let Some(item) = contents.remove(item_name) { player.take(item_name, Some(item)); CmdResult::new(true, "Taken.".to_owned()) } else { CmdResult::new( false, format!("There is no {} in the {}.", item_name, container_name), ) } } else { CmdResult::new( false, format!("The {} cannot hold anything.", container_name), ) } } else { CmdResult::new(false, format!("There is no {} here.", container_name)) } } pub fn give_all(&mut self) -> ItemMap { self.get_curr_room_mut().items_mut().drain().collect() } // insert an Item into the current Room pub fn insert(&mut self, name: &str, item: Option<Box<Item>>) -> CmdResult { if let Some(obj) = item { self.get_curr_room_mut() .items_mut() .insert(obj.name().to_owned(), obj); CmdResult::new(true, "Dropped.".to_owned()) } else { dont_have(name) } } // insert an Item into a container Item in the current Room pub fn insert_into( &mut self, player: &mut Player, item_name: &str, container_name: &str, ) -> CmdResult { let is_closed = if let Some(container) = self.get_curr_room().items().get(container_name) { container.is_closed() } else { return dont_have(container_name); }; if is_closed == Some(true) { CmdResult::new(false, format!("The {} is closed.", container_name)) } else if let Some(obj) = player.remove(item_name) { if let Some(container) = self.get_curr_room_mut().items_mut().get_mut(container_name) { if let Some(ref mut contents) = container.contents_mut() { contents.insert(obj.name().to_owned(), obj); CmdResult::new(true, "Placed.".to_owned()) } else { CmdResult::new(true, "You can not put anything in there.".to_owned()) } } else { CmdResult::new(false, format!("There is no \"{}\" here.", container_name)) } } else { dont_have(item_name) } } // interact with an Ally pub fn hail(&self, ally_name: &str) -> CmdResult { if let Some(_ally) = self.get_curr_room().allies().get(ally_name) { CmdResult::new(false, "TODO: interact with ally".to_owned()) } else { CmdResult::new(false, format!("There is no \"{}\" here.", ally_name)) } } }
#![allow(unused_variables, dead_code, unreachable_code)] pub mod machine; pub mod xstate; pub type XState<'i, 'h, Id, Context, Event> = xstate::XState<'i, 'h, Id, Context, Event>; pub type Machine<'s, 'i, 'h, Id, Context, Event> = machine::Machine<'s, 'i, 'h, Id, Context, Event>; pub type TaskResult = Result<TaskOutput, TaskError>; pub type InvokeFunction = std::pin::Pin<Box<dyn std::future::Future<Output = TaskResult> + Send + Sync>>; pub type InvokeFunctionProvider<'i, Context, Event> = &'i (dyn Fn(&mut Context, EventReceiver<Event>) -> InvokeFunction + Send + Sync); pub type EventSender<Event> = tokio::sync::mpsc::Sender<Event>; pub type EventReceiver<Event> = tokio::sync::mpsc::Receiver<Event>; pub type EventHandlerFunction<Id, Context, Event> = fn(&mut Context, &Event, &Option<&mut EventSender<Event>>) -> EventHandlerResponse<Id>; pub type EventHandler<'h, Id, Context, Event> = &'h dyn Fn(&mut Context, &Event, &Option<&mut EventSender<Event>>) -> EventHandlerResponse<Id>; pub trait IdType: 'static + std::fmt::Debug + std::default::Default + std::cmp::Eq + std::hash::Hash + Copy {} pub trait EventType: 'static + std::fmt::Debug { fn task_done(res: TaskOutput) -> Self; fn task_error(res: TaskError) -> Self; } pub trait ContextType {} #[derive(Debug)] pub enum TaskOutput { Ok, Aborted, } #[derive(Debug)] pub enum TaskError { } #[derive(Debug)] pub enum EventHandlerResponse<Id: IdType> { Unhandled, DoNothing, TryTransition(Id), }
use crate::ir::{function::*, module::*, opcode::*, types::*, value::*}; use rustc_hash::FxHashMap; #[derive(Debug, Clone, PartialEq)] pub enum ConcreteValue { Void, Int1(bool), Int32(i32), Mem(*mut u8), } #[derive(Debug)] pub struct Interpreter<'a> { module: &'a Module, } impl<'a> Interpreter<'a> { pub fn new(module: &'a Module) -> Self { Self { module } } // TODO: Refactor pub fn run_function(&mut self, id: FunctionId, args: Vec<ConcreteValue>) -> ConcreteValue { let f = self.module.function_ref(id); let mut mem = FxHashMap::default(); fn get_value( val: &Value, args: &[ConcreteValue], mem: &mut FxHashMap<InstructionId, ConcreteValue>, ) -> ConcreteValue { match val { Value::Argument(ArgumentValue { index, .. }) => args[*index].clone(), Value::Instruction(InstructionValue { id, .. }) => mem.get(&id).unwrap().clone(), Value::Immediate(im) => match im { ImmediateValue::Int32(i) => ConcreteValue::Int32(*i), }, Value::Function(_id) => unimplemented!(), Value::None => unimplemented!(), } } let (mut cur_bb_id, mut bb) = f.basic_blocks.iter().next().unwrap(); let mut last_bb_id = cur_bb_id; let ret = 'main: loop { for val in &bb.iseq { let instr_id = val.get_instr_id().unwrap(); let instr = &f.instr_table[instr_id]; match &instr.opcode { Opcode::Add(v1, v2) => { let val = get_value(&v1, &args, &mut mem).add(get_value(&v2, &args, &mut mem)); mem.insert(instr_id, val); } Opcode::Sub(v1, v2) => { let val = get_value(&v1, &args, &mut mem).sub(get_value(&v2, &args, &mut mem)); mem.insert(instr_id, val); } Opcode::Alloca(ty) => { mem.insert( instr_id, ConcreteValue::Mem(match ty { Type::Int1 => Box::into_raw(Box::new(0u8)) as *mut u8, Type::Int32 => Box::into_raw(Box::new(0u32)) as *mut u8, Type::Pointer(_) => unimplemented!(), Type::Void => unreachable!(), Type::Function(_) => unimplemented!(), }), ); } Opcode::ICmp(kind, v1, v2) => { let val = match kind { ICmpKind::Eq => get_value(&v1, &args, &mut mem) .eq(get_value(&v2, &args, &mut mem)), ICmpKind::Le => get_value(&v1, &args, &mut mem) .le(get_value(&v2, &args, &mut mem)), }; mem.insert(instr_id, val); } Opcode::Br(id) => { last_bb_id = cur_bb_id; cur_bb_id = *id; bb = f.basic_block_ref(*id); break; } Opcode::CondBr(cond, bb1, bb2) => { let cond = get_value(&cond, &args, &mut mem).i1_as_bool().unwrap(); bb = f.basic_block_ref({ last_bb_id = cur_bb_id; cur_bb_id = if cond { *bb1 } else { *bb2 }; cur_bb_id }); break; } Opcode::Phi(pairs) => { let val = get_value( &pairs.iter().find(|&(_, bb)| bb == &last_bb_id).unwrap().0, &args, &mut mem, ); mem.insert(instr_id, val); } Opcode::Call(f, f_args) => match f { Value::Function(id) => { let val = self.run_function( *id, f_args .iter() .map(|arg| get_value(&arg, &args, &mut mem)) .collect(), ); if val != ConcreteValue::Void { mem.insert(instr_id, val); } } _ => unimplemented!(), }, Opcode::Load(v) => { let ptr = match get_value(&v, &args, &mut mem) { ConcreteValue::Mem(ptr) => ptr, _ => unreachable!(), }; let val = match v.get_type(&self.module).get_element_ty().unwrap() { Type::Int1 => { ConcreteValue::Int1(if unsafe { *(ptr as *mut u8) } == 0 { false } else { true }) } Type::Int32 => ConcreteValue::Int32(unsafe { *(ptr as *mut i32) }), _ => unimplemented!(), }; mem.insert(instr_id, val); } Opcode::Ret(v) => break 'main get_value(&v, &args, &mut mem), } } }; for (_, cv) in mem { if let ConcreteValue::Mem(m) = cv { unsafe { Box::from_raw(m) }; } } ret } } impl ConcreteValue { pub fn add(self, v: ConcreteValue) -> Self { match (self, v) { (ConcreteValue::Int32(i1), ConcreteValue::Int32(i2)) => ConcreteValue::Int32(i1 + i2), _ => unimplemented!(), } } pub fn sub(self, v: ConcreteValue) -> Self { match (self, v) { (ConcreteValue::Int32(i1), ConcreteValue::Int32(i2)) => ConcreteValue::Int32(i1 - i2), _ => unimplemented!(), } } pub fn eq(self, v: ConcreteValue) -> Self { match (self, v) { (ConcreteValue::Int32(i1), ConcreteValue::Int32(i2)) => ConcreteValue::Int1(i1 == i2), (ConcreteValue::Int1(i1), ConcreteValue::Int1(i2)) => ConcreteValue::Int1(i1 == i2), _ => unimplemented!(), } } pub fn le(self, v: ConcreteValue) -> Self { match (self, v) { (ConcreteValue::Int32(i1), ConcreteValue::Int32(i2)) => ConcreteValue::Int1(i1 <= i2), _ => unimplemented!(), } } pub fn i1_as_bool(self) -> Option<bool> { match self { ConcreteValue::Int1(b) => Some(b), _ => None, } } }
//use crate::rust_decimal::prelude::FromPrimitive; //use crate::rust_decimal::prelude::ToPrimitive; //use crate::rust_decimal::prelude::Zero; //// use common::bitmap::bitmap; // #[test] // fn bitmap() { // //{{{ // /* // use rbtree::RBTree; // let mut m = RBTree::new(); // assert_eq!(m.len(), 0); // m.insert(1, 2); // assert_eq!(m.len(), 1); // m.insert(2, 4); // assert_eq!(m.len(), 2); // assert_eq!(*m.get(&1).unwrap(), 2); // assert_eq!(*m.get(&2).unwrap(), 4); // */ // let mut bt: BTreeMap<i32, i32> = BTreeMap::new(); // bt.insert(1, 2); // bt.insert(4, 5); // } //}}} // #[cfg(test)] // mod tests {}
pub type Result<T> = std::result::Result<T, Error>; #[derive(thiserror::Error, Debug)] pub enum Error { #[error("error parsing socket address: {0}")] AddrParseError(#[from] std::net::AddrParseError), #[error("error during hyper operation: {0}")] HyperError(#[from] hyper::Error), #[error("error during I/O operation: {0}")] IoError(#[from] std::io::Error), #[error("Database server is already the master")] AlreadyMaster, #[error("{0}")] PgCtlError(String), } impl<T> Into<Result<T>> for Error { fn into(self) -> Result<T> { Err(self) } }
use nom::{IResult, InputTakeAtPosition, AsChar, InputIter}; use nom::sequence::tuple; use nom::character::complete::multispace0; use nom::number::complete::{float, le_u8, le_f32, le_u32, be_u8}; use crate::PrimShape::{*}; use std::convert::TryFrom; use nom::error::ErrorKind; use nom::multi::separated_list0; use nom::combinator::opt; use crate::PrimShape::PrimShapes::*; use crate::tuple_kinds::{*}; use nom::bytes::complete::{tag, take_until}; use crate::stack_cntb::Stack; use lazy_static::lazy_static; use std::sync::RwLock; mod PrimShape; mod tuple_kinds; mod stack_cntb; mod date_shape; lazy_static!{ pub static ref INC: RwLock<Stack<char>> = RwLock::new(Stack::new(10)); pub static ref Vect:RwLock<Vec<&str>>=RwLock::new(vec![]); } fn main() { //static mut S:Stack<char> =Stack::new(10); println!("Hello, world!"); let data=r#"PRIM 1 1 4 0.0000000 -0.0007432 -0.0006691 18.0189056 0.0010000 0.0000000 0.0000000 -7.8400001 0.0000000 -0.0006691 0.0007432 74.5573043 -20.65 -20.65 -109.55 20.65 20.65 109.55 20.6499996 20.6499996 219.1017761"#; let (input,out)=tuple_prim(data).unwrap(); } #[test] fn test_CNTB(){ let data="CNTB 1 2 /542966-1/过热器集箱 0.00 0.00 0.00 1"; tuple_CNTB(data).unwrap(); let stack=INC.read().unwrap(); println!("stack={:?}",stack.top); } fn tuple_CNTB(input:&str)->IResult<&str,Vec<&str>>{ let (input,(key,_,x,_,y,_,value,arr,_,z))=tuple(( key, multispace0, float, multispace0, float, multispace0, take_until("\n"), tuple_vector, multispace0, float, ))(input)?; let arr=vec![]; let value=value as &str; let mut stack =INC.write().unwrap(); stack.push('('); println!("vec={:?}",value); Ok((input,arr)) } fn tuple_prim(input:&str)->IResult<&str,(&str,Vec<f32>,Vec<Vec<f32>>)>{ let (input,(key,_,e1,_,e2,_,types,_,x,y,z,e3,e4))=tuple((//(key,_,e1,_,e2,_,types,_,x,y,z,e3,e4,_,e5,_,e6) key, multispace0, float, multispace0, float, multispace0, float, multispace0, tuple_xyz, tuple_xyz, tuple_xyz, tuple_vector, tuple_vector, ))(input)?; println!("key={},e1={},e2={},types={},x={:?},y={:?},z={:?},e3={:?},e4={:?}",key,e1,e2,types,x,y,z,e3,e4); let (input,shapes)=tuple_kind(types,input).unwrap(); println!("PrimShapes={:?}",shapes); let mut arr1=vec![]; let mut arr2=vec![]; arr1.push(e1); arr1.push(e2); arr1.push(types); arr2.push(x); arr2.push(y); arr2.push(z); arr2.push(e3); arr2.push(e4); Ok((input,(key,arr1,arr2))) } fn tuple_kind(types:f32,input:&str)->IResult<&str,PrimShapes>{ match types { 1.0=>{ let (input,pyramid)=tuple_pyramid(input).unwrap(); Ok((input,PyramidShape(pyramid))) }, 2.0=>{ let (input,boxs)=tuple_box(input).unwrap(); Ok((input,BoxShape(boxs))) } 3.0=>{ let (input,rectangularTorus)=tuple_rectangularTorus(input).unwrap(); Ok((input,RectangularTorusShape(rectangularTorus))) } 4.0=>{ let (input,CircularTorus)=tuple_CircularTorus(input).unwrap(); Ok((input,CircularTorusShape(CircularTorus))) } 5.0=>{ let (input,EllipticalDish)=tuple_EllipticalDish(input).unwrap(); Ok((input,EllipticalDishShape(EllipticalDish))) } 6.0=>{ let (input,SphericalDish)=tuple_SphericalDish(input).unwrap(); Ok((input,SphericalDishShape(SphericalDish))) } 7.0=>{ let (input,Snout)=tuple_Snout(input).unwrap(); Ok((input,SnoutShape(Snout))) } 8.0=>{ let (input,Cylinder)=tuple_Cylinder(input).unwrap(); Ok((input,CylinderShape(Cylinder))) } 9.0=>{ let (input,Sphere)=tuple_Sphere(input).unwrap(); Ok((input,SphereShape(Sphere))) } 10.0=>{ let (input,Line)=tuple_Line(input).unwrap(); Ok((input,LineShape(Line))) } _ =>Err(panic!("Problem opening the file")), } } fn tuple_area(input:&str)->IResult<&str,Vec<f32>>{ let (input,(_,x,_,y,_,z))=tuple(( multispace0, float, multispace0, float, multispace0, opt(float), ))(input)?; //println!("out={:?}",out); let mut arr=vec![]; arr.push(x); arr.push(y); match z { Some(x)=>arr.push(x), _=>{}, } Ok((input,arr)) } fn tuple_xyz(input:&str)->IResult<&str,Vec<f32>>{ let (input,(_,x,_,y,_,z,_,v))=tuple(( multispace0, float, multispace0, float, multispace0, float, multispace0, float, ))(input)?; let mut arr=vec![]; arr.push(x); arr.push(y); arr.push(z); arr.push(v); //println!("out={:?}",out); Ok((input,arr)) } fn tuple_vector(input:&str)->IResult<&str,Vec<f32>>{ let (input,(_,x,_,y,_,z))=tuple(( multispace0, float, multispace0, float, multispace0, float, ))(input)?; let mut arr=vec![]; arr.push(x); arr.push(y); arr.push(z); Ok((input,arr)) } #[test] fn test_tuple_pyramid(){ let data=" 20.6499996 219.1017761 219.1017761 219.1017761 219.1017761 219.1017761 219.1017761"; let (input,Pyramid)=tuple_pyramid(data).unwrap(); println!("Pyramid={:?}",Pyramid); } //#[test] // fn test_turn_arr(){ // let arr=vec![20.65f32, 219.10178,219.10178]; // let (input,out)=turn_arr(4f32,arr).unwrap(); // println!("out={:?}",out); // } #[test] fn test_tuple_area(){ let data=r#"20.6499996 219.1017761 219.1017761"#; let (input,out)=tuple_area(data).unwrap(); println!("out={:?}",out); } #[test] fn test_tuple_xyz(){ let data=r#"0.0000000 -0.0007432 -0.0006691 18.0189056"#; let (input,out)=tuple_xyz(data).unwrap(); println!("out={:?}",out); } #[test] fn test_tuple_vector(){ let data=r#" -20.65 -20.65 -109.55"#; let (input,value)=tuple_vector(data).unwrap(); println!("vale={:?}",value); } pub fn key(input:&str) ->IResult<&str,&str>{ input.split_at_position1_complete(|item| !( item.is_alphanum() ||item.as_char()=='_'||item.as_char()=='-' ),ErrorKind::Alpha) } #[test] fn test_tuple_alpha(){ let data="/及 "; let (input,data)=tuple_alpha(data).unwrap(); println!("data={}",data); } fn tuple_alpha(input:&str)->IResult<&str,&str>{ let (input,(x,))=tuple(( take_until(" "), ))(input)?; // println!("out={:?}",out); Ok((input,x)) }
const REPORT_LEN: i64 = 10000000; fn main() { let mut a: f64 = 1.0; let mut b: f64 = 0.0; //println!("Hello, world"); loop { for _i in 0..REPORT_LEN { b += 1.0 / a; a += 1.0; } println!("{}", b); } }
#[doc = "Register `DINR5` reader"] pub type R = crate::R<DINR5_SPEC>; #[doc = "Field `DIN5` reader - Input data received from MDIO Master during write frames"] pub type DIN5_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:15 - Input data received from MDIO Master during write frames"] #[inline(always)] pub fn din5(&self) -> DIN5_R { DIN5_R::new((self.bits & 0xffff) as u16) } } #[doc = "MDIOS input data register 5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dinr5::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DINR5_SPEC; impl crate::RegisterSpec for DINR5_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dinr5::R`](R) reader structure"] impl crate::Readable for DINR5_SPEC {} #[doc = "`reset()` method sets DINR5 to value 0"] impl crate::Resettable for DINR5_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! Tests auto-converted from "sass-spec/spec/libsass-todo-issues/issue_2295/error" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-todo-issues/issue_2295/error/basic.hrx" // Ignoring "basic", error tests are not supported yet. // From "sass-spec/spec/libsass-todo-issues/issue_2295/error/wrapped.hrx" // Ignoring "wrapped", error tests are not supported yet.
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// PagerDutyServiceName : PagerDuty service object name. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PagerDutyServiceName { /// Your service name associated service key in PagerDuty. #[serde(rename = "service_name")] pub service_name: String, } impl PagerDutyServiceName { /// PagerDuty service object name. pub fn new(service_name: String) -> PagerDutyServiceName { PagerDutyServiceName { service_name, } } }
pub fn part_01(data: &str) -> usize { use std::collections::HashSet; data .split_terminator("\n\n") .map(|v| v.replace("\n", "")) .map(|v| v .chars() .collect::<HashSet<char>>().len()) .sum() } pub fn part_02(data: &str) -> usize { use std::collections::HashSet; use std::iter::FromIterator; data .split_terminator("\n\n") .map(|v| v .split_whitespace() .map(|w| w .chars() .collect::<HashSet<char>>()) .fold(HashSet::<char>::from_iter("abcdefghijklmnopqrstuvwxyz".chars()), |init, mate| init .intersection(&mate) .cloned() .collect::<HashSet<_>>())) .map(|v| v.len()) .sum() }
use kappa::Rule; pub fn bind(label: &str) -> Rule { let name = format!("bind | target == {0}", label); rule!( ?name { MACHINE(ip[.], state{bind}, target{?label}), PROG(cm[.], ins[0]), LBL(prog[0], l{?label}) } => { MACHINE(ip[1], state{run}, target{_none}), PROG(cm[1], ins[0]), LBL(prog[0], l{?label}) } @ 1.0 ) } pub fn next() -> Rule { rule!( "move" { MACHINE(ip[0], state{next}), PROG(cm[0], next[1]), PROG(cm[.], prev[1]), } => { MACHINE(ip[0], state{run}), PROG(cm[.], next[1]), PROG(cm[0], prev[1]), } @ 1.0 ) } pub fn reset_units() -> Rule { rule!( "reset_units" { UNIT(prev[.], next[0], r{#}), UNIT(prev[0], r{#}) } => { UNIT(prev[.], next[.], r{_none}), UNIT(prev[.], r{_none}) } @ std::f64::INFINITY ) } pub fn relabel_units(r1: &str, r2: &str) -> Rule { let name = format!("relabel_units | {0} -> {1}", r1, r2); rule!( ?name { UNIT(prev[_], next[0], r{?r1}), UNIT(prev[0], r{?r2}) } => { UNIT(prev[_], next[0], r{?r1}), UNIT(prev[0], r{?r1}) } @ std::f64::INFINITY ) } pub mod instructions { use super::Rule; pub fn add_zerosrc(src: &str, dst: &str) -> Rule { let name = format!("add({0}, {1}) | {0} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[.]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}), } => { MACHINE(ip[0], state{next}, ?src[.]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}), } @ 1.0 ) } pub fn add_zerodst(src: &str, dst: &str) -> Rule { let name = format!("add({0}, {1}) | {1} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[2], ?dst[.]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[2]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), } @ 1.0 ) } pub fn add_nonzero(src: &str, dst: &str) -> Rule { let name = format!("add({0}, {1}) | {0} != 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[2], ?dst[_]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), // Unit linked to %src UNIT(next[.], r{?dst}), // Top unit of %dst stack } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[_]), PROG(cm[0], ins[1]), ADD(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), UNIT(next[2], r{?dst}) } @ 1.0 ) } pub fn clr_zero(reg: &str) -> Rule { let name = format!("clr({0}) | {0} == 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[.]), PROG(cm[0], ins[1]), CLR(prog[1], r{?reg}) } => { MACHINE(ip[0], state{next}, ?reg[.]), PROG(cm[0], ins[1]), CLR(prog[1], r{?reg}) } @ 1.0 ) } pub fn clr_nonzero(reg: &str) -> Rule { let name = format!("clr({0}) | {0} == 1", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[2]), PROG(cm[0], ins[1]), CLR(prog[1], r{?reg}), UNIT(prev[2], r{?reg}), } => { MACHINE(ip[0], state{next}, ?reg[.]), PROG(cm[0], ins[1]), CLR(prog[1], r{?reg}), UNIT(prev[.], r{_none}), } @ 1.0 ) } pub fn dec_zero(reg: &str) -> Rule { let name = format!("dec({0}) | {0} == 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[.]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}) } => { MACHINE(ip[0], state{next}, ?reg[.]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}) } @ 1.0 ) } pub fn dec_one(reg: &str) -> Rule { let name = format!("dec({0}) | {0} == 1", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[2]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}), UNIT(prev[2], next[.], r{?reg}), } => { MACHINE(ip[0], state{next}, ?reg[.]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}), UNIT(prev[.], next[.], r{_none}), } @ 1.0 ) } pub fn dec_more(reg: &str) -> Rule { let name = format!("dec({0}) | {0} >= 2", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[2]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}), UNIT(prev[2], next[3], r{?reg}), UNIT(prev[3]), } => { MACHINE(ip[0], state{next}, ?reg[3]), PROG(cm[0], ins[1]), DEC(prog[1], r{?reg}), UNIT(prev[.], next[.], r{_none}), UNIT(prev[3]), } @ 1.0 ) } pub fn inc_zero(reg: &str) -> Rule { let name = format!("inc({0}) | {0} == 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[.]), PROG(cm[0], ins[1]), INC(prog[1], r{?reg}), UNIT(prev[.], next[.], r{_none}), } => { MACHINE(ip[0], state{next}, ?reg[2]), PROG(cm[0], ins[1]), INC(prog[1], r{?reg}), UNIT(prev[2], next[.], r{?reg}), } @ 1.0 ) } pub fn inc_nonzero(reg: &str) -> Rule { let name = format!("inc({0}) | {0} != 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[2]), PROG(cm[0], ins[1]), INC(prog[1], r{?reg}), UNIT(prev[2]), UNIT(prev[.], next[.], r{_none}), } => { MACHINE(ip[0], state{next}, ?reg[2]), PROG(cm[0], ins[1]), INC(prog[1], r{?reg}), UNIT(prev[3]), UNIT(prev[2], next[3], r{?reg}), } @ 1.0 ) } pub fn jmp(label: &str) -> Rule { let name = format!("jmp({0})", label); rule!( ?name { MACHINE(ip[0], state{run}, target{_none}), PROG(cm[0], ins[1]), JMP(prog[1], l{?label}), } => { MACHINE(ip[.], state{bind}, target{?label}), PROG(cm[.], ins[1]), JMP(prog[1], l{?label}), } @ 1.0 ) } pub fn jnz_nonzero(reg: &str, label: &str) -> Rule { let name = format!("jnz({0}, {1}) | {0} != 0", reg, label); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[_], target{_none}), PROG(cm[0], ins[1]), JNZ(prog[1], r{?reg}, l{?label}), } => { MACHINE(ip[.], state{bind}, ?reg[_], target{?label}), PROG(cm[.], ins[1]), JNZ(prog[1], r{?reg}, l{?label}), } @ 1.0 ) } pub fn jnz_zero(reg: &str) -> Rule { let name = format!("jnz({0}, *) | {0} != 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[.]), PROG(cm[0], ins[1]), JNZ(prog[1], r{?reg}) } => { MACHINE(ip[0], state{next}, ?reg[.]), PROG(cm[0], ins[1]), JNZ(prog[1], r{?reg}) } @ 1.0 ) } pub fn jz_nonzero(reg: &str) -> Rule { let name = format!("jz({0}, *) | {0} != 0", reg); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[_]), PROG(cm[0], ins[1]), JZ(prog[1], r{?reg}), } => { MACHINE(ip[0], state{next}, ?reg[_]), PROG(cm[0], ins[1]), JZ(prog[1], r{?reg}), } @ 1.0 ) } pub fn jz_zero(reg: &str, label: &str) -> Rule { let name = format!("jz({0}, {1}) | {0} == 0", reg, label); rule!( ?name { MACHINE(ip[0], state{run}, ?reg[.], target{_none}), PROG(cm[0], ins[1]), JZ(prog[1], r{?reg}, l{?label}), } => { MACHINE(ip[.], state{bind}, ?reg[.], target{?label}), PROG(cm[.], ins[1]), JZ(prog[1], r{?reg}, l{?label}), } @ 1.0 ) } pub fn lbl() -> Rule { rule!( "label" { MACHINE(ip[0], state{run}), PROG(cm[0], ins[1]), LBL(prog[1]) } => { MACHINE(ip[0], state{next}), PROG(cm[0], ins[1]), LBL(prog[1]) } @ 1.0 ) } pub fn mov_zero(src: &str, dst: &str) -> Rule { let name = format!("mov({0}, {1}) | {0} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[.], ?dst[#]), PROG(cm[0], ins[1]), MOV(prog[1], src{?src}, dst{?dst}), } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[.]), PROG(cm[0], ins[1]), MOV(prog[1], src{?src}, dst{?dst}), } @ 1.0 ) } pub fn mov_nonzero(src: &str, dst: &str) -> Rule { let name = format!("mov({0}, {1}) | {0} != 0, {1} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[2], ?dst[#]), PROG(cm[0], ins[1]), MOV(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[2]), PROG(cm[0], ins[1]), MOV(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), } @ 1.0 ) } pub fn swp_zero(src: &str, dst: &str) -> Rule { let name = format!("swp({0}, {1}) | {0} == {1} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[.], ?dst[.]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[.]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), } @ 1.0 ) } pub fn swp_zerosrc(src: &str, dst: &str) -> Rule { let name = format!("swp({0}, {1}) | {0} == 0, {1} != 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[.], ?dst[2]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), } => { MACHINE(ip[0], state{next}, ?src[2], ?dst[.]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), } @ 1.0 ) } pub fn swp_zerodst(src: &str, dst: &str) -> Rule { let name = format!("swp({0}, {1}) | {1} == 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[2], ?dst[.]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), } => { MACHINE(ip[0], state{next}, ?src[.], ?dst[2]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), } @ 1.0 ) } pub fn swp_nonzero(src: &str, dst: &str) -> Rule { let name = format!("swp({0}, {1}) | {0} != 0, {1} != 0", src, dst); rule!( ?name { MACHINE(ip[0], state{run}, ?src[2], ?dst[3]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?src}), UNIT(prev[3], r{?dst}), } => { MACHINE(ip[0], state{next}, ?src[3], ?dst[2]), PROG(cm[0], ins[1]), SWP(prog[1], src{?src}, dst{?dst}), UNIT(prev[2], r{?dst}), UNIT(prev[3], r{?src}), } @ 1.0 ) } }
pub mod alternative; pub mod issue; pub mod session; pub mod user; pub mod vote; use actix::prelude::*; use sqlx::{ postgres::{PgConnectOptions, PgPoolOptions}, PgPool, }; #[derive(Debug)] pub struct DbExecutor(pub PgPool); impl DbExecutor { pub fn pool(&mut self) -> PgPool { self.0.clone() } } impl Actor for DbExecutor { type Context = Context<Self>; } impl Default for DbExecutor { fn default() -> Self { unimplemented!("DbExecutor cannot automatically be started"); } } impl SystemService for DbExecutor {} impl Supervised for DbExecutor {} pub async fn new_pool(database_url: &str) -> Result<PgPool, sqlx::Error> { new_pool_with(database_url.parse()?).await } pub async fn new_pool_with(connect_options: PgConnectOptions) -> Result<PgPool, sqlx::Error> { PgPoolOptions::new() .max_connections(5 as u32) .connect_with(connect_options) .await }
use crate::material::Material; use crate::types::{Face, MeshVertex, Vertex}; unzip_n::unzip_n!(4); #[derive(Debug)] pub struct Mesh { pub faces: Vec<[u32; 3]>, pub positions: Vec<[f32; 3]>, pub uvs: Option<Vec<[f32; 2]>>, pub normals: Option<Vec<[f32; 3]>>, pub tangents: Option<Vec<[f32; 3]>>, pub material: Option<Material>, pub name: Option<String>, } impl Default for Mesh { fn default() -> Self { Self { faces: Vec::new(), positions: Vec::new(), uvs: None, normals: None, tangents: None, material: None, name: None, } } } impl Mesh { /// Calculates the tangent vectors based on the texture coordinates /// and positions of the three vertices that make up a face. A vertex could /// be part of multiple faces (i.e., has multiple tangents), so we take /// average of those faces by first keeping track of the tangent sum and /// count of every vertex, and finally divide the sum by the count to /// get the average. /// /// Maths: https://learnopengl.com/Advanced-Lighting/Normal-Mapping pub fn calculate_tangents(&mut self) { let mut countsum = Vec::with_capacity(self.positions.len()); countsum.resize(self.positions.len(), (0, na::Vector3::<f32>::zeros())); let uvs = self .uvs .as_ref() .expect("[ERROR] To calculate tangents the mesh must contain texture coordinates."); // Finding sums and count for [i1, i2, i3] in self.faces.iter() { let uv1: na::Vector2<f32> = uvs[*i1 as usize].into(); let uv2: na::Vector2<f32> = uvs[*i2 as usize].into(); let uv3: na::Vector2<f32> = uvs[*i3 as usize].into(); let pos1: na::Vector3<f32> = self.positions[*i1 as usize].into(); let pos2: na::Vector3<f32> = self.positions[*i2 as usize].into(); let pos3: na::Vector3<f32> = self.positions[*i3 as usize].into(); let duv1 = uv2 - uv1; let duv2 = uv3 - uv1; let e1 = pos2 - pos1; let e2 = pos3 - pos1; let e = na::Matrix2x3::from_rows(&[e1.transpose(), e2.transpose()]); let d = na::Matrix2::new(duv2.y, -duv1.y, -duv2.x, duv1.x); let fac = duv1.x * duv2.y - duv2.x * duv1.y; let tb = 1. / fac * d * e; let t = tb.row(0).transpose(); countsum[*i1 as usize].1 += t; countsum[*i1 as usize].0 += 1; countsum[*i2 as usize].1 += t; countsum[*i2 as usize].0 += 1; countsum[*i3 as usize].1 += t; countsum[*i3 as usize].0 += 1; } // Averaging self.tangents = Some( countsum .iter() .map(|(n, sum)| (sum / *n as f32).into()) .collect::<Vec<[f32; 3]>>(), ); println!("{:#?}", self.tangents); } /// Creates a vertex and index buffer, ready for rendering pub fn render_data<F, V>(&self, vgen: F) -> (Vec<V>, Vec<[u32; 3]>) where F: Fn(MeshVertex) -> V, { let mut vertices = Vec::with_capacity(self.positions.len()); for i in 0..self.positions.len() { let v = MeshVertex { position: self.positions[i], normal: if let Some(n) = &self.normals { Some(n[i]) } else { None }, tangent: if let Some(n) = &self.tangents { Some(n[i]) } else { None }, uv: if let Some(n) = &self.uvs { Some(n[i]) } else { None }, }; let v = vgen(v); vertices.push(v); } (vertices, self.faces.clone()) } } impl From<(Vec<Vertex>, Vec<Face>)> for Mesh { fn from((vs, fs): (Vec<Vertex>, Vec<Face>)) -> Self { let (positions, normals, uvs, tangents) = vs .iter() .map(|v| (v.position, v.normal, v.uv, v.tangent)) .unzip_n(); Mesh { faces: fs, positions, uvs: Some(uvs), normals: Some(normals), tangents: Some(tangents), material: None, name: None, } } }