text
stringlengths
8
4.13M
use crate::storepaths::StorePaths; use crate::{Opt, STORE}; use atty::{self, Stream}; use colored::{self, ColoredString, Colorize}; use env_logger::Builder; use log::{Level, LevelFilter}; use std::io; use std::io::prelude::*; use std::path::Path; use std::time::Duration; #[derive(Debug, Clone, PartialEq)] pub struct Output { pub level: LevelFilter, pub oneline: bool, pub color: bool, pub list: bool, } impl Default for Output { fn default() -> Self { Output { level: LevelFilter::Off, oneline: false, color: false, list: false, } } } impl Output { pub fn new(verbose: bool, debug: bool, oneline: bool, color: &str, list: bool) -> Output { Output { level: match (verbose, debug) { (_, true) => LevelFilter::Debug, (true, _) => LevelFilter::Info, _ => LevelFilter::Warn, }, color: match color { "always" => true, "never" => false, _ => atty::is(Stream::Stdout) && atty::is(Stream::Stderr), }, oneline, list, } } /// Sets up logging with colored output if requested. pub fn log_init(&self) { colored::control::set_override(self.color); Builder::new() .format(|buf, r| match r.level() { Level::Error => { writeln!(buf, "{}: {}", r.level().to_string().red().bold(), r.args()) } Level::Warn => writeln!(buf, "{}: {}", r.level().to_string().yellow(), r.args()), Level::Info => writeln!(buf, "{}", r.args()), _ => writeln!(buf, "{}", r.args().to_string().blue()), }) .filter(None, self.level) .init(); } /// Outputs the name of a scanned file together with the store paths found inside. /// /// Depending on the desired output format the files are either space- or newline-separated. pub fn write_store_paths(&self, w: &mut dyn Write, sp: &StorePaths) -> io::Result<()> { let filename = format!( "{}{}", sp.path().display(), if self.oneline { ":" } else { "" } ); write!(w, "{}", filename.purple().bold())?; let sep = if self.oneline { " " } else { "\n" }; for r in sp.iter_refs() { write!(w, "{}{}{}", sep, STORE, r.display())? } writeln!(w, "{}", if self.oneline { "" } else { "\n" }) } #[inline] pub fn print_store_paths(&self, sp: &StorePaths) { if !self.list { return; } let w = io::stdout(); let mut w = io::BufWriter::new(w.lock()); self.write_store_paths(&mut w, sp).ok(); } } impl<'a> From<&'a Opt> for Output { fn from(opt: &'a Opt) -> Self { Output::new(opt.verbose, opt.debug, opt.oneline, &opt.color, opt.list) } } /// Path to String with coloring pub fn p2s<P: AsRef<Path>>(path: P) -> ColoredString { path.as_ref().display().to_string().green() } /// Duration to seconds /// /// Converts a `time::Duration` value into a floating-point seconds value. pub fn d2s(d: Duration) -> f32 { d.as_secs() as f32 + (d.subsec_nanos() as f32) / 1e9 } #[cfg(test)] mod tests { use super::*; #[test] fn color_default_argument() { let o = Output::new(false, false, false, "never", false); assert!(!o.color); let o = Output::new(false, false, false, "always", false); assert!(o.color); } }
use std::cell::{Cell, RefCell}; use std::collections::HashSet; use std::mem; use std::ptr::null_mut; use bincode; use flate2; use libc::c_void; use bw; use save::{fread_num, fread, fwrite, fwrite_num, SaveError, LoadError, print_text}; use save::{SaveMapping, LoadMapping}; use send_pointer::SendPtr; use units::{unit_to_id, unit_from_id}; const SPRITE_LIMIT: usize = 200000; const IMAGE_LIMIT: usize = 400000; ome2_thread_local! { SPRITE_ARRAY: RefCell<RawVec<bw::Sprite>> = sprite_array(RefCell::new(RawVec::with_capacity(SPRITE_LIMIT))); IMAGE_ARRAY: RefCell<RawVec<bw::Image>> = image_array(RefCell::new(RawVec::with_capacity(IMAGE_LIMIT))); SPRITES: RefCell<HashSet<SendPtr<bw::Sprite>>> = all_sprites(RefCell::new(HashSet::new())); // Both lone and fow LONE_SPRITES: RefCell<HashSet<SendPtr<bw::LoneSprite>>> = all_lone_sprites(RefCell::new(HashSet::new())); NEXT_SPRITE_ID: Cell<u64> = next_sprite_id(Cell::new(0)); SPRITE_DRAW_BUFFER: RefCell<Vec<SendPtr<bw::Sprite>>> = sprite_draw_buffer(RefCell::new(Vec::with_capacity(0x800))); SPRITE_SAVE_MAPPING: RefCell<SaveMapping<bw::Sprite>> = sprite_save_mapping(RefCell::new(SaveMapping::new())); SPRITE_LOAD_MAPPING: RefCell<LoadMapping<bw::Sprite>> = sprite_load_mapping(RefCell::new(LoadMapping::new())); LONE_SPRITE_SAVE_MAPPING: RefCell<SaveMapping<bw::LoneSprite>> = lone_sprite_save_mapping(RefCell::new(SaveMapping::new())); LONE_SPRITE_LOAD_MAPPING: RefCell<LoadMapping<bw::LoneSprite>> = lone_sprite_load_mapping(RefCell::new(LoadMapping::new())); } struct RawVec<T> { ptr: *mut T, size: usize, capacity: usize, } unsafe impl<T> Send for RawVec<T> {} unsafe impl<T> Sync for RawVec<T> {} impl<T> RawVec<T> { fn with_capacity(cap: usize) -> RawVec<T> { let (ptr, size, capacity) = Vec::with_capacity(cap).into_raw_parts(); RawVec { ptr, size, capacity, } } fn push(&mut self) -> *mut T { unsafe { if self.size == self.capacity { null_mut() } else { self.size += 1; self.ptr.add(self.size - 1) } } } fn iter(&self) -> impl Iterator<Item = *mut T> { unsafe { let ptr = self.ptr; (0..self.size).map(move |x| ptr.add(x)) } } } const SPRITE_SAVE_MAGIC: u16 = 0xffee; // 16 megabytes, should be more than enough, both compressed and without. const SPRITE_SAVE_MAX_SIZE: u32 = 0x1000000; #[derive(Serialize, Deserialize)] struct SaveGlobals { horizontal_lines: Vec<(u32, u32)>, sprite_count: u32, lone_count: u32, fow_count: u32, cursor_marker: u32, } #[derive(Serialize, Deserialize)] struct SpriteSerializable { prev: u32, next: u32, sprite_id: u16, player: u8, selection_index: u8, visibility_mask: u8, elevation: u8, flags: u8, selection_flash_timer: u8, index: u16, width: u8, height: u8, position: bw::Point, main_image_id: u32, images: Vec<ImageSerializable>, extra: bw::SpriteExtension, } #[derive(Serialize, Deserialize)] struct ImageSerializable { offset: usize, image_id: u16, drawfunc: u8, direction: u8, flags: u16, x_offset: i8, y_offset: i8, iscript: bw::Iscript, frameset: u16, frame: u16, map_position: bw::Point, screen_position: [i16; 2], grp_bounds: [i16; 4], grp: u16, drawfunc_param: u32, } #[derive(Serialize, Deserialize)] struct LoneSpriteSerializable { sprite: u32, value: u32, } fn allocate_sprite() -> *mut bw::Sprite { let mut sprites = sprite_array().borrow_mut(); sprites.push() } fn allocate_image() -> *mut bw::Image { let mut array = image_array().borrow_mut(); array.push() } unsafe fn refill_sprite_image_list() { let mut sprites = all_sprites().borrow_mut(); if sprites.len() == 0 { // Init *bw::first_free_sprite = null_mut(); *bw::last_free_sprite = null_mut(); *bw::first_free_image = null_mut(); *bw::last_free_image = null_mut(); } let sprite_count = BwLinkedListIter(*bw::first_free_sprite).count(); if sprite_count < 500 { for _ in 0..(500 - sprite_count) { let sprite = allocate_sprite(); if sprite.is_null() { break; } *sprite = bw::Sprite { next: *bw::first_free_sprite, ..mem::zeroed() }; if *bw::first_free_sprite != null_mut() { (**bw::first_free_sprite).prev = sprite; } else { *bw::last_free_sprite = sprite; } *bw::first_free_sprite = sprite; sprites.insert(sprite.into()); } } let image_count = BwLinkedListIter(*bw::first_free_image).count(); if image_count < 1500 { for _ in 0..(1500 - image_count) { let image = allocate_image(); if image.is_null() { break; } *image = bw::Image { next: *bw::first_free_image, ..mem::zeroed() }; if *bw::first_free_image != null_mut() { (**bw::first_free_image).prev = image; } else { *bw::last_free_image = image; } *bw::first_free_image = image; } } } pub unsafe fn create_sprite( sprite_id: u32, x: u32, y: u32, player: u32, orig: unsafe extern fn(u32, u32, u32, u32) -> *mut bw::Sprite, ) -> *mut bw::Sprite { if *bw::scmain_state != 3 { // Lobby minimap preview, since this plugin doesn't reset sprites aren // on game init (only end), but BW does, calling the hook is problematic in lobby. return orig(sprite_id, x, y, player); } refill_sprite_image_list(); let actual_sprite = orig(sprite_id, x, y, player); if actual_sprite != null_mut() { let cell = next_sprite_id(); (*actual_sprite).extra.spawn_order = (cell.get() as u32, (cell.get() >> 32) as u32); cell.set(cell.get().checked_add(1).unwrap()); } actual_sprite } pub unsafe fn create_lone( sprite_id: u32, x: u32, y: u32, player: u32, orig: unsafe extern fn(u32, u32, u32, u32) -> *mut bw::LoneSprite, ) -> *mut bw::LoneSprite { let sprite = Box::new(bw::LoneSprite { ..mem::zeroed() }); let sprite = Box::into_raw(sprite); *bw::first_free_lone_sprite = sprite; *bw::last_free_lone_sprite = sprite; let actual_sprite = orig(sprite_id, x, y, player); *bw::first_free_lone_sprite = null_mut(); *bw::last_free_lone_sprite = null_mut(); if actual_sprite == null_mut() { info!( "Couldn't create lone sprite {:x} at {:x}.{:x}", sprite_id, x, y); let _ = Box::from_raw(sprite); return null_mut(); } else if actual_sprite != sprite { error!( "Created a different lone sprite from what was expected: {:p} {:p}", sprite, actual_sprite, ); } let mut sprites = all_lone_sprites().borrow_mut(); sprites.insert(sprite.into()); sprite } pub unsafe fn create_fow( unit_id: u32, base: *mut bw::Sprite, orig: unsafe extern fn(u32, *mut bw::Sprite) -> *mut bw::LoneSprite, ) -> *mut bw::LoneSprite { let sprite = Box::new(bw::LoneSprite { ..mem::zeroed() }); let sprite = Box::into_raw(sprite); *bw::first_free_fow_sprite = sprite; *bw::last_free_fow_sprite = sprite; let actual_sprite = orig(unit_id, base); *bw::first_free_fow_sprite = null_mut(); *bw::last_free_fow_sprite = null_mut(); if actual_sprite == null_mut() { info!("Couldn't create fow sprite {:x}", unit_id); let _ = Box::from_raw(sprite); return null_mut(); } else if actual_sprite != sprite { error!( "Created a different fow sprite from what was expected: {:p} {:p}", sprite, actual_sprite, ); } let mut sprites = all_lone_sprites().borrow_mut(); sprites.insert(sprite.into()); sprite } pub unsafe fn delete_sprite(sprite: *mut bw::Sprite, orig: unsafe extern fn(*mut bw::Sprite)) { orig(sprite); } pub unsafe fn step_lone_frame( sprite: *mut bw::LoneSprite, orig: unsafe extern fn(*mut bw::LoneSprite), ) { *bw::first_free_lone_sprite = null_mut(); *bw::last_free_lone_sprite = null_mut(); orig(sprite); if *bw::first_free_lone_sprite == sprite { let _ = Box::from_raw(sprite); let mut sprites = all_lone_sprites().borrow_mut(); sprites.remove(&sprite.into()); } *bw::first_free_lone_sprite = null_mut(); *bw::last_free_lone_sprite = null_mut(); } pub unsafe fn step_fow_frame( sprite: *mut bw::LoneSprite, orig: unsafe extern fn(*mut bw::LoneSprite), ) { *bw::first_free_fow_sprite = null_mut(); *bw::last_free_fow_sprite = null_mut(); orig(sprite); if *bw::first_free_fow_sprite == sprite { let _ = Box::from_raw(sprite); let mut sprites = all_lone_sprites().borrow_mut(); sprites.remove(&sprite.into()); } *bw::first_free_fow_sprite = null_mut(); *bw::last_free_fow_sprite = null_mut(); } pub unsafe fn create_image(orig: unsafe extern fn() -> *mut bw::Image) -> *mut bw::Image { orig() } pub unsafe fn delete_image(image: *mut bw::Image, orig: unsafe extern fn(*mut bw::Image)) { orig(image); } pub unsafe fn delete_all() { let mut sprites = all_sprites().borrow_mut(); sprites.clear(); sprite_array().borrow_mut().size = 0; image_array().borrow_mut().size = 0; } unsafe fn is_selection_image(image: *mut bw::Image) -> bool { ((*image).image_id >= 0x231 && (*image).image_id <= 0x23a) || (*image).drawfunc == 0xb } pub unsafe fn add_to_drawn_sprites(sprite: *mut bw::Sprite) { let mut buf = sprite_draw_buffer().borrow_mut(); buf.push(sprite.into()); sprite_vision_sync(sprite); } unsafe fn sprite_vision_sync(sprite: *mut bw::Sprite) { use std::cmp::{max, min}; let sync = *(*bw::sprite_include_in_vision_sync).offset((*sprite).sprite_id as isize); if sync != 0 { let y_tile = min(max((*sprite).position.y / 32, 0), *bw::map_height_tiles as i16); bw::sync_horizontal_lines[y_tile as usize] ^= *bw::player_visions as u8; } } pub unsafe fn draw_sprites() { let mut buf = sprite_draw_buffer().borrow_mut(); buf.sort_by(|&SendPtr(a), &SendPtr(b)| { use std::cmp::Ordering; match (*a).elevation.cmp(&(*b).elevation) { Ordering::Equal => (), x => return x, } // Ground units are sorted by y position if (*a).elevation <= 4 { match (*a).position.y.cmp(&(*b).position.y) { Ordering::Equal => (), x => return x, } } match ((*a).flags & 0x10).cmp(&((*b).flags & 0x10)) { Ordering::Equal => (), x => return x, } (*a).extra.spawn_order.cmp(&(*b).extra.spawn_order) }); for &SendPtr(sprite) in buf.iter() { bw::draw_sprite(sprite); } } pub unsafe fn redraw_screen_hook(orig: unsafe extern fn()) { orig(); // The buffer may be filled but not used if the screen doesn't need to be redrawn. let mut buf = sprite_draw_buffer().borrow_mut(); buf.clear(); } pub unsafe fn save_sprite_chunk(file: *mut c_void) -> u32 { if let Err(e) = save_sprites(file) { error!("Couldn't save sprites: {}", e); print_text(&format!("Unable to save the game: {}", e)); return 0; } 1 } unsafe fn save_sprites(file: *mut c_void) -> Result<(), SaveError> { let data = serialize_sprites()?; fwrite_num(file, SPRITE_SAVE_MAGIC)?; fwrite_num(file, 1u32)?; fwrite_num(file, data.len() as u32)?; fwrite(file, &data)?; Ok(()) } unsafe fn serialize_sprites() -> Result<Vec<u8>, SaveError> { let ptr_to_id_map = sprite_pointer_to_id_map(); let lone_ptr_to_id_map = lone_sprite_pointer_to_id_map(); let buf = Vec::with_capacity(0x10000); let mut writer = flate2::write::DeflateEncoder::new(buf, flate2::Compression::Default); let size_limit = bincode::Bounded(SPRITE_SAVE_MAX_SIZE as u64); let horizontal_lines = (0..*bw::map_height_tiles as usize).map(|i| { Ok((ptr_to_id_map.id(bw::horizontal_sprite_lines_begin[i])?, ptr_to_id_map.id(bw::horizontal_sprite_lines_end[i])?)) }).collect::<Result<Vec<_>, SaveError>>()?; let globals = SaveGlobals { horizontal_lines, sprite_count: ptr_to_id_map.len() as u32, lone_count: lone_ptr_to_id_map.len() as u32, fow_count: lone_sprites(*bw::first_active_fow_sprite).count() as u32, cursor_marker: lone_ptr_to_id_map.id(*bw::cursor_marker)?, }; bincode::serialize_into(&mut writer, &globals, size_limit)?; { let sprites = sprite_array().borrow_mut(); for sprite in sprites.iter() { let serializable = sprite_serializable(sprite, &ptr_to_id_map)?; bincode::serialize_into(&mut writer, &serializable, size_limit)?; if writer.total_in() > SPRITE_SAVE_MAX_SIZE as u64 { return Err(SaveError::SizeLimit(writer.total_in())); } } } for sprite in lone_sprites(*bw::first_active_lone_sprite) { let serializable = lone_sprite_serializable(sprite, &ptr_to_id_map)?; bincode::serialize_into(&mut writer, &serializable, size_limit)?; if writer.total_in() > SPRITE_SAVE_MAX_SIZE as u64 { return Err(SaveError::SizeLimit(writer.total_in())); } } for sprite in lone_sprites(*bw::first_active_fow_sprite) { let serializable = lone_sprite_serializable(sprite, &ptr_to_id_map)?; bincode::serialize_into(&mut writer, &serializable, size_limit)?; if writer.total_in() > SPRITE_SAVE_MAX_SIZE as u64 { return Err(SaveError::SizeLimit(writer.total_in())); } } let mut global_mapping = sprite_save_mapping().borrow_mut(); *global_mapping = ptr_to_id_map; let mut lone_global = lone_sprite_save_mapping().borrow_mut(); *lone_global = lone_ptr_to_id_map; Ok(writer.finish()?) } unsafe fn sprite_pointer_to_id_map() -> SaveMapping<bw::Sprite> { let sprites = sprite_array().borrow_mut(); sprites.iter().enumerate().map(|(x, y)| (y.into(), x as u32 + 1)).collect() } unsafe fn lone_sprites(ptr: *mut bw::LoneSprite) -> BwLinkedListIter<bw::LoneSprite> { BwLinkedListIter(ptr) } struct BwLinkedListIter<T: BwLinkedListObject>(*mut T); trait BwLinkedListObject { unsafe fn next(val: *mut Self) -> *mut Self; } impl BwLinkedListObject for bw::Sprite { unsafe fn next(val: *mut bw::Sprite) -> *mut bw::Sprite { (*val).next } } impl BwLinkedListObject for bw::LoneSprite { unsafe fn next(val: *mut bw::LoneSprite) -> *mut bw::LoneSprite { (*val).next } } impl BwLinkedListObject for bw::Image { unsafe fn next(val: *mut bw::Image) -> *mut bw::Image { (*val).next } } impl<T: BwLinkedListObject> Iterator for BwLinkedListIter<T> { type Item = *mut T; fn next(&mut self) -> Option<*mut T> { unsafe { let val = self.0; if val != null_mut() { self.0 = T::next(val); Some(val) } else { None } } } } unsafe fn lone_sprite_pointer_to_id_map() -> SaveMapping<bw::LoneSprite> { lone_sprites(*bw::first_active_lone_sprite) .enumerate() .map(|(x, y)| (y.into(), x as u32 + 1)) .collect() } pub fn sprite_to_id_current_mapping(sprite: *mut bw::Sprite) -> Result<u32, SaveError> { let mapping = sprite_save_mapping().borrow(); mapping.id(sprite) } pub fn sprite_from_id_current_mapping(id: u32) -> Result<*mut bw::Sprite, LoadError> { let mapping = sprite_load_mapping().borrow(); mapping.pointer(id) } pub fn lone_sprite_to_id_current_mapping(sprite: *mut bw::LoneSprite) -> Result<u32, SaveError> { let mapping = lone_sprite_save_mapping().borrow(); mapping.id(sprite) } pub fn lone_sprite_from_id_current_mapping(id: u32) -> Result<*mut bw::LoneSprite, LoadError> { let mapping = lone_sprite_load_mapping().borrow(); mapping.pointer(id) } unsafe fn sprite_serializable( sprite: *const bw::Sprite, mapping: &SaveMapping<bw::Sprite>, ) -> Result<SpriteSerializable, SaveError> { let bw::Sprite { prev, next, sprite_id, player, selection_index, visibility_mask, elevation, flags, selection_flash_timer, index, width, height, position, main_image, first_overlay, last_overlay: _, extra, } = *sprite; let (images, main_image_id) = images_serializable(first_overlay, main_image)?; Ok(SpriteSerializable { prev: mapping.id(prev)?, next: mapping.id(next)?, sprite_id, player, selection_index, visibility_mask, elevation, // Selection overlays are not saved flags: flags & !(0x1 | 0x8), selection_flash_timer, index, width, height, position, images, main_image_id, extra, }) } unsafe fn images_serializable( first: *mut bw::Image, main_image: *mut bw::Image ) -> Result<(Vec<ImageSerializable>, u32), SaveError> { let mut out = Vec::new(); let mut main_index = 0; let mut image = first; // It's possible for the main image to be unreachable and dead value. let mut index = 0; while image != null_mut() { if !is_selection_image(image) { index += 1; let bw::Image { prev: _, next: _, image_id, drawfunc, direction, flags, x_offset, y_offset, iscript, frameset, frame, map_position, screen_position, grp_bounds, grp, drawfunc_param, draw: _, step_frame: _, parent: _, } = *image; if image == main_image { main_index = index; } let offset = image as usize - image_array().borrow().ptr as usize; out.push(ImageSerializable { offset, image_id, drawfunc, direction, flags, x_offset, y_offset, iscript, frameset, frame, map_position, screen_position, grp_bounds, grp: grp_to_id(grp)?, drawfunc_param: drawfunc_param_serializable(drawfunc, drawfunc_param)?, }); } image = (*image).next; } Ok((out, main_index)) } unsafe fn lone_sprite_serializable( sprite: *const bw::LoneSprite, mapping: &SaveMapping<bw::Sprite> ) -> Result<LoneSpriteSerializable, SaveError> { Ok(LoneSpriteSerializable { sprite: mapping.id((*sprite).sprite)?, value: (*sprite).value, }) } unsafe fn grp_to_id(grp: *mut bw::GrpSprite) -> Result<u16, SaveError> { if grp == null_mut() { Ok(0) } else { (0..image_count()).position(|i| *(*bw::image_grps).offset(i as isize) == grp) .map(|x| x as u16 + 1) .ok_or(SaveError::InvalidGrpPointer) } } unsafe fn image_count() -> u32 { (*bw::image_count_part1).checked_add(*bw::image_count_part2).unwrap() } unsafe fn grp_from_id(grp: u16) -> Result<*mut bw::GrpSprite, LoadError> { if grp == 0 { Ok(null_mut()) } else if grp as u32 - 1 < image_count() { Ok(*(*bw::image_grps).offset(grp as isize - 1)) } else { Err(LoadError::Corrupted(format!("Invalid grp {}", grp))) } } unsafe fn drawfunc_param_serializable(func: u8, param: *mut c_void) -> Result<u32, SaveError> { match func { 0x9 => { let param = param as *const u8; bw::remap_palettes.iter() .position(|palette| palette.data == param) .map(|x| x as u32 + 1) .ok_or(SaveError::InvalidRemapPalette) } 0xb => Ok(unit_to_id(param as *mut bw::Unit) as u32), _ => Ok(param as u32), } } unsafe fn deserialize_drawfunc_param(func: u8, param: u32) -> Result<*mut c_void, LoadError> { match func { 0x9 => { if param == 0 { Ok(null_mut()) } else if param as usize - 1 < bw::remap_palettes.len() { let pointer = bw::remap_palettes[param as usize - 1].data; Ok(pointer as *mut c_void) } else { Err(LoadError::Corrupted(format!("Invalid remap palette {}", param))) } } 0xb => Ok(unit_from_id(param as u16)? as *mut c_void), _ => Ok(param as *mut c_void), } } pub unsafe fn load_sprite_chunk(file: *mut c_void) -> u32 { if let Err(e) = load_sprites(file) { info!("Couldn't load a save: {}", e); return 0; } 1 } unsafe fn load_sprites(file: *mut c_void) -> Result<(), LoadError> { let magic = fread_num::<u16>(file)?; if magic != SPRITE_SAVE_MAGIC { return Err(LoadError::WrongMagic(magic)); } let version = fread_num::<u32>(file)?; if version != 1 { return Err(LoadError::Version(version)); } let size = fread_num::<u32>(file)?; if size > SPRITE_SAVE_MAX_SIZE { return Err(LoadError::Corrupted(format!("Sprite chunk size {} is too large", size))); } let data = fread(file, size)?; let mut reader = flate2::read::DeflateDecoder::new(&data[..]); let size_limit = bincode::Bounded(SPRITE_SAVE_MAX_SIZE as u64); let globals: SaveGlobals = bincode::deserialize_from(&mut reader, size_limit)?; let mapping; let lone_mapping; let mut lone_sprites; { let mut sprites = sprite_array().borrow_mut(); let mut images = image_array().borrow_mut(); mapping = allocate_sprites(&mut sprites, globals.sprite_count); let (lone_sprites_, lone_mapping_) = allocate_lone_sprites(globals.lone_count + globals.fow_count); lone_sprites = lone_sprites_; lone_mapping = lone_mapping_; for sprite_result in sprites.iter() { let serialized = bincode::deserialize_from(&mut reader, size_limit)?; let sprite = deserialize_sprite(&serialized, &mapping, sprite_result, &mut images)?; *sprite_result = sprite; if reader.total_out() > SPRITE_SAVE_MAX_SIZE as u64 { return Err(LoadError::SizeLimit) } } for lone_sprite_result in &mut lone_sprites { let serialized = bincode::deserialize_from(&mut reader, size_limit)?; let sprite = deserialize_lone_sprite(&serialized, &mapping)?; **lone_sprite_result = sprite; if reader.total_out() > SPRITE_SAVE_MAX_SIZE as u64 { return Err(LoadError::SizeLimit) } } for i in 0..lone_sprites.len() { if i != 0 && i != globals.lone_count as usize { lone_sprites[i - 1].next = &mut *lone_sprites[i]; } if i != globals.lone_count as usize - 1 && i != lone_sprites.len() - 1 { lone_sprites[i + 1].prev = &mut *lone_sprites[i]; } } let mut sprite_set = all_sprites().borrow_mut(); for sprite in sprites.iter() { sprite_set.insert(SendPtr(sprite)); } } *bw::first_free_sprite = null_mut(); *bw::last_free_sprite = null_mut(); *bw::first_free_image = null_mut(); *bw::last_free_image = null_mut(); *bw::first_active_lone_sprite = match globals.lone_count { 0 => null_mut(), _ => &mut *lone_sprites[0], }; *bw::last_active_lone_sprite = match globals.lone_count { 0 => null_mut(), _ => &mut *lone_sprites[globals.lone_count as usize - 1], }; *bw::first_active_fow_sprite = match globals.fow_count { 0 => null_mut(), _ => &mut *lone_sprites[globals.lone_count as usize], }; *bw::last_active_fow_sprite = match globals.fow_count { 0 => null_mut(), _ => &mut **lone_sprites.last_mut().unwrap(), }; { let mut lone_sprite_set = all_lone_sprites().borrow_mut(); for sprite in lone_sprites { lone_sprite_set.insert(Box::into_raw(sprite).into()); } } for (i, (begin, end)) in globals.horizontal_lines.into_iter().enumerate() { bw::horizontal_sprite_lines_begin[i] = mapping.pointer(begin)?; bw::horizontal_sprite_lines_end[i] = mapping.pointer(end)?; } *bw::cursor_marker = lone_mapping.pointer(globals.cursor_marker)?; { let mut global_mapping = sprite_load_mapping().borrow_mut(); *global_mapping = mapping; let mut lone_global_mapping = lone_sprite_load_mapping().borrow_mut(); *lone_global_mapping = lone_mapping; } // Refill sprite / image list for GPTP which allocates images from reading through // first_free_image during hooks. // Most of the time the refill_sprite_image_list at create_sprite_hook is good enough, // but loading a save may cause something else that allocates images to run before // any sprites are created. refill_sprite_image_list(); Ok(()) } unsafe fn deserialize_sprite( sprite: &SpriteSerializable, mapping: &LoadMapping<bw::Sprite>, pointer: *mut bw::Sprite, image_array: &mut RawVec<bw::Image>, ) -> Result<bw::Sprite, LoadError> { let SpriteSerializable { prev, next, sprite_id, player, selection_index, visibility_mask, elevation, flags, selection_flash_timer, index, width, height, position, ref images, main_image_id, ref extra, } = *sprite; let mut image_ptrs = deserialize_images(images, pointer, image_array)?; Ok(bw::Sprite { prev: mapping.pointer(prev)?, next: mapping.pointer(next)?, sprite_id, player, selection_index, visibility_mask, elevation, flags, selection_flash_timer, index, width, height, position, first_overlay: image_ptrs.first_mut() .map(|x| &mut **x as *mut bw::Image).unwrap_or(null_mut()), last_overlay: image_ptrs.last_mut() .map(|x| &mut **x as *mut bw::Image).unwrap_or(null_mut()), main_image: if main_image_id == 0 { null_mut() } else { image_ptrs.get_mut(main_image_id as usize - 1).map(|x| &mut **x).ok_or_else(|| { LoadError::Corrupted(format!("Invalid main image 0x{:x}", main_image_id)) })? }, extra: extra.clone(), }) } unsafe fn deserialize_images( images: &[ImageSerializable], parent: *mut bw::Sprite, image_array: &mut RawVec<bw::Image>, ) -> Result<Vec<*mut bw::Image>, LoadError> { let mut result: Vec<*mut bw::Image> = Vec::with_capacity(images.len()); for img in images { let ImageSerializable { offset, image_id, drawfunc, direction, flags, x_offset, y_offset, ref iscript, frameset, frame, map_position, screen_position, grp_bounds, grp, drawfunc_param, } = *img; let ptr = (image_array.ptr as usize + offset) as *mut bw::Image; let index = offset / mem::size_of::<bw::Image>(); if index >= image_array.size { image_array.size = index + 1; } *ptr = bw::Image { prev: result.last().copied().unwrap_or(null_mut()), next: null_mut(), image_id, drawfunc, direction, flags, x_offset, y_offset, iscript: iscript.clone(), frameset, frame, map_position, screen_position, grp_bounds, grp: grp_from_id(grp)?, drawfunc_param: deserialize_drawfunc_param(drawfunc, drawfunc_param)?, parent, draw: { let drawfunc = bw::image_drawfuncs.get(drawfunc as usize) .unwrap_or_else(|| &bw::image_drawfuncs[0]); match flags & 0x2 == 0 { true => drawfunc.normal, false => drawfunc.flipped, } }, step_frame: { let func = bw::image_updatefuncs.get(drawfunc as usize) .unwrap_or_else(|| &bw::image_updatefuncs[0]); func.func } }; if let Some(prev) = result.last() { (**prev).next = ptr; } result.push(ptr); } Ok(result) } unsafe fn deserialize_lone_sprite( sprite: &LoneSpriteSerializable, mapping: &LoadMapping<bw::Sprite>, ) -> Result<bw::LoneSprite, LoadError> { Ok(bw::LoneSprite { prev: null_mut(), next: null_mut(), value: sprite.value, sprite: mapping.pointer(sprite.sprite)?, }) } // Returning the pointer vector isn't really necessary, just simpler. Could also create a // vector abstraction that allows reading addresses of any Bullet while holding a &mut reference // to one of them. fn allocate_sprites(sprites: &mut RawVec<bw::Sprite>, count: u32) -> LoadMapping<bw::Sprite> { sprites.size = count as usize; LoadMapping((0..count).map(|i| { unsafe { SendPtr(sprites.ptr.add(i as usize)) } }).collect()) } fn allocate_lone_sprites(count: u32) -> (Vec<Box<bw::LoneSprite>>, LoadMapping<bw::LoneSprite>) { (0..count).map(|_| { let mut sprite = Box::new(unsafe { mem::zeroed() }); let pointer: *mut bw::LoneSprite = &mut *sprite; (sprite, pointer) }).unzip() }
// MIT License // // Copyright (c) 2021 Miguel Peláez // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use crossbeam_queue::ArrayQueue; use log::{Log, Metadata, Record}; use spin::{Lazy, Once}; use crate::prelude::*; const KERNEL_LOG_QUEUE_SIZE: usize = 512; pub static KERNEL_LOGGER: KernelLogger = KernelLogger::new(); pub type LoggerCallback = fn(); pub struct KernelLogger { logs: Lazy<ArrayQueue<String>>, callback: Once<LoggerCallback>, } impl KernelLogger { pub const fn new() -> KernelLogger { KernelLogger { logs: Lazy::new(|| ArrayQueue::new(KERNEL_LOG_QUEUE_SIZE)), callback: Once::new(), } } pub fn get_logs(&self) -> &ArrayQueue<String> { &self.logs } pub fn set_callback(&self, callback: LoggerCallback) { self.callback.call_once(|| callback); } } impl Log for KernelLogger { fn enabled(&self, _: &Metadata) -> bool { true } fn log(&self, record: &Record) { // Discard last log if queue is full if self.logs.is_full() { let _ = self.logs.pop(); } self.logs .push(format!("{} - {}\n", record.level(), record.args())) .expect("Failed to free log queue."); self.flush(); } fn flush(&self) { if let Some(callback) = self.callback.get() { callback(); } } }
use azure_core::errors::AzureError; use azure_core::headers::{utc_date_from_rfc2822, CommonStorageResponseHeaders}; use chrono::{DateTime, Utc}; use hyper::header::HeaderMap; use std::convert::TryInto; #[derive(Debug, Clone)] pub struct PutMessageResponse { pub common_storage_response_headers: CommonStorageResponseHeaders, pub queue_message: QueueMessage, } #[derive(Debug, Clone, Serialize, Deserialize)] struct PutMessageResponseInternal { #[serde(rename = "QueueMessage")] pub queue_message: QueueMessageInternal, } #[derive(Debug, Clone)] pub struct QueueMessage { pub message_id: String, pub insertion_time: DateTime<Utc>, pub expiration_time: DateTime<Utc>, pub pop_receipt: String, pub time_next_visible: DateTime<Utc>, } #[derive(Debug, Clone, Serialize, Deserialize)] struct QueueMessageInternal { #[serde(rename = "MessageId")] pub message_id: String, #[serde(rename = "InsertionTime")] pub insertion_time: String, #[serde(rename = "ExpirationTime")] pub expiration_time: String, #[serde(rename = "PopReceipt")] pub pop_receipt: String, #[serde(rename = "TimeNextVisible")] pub time_next_visible: String, } impl std::convert::TryFrom<(&HeaderMap, &[u8])> for PutMessageResponse { type Error = AzureError; fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> { let headers = value.0; let body = value.1; debug!("headers == {:?}", headers); let received = &std::str::from_utf8(body)?[3..]; debug!("receieved == {:#?}", received); let response: PutMessageResponseInternal = serde_xml_rs::from_reader(&body[3..])?; let queue_message = QueueMessage { message_id: response.queue_message.message_id, insertion_time: utc_date_from_rfc2822(&response.queue_message.insertion_time)?, expiration_time: utc_date_from_rfc2822(&response.queue_message.expiration_time)?, pop_receipt: response.queue_message.pop_receipt, time_next_visible: utc_date_from_rfc2822(&response.queue_message.time_next_visible)?, }; Ok(Self { common_storage_response_headers: headers.try_into()?, queue_message, }) } }
pub mod legacy; pub mod xdg;
use crate::logic::main::{get_distance, get_intersection, get_polygon_lines}; use crate::Ray; use crate::Shape; use macroquad::prelude::*; const WALL_THICKNESS: f32 = 1.0; pub struct Wall { pub x1: f32, pub y1: f32, pub x2: f32, pub y2: f32, pub color: Vec4, pub texture: Texture2D, pub z_offset: f32, } impl Wall { pub fn draw(&self) { draw_line( self.x1, self.y1, self.x2, self.y2, WALL_THICKNESS, Color::from_vec(self.color), ); } pub fn get_pts(&self) -> (f32, f32, f32, f32) { (self.x1, self.y1, self.x2, self.y2) } pub fn slope(&self) -> f32 { (self.y2 - self.y1) / (self.x2 - self.x1) } pub fn get_start(&self) -> Vec2 { vec2(self.x1, self.y1) } pub fn get_end(&self) -> Vec2 { vec2(self.x2, self.y2) } pub fn polygon( x: f32, y: f32, sides: u8, radius: f32, rotation: f32, color: Vec4, texture: Texture2D, ) -> Vec<Wall> { get_polygon_lines(x, y, sides, radius, rotation) .iter() .map(|(x1, y1, x2, y2)| Wall { x1: *x1, y1: *y1, x2: *x2, y2: *y2, color, texture, z_offset: 0.0, }) .collect() } pub fn check_intersection(&self, ray: &Ray) -> Option<Vec2> { return get_intersection(ray.get_pts(), self.get_pts()); } pub fn get_length(&self) -> f32 { get_distance(self.get_start(), self.get_end()) } pub fn get_closest_intersection_shapes<'shape>( ray: &Ray, shapes: &'shape Vec<Box<dyn Shape>>, ) -> Option<(&'shape Wall, f32, Vec2)> { let mut closest: Option<(&Wall, f32, Vec2)> = None; shapes.into_iter().for_each(|shape| { if let Some(intersection_data) = shape.get_intersection(ray) { match closest { Some(c) => { if intersection_data.1 < c.1 { closest = Some(intersection_data); } } None => closest = Some(intersection_data), } } }); closest } pub fn get_closest_intersection<'shape>( ray: &Ray, walls: &'shape Vec<Wall>, ) -> Option<(&'shape Wall, f32, Vec2)> { let mut closest: Option<(&'shape Wall, f32, Vec2)> = None; let ray_s = ray.get_start(); walls.iter().for_each(|wall| { if let Some(point) = wall.check_intersection(ray) { let d = get_distance(ray_s, point); match closest { Some(c) => { if d < c.1 { closest = Some((wall, d, point)) } } None => closest = Some((wall, d, point)), } } }); closest } pub fn get_intersection<'shape>( ray: &Ray, wall: &'shape Wall, ) -> Option<(&'shape Wall, f32, Vec2)> { match wall.check_intersection(ray) { Some(point) => Some((wall, get_distance(ray.get_start(), point), point)), None => None, } } }
use util::*; #[derive(Clone, Copy, Debug)] enum Instruction { North(i32), South(i32), West(i32), East(i32), Left(i32), Right(i32), Forward(i32), } fn rotate(wx: &mut i32, wy: &mut i32, rotation: i32) { match rotation.rem_euclid(360) { 90 => { let tmp = *wy; *wy = -*wx; *wx = tmp; } 180 => { *wy = -*wy; *wx = -*wx; } 270 => { let tmp = -*wy; *wy = *wx; *wx = tmp; } _ => panic!("Invalid rotation ({})", rotation), } } fn main() -> Result<(), Box<dyn std::error::Error>> { let timer = Timer::new(); let mut x = 0; let mut y = 0; let mut wx = 10; let mut wy = 1; let input = input::lines::<String>(&std::env::args().nth(1).unwrap()); input.iter().map(|l| match &l[0..1] { "N" => Instruction::North(l[1..].parse().unwrap()), "E" => Instruction::East(l[1..].parse().unwrap()), "S" => Instruction::South(l[1..].parse().unwrap()), "W" => Instruction::West(l[1..].parse().unwrap()), "F" => Instruction::Forward(l[1..].parse().unwrap()), "L" => Instruction::Left(l[1..].parse().unwrap()), "R" => Instruction::Right(l[1..].parse().unwrap()), _ => panic!("Invalid input. Got \"{}\"", l), }).for_each(|i|{ match i { Instruction::North(d) => wy += d, Instruction::South(d) => wy -= d, Instruction::West(d) => wx -= d, Instruction::East(d) => wx += d, Instruction::Left(a) => rotate(&mut wx, &mut wy, -a), Instruction::Right(a) => rotate(&mut wx, &mut wy, a), Instruction::Forward(d) => { x += wx * d; y += wy * d; } } }); timer.print(); println!("{}", x.abs() + y.abs()); Ok(()) }
#[doc = "Register `ICFR` writer"] pub type W = crate::W<ICFR_SPEC>; #[doc = "Field `CC1IF` writer - Clear COMP channel 1 Interrupt Flag"] pub type CC1IF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CC2IF` writer - Clear COMP channel 2 Interrupt Flag"] pub type CC2IF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl W { #[doc = "Bit 16 - Clear COMP channel 1 Interrupt Flag"] #[inline(always)] #[must_use] pub fn cc1if(&mut self) -> CC1IF_W<ICFR_SPEC, 16> { CC1IF_W::new(self) } #[doc = "Bit 17 - Clear COMP channel 2 Interrupt Flag"] #[inline(always)] #[must_use] pub fn cc2if(&mut self) -> CC2IF_W<ICFR_SPEC, 17> { CC2IF_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 = "Comparator interrupt clear flag register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`icfr::W`](W). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ICFR_SPEC; impl crate::RegisterSpec for ICFR_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [`icfr::W`](W) writer structure"] impl crate::Writable for ICFR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ICFR to value 0"] impl crate::Resettable for ICFR_SPEC { const RESET_VALUE: Self::Ux = 0; }
mod md5; pub use md5::Md5PuzzleTask; pub use md5::Md5PuzzleSolution;
#[doc = "Register `RGSR` reader"] pub type R = crate::R<RGSR_SPEC>; #[doc = "Field `OF0` reader - Trigger overrun event flag"] pub type OF0_R = crate::BitReader<OF0_A>; #[doc = "Trigger overrun event flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OF0_A { #[doc = "0: No new trigger event occured on DMA request generator channel x, before the request counter underrun"] NoTrigger = 0, #[doc = "1: New trigger event occured on DMA request generator channel x, before the request counter underrun"] Trigger = 1, } impl From<OF0_A> for bool { #[inline(always)] fn from(variant: OF0_A) -> Self { variant as u8 != 0 } } impl OF0_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OF0_A { match self.bits { false => OF0_A::NoTrigger, true => OF0_A::Trigger, } } #[doc = "No new trigger event occured on DMA request generator channel x, before the request counter underrun"] #[inline(always)] pub fn is_no_trigger(&self) -> bool { *self == OF0_A::NoTrigger } #[doc = "New trigger event occured on DMA request generator channel x, before the request counter underrun"] #[inline(always)] pub fn is_trigger(&self) -> bool { *self == OF0_A::Trigger } } #[doc = "Field `OF1` reader - Trigger overrun event flag"] pub use OF0_R as OF1_R; #[doc = "Field `OF2` reader - Trigger overrun event flag"] pub use OF0_R as OF2_R; #[doc = "Field `OF3` reader - Trigger overrun event flag"] pub use OF0_R as OF3_R; impl R { #[doc = "Bit 0 - Trigger overrun event flag"] #[inline(always)] pub fn of0(&self) -> OF0_R { OF0_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Trigger overrun event flag"] #[inline(always)] pub fn of1(&self) -> OF1_R { OF1_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Trigger overrun event flag"] #[inline(always)] pub fn of2(&self) -> OF2_R { OF2_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Trigger overrun event flag"] #[inline(always)] pub fn of3(&self) -> OF3_R { OF3_R::new(((self.bits >> 3) & 1) != 0) } } #[doc = "request generator interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rgsr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct RGSR_SPEC; impl crate::RegisterSpec for RGSR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`rgsr::R`](R) reader structure"] impl crate::Readable for RGSR_SPEC {} #[doc = "`reset()` method sets RGSR to value 0"] impl crate::Resettable for RGSR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//const WALL :char = '#'; //const SPACE:char = ' '; const SPIKES: [char; 2] = ['╱', '╲']; extern crate termion; use termion::raw::IntoRawMode; use termion::event::Key; use std::io::{Write, stdout}; use crate::termion::input::TermRead; #[derive(Debug, Copy, Clone, PartialEq)] struct Vec2 { pub x: f64, pub y: f64 } impl std::ops::AddAssign<Vec2> for Vec2 { fn add_assign(&mut self, other: Self) { *self = Self { x: self.x + other.x, y: self.y + other.y, }; } } impl std::ops::Add<Vec2> for Vec2 { type Output = Self; fn add(self, other: Self) -> Self { Vec2 { x: self.x + other.x, y: self.y + other.y, } } } impl Vec2 { /* fn limit_x(&mut self, n: f64) { if self.x > n { self.x = n; } else if self.x < -n { self.x = -n; } }*/ fn limit_y(&mut self, n: f64) { if self.y > n { self.y = n; } else if self.y < -n { self.y = -n; } } } struct Player { pos: Vec2, vel: Vec2, ch: char, } impl Player { fn update(&mut self, grid: &Vec<Vec<char>>) { self.vel += Vec2{x:0.0, y:0.1}; //self.vel.x *= 0.8; self.vel.x = 0.8; self.vel.limit_y(1.0); self.collide(&grid); self.pos += self.vel; } fn draw<W: Write>(&self, term: &mut Term<W>) { term.write_to(&self.ch.to_string(), 16, self.pos.y as u16); } fn collide(&mut self, grid: &Vec<Vec<char>>) { let next_pos = self.pos + self.vel; let next_ch_x = grid[self.pos.y as usize][next_pos.x as usize]; let next_ch_y = grid[next_pos.y as usize][self.pos.x as usize]; let next_ch_xy = grid[next_pos.y as usize][next_pos.x as usize]; let vel_x = next_pos.x as i64 - self.pos.x as i64; let vel_y = next_pos.y as i64 - self.pos.y as i64; if next_ch_y != ' ' { self.vel.y = 0.0; } if next_ch_x != ' ' { self.vel.x = 0.0; } if next_ch_xy != ' ' && next_ch_x == ' ' && next_ch_y == ' ' { self.vel.x = 0.0; self.vel.y = 0.0; } } fn jump(&mut self, file: &Vec<Vec<char>>) { if file[(self.pos.y + 1.0) as usize][self.pos.x as usize] != ' ' { self.vel.y = -0.9; } } fn on(&self, grid: &Vec<Vec<char>>) -> char { return grid[self.pos.y as usize + 1][self.pos.x as usize]; } } struct Term<W: Write> { screen: W, } impl<W: Write> Term<W> { fn goto(&mut self, x: u16, y: u16) { write!(self.screen, "{}", termion::cursor::Goto(x+1, y+1)).unwrap(); } fn flush(&mut self) { self.screen.flush().unwrap(); } fn write(&mut self, text:&str) { write!(self.screen, "{}", text).unwrap(); } fn write_to(&mut self, text:&str, x:u16, y:u16) { write!(self.screen, "{}{}", termion::cursor::Goto(x+1, y+1), text).unwrap(); } } fn draw_screen<W: Write>(screen: &mut Term<W>, file: &Vec<Vec<char>>, abs_xoffset: isize) { let mut xoffset: usize = 0; let mut i = 0; let mut j = 0; if abs_xoffset > 0 { xoffset = abs_xoffset as usize; } else { j = (-abs_xoffset) as u16; } let start = xoffset; let mut end: usize = xoffset + termion::terminal_size().unwrap().0 as usize - j as usize; for line in file { if end >= line.len() { end = line.len(); } screen.goto(j, i); let str: String = line[start..end].into_iter().collect(); screen.write(&str); i += 1; } } fn process_input(player: &mut Player, stdin: &mut termion::input::Keys<termion::AsyncReader>, file: &Vec<Vec<char>>) -> bool { if let Some(c) = stdin.next() { match c.unwrap() { // Exit. Key::Char('q') => return true, Key::Ctrl('c') => return true, //Key::Char(c) => println!("{}", c), //Key::Alt(c) => println!("Alt-{}", c), //Key::Left => player.vel.x -= 0.4, //Key::Right => player.vel.x += 0.4, Key::Up => player.jump(&file), Key::Down => println!("<down>"), _ => println!("Other"), } } return false; } fn main() { let file = std::fs::read_to_string("level.txt").expect("Could not open level file!"); let split = file.lines(); let mut grid: Vec<Vec<char>> = vec![]; for line in split { grid.push(line.chars().collect()); } let stdout = stdout().into_raw_mode().unwrap(); let mut stdin = termion::async_stdin().keys(); let screen = termion::screen::AlternateScreen::from(stdout).into_raw_mode().unwrap(); let mut term = Term{screen}; term.write_to(&termion::cursor::Hide.to_string(), 0, 0); let mut player = Player { pos: Vec2{x: 1.0, y: 16.0}, vel: Vec2{x: 0.0, y: 0.0}, ch: '▆', }; loop { let now = std::time::Instant::now(); draw_screen(&mut term, &grid, (player.pos.x - 16.0) as isize); if process_input(&mut player, &mut stdin, &grid) { break; } player.update(&grid); if player.vel.x < 0.1 { player.pos.x = 1.0; } if SPIKES.contains(&player.on(&grid)) { player.pos.x = 1.0; } player.draw(&mut term); term.flush(); std::thread::sleep(std::time::Duration::from_millis(1000 / 30) - now.elapsed()); } term.write_to(&termion::cursor::Show.to_string(), 0, 0); // Here the destructor is automatically called, and the terminal state is restored. }
use super::*; pub fn handle_u_type(regfile: &mut [u32], bytes: &[u8], pc: &mut u32, _extensions: &Extensions) -> Result<(), ExecutionError> { let opcode = get_opcode(bytes); let rd = get_rd(bytes); let immediate = decode_u_type_immediate(bytes); if opcode == 0x17 { // auipc regfile[rd as usize] = ((*pc as i32) + immediate) as u32; *pc += 4; } else if opcode == 0x37 { // lui regfile[rd as usize] = immediate as u32; *pc += 4; } else { return Err(ExecutionError::InvalidInstruction(encode_hex(bytes))); } Ok(()) }
#[doc = "Reader of register FIFO_ST"] pub type R = crate::R<u32, super::FIFO_ST>; #[doc = "Writer for register FIFO_ST"] pub type W = crate::W<u32, super::FIFO_ST>; #[doc = "Register FIFO_ST `reset()`'s with value 0x02"] impl crate::ResetValue for super::FIFO_ST { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x02 } } #[doc = "Reader of field `ROE`"] pub type ROE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ROE`"] pub struct ROE_W<'a> { w: &'a mut W, } impl<'a> ROE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `WOF`"] pub type WOF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WOF`"] pub struct WOF_W<'a> { w: &'a mut W, } impl<'a> WOF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `RDY`"] pub type RDY_R = crate::R<bool, bool>; #[doc = "Reader of field `VLD`"] pub type VLD_R = crate::R<bool, bool>; impl R { #[doc = "Bit 3 - Sticky flag indicating the RX FIFO was read when empty. This read was ignored by the FIFO."] #[inline(always)] pub fn roe(&self) -> ROE_R { ROE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Sticky flag indicating the TX FIFO was written when full. This write was ignored by the FIFO."] #[inline(always)] pub fn wof(&self) -> WOF_R { WOF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Value is 1 if this core's TX FIFO is not full (i.e. if FIFO_WR is ready for more data)"] #[inline(always)] pub fn rdy(&self) -> RDY_R { RDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Value is 1 if this core's RX FIFO is not empty (i.e. if FIFO_RD is valid)"] #[inline(always)] pub fn vld(&self) -> VLD_R { VLD_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 3 - Sticky flag indicating the RX FIFO was read when empty. This read was ignored by the FIFO."] #[inline(always)] pub fn roe(&mut self) -> ROE_W { ROE_W { w: self } } #[doc = "Bit 2 - Sticky flag indicating the TX FIFO was written when full. This write was ignored by the FIFO."] #[inline(always)] pub fn wof(&mut self) -> WOF_W { WOF_W { w: self } } }
//! This module is a port of ogsudo's `lib/util/term.c` with some minor changes to make it //! rust-like. use std::{ ffi::c_int, fs::{File, OpenOptions}, io::{self, Read, Write}, mem::MaybeUninit, os::fd::{AsRawFd, RawFd}, sync::atomic::{AtomicBool, Ordering}, }; use libc::{ c_void, cfgetispeed, cfgetospeed, cfmakeraw, cfsetispeed, cfsetospeed, ioctl, sigaction, sigemptyset, sighandler_t, siginfo_t, sigset_t, tcflag_t, tcgetattr, tcsetattr, termios, winsize, CS7, CS8, ECHO, ECHOCTL, ECHOE, ECHOK, ECHOKE, ECHONL, ICANON, ICRNL, IEXTEN, IGNCR, IGNPAR, IMAXBEL, INLCR, INPCK, ISIG, ISTRIP, IUTF8, IXANY, IXOFF, IXON, NOFLSH, OCRNL, OLCUC, ONLCR, ONLRET, ONOCR, OPOST, PARENB, PARMRK, PARODD, PENDIN, SIGTTOU, TCSADRAIN, TCSAFLUSH, TIOCGWINSZ, TIOCSWINSZ, TOSTOP, }; use super::{TermSize, Terminal}; use crate::{cutils::cerr, system::interface::ProcessId}; const INPUT_FLAGS: tcflag_t = IGNPAR | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL // | IUCLC /* FIXME: not in libc */ | IXON | IXANY | IXOFF | IMAXBEL | IUTF8; const OUTPUT_FLAGS: tcflag_t = OPOST | OLCUC | ONLCR | OCRNL | ONOCR | ONLRET; const CONTROL_FLAGS: tcflag_t = CS7 | CS8 | PARENB | PARODD; const LOCAL_FLAGS: tcflag_t = ISIG | ICANON // | XCASE /* FIXME: not in libc */ | ECHO | ECHOE | ECHOK | ECHONL | NOFLSH | TOSTOP | IEXTEN | ECHOCTL | ECHOKE | PENDIN; static GOT_SIGTTOU: AtomicBool = AtomicBool::new(false); extern "C" fn on_sigttou(_signal: c_int, _info: *mut siginfo_t, _: *mut c_void) { GOT_SIGTTOU.store(true, Ordering::SeqCst); } /// This is like `tcsetattr` but it only suceeds if we are in the foreground process group. fn tcsetattr_nobg(fd: c_int, flags: c_int, tp: *const termios) -> io::Result<()> { // This function is based around the fact that we receive `SIGTTOU` if we call `tcsetattr` and // we are not in the foreground process group. let mut original_action = MaybeUninit::<sigaction>::uninit(); let action = sigaction { // Call `on_sigttou` if `SIGTTOU` arrives. sa_sigaction: on_sigttou as sighandler_t, // Exclude any other signals from the set sa_mask: { let mut sa_mask = MaybeUninit::<sigset_t>::uninit(); unsafe { sigemptyset(sa_mask.as_mut_ptr()) }; unsafe { sa_mask.assume_init() } }, sa_flags: 0, sa_restorer: None, }; // Reset `GOT_SIGTTOU`. GOT_SIGTTOU.store(false, Ordering::SeqCst); // Set `action` as the action for `SIGTTOU` and store the original action in `original_action` // to restore it later. unsafe { sigaction(SIGTTOU, &action, original_action.as_mut_ptr()) }; // Call `tcsetattr` until it suceeds and ignore interruptions if we did not receive `SIGTTOU`. let result = loop { match cerr(unsafe { tcsetattr(fd, flags, tp) }) { Ok(_) => break Ok(()), Err(err) => { let got_sigttou = GOT_SIGTTOU.load(Ordering::SeqCst); if got_sigttou || err.kind() != io::ErrorKind::Interrupted { break Err(err); } } } }; // Restore the original action. unsafe { sigaction(SIGTTOU, original_action.as_ptr(), std::ptr::null_mut()) }; result } /// Type to manipulate the settings of the user's terminal. pub struct UserTerm { tty: File, original_termios: MaybeUninit<termios>, changed: bool, } impl UserTerm { /// Open the user's terminal. pub fn open() -> io::Result<Self> { Ok(Self { tty: OpenOptions::new().read(true).write(true).open("/dev/tty")?, original_termios: MaybeUninit::uninit(), changed: false, }) } pub(crate) fn get_size(&self) -> io::Result<TermSize> { let mut term_size = MaybeUninit::<TermSize>::uninit(); cerr(unsafe { ioctl( self.tty.as_raw_fd(), TIOCGWINSZ, term_size.as_mut_ptr().cast::<winsize>(), ) })?; Ok(unsafe { term_size.assume_init() }) } /// Copy the settings of the user's terminal to the `dst` terminal. pub fn copy_to<D: AsRawFd>(&self, dst: &D) -> io::Result<()> { let src = self.tty.as_raw_fd(); let dst = dst.as_raw_fd(); let mut tt_src = MaybeUninit::<termios>::uninit(); let mut tt_dst = MaybeUninit::<termios>::uninit(); let mut wsize = MaybeUninit::<winsize>::uninit(); cerr(unsafe { tcgetattr(src, tt_src.as_mut_ptr()) })?; cerr(unsafe { tcgetattr(dst, tt_dst.as_mut_ptr()) })?; let tt_src = unsafe { tt_src.assume_init() }; let mut tt_dst = unsafe { tt_dst.assume_init() }; // Clear select input, output, control and local flags. tt_dst.c_iflag &= !INPUT_FLAGS; tt_dst.c_oflag &= !OUTPUT_FLAGS; tt_dst.c_cflag &= !CONTROL_FLAGS; tt_dst.c_lflag &= !LOCAL_FLAGS; // Copy select input, output, control and local flags. tt_dst.c_iflag |= tt_src.c_iflag & INPUT_FLAGS; tt_dst.c_oflag |= tt_src.c_oflag & OUTPUT_FLAGS; tt_dst.c_cflag |= tt_src.c_cflag & CONTROL_FLAGS; tt_dst.c_lflag |= tt_src.c_lflag & LOCAL_FLAGS; // Copy special chars from src verbatim. tt_dst.c_cc.copy_from_slice(&tt_src.c_cc); // Copy speed from `src`. { let mut speed = unsafe { cfgetospeed(&tt_src) }; // Zero output speed closes the connection. if speed == libc::B0 { speed = libc::B38400; } unsafe { cfsetospeed(&mut tt_dst, speed) }; speed = unsafe { cfgetispeed(&tt_src) }; unsafe { cfsetispeed(&mut tt_dst, speed) }; } tcsetattr_nobg(dst, TCSAFLUSH, &tt_dst)?; cerr(unsafe { ioctl(src, TIOCGWINSZ, &mut wsize) })?; cerr(unsafe { ioctl(dst, TIOCSWINSZ, &wsize) })?; Ok(()) } /// Set the user's terminal to raw mode. Enable terminal signals if `with_signals` is set to /// `true`. pub fn set_raw_mode(&mut self, with_signals: bool) -> io::Result<()> { let fd = self.tty.as_raw_fd(); if !self.changed { cerr(unsafe { tcgetattr(fd, self.original_termios.as_mut_ptr()) })?; } // Retrieve the original terminal. let mut term = unsafe { self.original_termios.assume_init() }; // Set terminal to raw mode. unsafe { cfmakeraw(&mut term) }; // Enable terminal signals. if with_signals { term.c_cflag |= ISIG; } tcsetattr_nobg(fd, TCSADRAIN, &term)?; self.changed = true; Ok(()) } /// Restore the saved terminal settings if we are in the foreground process group. /// /// This change is done after waiting for all the queued output to be written. To discard the /// queued input `flush` must be set to `true`. pub fn restore(&mut self, flush: bool) -> io::Result<()> { if self.changed { let fd = self.tty.as_raw_fd(); let flags = if flush { TCSAFLUSH } else { TCSADRAIN }; tcsetattr_nobg(fd, flags, self.original_termios.as_ptr())?; self.changed = false; } Ok(()) } /// This is like `tcsetpgrp` but it only suceeds if we are in the foreground process group. pub fn tcsetpgrp_nobg(&self, pgrp: ProcessId) -> io::Result<()> { // This function is based around the fact that we receive `SIGTTOU` if we call `tcsetpgrp` and // we are not in the foreground process group. let mut original_action = MaybeUninit::<sigaction>::uninit(); let action = sigaction { // Call `on_sigttou` if `SIGTTOU` arrives. sa_sigaction: on_sigttou as sighandler_t, // Exclude any other signals from the set sa_mask: { let mut sa_mask = MaybeUninit::<sigset_t>::uninit(); unsafe { sigemptyset(sa_mask.as_mut_ptr()) }; unsafe { sa_mask.assume_init() } }, sa_flags: 0, sa_restorer: None, }; // Reset `GOT_SIGTTOU`. GOT_SIGTTOU.store(false, Ordering::SeqCst); // Set `action` as the action for `SIGTTOU` and store the original action in `original_action` // to restore it later. unsafe { sigaction(SIGTTOU, &action, original_action.as_mut_ptr()) }; // Call `tcsetattr` until it suceeds and ignore interruptions if we did not receive `SIGTTOU`. let result = loop { match self.tty.tcsetpgrp(pgrp) { Ok(()) => break Ok(()), Err(err) => { let got_sigttou = GOT_SIGTTOU.load(Ordering::SeqCst); if got_sigttou || err.kind() != io::ErrorKind::Interrupted { break Err(err); } } } }; // Restore the original action. unsafe { sigaction(SIGTTOU, original_action.as_ptr(), std::ptr::null_mut()) }; result } } impl AsRawFd for UserTerm { fn as_raw_fd(&self) -> RawFd { self.tty.as_raw_fd() } } impl Read for UserTerm { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.tty.read(buf) } } impl Write for UserTerm { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.tty.write(buf) } fn flush(&mut self) -> io::Result<()> { self.tty.flush() } }
extern crate proc_macro_bug_impl; use proc_macro_bug_impl::some_macro; #[some_macro(0)] struct Abc {} #[some_macro(0)] struct Cde {} fn main() {}
//! Logging and log syntax highlighting. use colored::{ColoredString, Colorize}; use prefix::{Name, Prefix}; use std::fmt::Debug; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; static VERBOSITY: AtomicUsize = ATOMIC_USIZE_INIT; pub const ERROR: usize = 1; pub const INFO: usize = 2; pub const DEBUG: usize = 3; pub fn set_verbosity(verbosity: usize) { VERBOSITY.store(verbosity, Ordering::Relaxed) } pub fn verbosity() -> usize { VERBOSITY.load(Ordering::Relaxed) } /// Log error. macro_rules! error { ($($arg:tt)*) => { if $crate::log::verbosity() >= $crate::log::ERROR { use $crate::colored::Colorize; println!("{}", format!($($arg)*).red()) } } } /// Log info. macro_rules! info { ($($arg:tt)*) => { if $crate::log::verbosity() >= $crate::log::INFO { println!($($arg)*) } } } /// Log debug macro_rules! debug { ($($arg:tt)*) => { if $crate::log::verbosity() >= $crate::log::DEBUG { println!($($arg)*) } } } #[allow(unused)] pub fn name(name: &Name) -> ColoredString { format!("{:?}", name).bright_blue() } pub fn prefix(prefix: &Prefix) -> ColoredString { if *prefix == Prefix::EMPTY { "[]".bright_blue() } else { format!("[{}]", prefix).bright_blue() } } #[allow(unused)] pub fn message<T: Debug>(msg: &T) -> ColoredString { format!("{:?}", msg).bright_magenta() }
use strum::{Display, EnumIter}; #[derive(Debug, Display, EnumIter)] pub enum HypervisorTraits { // P4 Traits ApexProcessP4Ext, ApexPartitionP4, ApexTimeP4Ext, ApexErrorP4Ext, ApexQueuingPortP4Ext, ApexSamplingPortP4Ext, // P1 Traits ApexProcessP1Ext, ApexTimeP1Ext, ApexEventP1Ext, ApexMutexP1Ext, ApexErrorP1Ext, ApexBufferP1Ext, ApexQueuingPortP1Ext, ApexSamplingPortP1Ext, ApexSemaphoreP1Ext, ApexBlackboardP1Ext, // TODO soon P2 Traits }
#[no_mangle] pub extern fn doubler(x: f64) -> f64 { println!("Called with x={}", x); x * 2. }
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use rocksdb::*; use rocksdb::{DBStatisticsHistogramType as HistogramType, DBStatisticsTickerType as TickerType}; use super::tempdir_with_prefix; #[test] fn test_db_statistics() { let path = tempdir_with_prefix("_rust_rocksdb_statistics"); let mut opts = DBOptions::new(); opts.create_if_missing(true); let statistics = Statistics::new(); opts.set_statistics(&statistics); let db = DB::open(opts, path.path().to_str().unwrap()).unwrap(); let wopts = WriteOptions::new(); db.put_opt(b"k0", b"a", &wopts).unwrap(); db.put_opt(b"k1", b"b", &wopts).unwrap(); db.put_opt(b"k2", b"c", &wopts).unwrap(); let mut fopts = FlushOptions::default(); fopts.set_wait(true); db.flush(&fopts).unwrap(); // flush memtable to sst file. assert_eq!(db.get(b"k0").unwrap().unwrap(), b"a"); assert_eq!(db.get(b"k1").unwrap().unwrap(), b"b"); assert_eq!(db.get(b"k2").unwrap().unwrap(), b"c"); assert!(statistics.get_ticker_count(TickerType::BlockCacheHit) > 0); assert!(statistics.get_and_reset_ticker_count(TickerType::BlockCacheHit) > 0); assert_eq!(statistics.get_ticker_count(TickerType::BlockCacheHit), 0); assert!(statistics .get_histogram_string(HistogramType::DbGet) .is_some()); assert!(statistics.get_histogram(HistogramType::DbGet).is_some()); let get_micros = statistics.get_histogram(HistogramType::DbGet).unwrap(); assert!(get_micros.max > 0.0); statistics.reset(); let get_micros = statistics.get_histogram(HistogramType::DbGet).unwrap(); assert_eq!(get_micros.max, 0.0); } #[test] fn test_disable_db_statistics() { let path = tempdir_with_prefix("_rust_rocksdb_statistics"); let mut opts = DBOptions::new(); opts.create_if_missing(true); let statistics = Statistics::new_empty(); opts.set_statistics(&statistics); let db = DB::open(opts, path.path().to_str().unwrap()).unwrap(); let wopts = WriteOptions::new(); db.put_opt(b"k0", b"a", &wopts).unwrap(); db.put_opt(b"k1", b"b", &wopts).unwrap(); db.put_opt(b"k2", b"c", &wopts).unwrap(); let mut fopts = FlushOptions::default(); fopts.set_wait(true); db.flush(&fopts).unwrap(); // flush memtable to sst file. assert_eq!(db.get(b"k0").unwrap().unwrap(), b"a"); assert_eq!(db.get(b"k1").unwrap().unwrap(), b"b"); assert_eq!(db.get(b"k2").unwrap().unwrap(), b"c"); assert_eq!(statistics.get_ticker_count(TickerType::BlockCacheHit), 0); assert_eq!( statistics.get_and_reset_ticker_count(TickerType::BlockCacheHit), 0 ); assert!(statistics .get_histogram_string(HistogramType::DbGet) .is_none()); assert!(statistics.get_histogram(HistogramType::DbGet).is_none()); } #[test] fn test_shared_db_statistics() { let path1 = tempdir_with_prefix("_rust_rocksdb_statistics"); let path2 = tempdir_with_prefix("_rust_rocksdb_statistics"); let mut opts = DBOptions::new(); opts.create_if_missing(true); let statistics = Statistics::new(); opts.set_statistics(&statistics); let _db_inactive = DB::open(opts.clone(), path1.path().to_str().unwrap()).unwrap(); let db = DB::open(opts, path2.path().to_str().unwrap()).unwrap(); let wopts = WriteOptions::new(); db.put_opt(b"k0", b"a", &wopts).unwrap(); db.put_opt(b"k1", b"b", &wopts).unwrap(); db.put_opt(b"k2", b"c", &wopts).unwrap(); let mut fopts = FlushOptions::default(); fopts.set_wait(true); db.flush(&fopts).unwrap(); // flush memtable to sst file. assert_eq!(db.get(b"k0").unwrap().unwrap(), b"a"); assert_eq!(db.get(b"k1").unwrap().unwrap(), b"b"); assert_eq!(db.get(b"k2").unwrap().unwrap(), b"c"); assert!(statistics.get_ticker_count(TickerType::BlockCacheHit) > 0); assert!(statistics.get_and_reset_ticker_count(TickerType::BlockCacheHit) > 0); assert_eq!(statistics.get_ticker_count(TickerType::BlockCacheHit), 0); assert!(statistics .get_histogram_string(HistogramType::DbGet) .is_some()); assert!(statistics.get_histogram(HistogramType::DbGet).is_some()); let get_micros = statistics.get_histogram(HistogramType::DbGet).unwrap(); assert!(get_micros.max > 0.0); statistics.reset(); let get_micros = statistics.get_histogram(HistogramType::DbGet).unwrap(); assert_eq!(get_micros.max, 0.0); }
use std::fmt; // START OMIT #[derive(Debug)] struct Struct { a: u8, b: u32, c: bool, } fn main() { let s = Struct {a: 7, b: 3333, c: true, }; // HL println!("{}", s); } // END OMIT impl fmt::Display for Struct { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {}, {})", self.a, self.b, self.c) } }
use crate::highlighter::*; use bitflags::bitflags; use std::cmp::{max, min}; use std::fmt; bitflags! { struct Block: u8 { const NONE = 0b00; const FULL = 0b11; const TOP = 0b01; const BOTTOM = 0b10; } } impl fmt::Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match *self { Block::FULL => '▌', Block::TOP => '▘', Block::BOTTOM => '▖', _ => ' ', } ) } } #[derive(Debug)] struct Line { values: Vec<(Block, Highlight)>, } impl Line { pub fn new(highlights: &[Highlight]) -> Self { let len = highlights.len(); let mut values = Vec::with_capacity(len); values.push(if highlights[0] > 0 { (Block::FULL, highlights[0]) } else { (Block::NONE, 0) }); for i in 1..len { let prev = highlights[i - 1]; let curr = highlights[i]; let mut block = Block::NONE; let mut highlight = 0; if prev > 0 { block |= Block::TOP; highlight = prev; } if curr > 0 { block |= Block::BOTTOM; highlight = curr; } values.push((block, highlight)); } Line { values } } #[allow(clippy::needless_range_loop)] pub fn scale(&self, height: usize) -> Self { let len = self.values.len(); let scale = len as f64 / height as f64; let mut result = Vec::with_capacity(height); for i in 0..height { let offset = ((i as f64) * scale) as usize; let limit = ((i + 1) as f64 * scale) as usize; let init = self.values[offset]; let range = &self.values[offset..limit]; let block = range.iter().fold(init.0, |acc, val| acc | val.0); let highlight = range.iter().fold(init.1, |acc, val| max(acc, val.1)); result.push((block, highlight)); } let mut prev_block = self.values[0].0; for i in 1..height { let block = result[i].0; if prev_block == block && block == Block::BOTTOM { result[i].0 = Block::FULL; } prev_block = block; } for i in (height - 1)..0 { let block = result[i].0; if prev_block == block && block == Block::TOP { result[i].0 = Block::FULL; } prev_block = block; } Line { values: result } } } impl std::ops::Index<usize> for Line { type Output = (Block, Highlight); fn index(&self, index: usize) -> &Self::Output { &self.values[index] } } #[derive(Clone, Copy)] pub struct Frame { pub top: u64, pub bottom: u64, } impl Default for Frame { fn default() -> Self { Frame { top: 0, bottom: 0 } } } impl Frame { fn contains(&self, offset: f64, scale: f64) -> bool { let top = min(self.top, self.bottom); let bottom = max(self.top, self.bottom); top < (offset + scale) as u64 && bottom >= offset as u64 } } #[derive(Clone, Copy)] pub struct Modifier { pub cursor: u64, pub visible_frame: Frame, pub select_frame: Option<Frame>, } impl Default for Modifier { fn default() -> Self { Modifier { cursor: 0, visible_frame: Frame::default(), select_frame: None, } } } impl Modifier { pub fn new(cursor: u64, visible_frame: Frame) -> Self { Modifier { cursor, visible_frame, select_frame: None, } } pub fn to_char(&self, i: u64, len: usize, height: u64) -> char { let scale = len as f64 / height as f64; let offset = (i as f64) * scale; if offset as u64 <= self.cursor && (self.cursor as f64) < offset + scale { return 'c'; } if let Some(frame) = &self.select_frame { if frame.contains(offset, scale) { return 's'; } } if self.visible_frame.contains(offset, scale) { return 'v'; } ' ' } } pub struct Picomap { pub changes: Highlights, pub diags: Highlights, pub modifier: Modifier, } impl Default for Picomap { fn default() -> Self { Picomap { changes: Highlights::default(), diags: Highlights::default(), modifier: Modifier::default(), } } } impl Picomap { pub fn new(changes: Highlights, diags: Highlights, modifier: Modifier) -> Self { Picomap { changes, diags, modifier, } } pub fn to_strings(&self, len: usize, height: u64) -> Vec<String> { let mut result = Vec::with_capacity(height as usize); if len == 0 || height == 0 { return vec![]; } let change_line = Line::new(&self.changes).scale(height as usize); let diag_line = Line::new(&self.diags).scale(height as usize); for i in 0..height { let change = change_line[i as usize]; let diag = diag_line[i as usize]; result.push(format!( "{}{}{:>02}{:>02}{}", change.0, diag.0, change.1, diag.1, self.modifier.to_char(i, len, height), )); } result } } #[cfg(test)] mod tests { use super::*; #[test] fn test_picomap_format() { let len = 3; let height = 3; let changes = vec![1, 2, 3]; let diags = vec![0, 0, 0]; let modifier = Modifier::default(); let picomap = Picomap::new(changes, diags, modifier); assert_eq!( picomap.to_strings(len, height), vec!["▌ 0100c", "▌ 0200 ", "▌ 0300 ",] ); } #[test] fn test_picomap_format_zoom_in() { let len = 3; let height = 10; let changes = vec![1, 2, 3]; let diags = vec![0, 0, 0]; let modifier = Modifier::default(); let picomap = Picomap::new(changes, diags, modifier); assert_eq!( picomap.to_strings(len, height), vec![ "▌ 0100c", "▌ 0100c", "▌ 0100c", "▌ 0100c", "▌ 0200 ", "▌ 0200 ", "▌ 0200 ", "▌ 0300 ", "▌ 0300 ", "▌ 0300 ", ] ); } #[test] fn test_picomap_format_zoom_out() { let len = 10; let height = 5; let changes = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let diags = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let modifier = Modifier::default(); let picomap = Picomap::new(changes, diags, modifier); assert_eq!( picomap.to_strings(len, height), vec!["▖ 0100c", "▌ 0300 ", "▌ 0500 ", "▌ 0700 ", "▌ 0900 ",] ); } }
use std::sync::Arc; use crossbeam_channel::Sender; use serde::Serialize; use crate::stdio_server::rpc::{Call, RpcClient}; use crate::stdio_server::vim::Vim; /// Current State of Vim/NeoVim client. #[derive(Serialize)] pub struct State { #[serde(skip_serializing)] pub tx: Sender<Call>, #[serde(skip_serializing)] pub vim: Vim, /// Highlight match ids. pub highlights: Vec<u32>, } impl State { pub fn new(tx: Sender<Call>, client: Arc<RpcClient>) -> Self { Self { tx, vim: Vim::new(client), highlights: Default::default(), } } }
#[macro_export] macro_rules! make_response { ($name:ident, $inner:ident, $func:ident) => { pub type $name = AniListResponse<Single<$inner>>; impl $name { pub fn $func(&self) -> Option<$inner> { self.data.item.to_owned() } } }; } #[macro_export] macro_rules! make_paged_response { ($name:ident, $inner:ident, $func:ident) => { pub type $name = AniListResponse<Paged<$inner>>; impl $name { pub fn $func(&self) -> Vec<$inner> { self.data.page.items.to_owned() } } }; }
#![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 CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudErrorBody { #[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 AttestationPolicy { #[serde(default, skip_serializing_if = "Option::is_none")] pub policy: Option<String>, }
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use crate::provider::CredentialsProvider; use smithy_http::middleware::AsyncMapRequest; use smithy_http::operation::Request; use std::future::Future; use std::pin::Pin; /// Middleware stage that requests credentials from a [CredentialsProvider] and places them in /// the property bag of the request. /// /// [CredentialsStage] implements [`AsyncMapRequest`](smithy_http::middleware::AsyncMapRequest), and: /// 1. Retrieves a `CredentialsProvider` from the property bag. /// 2. Calls the credential provider's `provide_credentials` and awaits its result. /// 3. Places returned `Credentials` into the property bad to drive downstream signing middleware. #[derive(Clone, Default)] #[non_exhaustive] pub struct CredentialsStage; impl CredentialsStage { pub fn new() -> Self { CredentialsStage } } mod error { use crate::provider::CredentialsError; use std::error::Error as StdError; use std::fmt; #[derive(Debug)] pub enum CredentialsStageError { MissingCredentialsProvider, CredentialsLoadingError(CredentialsError), } impl StdError for CredentialsStageError {} impl fmt::Display for CredentialsStageError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use CredentialsStageError::*; match self { MissingCredentialsProvider => { write!(f, "No credentials provider in the property bag") } CredentialsLoadingError(err) => write!( f, "Failed to load credentials from the credentials provider: {}", err ), } } } impl From<CredentialsError> for CredentialsStageError { fn from(err: CredentialsError) -> Self { CredentialsStageError::CredentialsLoadingError(err) } } } pub use error::*; type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>; impl AsyncMapRequest for CredentialsStage { type Error = CredentialsStageError; type Future = Pin<Box<dyn Future<Output = Result<Request, Self::Error>> + Send + 'static>>; fn apply(&self, mut request: Request) -> BoxFuture<Result<Request, Self::Error>> { Box::pin(async move { let provider = { let properties = request.properties(); let credential_provider = properties .get::<CredentialsProvider>() .ok_or(CredentialsStageError::MissingCredentialsProvider)?; // we need to enable releasing the config lock so that we don't hold the config // lock across an await point credential_provider.clone() }; let cred_future = { provider.provide_credentials() }; let credentials = cred_future.await?; request.properties_mut().insert(credentials); Ok(request) }) } } #[cfg(test)] mod tests { use super::CredentialsStage; use crate::provider::set_provider; use crate::Credentials; use smithy_http::body::SdkBody; use smithy_http::middleware::AsyncMapRequest; use smithy_http::operation; use std::sync::Arc; #[tokio::test] async fn async_map_request_apply_requires_credential_provider() { let req = operation::Request::new(http::Request::new(SdkBody::from("some body"))); CredentialsStage::new() .apply(req) .await .expect_err("should fail if there's no credential provider in the bag"); } #[tokio::test] async fn async_map_request_apply_populates_credentials() { let mut req = operation::Request::new(http::Request::new(SdkBody::from("some body"))); set_provider( &mut req.properties_mut(), Arc::new(Credentials::from_keys("test", "test", None)), ); let req = CredentialsStage::new() .apply(req) .await .expect("credential provider is in the bag; should succeed"); assert!( req.properties().get::<Credentials>().is_some(), "it should set credentials on the request config" ); } }
use crate::Operation; use failure::Fallible; use std::collections::HashMap; use uuid::Uuid; mod inmemory; mod kv; pub use self::kv::KVStorage; pub use inmemory::InMemoryStorage; /// An in-memory representation of a task as a simple hashmap pub type TaskMap = HashMap<String, String>; #[cfg(test)] fn taskmap_with(mut properties: Vec<(String, String)>) -> TaskMap { let mut rv = TaskMap::new(); for (p, v) in properties.drain(..) { rv.insert(p, v); } rv } /// A TaskStorage transaction, in which storage operations are performed. /// Serializable consistency is maintained, and implementations do not optimize /// for concurrent access so some may simply apply a mutex to limit access to /// one transaction at a time. Transactions are aborted if they are dropped. /// It's safe to drop transactions that did not modify any data. pub trait TaskStorageTxn { /// Get an (immutable) task, if it is in the storage fn get_task(&mut self, uuid: &Uuid) -> Fallible<Option<TaskMap>>; /// Create an (empty) task, only if it does not already exist. Returns true if /// the task was created (did not already exist). fn create_task(&mut self, uuid: Uuid) -> Fallible<bool>; /// Set a task, overwriting any existing task. If the task does not exist, this implicitly /// creates it (use `get_task` to check first, if necessary). fn set_task(&mut self, uuid: Uuid, task: TaskMap) -> Fallible<()>; /// Delete a task, if it exists. Returns true if the task was deleted (already existed) fn delete_task(&mut self, uuid: &Uuid) -> Fallible<bool>; /// Get the uuids and bodies of all tasks in the storage, in undefined order. fn all_tasks<'a>(&mut self) -> Fallible<Vec<(Uuid, TaskMap)>>; /// Get the uuids of all tasks in the storage, in undefined order. fn all_task_uuids<'a>(&mut self) -> Fallible<Vec<Uuid>>; /// Get the current base_version for this storage -- the last version synced from the server. fn base_version(&mut self) -> Fallible<u64>; /// Set the current base_version for this storage. fn set_base_version(&mut self, version: u64) -> Fallible<()>; /// Get the current set of outstanding operations (operations that have not been sync'd to the /// server yet) fn operations<'a>(&mut self) -> Fallible<Vec<Operation>>; /// Add an operation to the end of the list of operations in the storage. Note that this /// merely *stores* the operation; it is up to the DB to apply it. fn add_operation(&mut self, op: Operation) -> Fallible<()>; /// Replace the current list of operations with a new list. fn set_operations(&mut self, ops: Vec<Operation>) -> Fallible<()>; /// Get the entire working set, with each task UUID at its appropriate (1-based) index. /// Element 0 is always None. fn get_working_set(&mut self) -> Fallible<Vec<Option<Uuid>>>; /// Add a task to the working set and return its (one-based) index. This index will be one greater /// than the highest used index. fn add_to_working_set(&mut self, uuid: Uuid) -> Fallible<u64>; /// Remove a task from the working set. Other tasks' indexes are not affected. fn remove_from_working_set(&mut self, index: u64) -> Fallible<()>; /// Clear all tasks from the working set in preparation for a garbage-collection operation. fn clear_working_set(&mut self) -> Fallible<()>; /// Commit any changes made in the transaction. It is an error to call this more than /// once. fn commit(&mut self) -> Fallible<()>; } /// A trait for objects able to act as backing storage for a DB. This API is optimized to be /// easy to implement, with all of the semantic meaning of the data located in the DB /// implementation, which is the sole consumer of this trait. /// /// Conceptually, task storage contains the following: /// /// - tasks: a set of tasks indexed by uuid /// - base_version: the number of the last version sync'd from the server /// - operations: all operations performed since base_version /// - working_set: a mapping from integer -> uuid, used to keep stable small-integer indexes /// into the tasks. The replica maintains this list. It is not covered by operations. /// /// The `operations` are already reflected in `tasks`, so the following invariant holds: /// > Applying `operations` to the set of tasks at `base_version` gives a set of tasks identical /// > to `tasks`. /// /// It is up to the caller (DB) to maintain this invariant. pub trait TaskStorage { /// Begin a transaction fn txn<'a>(&'a mut self) -> Fallible<Box<dyn TaskStorageTxn + 'a>>; }
use criterion::{criterion_group, criterion_main, Criterion}; use rust_fizzbuzz::{fizzbuzz_kronke, fizzbuzz_kronke_branchless}; use rust_fizzbuzz::fizzbuzz_kronke_inverted; use rust_fizzbuzz::fizzbuzz_lsitarski; use std::time; pub fn fizzbuzz(c: &mut Criterion) { let mut group = c.benchmark_group("FizzBuzz"); group.sample_size(1000); group.warm_up_time(time::Duration::from_secs(10)); group.bench_function("fizzbuzz lsitarski", |b| b.iter(|| { for i in 0..60000 { fizzbuzz_lsitarski(i); } })); group.bench_function("fizzbuzz kronke", |b| b.iter(|| { for i in 0..60000 { fizzbuzz_kronke(i); } })); group.bench_function("fizzbuzz kronke inverted", |b| b.iter(|| { for i in 0..60000 { fizzbuzz_kronke_inverted(i); } })); group.bench_function("fizzbuzz kronke branchless", |b| b.iter(|| { for i in 0..60000 { fizzbuzz_kronke_branchless(i); } })); group.finish(); } criterion_group!(benches, fizzbuzz); criterion_main!(benches);
use super::*; use frame_system::RawOrigin; use frame_benchmarking::{benchmarks, account}; use sp_runtime::traits::{Bounded, Dispatchable}; const SEED: u32 = 0; benchmarks! { _ { let u in 1..1000 => (); } create_multisig_wallet { let u in ...; let creator: T::AccountId = account("creator", u, SEED); let member1 = account("member1", u, SEED); let member2 = account("member2", u, SEED); let mut members = vec![creator.clone(), member1, member2]; members.sort(); }: _(RawOrigin::Signed(creator), members, Percent::from_percent(50)) }
use toml; use std::fs::File; use std::io::prelude::*; use std::net::SocketAddr; #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct ServerConfig { pub interface_and_port: SocketAddr, pub max_ping_ms: u64, } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct GrabberConfig { pub servers: Vec<SocketAddr>, pub max_ping_ms: u64, pub mouse_interval_ms: u64, pub keyboard_and_clicks_interval_ms: u64, } #[derive(Deserialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct SecurityConfig { pub password: String, } macro_rules! generate_loader { ($struct:tt) => { impl $struct { pub fn load() -> $struct { let filename = stringify!($struct).to_string() + ".toml"; let filename = &filename; let mut file = File::open(filename) .unwrap_or_else(|_| panic!("File {} doesn't exist", filename)); let mut contents = String::new(); file.read_to_string(&mut contents) .unwrap_or_else(|_| panic!("{} is not UTF-8 formatted", filename)); toml::from_str(&contents) .unwrap_or_else(|_| panic!("{} is not a valid TOML file", filename)) } } }; } generate_loader!(ServerConfig); generate_loader!(GrabberConfig); generate_loader!(SecurityConfig);
enum Color { Red, Green, Blue, RGBColor(u8, u8, u8), // tuple CmykColor { // struct cyan: u8, magenta: u8, yellow: u8, black: u8 } } enum Gender { TheMan, Chupakabra, TheWoman } struct User { gender: Gender, favorite_color: Color } pub fn run() { println!("\n====4.19 ENUMS===="); // Create new color let c:Color = Color::Green; match c { Color::Red => println!("RED"), // Color::Green => println!("GREEN"), Color::Blue => println!("BLUE"), Color::RGBColor(0, 0, 0) => println!("BLACK"), // Если не сматчитлся, то напечатать "SOME COLOR" // Попробуй закомментить Color::Green => println!("GREEN"). // Так же попробуй закоментить Color::Green => println!("GREEN") и строку _ => println!("SOME COLOR") ниже. // Компилятор наорет на тебя, что не все случаи обработаны "pattern <Pattern> not covered" _ => println!("SOME COLOR") }; let rgb_black: Color = Color::RGBColor(0, 0, 0); match_color(rgb_black); let some_user: User = User { gender: Gender::Chupakabra, favorite_color: Color::RGBColor(1,2,3) }; println!("The user gender is {}, and user like {} color", match_gender(some_user.gender), match_color(some_user.favorite_color) ); let enother_user: User = User { gender: Gender::TheMan, favorite_color: Color::CmykColor{ cyan: 1, magenta: 2, yellow: 3, black: 255 } }; println!("The user gender is {}, and user like {} color", match_gender(enother_user.gender), match_color(enother_user.favorite_color) ); let one_more_user: User = User { gender: Gender::TheWoman, favorite_color: Color::CmykColor{ cyan: 1, magenta: 2, yellow: 3, black: 30 } }; println!("The user gender is {}, and user like {} color", match_gender(one_more_user.gender), match_color(one_more_user.favorite_color) ); } fn match_gender(gender: Gender) -> String { // Лучше сделать, impl fmt::Display for Gender но это будет в следующих уроках. match gender { Gender::TheMan => String::from("man"), Gender::TheWoman => String::from("woman "), Gender::Chupakabra => String::from("chupakabra"), } } fn match_color(color: Color) -> String { // Не переношу повторяющийся код из run() для того чтобы пример был понятным. // Лучше сделать, impl fmt::Display for Color но это будет в следующих уроках. match color { Color::Red => String::from("RED"), Color::Green => String::from("GREEN"), Color::Blue => String::from("BLUE"), Color::RGBColor(0, 0, 0) // rgb black = 000 // | Color::CmykColor{cyan: _, magenta: _, yellow: _, black: 255} => format!("BLACK"), // Cmyk blaack is when black 255 "_" mean any value // the same as: | Color::CmykColor{black: 255, ..} => format!("BLACK"), // Cmyk blaack is when black 255 "_" mean any value Color::RGBColor(r, g, b) => format!("rgb({}, {}, {})", r, g, b), Color::CmykColor{cyan: c, magenta: m, yellow: y, black: b} => format!("cmyk({}, {}, {}, {})", c, m, y, b), _ => String::from("SOME COLOR") } }
use std::io::Result; use std::pin::Pin; use std::task::{Context, Poll}; use discovery::ServiceDiscover; use protocol::Protocol; use stream::{AsyncReadAll, AsyncWriteAll, Request, Response}; macro_rules! define_endpoint { ($($top:tt, $item:ident, $type_name:tt, $ep:expr);+) => { #[derive(Clone)] pub enum Topology<P> { $($item($top<P>)),+ } impl<P> Topology<P> { pub fn from(parser:P, endpoint:String) -> Option<Self> { match &endpoint[..]{ $($ep => Some(Self::$item(parser.into())),)+ _ => None, } } } impl<P> discovery::Topology for Topology<P> where P:Clone+Sync+Send+Protocol+'static{ fn update(&mut self, cfg: &str, name: &str) { match self { $(Self::$item(s) => discovery::Topology::update(s, cfg, name),)+ } } } pub enum Endpoint<P> { $($item($type_name<P>)),+ } impl<P> Endpoint<P> { pub async fn from_discovery<D>(name: &str, p:P, discovery:D) -> Result<Option<Self>> where D: ServiceDiscover<Topology<P>> + Unpin + 'static, P:protocol::Protocol, { match name { $($ep => Ok(Some(Self::$item($type_name::from_discovery(p, discovery).await?))),)+ _ => Ok(None), } } } impl<P> AsyncReadAll for Endpoint<P> where P: Unpin+Protocol{ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<Response>> { match &mut *self { $(Self::$item(ref mut p) => Pin::new(p).poll_next(cx),)+ } } } impl<P> AsyncWriteAll for Endpoint<P> where P:Unpin+Protocol{ fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &Request) -> Poll<Result<()>>{ match &mut *self { $(Self::$item(ref mut p) => Pin::new(p).poll_write(cx, buf),)+ } } } }; } mod cacheservice; //mod pipe; use cacheservice::CacheService; use cacheservice::Topology as CSTopology; //use pipe::{Pipe, PipeTopology}; define_endpoint! { // PipeTopology, Pipe, Pipe, "pipe"; CSTopology, CacheService, CacheService, "cs" } impl<P> left_right::Absorb<(String, String)> for Topology<P> where P: Clone + Sync + Send + Protocol + 'static, { fn absorb_first(&mut self, cfg: &mut (String, String), _other: &Self) { discovery::Topology::update(self, &cfg.0, &cfg.1) } fn sync_with(&mut self, first: &Self) { *self = first.clone(); } }
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(stmt_expr_attributes)] #![warn(clippy::deprecated_cfg_attr)] // This doesn't get linted, see known problems #![cfg_attr(rustfmt, rustfmt_skip)] #[rustfmt::skip] trait Foo { fn foo( ); } fn skip_on_statements() { #[cfg_attr(rustfmt, rustfmt::skip)] 5+3; } #[cfg_attr(rustfmt, rustfmt_skip)] fn main() { foo::f(); } mod foo { #![cfg_attr(rustfmt, rustfmt_skip)] pub fn f() {} }
// Copyright (c) 2017 The Noise-rs Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT // or http://opensource.org/licenses/MIT>, at your option. All files in the // project carrying such notice may not be copied, modified, or distributed // except according to those terms. use modules::NoiseModule; use num_traits::Float; /// Noise module that outputs a constant value. /// /// This module takes a input, value, and returns that input for all points, /// producing a constant-valued field. /// /// This module is not very useful by itself, but can be used as a source /// module for other noise modules. #[derive(Clone, Copy, Debug)] pub struct Constant<T: Float> { /// Constant value. pub value: T, } impl<T: Float> Constant<T> { pub fn new(value: T) -> Constant<T> { Constant { value: value } } } impl<T, U> NoiseModule<T, U> for Constant<U> where T: Copy, U: Float, { fn get(&self, _point: T) -> U { self.value } }
// figure.rs Example using a figure // // Copyright (c) 2017 Douglas P Lau // extern crate footile; use footile::{ FillRule, PlotterBuilder }; fn main() { let mut p = PlotterBuilder::new() .width(64) .height(64) .build(); p.pen_width(1f32, false); p.move_to(4f32, 4f32); p.line_to(28f32, 12f32); p.line_to(28f32, -12f32); p.line_to(-12f32, 28f32); p.line_to(12f32, 28f32); p.line_to(-28f32, -4f32); p.line_to(-28f32, 4f32); p.line_to(12f32, -28f32); p.close(); p.fill(FillRule::EvenOdd); p.write_pgm("./figure.pgm").unwrap(); }
use super::OM_uint32; extern "C" { #[link_name = "GSS_C_DELEG_FLAG_SHIM"] pub static GSS_C_DELEG_FLAG: OM_uint32; #[link_name = "GSS_C_MUTUAL_FLAG_SHIM"] pub static GSS_C_MUTUAL_FLAG: OM_uint32; #[link_name = "GSS_C_REPLAY_FLAG_SHIM"] pub static GSS_C_REPLAY_FLAG: OM_uint32; #[link_name = "GSS_C_SEQUENCE_FLAG_SHIM"] pub static GSS_C_SEQUENCE_FLAG: OM_uint32; #[link_name = "GSS_C_CONF_FLAG_SHIM"] pub static GSS_C_CONF_FLAG: OM_uint32; #[link_name = "GSS_C_INTEG_FLAG_SHIM"] pub static GSS_C_INTEG_FLAG: OM_uint32; #[link_name = "GSS_C_ANON_FLAG_SHIM"] pub static GSS_C_ANON_FLAG: OM_uint32; #[link_name = "GSS_C_PROT_READY_FLAG_SHIM"] pub static GSS_C_PROT_READY_FLAG: OM_uint32; #[link_name = "GSS_C_TRANS_FLAG_SHIM"] pub static GSS_C_TRANS_FLAG: OM_uint32; #[link_name = "GSS_C_DELEG_POLICY_FLAG_SHIM"] pub static GSS_C_DELEG_POLICY_FLAG: OM_uint32; /// Status code types for gss_display_status. #[link_name = "GSS_C_GSS_CODE_SHIM"] pub static GSS_C_GSS_CODE: ::std::os::raw::c_int; /// Status code types for gss_display_status. #[link_name = "GSS_C_MECH_CODE_SHIM"] pub static GSS_C_MECH_CODE: ::std::os::raw::c_int; #[link_name = "GSS_S_COMPLETE_SHIM"] pub static GSS_S_COMPLETE: OM_uint32; #[link_name = "GSS_C_SUPPLEMENTARY_OFFSET_SHIM"] pub static GSS_C_SUPPLEMENTARY_OFFSET: OM_uint32; #[link_name = "GSS_S_CONTINUE_NEEDED_SHIM"] pub static GSS_S_CONTINUE_NEEDED: OM_uint32; #[link_name = "GSS_S_DUPLICATE_TOKEN_SHIM"] pub static GSS_S_DUPLICATE_TOKEN: OM_uint32; #[link_name = "GSS_S_OLD_TOKEN_SHIM"] pub static GSS_S_OLD_TOKEN: OM_uint32; #[link_name = "GSS_S_UNSEQ_TOKEN_SHIM"] pub static GSS_S_UNSEQ_TOKEN: OM_uint32; #[link_name = "GSS_S_GAP_TOKEN_SHIM"] pub static GSS_S_GAP_TOKEN: OM_uint32; }
#![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 ClusterProperties { #[serde(rename = "clusterId", skip_serializing)] pub cluster_id: Option<String>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<cluster_properties::ProvisioningState>, #[serde(rename = "isDoubleEncryptionEnabled", skip_serializing_if = "Option::is_none")] pub is_double_encryption_enabled: Option<bool>, #[serde(rename = "isAvailabilityZonesEnabled", skip_serializing_if = "Option::is_none")] pub is_availability_zones_enabled: Option<bool>, #[serde(rename = "billingType", skip_serializing_if = "Option::is_none")] pub billing_type: Option<cluster_properties::BillingType>, #[serde(rename = "keyVaultProperties", skip_serializing_if = "Option::is_none")] pub key_vault_properties: Option<KeyVaultProperties>, } pub mod cluster_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Succeeded, Failed, Canceled, Deleting, ProvisioningAccount, Updating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum BillingType { Cluster, Workspaces, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterErrorResponse { #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<ErrorResponse>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterPatchProperties { #[serde(rename = "keyVaultProperties", skip_serializing_if = "Option::is_none")] pub key_vault_properties: Option<KeyVaultProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterPatch { #[serde(skip_serializing_if = "Option::is_none")] pub properties: Option<ClusterPatchProperties>, #[serde(skip_serializing_if = "Option::is_none")] pub identity: Option<Identity>, #[serde(skip_serializing_if = "Option::is_none")] pub sku: Option<ClusterSku>, #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Cluster { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(skip_serializing_if = "Option::is_none")] pub identity: Option<Identity>, #[serde(skip_serializing_if = "Option::is_none")] pub sku: Option<ClusterSku>, #[serde(skip_serializing_if = "Option::is_none")] pub properties: Option<ClusterProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterListResult { #[serde(rename = "nextLink", skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] pub value: Vec<Cluster>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyVaultProperties { #[serde(rename = "keyVaultUri", skip_serializing_if = "Option::is_none")] pub key_vault_uri: Option<String>, #[serde(rename = "keyName", skip_serializing_if = "Option::is_none")] pub key_name: Option<String>, #[serde(rename = "keyVersion", skip_serializing_if = "Option::is_none")] pub key_version: Option<String>, #[serde(rename = "rsaKeySize", skip_serializing_if = "Option::is_none")] pub rsa_key_size: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClusterSku { #[serde(skip_serializing_if = "Option::is_none")] pub capacity: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<cluster_sku::Name>, } pub mod cluster_sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { CapacityReservation, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identity { #[serde(rename = "principalId", skip_serializing)] pub principal_id: Option<String>, #[serde(rename = "tenantId", skip_serializing)] pub tenant_id: Option<String>, #[serde(rename = "type")] pub type_: identity::Type, #[serde(rename = "userAssignedIdentities", 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, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserIdentityProperties { #[serde(rename = "principalId", skip_serializing)] pub principal_id: Option<String>, #[serde(rename = "clientId", skip_serializing)] pub client_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", skip_serializing)] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(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(skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(skip_serializing)] pub code: Option<String>, #[serde(skip_serializing)] pub message: Option<String>, #[serde(skip_serializing)] pub target: Option<String>, #[serde(skip_serializing)] pub details: Vec<ErrorResponse>, #[serde(rename = "additionalInfo", skip_serializing)] pub additional_info: Vec<ErrorAdditionalInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorAdditionalInfo { #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, #[serde(skip_serializing)] pub info: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(skip_serializing)] pub id: Option<String>, #[serde(skip_serializing)] pub name: Option<String>, #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, }
fn main() { println!("Hello, world!"); my_function(123); let a = { let b = 4; // 这句不能有分号,否则为表达式,不产生返回值 b+1 }; println!("a:{}", a); println!("five():{}", five()); println!("============="); test_loop(); println!("============="); test_for(); } fn my_function(x : i32) { println!("param x:{}", x); } fn five() ->i32{ 5 } fn test_loop(){ let mut i = 0; loop{ if i>4{ break } i = i+1; println!("again!"); } } fn test_for(){ for num in (1..4).rev(){ println!("{}!", num); } }
mod header; pub use header::Header;
use ansi_term::Style; use console::strip_ansi_codes; use pulldown_cmark::{Options, Parser}; use std::convert::TryInto; use std::fs; use std::io::{self, Read}; use std::path::PathBuf; use structopt::StructOpt; use syncat_stylesheet::Stylesheet; use terminal_size::{terminal_size, Width}; mod dirs; mod printer; mod str_width; mod table; mod termpix; mod words; use printer::Printer; use str_width::str_width; use words::Words; /// Prints papers in your terminal #[derive(StructOpt, Debug)] #[structopt(name = "paper")] #[structopt(rename_all = "kebab-case")] #[structopt(setting = structopt::clap::AppSettings::ColoredHelp)] pub struct Opts { /// Margin (shortcut for horizontal and vertical margin set to the same value) #[structopt(short, long, default_value = "6")] pub margin: usize, /// Horizontal margin (overrides --margin) #[structopt(short, long)] pub h_margin: Option<usize>, /// Vertical margin (overrides --margin) #[structopt(short, long)] pub v_margin: Option<usize>, /// The width of the paper (including the space used for the margin) #[structopt(short, long, default_value = "92")] pub width: usize, /// Don't parse as Markdown, just render the plain text on a paper #[structopt(short, long)] pub plain: bool, /// The length to consider tabs as. #[structopt(short, long, default_value = "4")] pub tab_length: usize, /// Hide link URLs #[structopt(short = "u", long)] pub hide_urls: bool, /// Disable drawing images #[structopt(short = "i", long)] pub no_images: bool, /// Use syncat to highlight code blocks. Requires you have syncat installed. #[structopt(short, long)] pub syncat: bool, /// Print in debug mode #[structopt(long)] pub dev: bool, /// Files to print #[structopt(name = "FILE", parse(from_os_str))] pub files: Vec<PathBuf>, } fn normalize(tab_len: usize, source: &str) -> String { source .lines() .map(|line| { let mut len = 0; let line = strip_ansi_codes(line); if line.contains('\t') { line.chars() .flat_map(|ch| { if ch == '\t' { let missing = tab_len - (len % tab_len); len += missing; vec![' '; missing] } else { len += 1; vec![ch] } }) .collect::<String>() .into() } else { line } }) .map(|line| format!("{}\n", line)) .collect::<String>() } fn print<I>(opts: Opts, sources: I) where I: Iterator<Item = Result<String, std::io::Error>>, { let h_margin = opts.h_margin.unwrap_or(opts.margin); let v_margin = opts.v_margin.unwrap_or(opts.margin); let terminal_width = terminal_size() .map(|(Width(width), _)| width) .unwrap_or(opts.width as u16) as usize; let width = usize::min(opts.width, terminal_width - 1); if width < h_margin * 2 + 40 { eprintln!("The width is too short!"); return; } let centering = " ".repeat((terminal_width.saturating_sub(width)) / 2); let stylesheet = Stylesheet::from_file(dirs::active_color().join("paper.syncat")) .unwrap_or_else(|_| { include_str!("default.syncat") .parse::<Stylesheet>() .unwrap() }); let paper_style: Style = stylesheet .style(&"paper".into()) .unwrap_or_default() .try_into() .unwrap_or_default(); let shadow_style: Style = stylesheet .style(&"shadow".into()) .unwrap_or_default() .try_into() .unwrap_or_default(); let blank_line = format!("{}", paper_style.paint(" ".repeat(width))); let end_shadow = format!("{}", shadow_style.paint(" ")); let margin = format!("{}", paper_style.paint(" ".repeat(h_margin))); let available_width = width - 2 * h_margin; for source in sources { let source = match source { Ok(source) => normalize(opts.tab_length, &source), Err(error) => { println!("{}", error); continue; } }; if opts.plain { println!("{}{}", centering, blank_line); for _ in 0..v_margin { println!("{}{}{}", centering, blank_line, end_shadow); } for line in source.lines() { let mut buffer = String::new(); let mut indent = None; for word in Words::preserving_whitespace(line) { if str_width(&buffer) + str_width(&word) > available_width { println!( "{}{}{}{}{}{}", centering, margin, paper_style.paint(&buffer), paper_style.paint( " ".repeat(available_width.saturating_sub(str_width(&buffer))) ), margin, shadow_style.paint(" "), ); buffer.clear(); } if buffer.is_empty() { if indent.is_none() { let indent_len = word.chars().take_while(|ch| ch.is_whitespace()).count(); indent = Some(word[0..indent_len].to_string()); } buffer.push_str(indent.as_ref().unwrap()); buffer.push_str(word.trim()); } else { buffer.push_str(&word); } } println!( "{}{}{}{}{}{}", centering, margin, paper_style.paint(&buffer), paper_style .paint(" ".repeat(available_width.saturating_sub(str_width(&buffer)))), margin, shadow_style.paint(" "), ); } for _ in 0..v_margin { println!("{}{}{}", centering, blank_line, end_shadow); } println!("{} {}", centering, shadow_style.paint(" ".repeat(width))); } else if opts.dev { let parser = Parser::new_ext(&source, Options::all()); for event in parser { println!("{:?}", event); } } else { let parser = Parser::new_ext(&source, Options::all()); println!("{}{}", centering, blank_line); for _ in 0..v_margin { println!("{}{}{}", centering, blank_line, end_shadow); } let mut printer = Printer::new(&centering, &margin, available_width, &stylesheet, &opts); for event in parser { printer.handle(event); } for _ in 0..v_margin { println!("{}{}{}", centering, blank_line, end_shadow); } println!("{} {}", centering, shadow_style.paint(" ".repeat(width))); } } } fn main() { let opts = Opts::from_args(); if opts.files.is_empty() { let mut string = String::new(); io::stdin().read_to_string(&mut string).unwrap(); print(opts, vec![Ok(string)].into_iter()); } else { let sources = opts .files .clone() .into_iter() .map(|path| fs::read_to_string(&path)); print(opts, sources); } }
use super::{Environment, Event, MarketData, Order}; use crate::economy::Market; use crate::traders::Action; use async_trait::async_trait; use binance_async::Binance; use sqlx::PgPool; use std::time::Duration; struct MarketValueChange { symbol: String, value: f64, timestamp: i64, } pub struct Historical { timestamp: i64, buffer: Vec<MarketValueChange>, pool: PgPool, binance: Binance, events: Vec<Event>, } impl Historical { pub async fn new(start_at: i64) -> Historical { dotenv::dotenv().ok(); Historical { timestamp: start_at, buffer: Vec::new(), pool: PgPool::new(&std::env::var("DATABASE_URL").unwrap()) .await .unwrap(), binance: Binance::with_credential( &std::env::var("BINANCE_API_KEY").unwrap(), &std::env::var("BINANCE_SECRET_KEY").unwrap(), ), events: vec![Event::SetAssetBalance(String::from("USDT"), 200.0)], } } } #[async_trait] impl Environment for Historical { async fn initialize(&mut self) -> Result<Vec<MarketData>, ()> { let stats = self .binance .get_24h_price_stats_all() .unwrap() .await .unwrap(); let mut symbols = Vec::new(); for stat in stats { if stat.count >= 3600 { symbols.push(stat.symbol); } } let exchange_info = self.binance.get_exchange_info().unwrap().await.unwrap(); let mut markets = Vec::new(); for symbol in exchange_info.symbols { if symbols.contains(&symbol.symbol) && (symbol.base_asset == "USDT" || symbol.quote_asset == "USDT") { markets.push(symbol); } } Ok(markets) } async fn poll(&mut self) -> Event { if let Some(event) = self.events.pop() { return event; } if self.buffer.is_empty() { println!("fetching data ..."); self.buffer = sqlx::query_as!( MarketValueChange, " SELECT symbol, value, timestamp * 60 AS timestamp FROM tickers WHERE timestamp >= $1::BIGINT / 60 AND timestamp < $1::BIGINT / 60 + 60 * 24 ORDER BY timestamp DESC ", self.timestamp ) .fetch_all(&self.pool) .await .unwrap(); } let timestamp = self.buffer.last().unwrap().timestamp; if timestamp > self.timestamp { let duration = Duration::from_secs((timestamp - self.timestamp) as u64); self.timestamp = timestamp; return Event::Evaluate(0); } let next = self.buffer.pop().unwrap(); Event::SetMarketValue(next.symbol, next.value) } async fn order(&mut self, symbol: &str, order: Order) -> Result<(), ()> { Ok(()) } }
#[doc = "Register `AXIMC_PERIPH_ID_3` reader"] pub type R = crate::R<AXIMC_PERIPH_ID_3_SPEC>; #[doc = "Field `CUST_MOD_NUM` reader - CUST_MOD_NUM"] pub type CUST_MOD_NUM_R = crate::FieldReader; #[doc = "Field `REV_AND` reader - REV_AND"] pub type REV_AND_R = crate::FieldReader; impl R { #[doc = "Bits 0:3 - CUST_MOD_NUM"] #[inline(always)] pub fn cust_mod_num(&self) -> CUST_MOD_NUM_R { CUST_MOD_NUM_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - REV_AND"] #[inline(always)] pub fn rev_and(&self) -> REV_AND_R { REV_AND_R::new(((self.bits >> 4) & 0x0f) as u8) } } #[doc = "AXIMC peripheral ID3 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`aximc_periph_id_3::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct AXIMC_PERIPH_ID_3_SPEC; impl crate::RegisterSpec for AXIMC_PERIPH_ID_3_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`aximc_periph_id_3::R`](R) reader structure"] impl crate::Readable for AXIMC_PERIPH_ID_3_SPEC {} #[doc = "`reset()` method sets AXIMC_PERIPH_ID_3 to value 0"] impl crate::Resettable for AXIMC_PERIPH_ID_3_SPEC { const RESET_VALUE: Self::Ux = 0; }
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Defines messages used for communication between Trichechus and Cronista for storing and //! retrieving persistent data. use serde::{Deserialize, Serialize}; use crate::storage::StorableMember; /// Represents the possible status codes from an RPC. /// Values are assigned to make it easier to interface with D-Bus. #[derive(Debug, Deserialize, Serialize)] pub enum Status { Success = 0, Failure = 1, } /// Should the data be globally available or only available within the users' sessions. /// Values are assigned to make it easier to interface with D-Bus. #[derive(Debug, Deserialize, Serialize)] pub enum Scope { System = 0, Session = 1, Test = -1, } //TODO These messages also need to carry enough information to prove the entry was recorded in the //log. #[derive(Deserialize, Serialize)] pub enum Request { Persist { scope: Scope, domain: String, identifier: String, data: StorableMember, }, Retrieve { scope: Scope, domain: String, identifier: String, }, } #[derive(Deserialize, Serialize)] pub enum Response { Persist { status: Status, }, Retrieve { status: Status, data: StorableMember, }, }
use csv::ReaderBuilder; use std::io; use structopt::StructOpt; /// Read newline delimited data from stdin and structurally parse based on delimiters #[derive(StructOpt, Debug)] struct Cli { /// The character delimiter used to split a line into fields #[structopt(short = "d", long = "delimiter", default_value = ",")] delimiter: String, /// The fields you would like to return. E.g. for the first, fifth to seventh inclusive, and tenth onwards: '1,5-7,10-' (spaces will be ignored) #[structopt(short = "f", long = "fields")] fields: String, /// Escape character, fields wrapped in this character will not be split by the delimiter. Double escape character will not escape and be read as the character. #[structopt(short = "e", long = "escape-character", default_value = "\"")] escape_char: String, /// Use zero based indexing for fields #[structopt(short = "z", long = "zero-index")] zero_index: bool, } struct SvfBufReader { buffer: Vec<u8> } impl SvfBufReader { fn new() -> SvfBufReader { // TODO: check the performance impact SvfBufReader { buffer: Vec::with_capacity(1000) } } // fn read_record(&self) { // vec!["testing", "testing", "123"] // } } fn main() -> io::Result<()> { let args = Cli::from_args(); let mut rdr = ReaderBuilder::new() .delimiter(args.delimiter.as_bytes()[0]) .from_reader(io::stdin()); for record in rdr.records() { println!("Record is: {:?}", record); } Ok(()) }
// 2019-01-06 // Les fonctions associées sont définies dans un bloc d'implémentation mais ne // prennent pas self comme paramètre. // Ici on va définir une fonction associée construira une instance de struct. // square() fabriquera une instance de Rectangle qui sera un carré. use std::io; #[derive(Debug)] // Définition du struct. struct Rectangle { largeur: u32, longueur: u32, } fn main() { // demander à l'utilisateur le côté du carré, variable 'cote' println!("Quel côté aura votre carré ?"); let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Pas pu lire l'entrée"); let cote: u32 = input .trim() .parse() .expect("On veut un nombre !"); println!( "Nous avons créé votre carré, le voici : {:#?} et son aire est de {} pixels carrés.", // voici la syntaxe pour appeler fonction associée // Struct::fonction(paramètre) // Cette chose est de facto une instance du struct Rectangle ! Rectangle::square(cote), // syntaxe d'une méthode // paramètre.méthode() // ici le paramètre est l'instance du struct retourné par la fonction // associée. Dingue ! Rectangle::square(cote).aire() ); } // Dans un seul bloc d'implémentation, on peut définir plusieurs méthodes impl Rectangle { // la fonction associée square() construit une instance de Rectangle // le paramètre doit être un entier // la fonction renvoie une instance du Struct, utilisable directement ! fn square(size: u32) -> Rectangle { Rectangle { largeur: size, longueur: size} } // MÉTHODE qui calcule l'aire fn aire(&self) -> u32 { self.longueur * self.largeur } }
#[cfg(test)] mod tests { use tests_writing::libx::x; use tests_writing::liby::y; use tests_writing::test_helper::helper; #[test] fn test_together() { assert_eq!(x() + y(), 66); assert_eq!(helper(), "Hello"); } }
use serde::{de, ser}; use std::fmt; pub type SerdeResult<T> = std::result::Result<T, SerdeError>; #[derive(Debug)] pub struct SerdeError { err: Box<ErrorCode>, } impl SerdeError { pub(crate) fn create(msg: impl Into<ErrorCode>) -> Self { Self { err: Box::new(msg.into()), } } pub(crate) fn impl_err(msg: impl Into<String>) -> Self { Self { err: Box::new(ErrorCode::ImplementationError(msg.into())), } } } impl fmt::Display for SerdeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.err) } } impl ser::Error for SerdeError { fn custom<T: fmt::Display>(msg: T) -> Self { Self::create(msg.to_string()) } } impl de::Error for SerdeError { fn custom<T: fmt::Display>(msg: T) -> Self { Self::create(msg.to_string()) } fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self { if let de::Unexpected::Unit = unexp { SerdeError::custom(format_args!("invalid type: null, expected {}", exp)) } else { SerdeError::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) } } } impl std::error::Error for SerdeError { fn cause(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(self) } } impl From<std::str::Utf8Error> for SerdeError { fn from(m: std::str::Utf8Error) -> Self { Self::create(m.to_string()) } } impl From<std::string::FromUtf8Error> for SerdeError { fn from(m: std::string::FromUtf8Error) -> Self { Self::create(m.to_string()) } } #[derive(Debug)] pub(crate) enum ErrorCode { Message(String), ImplementationError(String), UnexpectedEndOfBytes, UnexpectedTrailingBytes, VirtualIllegalAssignment, } impl fmt::Display for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Message(b_str) => write!(f, "{}", b_str), Self::ImplementationError(b_str) => write!( f, "{}\n - This is an implementation error, check custom Serde implementations", b_str ), Self::UnexpectedEndOfBytes => write!(f, "Unexpected end of bytes"), Self::UnexpectedTrailingBytes => { write!(f, "Unexpected trailing bytes left in the input") } Self::VirtualIllegalAssignment => write!( f, "Virtual marker and value must be consumed before setting new one" ), } } } impl From<String> for ErrorCode { fn from(s: String) -> Self { Self::Message(s) } } impl From<&str> for ErrorCode { fn from(s: &str) -> Self { Self::Message(s.to_owned()) } }
pub mod models; pub mod schema; pub mod listdao;
// Copyright 2020 EinsteinDB Project Authors. Licensed under Apache-2.0. use super::{AckedIndexer, VoteResult}; use crate::util::Union; use crate::HashSet; use crate::MajorityConfig; use std::cmp; /// A configuration of two groups of (possibly overlapping) majority configurations. /// Decisions require the support of both majorities. #[derive(Clone, Debug, Default, PartialEq)] pub struct Configuration { pub(crate) incoming: MajorityConfig, pub(crate) outgoing: MajorityConfig, } impl Configuration { /// Creates a new configuration using the given IDs. pub fn new(voters: HashSet<u64>) -> Configuration { Configuration { incoming: MajorityConfig::new(voters), outgoing: MajorityConfig::default(), } } #[cfg(test)] pub(crate) fn new_joint_from_majorities( incoming: MajorityConfig, outgoing: MajorityConfig, ) -> Self { Self { incoming, outgoing } } /// Creates an empty configuration with given capacity. pub fn with_capacity(cap: usize) -> Configuration { Configuration { incoming: MajorityConfig::with_capacity(cap), outgoing: MajorityConfig::default(), } } /// Returns the largest committed index for the given joint quorum. An index is /// jointly committed if it is committed in both constituent majorities. /// /// The bool flag indicates whether the index is computed by group commit algorithm /// successfully. It's true only when both majorities use group commit. pub fn committed_index(&self, use_group_commit: bool, l: &impl AckedIndexer) -> (u64, bool) { let (i_idx, i_use_gc) = self.incoming.committed_index(use_group_commit, l); let (o_idx, o_use_gc) = self.outgoing.committed_index(use_group_commit, l); (cmp::min(i_idx, o_idx), i_use_gc && o_use_gc) } /// Takes a mapping of voters to yes/no (true/false) votes and returns a result /// indicating whether the vote is pending, lost, or won. A joint quorum requires /// both majority quorums to vote in favor. pub fn vote_result(&self, check: impl Fn(u64) -> Option<bool>) -> VoteResult { let i = self.incoming.vote_result(&check); let o = self.outgoing.vote_result(check); match (i, o) { // It won if won in both. (VoteResult::Won, VoteResult::Won) => VoteResult::Won, // It lost if lost in either. (VoteResult::Lost, _) | (_, VoteResult::Lost) => VoteResult::Lost, // It remains pending if pending in both or just won in one side. _ => VoteResult::Pending, } } /// Clears all IDs. pub fn clear(&mut self) { self.incoming.clear(); self.outgoing.clear(); } /// Returns true if (and only if) there is only one voting member /// (i.e. the leader) in the current configuration. pub fn is_singleton(&self) -> bool { self.outgoing.is_empty() && self.incoming.len() == 1 } /// Returns an iterator over two hash set without cloning. pub fn ids(&self) -> Union<'_> { Union::new(&self.incoming, &self.outgoing) } /// Check if an id is a voter. #[inline] pub fn contains(&self, id: u64) -> bool { self.incoming.contains(&id) || self.outgoing.contains(&id) } /// Describe returns a (multi-line) representation of the commit indexes for the /// given lookuper. #[cfg(test)] pub(crate) fn describe(&self, l: &impl AckedIndexer) -> String { MajorityConfig::new(self.ids().iter().collect()).describe(l) } }
// Copyright 2019, 2020 Wingchain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fs; use std::net::SocketAddrV4; use std::path::{Path, PathBuf}; use std::sync::Arc; use crypto::dsa::{Dsa, DsaImpl, KeyPair}; use main_base::config::Config as FileConfig; use node_api::ApiConfig; use node_chain::{Basic, ChainConfig}; use node_coordinator::{ ed25519, CoordinatorConfig, Keypair, LinkedHashMap, Multiaddr, PeerId, Protocol, }; use node_db::{DBConfig, Partition}; use node_txpool::TxPoolConfig; use primitives::errors::CommonResult; use primitives::SecretKey; use crate::errors::ErrorKind; use crate::{errors, ServiceConfig}; use node_consensus::{ConsensusConfig, HotStuffConfig, PoaConfig, RaftConfig}; pub struct OtherConfig { pub txpool: TxPoolConfig, pub api: ApiConfig, pub consensus: ConsensusConfig, pub coordinator: CoordinatorConfig, } pub fn get_file_config(home: &Path) -> CommonResult<FileConfig> { let config_path = home.join(main_base::CONFIG).join(main_base::CONFIG_FILE); let config = fs::read_to_string(&config_path).map_err(|_| { errors::ErrorKind::Config(format!("Failed to read config file: {:?}", config_path)) })?; let config = toml::from_str(&config) .map_err(|e| errors::ErrorKind::Config(format!("Failed to parse config file: {:?}", e)))?; Ok(config) } pub fn get_chain_config( file_config: &FileConfig, service_config: &ServiceConfig, ) -> CommonResult<ChainConfig> { let home = &service_config.home; let db = get_db_config(file_config, home)?; let chain_config = ChainConfig { home: home.to_path_buf(), db, }; Ok(chain_config) } pub fn get_other_config( file_config: &FileConfig, service_config: &ServiceConfig, basic: Arc<Basic>, ) -> CommonResult<OtherConfig> { let home = &service_config.home; let agent_version = &service_config.agent_version; let config = OtherConfig { txpool: get_txpool_config(&file_config)?, api: get_api_config(&file_config)?, consensus: get_consensus_config(&file_config, home, basic)?, coordinator: get_coordinator_config(&file_config, home, agent_version)?, }; Ok(config) } fn get_txpool_config(file_config: &FileConfig) -> CommonResult<TxPoolConfig> { let txpool = TxPoolConfig { pool_capacity: file_config.txpool.pool_capacity, }; Ok(txpool) } fn get_api_config(file_config: &FileConfig) -> CommonResult<ApiConfig> { let api = ApiConfig { rpc_addr: file_config.api.rpc_addr.clone(), rpc_workers: file_config.api.rpc_workers, rpc_maxconn: file_config.api.rpc_maxconn, }; Ok(api) } fn get_db_config(file_config: &FileConfig, home: &Path) -> CommonResult<DBConfig> { let path = { let path = file_config .db .path .clone() .unwrap_or_else(|| PathBuf::from(main_base::DATA).join(main_base::DB)); get_abs_path(&path, home) }; let partitions = match &file_config.db.partitions { Some(partitions) => partitions .iter() .map(|p| { let path = get_abs_path(&p.path, home); Partition { path, target_size: p.target_size, } }) .collect(), None => vec![], }; let db = DBConfig { memory_budget: file_config.db.memory_budget, path, partitions, }; Ok(db) } fn get_consensus_config( file_config: &FileConfig, home: &Path, basic: Arc<Basic>, ) -> CommonResult<ConsensusConfig> { let poa = match &file_config.consensus.poa { Some(poa) => { let secret_key = match &poa.secret_key_file { Some(file) => Some(get_secret_key(file, home, &basic)?), None => None, }; Some(PoaConfig { secret_key }) } None => None, }; let raft = match &file_config.consensus.raft { Some(raft) => { let secret_key = match &raft.secret_key_file { Some(file) => Some(get_secret_key(file, home, &basic)?), None => None, }; Some(RaftConfig { secret_key, init_extra_election_timeout: raft.init_extra_election_timeout, extra_election_timeout_per_kb: raft.extra_election_timeout_per_kb, request_proposal_min_interval: raft.request_proposal_min_interval, }) } None => None, }; let hotstuff = match &file_config.consensus.hotstuff { Some(hotstuff) => { let secret_key = match &hotstuff.secret_key_file { Some(file) => Some(get_secret_key(file, home, &basic)?), None => None, }; Some(HotStuffConfig { secret_key, init_extra_timeout: hotstuff.init_extra_timeout, }) } None => None, }; let consensus = ConsensusConfig { poa, raft, hotstuff, }; Ok(consensus) } fn get_coordinator_config( file_config: &FileConfig, home: &Path, agent_version: &str, ) -> CommonResult<CoordinatorConfig> { let listen_addresses = parse_from_socket_addresses(&file_config.network.listen_addresses)?; let external_addresses = parse_from_socket_addresses(&file_config.network.external_addresses)?; let bootnodes = parse_from_multi_addresses(&file_config.network.bootnodes)?; let reserved_nodes = parse_from_multi_addresses(&file_config.network.reserved_nodes)?; let local_key_pair = { let file = &file_config.network.secret_key_file; let file = get_abs_path(file, home); let mut secret_key = read_secret_key_file(&file)?; let dsa = DsaImpl::Ed25519; let key_pair = dsa.key_pair_from_secret_key(&secret_key)?; let (_, public_key_len, _) = dsa.length().into(); let mut public_key = vec![0u8; public_key_len]; key_pair.public_key(&mut public_key); secret_key.extend(public_key); let key_pair = ed25519::Keypair::decode(&mut secret_key[..]) .map_err(|_| errors::ErrorKind::Config(format!("Invalid secret key in: {:?}", file)))?; Keypair::Ed25519(key_pair) }; let network_config = node_coordinator::NetworkConfig { max_in_peers: file_config.network.max_in_peers, max_out_peers: file_config.network.max_out_peers, listen_addresses, external_addresses, bootnodes, reserved_nodes, reserved_only: file_config.network.reserved_only, agent_version: agent_version.to_string(), local_key_pair, handshake_builder: None, }; let config = CoordinatorConfig { network_config }; Ok(config) } fn parse_from_socket_addresses(addresses: &[String]) -> CommonResult<LinkedHashMap<Multiaddr, ()>> { let addresses = addresses.iter().map(|x| -> CommonResult<Multiaddr> { let addr: SocketAddrV4 = x .parse() .map_err(|_| ErrorKind::Config(format!("Invalid socket address: {:?}", x)))?; let addr = Multiaddr::empty() .with(Protocol::Ip4(*addr.ip())) .with(Protocol::Tcp(addr.port())); Ok(addr) }); let mut result = LinkedHashMap::new(); for address in addresses { result.insert(address?, ()); } Ok(result) } fn parse_from_multi_addresses( addresses: &[String], ) -> CommonResult<LinkedHashMap<(PeerId, Multiaddr), ()>> { let addresses = addresses .iter() .map(|x| -> CommonResult<(PeerId, Multiaddr)> { let mut addr: Multiaddr = x .parse() .map_err(|_| ErrorKind::Config(format!("Invalid multi address: {:?}", x)))?; let peer_id = match addr.pop() { Some(Protocol::P2p(key)) => PeerId::from_multihash(key) .map_err(|_| ErrorKind::Config(format!("Invalid multi address: {:?}", x)))?, _ => { return Err(ErrorKind::Config(format!("Invalid multi address: {:?}", x)).into()); } }; Ok((peer_id, addr)) }); let mut result = LinkedHashMap::new(); for address in addresses { result.insert(address?, ()); } Ok(result) } fn get_secret_key(file: &Path, home: &Path, basic: &Arc<Basic>) -> CommonResult<SecretKey> { let file = get_abs_path(file, home); let secret_key = read_secret_key_file(&file)?; let _key_pair = basic .dsa .key_pair_from_secret_key(&secret_key) .map_err(|_| errors::ErrorKind::Config(format!("Invalid secret key in: {:?}", file)))?; Ok(SecretKey(secret_key)) } fn read_secret_key_file(file: &Path) -> CommonResult<Vec<u8>> { let secret_key = { let secret_key = fs::read_to_string(&file).map_err(|_| { errors::ErrorKind::Config(format!("Failed to read secret key file: {:?}", file)) })?; let secret_key = hex::decode(secret_key.trim()) .map_err(|_| errors::ErrorKind::Config(format!("Invalid secret key in: {:?}", file)))?; secret_key }; Ok(secret_key) } fn get_abs_path(path: &Path, home: &Path) -> PathBuf { if path.starts_with("/") { path.to_path_buf() } else { home.join(path) } }
#[doc = "Reader of register NVIC_IPR0"] pub type R = crate::R<u32, super::NVIC_IPR0>; #[doc = "Writer for register NVIC_IPR0"] pub type W = crate::W<u32, super::NVIC_IPR0>; #[doc = "Register NVIC_IPR0 `reset()`'s with value 0"] impl crate::ResetValue for super::NVIC_IPR0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `IP_3`"] pub type IP_3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IP_3`"] pub struct IP_3_W<'a> { w: &'a mut W, } impl<'a> IP_3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 30)) | (((value as u32) & 0x03) << 30); self.w } } #[doc = "Reader of field `IP_2`"] pub type IP_2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IP_2`"] pub struct IP_2_W<'a> { w: &'a mut W, } impl<'a> IP_2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22); self.w } } #[doc = "Reader of field `IP_1`"] pub type IP_1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IP_1`"] pub struct IP_1_W<'a> { w: &'a mut W, } impl<'a> IP_1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Reader of field `IP_0`"] pub type IP_0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IP_0`"] pub struct IP_0_W<'a> { w: &'a mut W, } impl<'a> IP_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6); self.w } } impl R { #[doc = "Bits 30:31 - Priority of interrupt 3"] #[inline(always)] pub fn ip_3(&self) -> IP_3_R { IP_3_R::new(((self.bits >> 30) & 0x03) as u8) } #[doc = "Bits 22:23 - Priority of interrupt 2"] #[inline(always)] pub fn ip_2(&self) -> IP_2_R { IP_2_R::new(((self.bits >> 22) & 0x03) as u8) } #[doc = "Bits 14:15 - Priority of interrupt 1"] #[inline(always)] pub fn ip_1(&self) -> IP_1_R { IP_1_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bits 6:7 - Priority of interrupt 0"] #[inline(always)] pub fn ip_0(&self) -> IP_0_R { IP_0_R::new(((self.bits >> 6) & 0x03) as u8) } } impl W { #[doc = "Bits 30:31 - Priority of interrupt 3"] #[inline(always)] pub fn ip_3(&mut self) -> IP_3_W { IP_3_W { w: self } } #[doc = "Bits 22:23 - Priority of interrupt 2"] #[inline(always)] pub fn ip_2(&mut self) -> IP_2_W { IP_2_W { w: self } } #[doc = "Bits 14:15 - Priority of interrupt 1"] #[inline(always)] pub fn ip_1(&mut self) -> IP_1_W { IP_1_W { w: self } } #[doc = "Bits 6:7 - Priority of interrupt 0"] #[inline(always)] pub fn ip_0(&mut self) -> IP_0_W { IP_0_W { w: self } } }
use std::fmt::{self, Display}; use amethyst::input::{BindingTypes}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)] pub enum AxisBinding { ZAxis, YAxis, XAxis, } #[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)] pub enum ActionBinding { Interact, } impl Display for AxisBinding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl Display for ActionBinding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } #[derive(Debug)] pub struct GameBindings; impl BindingTypes for GameBindings { type Axis = AxisBinding; type Action = ActionBinding; }
pub use self::alloca::AllocaInst; pub use self::load::LoadInst; pub use self::extract_value::ExtractValueInst; pub use self::vaarg::VAArgInst; pub use self::cast::*; pub mod alloca; pub mod load; pub mod extract_value; pub mod vaarg; pub mod cast; use ir::Instruction; pub struct UnaryInst<'ctx>(Instruction<'ctx>); impl_subtype!(UnaryInst => Instruction);
use anyhow::{anyhow, Context, Error, Result}; use fehler::{throw, throws}; use rusoto_core::Region; use rusoto_ec2::{ DescribeInstancesRequest, Ec2 as _, Ec2Client, Instance, RebootInstancesRequest, StartInstancesRequest, StopInstancesRequest, TerminateInstancesRequest, }; use rusoto_logs::{ CloudWatchLogs, CloudWatchLogsClient, DescribeLogGroupsRequest, DescribeLogStreamsRequest, }; use rusoto_s3::{S3Client, S3 as _}; use std::{thread, time}; use structopt::StructOpt; fn get_instance_name(instance: &Instance) -> Option<String> { if let Some(tags) = &instance.tags { for tag in tags { if let Some(key) = &tag.key { if key == "Name" { if let Some(value) = &tag.value { return Some(value.into()); } } } } } None } fn get_instance_state_name(instance: &Instance) -> Option<String> { if let Some(state) = &instance.state { if let Some(name) = &state.name { return Some(name.into()); } } None } #[throws] fn ec2_list_instances() { let client = Ec2Client::new(Region::default()); let output = client .describe_instances(DescribeInstancesRequest { ..Default::default() }) .sync() .context("failed to list instances")?; let reservations = output.reservations.context("missing reservations field")?; struct Row { id: String, name: String, state: String, } let mut instances = Vec::new(); for reservation in reservations { if let Some(res_instances) = reservation.instances { for instance in res_instances { let id = instance .instance_id .clone() .unwrap_or_else(|| "i-?????????????????".to_string()); let name = get_instance_name(&instance) .unwrap_or_else(|| "<no-name>".into()); let state = get_instance_state_name(&instance) .unwrap_or_else(|| "unknown".into()); instances.push(Row { id, name, state }); } } } // Sort the instances by name instances.sort_unstable_by_key(|row| row.name.clone()); // Get the maximum length of the state field let state_width = instances .iter() .map(|row| row.state.len()) .max() .unwrap_or(0); for row in instances { println!( "{:19} {:state_width$} {}", row.id, row.state, row.name, state_width = state_width ); } } #[throws] fn ec2_show_addresses(instance_id: String) { println!("{}:", instance_id); let client = Ec2Client::new(Region::default()); let output = client .describe_instances(DescribeInstancesRequest { instance_ids: Some(vec![instance_id]), ..Default::default() }) .sync() .context("failed to get instance details")?; let reservations = output.reservations.context("missing reservations field")?; for reservation in reservations { if let Some(res_instances) = reservation.instances { for instance in res_instances { println!( " private IP: {}", instance.private_ip_address.unwrap_or_default() ); println!( " public IP: {}", instance.public_ip_address.unwrap_or_default() ); } } } } #[throws] fn ec2_start_instance(instance_id: String) { let client = Ec2Client::new(Region::default()); client .start_instances(StartInstancesRequest { instance_ids: vec![instance_id], ..Default::default() }) .sync() .context("failed to start instance")?; } #[throws] fn ec2_stop_instance(instance_id: String) { let client = Ec2Client::new(Region::default()); client .stop_instances(StopInstancesRequest { instance_ids: vec![instance_id], ..Default::default() }) .sync() .context("failed to stop instance")?; } #[throws] fn ec2_terminate_instance(instance_id: String) { let client = Ec2Client::new(Region::default()); client .terminate_instances(TerminateInstancesRequest { instance_ids: vec![instance_id], ..Default::default() }) .sync() .context("failed to terminate instance")?; } #[throws] fn ec2_reboot_instance(instance_id: String) { let client = Ec2Client::new(Region::default()); client .reboot_instances(RebootInstancesRequest { instance_ids: vec![instance_id], ..Default::default() }) .sync() .context("failed to reboot instance")?; } // Not using #[throws] here because of // github.com/withoutboats/fehler/issues/52 fn logs_groups(args: ListLogGroups) -> Result<(), Error> { let client = CloudWatchLogsClient::new(Region::default()); let mut next_token = None; loop { let resp = client .describe_log_groups(DescribeLogGroupsRequest { log_group_name_prefix: args.prefix.clone(), next_token: next_token.clone(), ..Default::default() }) .sync() .context("failed to list groups")?; if let Some(log_groups) = resp.log_groups { for log_group in log_groups { println!( "{}", log_group .log_group_name .ok_or_else(|| anyhow!("missing log group name"))? ); } } // Finish if there are no more results if resp.next_token.is_none() { return Ok(()); } next_token = resp.next_token; } } // Not using #[throws] here because of // github.com/withoutboats/fehler/issues/52 fn logs_recent_streams(args: RecentLogStreams) -> Result<(), Error> { let client = CloudWatchLogsClient::new(Region::default()); let mut next_token = None; let mut remaining = args.limit as i64; loop { // The describe-log-streams operation has a limit of five // transactions per second, so attempt up to five requests and // then sleep for 1 second. for _ in 0..5 { // 50 is the maximum for a single request let limit = std::cmp::min(remaining, 50); let resp = client .describe_log_streams(DescribeLogStreamsRequest { log_group_name: args.log_group_name.clone(), limit: Some(limit), order_by: Some("LastEventTime".to_string()), next_token: next_token.clone(), descending: Some(true), ..Default::default() }) .sync() .context("failed to list streams")?; if let Some(log_streams) = resp.log_streams { for log_stream in log_streams { println!( "{}", log_stream.log_stream_name.ok_or_else(|| anyhow!( "missing log stream name" ))? ); } } // Finish if there are no more results if resp.next_token.is_none() { return Ok(()); } remaining -= limit; // Finish if the number of requested streams has already // been shown if remaining <= 0 { return Ok(()); } next_token = resp.next_token; } thread::sleep(time::Duration::from_secs(1)); } } #[throws] fn s3_list_buckets() { let client = S3Client::new(Region::default()); let output = client .list_buckets() .sync() .context("failed to list buckets")?; let buckets = output.buckets.context("missing buckets field")?; for bucket in buckets { let name = bucket.name.context("missing bucket name")?; println!("{}", name); } } #[derive(Debug, StructOpt)] enum Ec2 { /// List instances. Instances, /// Show an instance's IP address(es) Addr { instance_ids: Vec<String> }, /// Start an instance. Start { instance_ids: Vec<String> }, /// Stop an instance. Stop { instance_ids: Vec<String> }, /// Terminate an instance. Terminate { instance_ids: Vec<String> }, /// Reboot an instance. Reboot { instance_ids: Vec<String> }, } #[derive(Debug, StructOpt)] struct ListLogGroups { prefix: Option<String>, } #[derive(Debug, StructOpt)] struct RecentLogStreams { log_group_name: String, #[structopt(long, default_value = "10")] limit: usize, } #[derive(Debug, StructOpt)] enum Logs { /// List CloudWatch Logs groups. Groups(ListLogGroups), /// List recent CloudWatch Logs streams. RecentStreams(RecentLogStreams), } #[derive(Debug, StructOpt)] enum S3 { /// List buckets. Buckets, } #[derive(Debug, StructOpt)] #[structopt(about = "AWS command-line tool")] enum Command { Ec2(Ec2), Logs(Logs), S3(S3), } #[throws] fn for_each<F: Fn(String) -> Result<()>>( func: F, mut instance_ids: Vec<String>, ) { let mut any_errors = false; for id in instance_ids.drain(..) { if let Err(err) = func(id) { eprintln!("{}", err); any_errors = true; } } if any_errors { throw!(anyhow!("one or more operations failed")); } } fn main() -> Result<(), Error> { match Command::from_args() { Command::Ec2(Ec2::Instances) => ec2_list_instances(), Command::Ec2(Ec2::Addr { instance_ids }) => { for_each(ec2_show_addresses, instance_ids) } Command::Ec2(Ec2::Start { instance_ids }) => { for_each(ec2_start_instance, instance_ids) } Command::Ec2(Ec2::Stop { instance_ids }) => { for_each(ec2_stop_instance, instance_ids) } Command::Ec2(Ec2::Terminate { instance_ids }) => { for_each(ec2_terminate_instance, instance_ids) } Command::Ec2(Ec2::Reboot { instance_ids }) => { for_each(ec2_reboot_instance, instance_ids) } Command::Logs(Logs::Groups(args)) => logs_groups(args), Command::Logs(Logs::RecentStreams(args)) => logs_recent_streams(args), Command::S3(S3::Buckets) => s3_list_buckets(), } }
use wasm_bindgen::JsValue; use wasm_bindgen_test::*; use js_sys::*; #[wasm_bindgen_test] fn new() { let error = Error::new(&"some message".into()); assert_eq!(JsValue::from(error.message()), "some message"); } #[wasm_bindgen_test] fn set_message() { let error = Error::new(&"test".into()); error.set_message(&"another".into()); assert_eq!(JsValue::from(error.message()), "another"); } #[wasm_bindgen_test] fn name() { let error = Error::new(&"test".into()); assert_eq!(JsValue::from(error.name()), "Error"); } #[wasm_bindgen_test] fn set_name() { let error = Error::new(&"test".into()); error.set_name(&"different".into()); assert_eq!(JsValue::from(error.name()), "different"); } #[wasm_bindgen_test] fn to_string() { let error = Error::new(&"error message 1".into()); assert_eq!(JsValue::from(error.to_string()), "Error: error message 1"); error.set_name(&"error_name_1".into()); assert_eq!(JsValue::from(error.to_string()), "error_name_1: error message 1"); }
fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() < 2 { panic!("Please supply an input file as argument 1"); } let input_string = std::fs::read_to_string(&args[1]).expect("Failed to load input"); let mut names: Vec<&str> = input_string .trim() .split(",") .map(|s| s.trim_matches('"')) .collect(); names.sort(); let (val, _) = names.iter().fold((0u64, 1u64), |(a, c), v| { ( a + c * v.as_bytes().iter().fold(0u64, |a, c| a + *c as u64 - 64), c + 1, ) }); println!("{}", val); }
use crate::message::{ExchangeReply, TraderRequest}; use crate::trader::subscriptions::HandleSubscriptionUpdates; use crate::types::{DateTime, StdRng}; pub mod examples; pub mod subscriptions; pub trait Trader: HandleSubscriptionUpdates { fn exchange_to_trader_latency(rng: &mut StdRng, dt: DateTime) -> u64; fn trader_to_exchange_latency(rng: &mut StdRng, dt: DateTime) -> u64; fn handle_exchange_reply(&mut self, exchange_dt: DateTime, delivery_dt: DateTime, reply: ExchangeReply) -> Vec<TraderRequest>; fn exchange_open(&mut self, exchange_dt: DateTime, delivery_dt: DateTime); fn exchange_closed(&mut self, exchange_dt: DateTime, delivery_dt: DateTime); }
#![allow(dead_code)] use pwasm_abi::eth::EndpointInterface; use pwasm_abi_derive::eth_abi; #[eth_abi(DoubleArrayEndpoint, DoubleArrayClient)] pub trait DoubleArrayContract { fn double_array(&mut self, v: [u8; 16]); } const PAYLOAD_SAMPLE_1: &[u8] = &[ 0x71, 0x3d, 0x4b, 0x80, 0x12, 0x24, 0x36, 0x48, 0x60, 0x72, 0x84, 0x96, 0x07, 0x14, 0x21, 0x28, 0x35, 0x42, 0x49, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; #[test] fn bytes16() { #[derive(Default)] pub struct Instance { pub v1: [u8; 8], pub v2: [u8; 8], } impl DoubleArrayContract for Instance { fn double_array(&mut self, v: [u8; 16]) { self.v1.copy_from_slice(&v[0..8]); self.v2.copy_from_slice(&v[8..16]); } } let mut endpoint = DoubleArrayEndpoint::new(Instance::default()); endpoint.dispatch(PAYLOAD_SAMPLE_1); assert_eq!(endpoint.inner.v1, [0x12, 0x24, 0x36, 0x48, 0x60, 0x72, 0x84, 0x96]); assert_eq!(endpoint.inner.v2, [0x07, 0x14, 0x21, 0x28, 0x35, 0x42, 0x49, 0x56]); }
#[macro_use] extern crate serde_derive; extern crate futures; extern crate futures_cpupool; extern crate serde; extern crate serde_json; extern crate tokio_minihttp; extern crate tokio_proto; extern crate tokio_service; extern crate hyper; use std::io; use futures::{BoxFuture, Future}; use futures_cpupool::CpuPool; use tokio_minihttp::{Request, Response}; use tokio_proto::TcpServer; use tokio_service::Service; use hyper::Client as HttpClient; use std::sync::Arc; struct Server { client: Arc<HttpClient>, thread_pool: CpuPool, } #[derive(Serialize)] struct Message { status: u16, } impl Service for Server { type Request = Request; type Response = Response; type Error = io::Error; type Future = BoxFuture<Response, io::Error>; fn call(&self, _req: Request) -> Self::Future { let client = self.client.clone(); let msg = self.thread_pool.spawn_fn(move || { let res = client.get("http://www.google.com") .send() .map_err(|e| { io::Error::new(io::ErrorKind::Other, format!("timeout: {}", e)) })?; Ok(Message { status: res.status_raw().0 }) }); msg.map(|msg| { let json = serde_json::to_string(&msg).unwrap(); let mut response = Response::new(); response.body(&json); response }).boxed() } } fn main() { let addr = "127.0.0.1:8080".parse().unwrap(); let thread_pool = CpuPool::new(10); let hyper_client = Arc::new(HttpClient::new()); TcpServer::new(tokio_minihttp::Http, addr).serve(move || { Ok(Server { client: hyper_client.clone(), thread_pool: thread_pool.clone() }) }) }
// exercise.rs use std::collections::HashMap; use std::fmt::Debug; use std::fs::File; use std::io; use std::io::{ErrorKind, Read}; use std::env; fn main() { println!("Hello, Rust!"); let a: [i32; 5] = [1, 2, 3, 4, 5]; let b = [3; 5]; // let mut index = String::new(); // std::io::stdin() // .read_line(&mut index) // .expect("Failed to read line"); // let index: i32 = index // .trim() // .parse() // .expect("Index entered was not a number"); let index: u8 = 0; println!("{:?} {:?} index {}", a, b, index); let x = 5; let y = { let x = 3; x + 1 }; let num = if true { 5 } else { 6 }; println!("{} {} {}", x, y, num); let mut i = 0; let r = loop { i += 1; if i == 10 { break i * 2; // To r } }; println!("{} {}", i, r); let a = [10, 20, 30, 40, 50]; for e in a.iter() { print!("{}\t", e); } println!(); for n in (1..4).rev() { print!("{}\t", n); } println!(); // ownership let mut s = String::from("hello"); s.push_str(", world!"); // push_str() appends a literal to s string println!("{}", s); // This will print `hello, world!` { let _s = String::from("hello"); // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no longer valid let s1 = String::from("hello"); let s2 = s1; println!("{}, world!", s2); let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {} s2 = {}", s1, s2); let x = 5; let y = x; // copy trait println!("x = {} y = {}", x, y); fn give_ownership() -> String { String::from("hello") } let s = give_ownership(); println!("give = {}", s); fn calc_length(s: String) -> (String, usize) { let len = s.len(); // return into len (s, len) } let s = String::from("bingxio!"); let x = calc_length(s); println!("calc = {} {}", x.0, x.1); fn _calc(s: &String) -> usize { // s is reference to a String s.len() } // it does not have ownership, nothing happens. let mut s = String::from("return: "); fn change(s: &mut String) { s.push_str("OK!"); } change(&mut s); println!("{}", s); { let _r1 = &mut s; // _r1 drop } let _r2 = &mut s; let r1 = &s; // immutable borrow let r2 = &s; // let r3 = &mut s; mutable borrow, it is also borrowed as immutable println!("{} {}", r1, r2); let mut s = String::from("I LOVE U!"); let r1 = &s; let r2 = &s; println!("{} {}", r1, r2); // r1 and r2 will not be used after this point let r3 = &mut s; println!("{}", r3); // fn dangle() -> &String { // let s = String::from("hello"); // &s // } // s goes out of scope, and is dropped. Its memory goes away. fn _no_dangle() -> String { let s = String::from("hello"); s } fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } let mut s = String::from("hello, world!"); let word = first_word(&s); println!("{}", word); s.clear(); // make it equal to "" s.push_str("hello world"); let hello = &s[0..5]; let world = &s[6..11]; println!("{} {} {} {}", hello, world, &s[..2], &s[..]); fn first_w(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } let word = first_w(&s); // immutable borrow // s.clear(); // mutable borrow let my_str_literal = "hello world"; println!( "first word: {}, {}, {}", word, first_w(my_str_literal), first_w(&my_str_literal[0..6]) ); #[derive(Debug)] struct Color(i32, i32, i32); let black = Color(0, 0, 0); println!("{:?}", black); // structure #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { // implement fn area(&self) -> u32 { self.width * self.height } fn _hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size, } } } let rect = Rectangle { width: 30, height: 50, }; println!( "the area of the rectangle is {} square pixels.", rect.area() ); let rect = Rectangle::square(40); println!("{:?}", rect); enum _MyColor { RED, GREEN, } #[derive(Debug)] enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); // hui huan address println!("{:?} {:?}", home, loopback); #[derive(Debug)] enum Message { _Quit, _Move { x: i32, y: i32 }, Write(String), _ChangeColor(i32, i32, i32), } struct _QuitMessage; // unit struct struct _MoveMessage { x: i32, y: i32, } struct _WriteMessage(String); // tuple struct struct _ChangeColorMessage(i32, i32, i32); // tuple struct impl Message { fn call(&self) { // method body would be defined here } } let m = Message::Write(String::from("hello?")); m.call(); let some_number = Some(5); let some_string = Some("a string"); let absent_number: Option<i32> = None; println!("{:?} {:?} {:?}", some_number, some_string, absent_number); let x: i8 = 5; let y: Option<i8> = Some(5); // let sum = x + y; // no implementation for i8 + Option<i8> let sum = x + y.expect("WHAT ERROR !!"); println!("sum = {}", sum); #[derive(Debug)] enum State { Alabama, _Alaska, } enum Coin { Penny, Nickel, Dime, Quarter(State), } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => { println!("Luckly penny!"); 1 } Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter(state) => { println!("State quarter from {:?}!", state); 25 } } } println!( " {}\n {}\n {}\n {}", value_in_cents(Coin::Penny), value_in_cents(Coin::Nickel), value_in_cents(Coin::Dime), value_in_cents(Coin::Quarter(State::Alabama)) ); fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } println!("{:?} {:?}", plus_one(Some(5)), plus_one(None)); let some_u8 = 0u8; let x: u8 = match some_u8 { 1 => 2, 2 => 3, 3 => 4, _ => 5, }; println!("x = {}", x); let some_u8 = Some(5); if let Some(5) = some_u8 { println!("OK!"); } let coin = Coin::Quarter(State::Alabama); if let Coin::Quarter(state) = coin { println!("State quarter from {:?}", state); } else { println!("other"); } // call crate module crate::front_of_house::hosting::add_to_waitlist(); let mut v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {}", third); match v.get(2) { Some(num) => println!("{}", num), None => println!("NONE"), } println!("{:?} {:?}", v.get(1), v.get(200)); for i in &mut v { *i += 1; } for i in &v { print!("{} ", i); } println!(); let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let scores: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect(); println!("{:?}", scores); let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); map.insert(String::from("A"), String::from("123")); map.entry(String::from("B")).or_insert(String::from("456")); map.entry(String::from("C")).or_insert(String::from("789")); for (k, v) in &map { println!("{}: {}", k, v); } fn read_file() -> Result<String, io::Error> { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; // ? operator Ok(s) } match read_file() { Ok(content) => { println!("Read {}", content); } Err(e) => println!("Error: {}", e), } // And use function to handle it. File::open("1.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { println!("not found, and will create it named 1.txt on this path"); File::create("1.txt").unwrap() } else { panic!("WHAT'S UP!"); } }); fn largest_i32(list: &[i32]) -> i32 { let mut largest = list[0]; for &item in list { if item > largest { largest = item; } } largest } println!("largest {}", largest_i32(&vec![1, 2, 3, 4, 5])); struct Point<T, U> { x: T, y: U, } impl<T, U> Point<T, U> { fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> { Point { x: self.x, y: other.y, } } } let p1 = Point { x: 5, y: 10.4 }; let p2 = Point { x: "Hello", y: 'c' }; let p3 = p1.mixup(p2); println!("p3.x = {} p3.y = {}", p3.x, p3.y); trait Summary { fn summarize_def(&self) -> String; fn summarize(&self) -> String { String::from("(Read default impl)") } } struct Foo { x: i32, } impl Summary for Foo { fn summarize_def(&self) -> String { String::from("(Read implementation)") } } let f = Foo { x: 666 }; println!("{} {} {}", f.summarize(), f.summarize_def(), f.x); // Trais as parameter fn notify(item: &impl Summary) { println!("{} {}", item.summarize(), item.summarize_def()); } notify(&f); // Trait bound fn _notify_more<T: Summary + std::fmt::Display>(_item: &T) {} // fn _some_func_1<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {} // fn _some_func_2<T, U>(t: &T, u: &U) -> i32 // where // T: Display + Clone, // U: Clone + Debug, // { // } fn return_summary() -> impl Summary { // Foo was implementation of Summary trait Foo { x: 9 } } println!("{}", return_summary().summarize()); fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut larg = list[0]; for &item in list { if item > larg { larg = item; } } larg } let number = vec![34, 12, 56, 88, 45, 43, 22]; let chars = vec!['y', 'w', 'p', 'a']; println!("{} {}", largest(&number), largest(&chars)); struct Pair<T> { a: T, b: T, } impl<T> Pair<T> { fn new(a: T, b: T) -> Self { Self { a, b } } } impl<T: std::fmt::Display + PartialOrd + Copy> Pair<T> { fn cmp_display(&self) { println!( "largest member is {}", if self.a >= self.b { self.a } else { self.b } ); } } impl<T> ToString for Pair<T> { fn to_string(&self) -> std::string::String { String::from("My Pair{}") } } Pair::new(34, 12).cmp_display(); Pair::new('p', 'q').cmp_display(); println!("{}", Pair::new(1, 2).to_string()); // References with lifetimes // { // let r; // { // let x = 5; // r = &x; // } // r drop here // println!("{}", r); // } /* fn main() { { let r; // ---------+-- 'a // | { // | let x = 5; // -+-- 'b | r = &x; // | | } // -+ | // | println!("r: {}", r); // | } // ---------+ } */ /* fn main() { { let x = 5; // ----------+-- 'b // | let r = &x; // --+-- 'a | // | | println!("r: {}", r); // | | // --+ | } // ----------+ } */ struct Iter<'a> { a: [i32; 3], i: usize, _m: std::marker::PhantomData<&'a ()>, } impl<'a> Iterator for Iter<'a> { type Item = &'a i32; fn next(&mut self) -> Option<&'a i32> { if self.i < 3 { unsafe { let ret = Some(&(*(self as *mut Iter)).a[self.i]); self.i += 1; ret } } else { None } } } let mut it = Iter { a: [34, 12, 54], i: 0, _m: std::marker::PhantomData, }; for _i in 0..5 { println!("{:?}", it.next()); } // IO let args: Vec<String> = env::args().collect(); println!("args: {:?}", args); let add = |a: i32, b: i32| -> i32 { a + b }; println!("add {}", add(3, 2)); } #[derive(Debug)] pub struct Guess { value: i32, } impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); } Guess { value } } } mod front_of_house { pub mod hosting { pub fn add_to_waitlist() { println!("CALL {}", num()); } fn num() -> u8 { 6 } } } pub fn add_two(x: i32) -> i32 { x + x } pub struct Cacher<T> where T: Fn(u32) -> u32, { calculation: T, value: Option<u32>, } impl<T> Cacher<T> where T: Fn(u32) -> u32, { fn new(calculation: T) -> Cacher<T> { Cacher { calculation, value: None, } } fn value(&mut self, arg: u32) -> u32 { match self.value { Some(v) => v, None => { let v = (self.calculation)(arg); self.value = Some(v); v } } } } use std::thread; use std::time::Duration; fn generate_workout(intensity: u32, random_number: u32) { let mut expensive_result = Cacher::new(|num| { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }); if intensity < 25 { println!("Today, do {} pushups!", expensive_result.value(intensity)); println!("Next, do {} situps!", expensive_result.value(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_result.value(intensity) ); } } } #[cfg(test)] mod tests { use super::*; #[test] fn greater_than_100() { Guess::new(200); } #[test] fn it_works() -> Result<(), String> { if 2 + 2 == 4 { Ok(()) } else { Err(String::from("tow plus tow does not equal four")) } } #[test] fn add_test() { assert_eq!(add_two(4), 8); } #[test] fn call_with_different_values() { let mut c = Cacher::new(|x| x); let v1 = c.value(1); let v2 = c.value(2); assert_eq!(v2, 2); } }
use std::{borrow::Cow, convert::TryInto}; use num_traits::{FromPrimitive, ToPrimitive}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{document::Document, schema::view}; /// A document's entry in a View's mappings. #[derive(PartialEq, Debug)] pub struct Map<K: Key = (), V: Serialize = ()> { /// The id of the document that emitted this entry. pub source: u64, /// The key used to index the View. pub key: K, /// An associated value stored in the view. pub value: V, } impl<K: Key, V: Serialize> Map<K, V> { /// Serializes this map. pub fn serialized(&self) -> Result<Serialized, view::Error> { Ok(Serialized { source: self.source, key: self .key .as_big_endian_bytes() .map_err(view::Error::KeySerialization)? .to_vec(), value: serde_cbor::to_vec(&self.value)?, }) } } /// A document's entry in a View's mappings. #[derive(Debug)] pub struct MappedDocument<K: Key = (), V: Serialize = ()> { /// The id of the document that emitted this entry. pub document: Document<'static>, /// The key used to index the View. pub key: K, /// An associated value stored in the view. pub value: V, } impl<K: Key, V: Serialize> Map<K, V> { /// Creates a new Map entry for the document with id `source`. pub fn new(source: u64, key: K, value: V) -> Self { Self { source, key, value } } } /// Represents a document's entry in a View's mappings, serialized and ready to store. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Serialized { /// The id of the document that emitted this entry. pub source: u64, /// The key used to index the View. pub key: Vec<u8>, /// An associated value stored in the view. pub value: Vec<u8>, } impl Serialized { /// Deserializes this map. pub fn deserialized<K: Key, V: Serialize + DeserializeOwned>( &self, ) -> Result<Map<K, V>, view::Error> { Ok(Map { source: self.source, key: K::from_big_endian_bytes(&self.key).map_err(view::Error::KeySerialization)?, value: serde_cbor::from_slice(&self.value)?, }) } } /// A key value pair #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] pub struct MappedValue<K: Key, V> { /// The key responsible for generating the value pub key: K, /// The value generated by the `View` pub value: V, } /// A trait that enables a type to convert itself to a big-endian/network byte order. pub trait Key: Clone + Send + Sync { /// Convert `self` into a `Cow<[u8]>` containing bytes ordered in big-endian/network byte order. fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>>; /// Convert a slice of bytes into `Self` by interpretting `bytes` in big-endian/network byte order. fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self>; } impl<'k> Key for Cow<'k, [u8]> { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'k, [u8]>> { Ok(self.clone()) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { Ok(Cow::Owned(bytes.to_vec())) } } impl Key for Vec<u8> { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { Ok(Cow::Borrowed(self)) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { Ok(bytes.to_vec()) } } impl Key for String { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { Ok(Cow::Borrowed(self.as_bytes())) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { Ok(Self::from_utf8(bytes.to_vec())?) } } impl Key for () { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { Ok(Cow::default()) } fn from_big_endian_bytes(_: &[u8]) -> anyhow::Result<Self> { Ok(()) } } #[cfg(feature = "uuid")] impl<'k> Key for uuid::Uuid { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { Ok(Cow::Borrowed(self.as_bytes())) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { Ok(Self::from_bytes(bytes.try_into()?)) } } impl<T> Key for Option<T> where T: Key, { /// # Panics /// /// Panics if `T::into_big_endian_bytes` returns an empty `IVec`. // TODO consider removing this panic limitation by adding a single byte to // each key (at the end preferrably) so that we can distinguish between None // and a 0-byte type fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { if let Some(contents) = self { let contents = contents.as_big_endian_bytes()?; assert!(!contents.is_empty()); Ok(contents) } else { Ok(Cow::default()) } } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { if bytes.is_empty() { Ok(None) } else { Ok(Some(T::from_big_endian_bytes(bytes)?)) } } } /// Adds `Key` support to an enum. Requires implementing /// [`ToPrimitive`](num_traits::ToPrimitive) and /// [`FromPrimitive`](num_traits::FromPrimitive), or using a crate like /// [num-derive](https://crates.io/crates/num-derive) to do it automatically. /// Take care when using enums as keys: if the order changes or if the meaning /// of existing numerical values changes, make sure to update any related views' /// version number to ensure the values are re-evaluated. pub trait EnumKey: ToPrimitive + FromPrimitive + Clone + Send + Sync {} // ANCHOR: impl_key_for_enumkey impl<T> Key for T where T: EnumKey, { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { self.to_u64() .ok_or_else(|| anyhow::anyhow!("Primitive::to_u64() returned None"))? .as_big_endian_bytes() .map(|bytes| Cow::Owned(bytes.to_vec())) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { let primitive = u64::from_big_endian_bytes(bytes)?; Self::from_u64(primitive) .ok_or_else(|| anyhow::anyhow!("Primitive::from_u64() returned None")) } } // ANCHOR_END: impl_key_for_enumkey macro_rules! impl_key_for_primitive { ($type:ident) => { impl Key for $type { fn as_big_endian_bytes(&self) -> anyhow::Result<Cow<'_, [u8]>> { Ok(Cow::from(self.to_be_bytes().to_vec())) } fn from_big_endian_bytes(bytes: &[u8]) -> anyhow::Result<Self> { Ok($type::from_be_bytes(bytes.try_into()?)) } } }; } impl_key_for_primitive!(i8); impl_key_for_primitive!(u8); impl_key_for_primitive!(i16); impl_key_for_primitive!(u16); impl_key_for_primitive!(i32); impl_key_for_primitive!(u32); impl_key_for_primitive!(i64); impl_key_for_primitive!(u64); impl_key_for_primitive!(i128); impl_key_for_primitive!(u128); #[test] #[allow(clippy::cognitive_complexity)] // I disagree - @ecton fn primitive_key_encoding_tests() -> anyhow::Result<()> { macro_rules! test_primitive_extremes { ($type:ident) => { assert_eq!( &$type::MAX.to_be_bytes(), $type::MAX.as_big_endian_bytes()?.as_ref() ); assert_eq!( $type::MAX, $type::from_big_endian_bytes(&$type::MAX.as_big_endian_bytes()?)? ); assert_eq!( $type::MIN, $type::from_big_endian_bytes(&$type::MIN.as_big_endian_bytes()?)? ); }; } test_primitive_extremes!(i8); test_primitive_extremes!(u8); test_primitive_extremes!(i16); test_primitive_extremes!(u16); test_primitive_extremes!(i32); test_primitive_extremes!(u32); test_primitive_extremes!(i64); test_primitive_extremes!(u64); test_primitive_extremes!(i128); test_primitive_extremes!(u128); Ok(()) } #[test] fn optional_key_encoding_tests() -> anyhow::Result<()> { assert!(Option::<i8>::None.as_big_endian_bytes()?.is_empty()); assert_eq!( Some(1_i8), Option::from_big_endian_bytes(&Some(1_i8).as_big_endian_bytes()?)? ); Ok(()) } #[test] #[allow(clippy::unit_cmp)] // this is more of a compilation test fn unit_key_encoding_tests() -> anyhow::Result<()> { assert!(().as_big_endian_bytes()?.is_empty()); assert_eq!((), <() as Key>::from_big_endian_bytes(&[])?); Ok(()) } #[test] fn vec_key_encoding_tests() -> anyhow::Result<()> { const ORIGINAL_VALUE: &[u8] = b"bonsaidb"; let vec = Cow::<'_, [u8]>::from(ORIGINAL_VALUE); assert_eq!( vec.clone(), Cow::from_big_endian_bytes(&vec.as_big_endian_bytes()?)? ); Ok(()) } #[test] #[allow(clippy::use_self)] // Weird interaction with num_derive fn enum_derive_tests() -> anyhow::Result<()> { #[derive(Clone, num_derive::ToPrimitive, num_derive::FromPrimitive)] enum SomeEnum { One = 1, NineNineNine = 999, } impl EnumKey for SomeEnum {} let encoded = SomeEnum::One.as_big_endian_bytes()?; let value = SomeEnum::from_big_endian_bytes(&encoded)?; assert!(matches!(value, SomeEnum::One)); let encoded = SomeEnum::NineNineNine.as_big_endian_bytes()?; let value = SomeEnum::from_big_endian_bytes(&encoded)?; assert!(matches!(value, SomeEnum::NineNineNine)); Ok(()) }
use clap::{App, Arg}; use cocore::{convert, Representation}; use std::io; use std::io::prelude::*; use std::process::exit; fn main() { let matches = App::new("cocore") .version("0.1.0") .about("converts color representation such as HSL colors and RGB colors") .author("KoharaKazuya") .arg( Arg::with_name("to") .long("to") .value_name("representation") .help("color representation cocore converts into") .possible_values(&["hex", "rgb", "hsl"]) .default_value("hex") .takes_value(true), ) .arg(Arg::with_name("expression").multiple(true)) .get_matches(); let to = matches.value_of("to").unwrap(); let representation = match to { "rgb" => Representation::RGB, "hsl" => Representation::HSL, _ => Representation::Hex, }; let mut exit_status = 0; macro_rules! convert_and_print { ($e:expr) => { match convert($e, representation) { Ok(converted) => { println!("{}", converted); } Err(err) => { eprintln!("{}", err); exit_status = 1; } } }; } let is_tty = unsafe { libc::isatty(0) == 1 }; if !is_tty { let stdin = io::stdin(); for ret in stdin.lock().lines() { match ret { Ok(line) => convert_and_print!(&line), Err(err) => { eprintln!("{}", err); exit_status = 1; } } } } let arg_expression = matches .values_of("expression") .unwrap_or_default() .collect::<Vec<_>>() .join(" "); if arg_expression != "" { convert_and_print!(&arg_expression) } exit(exit_status); }
//! This module contains an [`ExtendedTable`] structure which is useful in cases where //! a structure has a lot of fields. //! #![cfg_attr(feature = "derive", doc = "```")] #![cfg_attr(not(feature = "derive"), doc = "```ignore")] //! use tabled::{Tabled, tables::ExtendedTable}; //! //! #[derive(Tabled)] //! struct Language { //! name: &'static str, //! designed_by: &'static str, //! invented_year: usize, //! } //! //! let languages = vec![ //! Language{ //! name: "C", //! designed_by: "Dennis Ritchie", //! invented_year: 1972 //! }, //! Language{ //! name: "Rust", //! designed_by: "Graydon Hoare", //! invented_year: 2010 //! }, //! Language{ //! name: "Go", //! designed_by: "Rob Pike", //! invented_year: 2009 //! }, //! ]; //! //! let table = ExtendedTable::new(languages).to_string(); //! //! let expected = "-[ RECORD 0 ]-+---------------\n\ //! name | C\n\ //! designed_by | Dennis Ritchie\n\ //! invented_year | 1972\n\ //! -[ RECORD 1 ]-+---------------\n\ //! name | Rust\n\ //! designed_by | Graydon Hoare\n\ //! invented_year | 2010\n\ //! -[ RECORD 2 ]-+---------------\n\ //! name | Go\n\ //! designed_by | Rob Pike\n\ //! invented_year | 2009"; //! //! assert_eq!(table, expected); //! ``` use std::borrow::Cow; use std::fmt::{self, Display}; use crate::grid::util::string::string_width; use crate::Tabled; /// `ExtendedTable` display data in a 'expanded display mode' from postgresql. /// It may be useful for a large data sets with a lot of fields. /// /// See 'Examples' in <https://www.postgresql.org/docs/current/app-psql.html>. /// /// It escapes strings to resolve a multi-line ones. /// Because of that ANSI sequences will be not be rendered too so colores will not be showed. /// /// ``` /// use tabled::tables::ExtendedTable; /// /// let data = vec!["Hello", "2021"]; /// let table = ExtendedTable::new(&data).to_string(); /// /// assert_eq!( /// table, /// concat!( /// "-[ RECORD 0 ]-\n", /// "&str | Hello\n", /// "-[ RECORD 1 ]-\n", /// "&str | 2021", /// ) /// ); /// ``` #[derive(Debug, Clone)] pub struct ExtendedTable { fields: Vec<String>, records: Vec<Vec<String>>, } impl ExtendedTable { /// Creates a new instance of `ExtendedTable` pub fn new<T>(iter: impl IntoIterator<Item = T>) -> Self where T: Tabled, { let data = iter .into_iter() .map(|i| { i.fields() .into_iter() .map(|s| s.escape_debug().to_string()) .collect() }) .collect(); let header = T::headers() .into_iter() .map(|s| s.escape_debug().to_string()) .collect(); Self { records: data, fields: header, } } /// Truncates table to a set width value for a table. /// It returns a success inticator, where `false` means it's not possible to set the table width, /// because of the given arguments. /// /// It tries to not affect fields, but if there's no enough space all records will be deleted and fields will be cut. /// /// The minimum width is 14. pub fn truncate(&mut self, max: usize, suffix: &str) -> bool { // -[ RECORD 0 ]- let teplate_width = self.records.len().to_string().len() + 13; let min_width = teplate_width; if max < min_width { return false; } let suffix_width = string_width(suffix); if max < suffix_width { return false; } let max = max - suffix_width; let fields_max_width = self .fields .iter() .map(|s| string_width(s)) .max() .unwrap_or_default(); // 3 is a space for ' | ' let fields_affected = max < fields_max_width + 3; if fields_affected { if max < 3 { return false; } let max = max - 3; if max < suffix_width { return false; } let max = max - suffix_width; truncate_fields(&mut self.fields, max, suffix); truncate_records(&mut self.records, 0, suffix); } else { let max = max - fields_max_width - 3 - suffix_width; truncate_records(&mut self.records, max, suffix); } true } } impl From<Vec<Vec<String>>> for ExtendedTable { fn from(mut data: Vec<Vec<String>>) -> Self { if data.is_empty() { return Self { fields: vec![], records: vec![], }; } let fields = data.remove(0); Self { fields, records: data, } } } impl Display for ExtendedTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.records.is_empty() { return Ok(()); } // It's possible that field|header can be a multiline string so // we escape it and trim \" chars. let fields = self.fields.iter().collect::<Vec<_>>(); let max_field_width = fields .iter() .map(|s| string_width(s)) .max() .unwrap_or_default(); let max_values_length = self .records .iter() .map(|record| record.iter().map(|s| string_width(s)).max()) .max() .unwrap_or_default() .unwrap_or_default(); for (i, records) in self.records.iter().enumerate() { write_header_template(f, i, max_field_width, max_values_length)?; for (value, field) in records.iter().zip(fields.iter()) { writeln!(f)?; write_record(f, field, value, max_field_width)?; } let is_last_record = i + 1 == self.records.len(); if !is_last_record { writeln!(f)?; } } Ok(()) } } fn truncate_records(records: &mut Vec<Vec<String>>, max_width: usize, suffix: &str) { for fields in records { truncate_fields(fields, max_width, suffix); } } fn truncate_fields(records: &mut Vec<String>, max_width: usize, suffix: &str) { for text in records { truncate(text, max_width, suffix); } } fn write_header_template( f: &mut fmt::Formatter<'_>, index: usize, max_field_width: usize, max_values_length: usize, ) -> fmt::Result { let mut template = format!("-[ RECORD {index} ]-"); let default_template_length = template.len(); // 3 - is responsible for ' | ' formatting let max_line_width = std::cmp::max( max_field_width + 3 + max_values_length, default_template_length, ); let rest_to_print = max_line_width - default_template_length; if rest_to_print > 0 { // + 1 is a space after field name and we get a next pos so its +2 if max_field_width + 2 > default_template_length { let part1 = (max_field_width + 1) - default_template_length; let part2 = rest_to_print - part1 - 1; template.extend( std::iter::repeat('-') .take(part1) .chain(std::iter::once('+')) .chain(std::iter::repeat('-').take(part2)), ); } else { template.extend(std::iter::repeat('-').take(rest_to_print)); } } write!(f, "{template}")?; Ok(()) } fn write_record( f: &mut fmt::Formatter<'_>, field: &str, value: &str, max_field_width: usize, ) -> fmt::Result { write!(f, "{field:max_field_width$} | {value}") } fn truncate(text: &mut String, max: usize, suffix: &str) { let original_len = text.len(); if max == 0 || text.is_empty() { *text = String::new(); } else { *text = cut_str_basic(text, max).into_owned(); } let cut_was_done = text.len() < original_len; if !suffix.is_empty() && cut_was_done { text.push_str(suffix); } } fn cut_str_basic(s: &str, width: usize) -> Cow<'_, str> { const REPLACEMENT: char = '\u{FFFD}'; let (length, count_unknowns, _) = split_at_pos(s, width); let buf = &s[..length]; if count_unknowns == 0 { return Cow::Borrowed(buf); } let mut buf = buf.to_owned(); buf.extend(std::iter::repeat(REPLACEMENT).take(count_unknowns)); Cow::Owned(buf) } fn split_at_pos(s: &str, pos: usize) -> (usize, usize, usize) { let mut length = 0; let mut i = 0; for c in s.chars() { if i == pos { break; }; let c_width = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0); // We cut the chars which takes more then 1 symbol to display, // in order to archive the necessary width. if i + c_width > pos { let count = pos - i; return (length, count, c.len_utf8()); } i += c_width; length += c.len_utf8(); } (length, 0, 0) }
mod token; mod spanned; use proc_macro::TokenStream; use syn::{parse_macro_input, DeriveInput}; /// The entry point for the derive macro #[proc_macro_derive(Builder, attributes(builder, each))] pub fn derive_builder(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); token::expand::derive(&input) .unwrap_or_else(|err| err.to_compile_error()) .into() }
use actix_web::{get, HttpResponse, Responder, Result as WebResult}; use serde_json::json; use octo_budget_lib::auth_token::UserId; #[get("/{user_id}/")] pub async fn show(_current_user_id: UserId) -> WebResult<impl Responder> { Ok(HttpResponse::Ok().json(json!({}))) }
#[doc = "Register `CALR` reader"] pub type R = crate::R<CALR_SPEC>; #[doc = "Register `CALR` writer"] pub type W = crate::W<CALR_SPEC>; #[doc = "Field `CALM` reader - Calibration minus"] pub type CALM_R = crate::FieldReader<u16>; #[doc = "Field `CALM` writer - Calibration minus"] pub type CALM_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 9, O, u16>; #[doc = "Field `CALW16` reader - Use a 16-second calibration cycle period"] pub type CALW16_R = crate::BitReader<CALW16_A>; #[doc = "Use a 16-second calibration cycle period\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CALW16_A { #[doc = "1: When CALW16 is set to ‘1’, the 16-second calibration cycle period is selected.This bit must not be set to ‘1’ if CALW8=1"] SixteenSecond = 1, } impl From<CALW16_A> for bool { #[inline(always)] fn from(variant: CALW16_A) -> Self { variant as u8 != 0 } } impl CALW16_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<CALW16_A> { match self.bits { true => Some(CALW16_A::SixteenSecond), _ => None, } } #[doc = "When CALW16 is set to ‘1’, the 16-second calibration cycle period is selected.This bit must not be set to ‘1’ if CALW8=1"] #[inline(always)] pub fn is_sixteen_second(&self) -> bool { *self == CALW16_A::SixteenSecond } } #[doc = "Field `CALW16` writer - Use a 16-second calibration cycle period"] pub type CALW16_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CALW16_A>; impl<'a, REG, const O: u8> CALW16_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "When CALW16 is set to ‘1’, the 16-second calibration cycle period is selected.This bit must not be set to ‘1’ if CALW8=1"] #[inline(always)] pub fn sixteen_second(self) -> &'a mut crate::W<REG> { self.variant(CALW16_A::SixteenSecond) } } #[doc = "Field `CALW8` reader - Use an 8-second calibration cycle period"] pub type CALW8_R = crate::BitReader<CALW8_A>; #[doc = "Use an 8-second calibration cycle period\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CALW8_A { #[doc = "1: When CALW8 is set to ‘1’, the 8-second calibration cycle period is selected"] EightSecond = 1, } impl From<CALW8_A> for bool { #[inline(always)] fn from(variant: CALW8_A) -> Self { variant as u8 != 0 } } impl CALW8_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<CALW8_A> { match self.bits { true => Some(CALW8_A::EightSecond), _ => None, } } #[doc = "When CALW8 is set to ‘1’, the 8-second calibration cycle period is selected"] #[inline(always)] pub fn is_eight_second(&self) -> bool { *self == CALW8_A::EightSecond } } #[doc = "Field `CALW8` writer - Use an 8-second calibration cycle period"] pub type CALW8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CALW8_A>; impl<'a, REG, const O: u8> CALW8_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "When CALW8 is set to ‘1’, the 8-second calibration cycle period is selected"] #[inline(always)] pub fn eight_second(self) -> &'a mut crate::W<REG> { self.variant(CALW8_A::EightSecond) } } #[doc = "Field `CALP` reader - Increase frequency of RTC by 488.5 ppm"] pub type CALP_R = crate::BitReader<CALP_A>; #[doc = "Increase frequency of RTC by 488.5 ppm\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CALP_A { #[doc = "0: No RTCCLK pulses are added"] NoChange = 0, #[doc = "1: One RTCCLK pulse is effectively inserted every 2^11 pulses (frequency increased by 488.5 ppm)"] IncreaseFreq = 1, } impl From<CALP_A> for bool { #[inline(always)] fn from(variant: CALP_A) -> Self { variant as u8 != 0 } } impl CALP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CALP_A { match self.bits { false => CALP_A::NoChange, true => CALP_A::IncreaseFreq, } } #[doc = "No RTCCLK pulses are added"] #[inline(always)] pub fn is_no_change(&self) -> bool { *self == CALP_A::NoChange } #[doc = "One RTCCLK pulse is effectively inserted every 2^11 pulses (frequency increased by 488.5 ppm)"] #[inline(always)] pub fn is_increase_freq(&self) -> bool { *self == CALP_A::IncreaseFreq } } #[doc = "Field `CALP` writer - Increase frequency of RTC by 488.5 ppm"] pub type CALP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CALP_A>; impl<'a, REG, const O: u8> CALP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "No RTCCLK pulses are added"] #[inline(always)] pub fn no_change(self) -> &'a mut crate::W<REG> { self.variant(CALP_A::NoChange) } #[doc = "One RTCCLK pulse is effectively inserted every 2^11 pulses (frequency increased by 488.5 ppm)"] #[inline(always)] pub fn increase_freq(self) -> &'a mut crate::W<REG> { self.variant(CALP_A::IncreaseFreq) } } impl R { #[doc = "Bits 0:8 - Calibration minus"] #[inline(always)] pub fn calm(&self) -> CALM_R { CALM_R::new((self.bits & 0x01ff) as u16) } #[doc = "Bit 13 - Use a 16-second calibration cycle period"] #[inline(always)] pub fn calw16(&self) -> CALW16_R { CALW16_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Use an 8-second calibration cycle period"] #[inline(always)] pub fn calw8(&self) -> CALW8_R { CALW8_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - Increase frequency of RTC by 488.5 ppm"] #[inline(always)] pub fn calp(&self) -> CALP_R { CALP_R::new(((self.bits >> 15) & 1) != 0) } } impl W { #[doc = "Bits 0:8 - Calibration minus"] #[inline(always)] #[must_use] pub fn calm(&mut self) -> CALM_W<CALR_SPEC, 0> { CALM_W::new(self) } #[doc = "Bit 13 - Use a 16-second calibration cycle period"] #[inline(always)] #[must_use] pub fn calw16(&mut self) -> CALW16_W<CALR_SPEC, 13> { CALW16_W::new(self) } #[doc = "Bit 14 - Use an 8-second calibration cycle period"] #[inline(always)] #[must_use] pub fn calw8(&mut self) -> CALW8_W<CALR_SPEC, 14> { CALW8_W::new(self) } #[doc = "Bit 15 - Increase frequency of RTC by 488.5 ppm"] #[inline(always)] #[must_use] pub fn calp(&mut self) -> CALP_W<CALR_SPEC, 15> { CALP_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 = "calibration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`calr::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 [`calr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CALR_SPEC; impl crate::RegisterSpec for CALR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`calr::R`](R) reader structure"] impl crate::Readable for CALR_SPEC {} #[doc = "`write(|w| ..)` method takes [`calr::W`](W) writer structure"] impl crate::Writable for CALR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CALR to value 0"] impl crate::Resettable for CALR_SPEC { const RESET_VALUE: Self::Ux = 0; }
extern crate chrono; extern crate env_logger; #[macro_use] extern crate log; extern crate kata_rs; use kata_rs::kata::*; fn main() { env_logger::init(); info!("Hello, world!"); it_works(); }
// Copyright 2022 Alibaba Cloud. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // mod protocols; mod utils; #[cfg(unix)] use protocols::r#async::{empty, streaming, streaming_ttrpc}; use ttrpc::context::{self, Context}; #[cfg(unix)] use ttrpc::r#async::Client; #[cfg(windows)] fn main() { println!("This example only works on Unix-like OSes"); } #[cfg(unix)] #[tokio::main(flavor = "current_thread")] async fn main() { simple_logging::log_to_stderr(log::LevelFilter::Info); let c = Client::connect(utils::SOCK_ADDR).unwrap(); let sc = streaming_ttrpc::StreamingClient::new(c); let _now = std::time::Instant::now(); let sc1 = sc.clone(); let t1 = tokio::spawn(echo_request(sc1)); let sc1 = sc.clone(); let t2 = tokio::spawn(echo_stream(sc1)); let sc1 = sc.clone(); let t3 = tokio::spawn(sum_stream(sc1)); let sc1 = sc.clone(); let t4 = tokio::spawn(divide_stream(sc1)); let sc1 = sc.clone(); let t5 = tokio::spawn(echo_null(sc1)); let sc1 = sc.clone(); let t6 = tokio::spawn(echo_null_stream(sc1)); let t7 = tokio::spawn(echo_default_value(sc)); let _ = tokio::join!(t1, t2, t3, t4, t5, t6, t7); } fn default_ctx() -> Context { let mut ctx = context::with_timeout(0); ctx.add("key-1".to_string(), "value-1-1".to_string()); ctx.add("key-1".to_string(), "value-1-2".to_string()); ctx.set("key-2".to_string(), vec!["value-2".to_string()]); ctx } #[cfg(unix)] async fn echo_request(cli: streaming_ttrpc::StreamingClient) { let echo1 = streaming::EchoPayload { seq: 1, msg: "Echo Me".to_string(), ..Default::default() }; let resp = cli.echo(default_ctx(), &echo1).await.unwrap(); assert_eq!(resp.msg, echo1.msg); assert_eq!(resp.seq, echo1.seq + 1); } #[cfg(unix)] async fn echo_stream(cli: streaming_ttrpc::StreamingClient) { let mut stream = cli.echo_stream(default_ctx()).await.unwrap(); let mut i = 0; while i < 100 { let echo = streaming::EchoPayload { seq: i as u32, msg: format!("{}: Echo in a stream", i), ..Default::default() }; stream.send(&echo).await.unwrap(); let resp = stream.recv().await.unwrap(); assert_eq!(resp.msg, echo.msg); assert_eq!(resp.seq, echo.seq + 1); i += 2; } stream.close_send().await.unwrap(); let ret = stream.recv().await; assert!(matches!(ret, Err(ttrpc::Error::Eof))); } #[cfg(unix)] async fn sum_stream(cli: streaming_ttrpc::StreamingClient) { let mut stream = cli.sum_stream(default_ctx()).await.unwrap(); let mut sum = streaming::Sum::new(); stream.send(&streaming::Part::new()).await.unwrap(); sum.num += 1; let mut i = -99i32; while i <= 100 { let addi = streaming::Part { add: i, ..Default::default() }; stream.send(&addi).await.unwrap(); sum.sum += i; sum.num += 1; i += 1; } stream.send(&streaming::Part::new()).await.unwrap(); sum.num += 1; let ssum = stream.close_and_recv().await.unwrap(); assert_eq!(ssum.sum, sum.sum); assert_eq!(ssum.num, sum.num); } #[cfg(unix)] async fn divide_stream(cli: streaming_ttrpc::StreamingClient) { let expected = streaming::Sum { sum: 392, num: 4, ..Default::default() }; let mut stream = cli.divide_stream(default_ctx(), &expected).await.unwrap(); let mut actual = streaming::Sum::new(); // NOTE: `for part in stream.recv().await.unwrap()` can't work. while let Some(part) = stream.recv().await.unwrap() { actual.sum += part.add; actual.num += 1; } assert_eq!(actual.sum, expected.sum); assert_eq!(actual.num, expected.num); } #[cfg(unix)] async fn echo_null(cli: streaming_ttrpc::StreamingClient) { let mut stream = cli.echo_null(default_ctx()).await.unwrap(); for i in 0..100 { let echo = streaming::EchoPayload { seq: i as u32, msg: "non-empty empty".to_string(), ..Default::default() }; stream.send(&echo).await.unwrap(); } let res = stream.close_and_recv().await.unwrap(); assert_eq!(res, empty::Empty::new()); } #[cfg(unix)] async fn echo_null_stream(cli: streaming_ttrpc::StreamingClient) { let stream = cli.echo_null_stream(default_ctx()).await.unwrap(); let (tx, mut rx) = stream.split(); let task = tokio::spawn(async move { loop { let ret = rx.recv().await; if matches!(ret, Err(ttrpc::Error::Eof)) { break; } } }); for i in 0..100 { let echo = streaming::EchoPayload { seq: i as u32, msg: "non-empty empty".to_string(), ..Default::default() }; tx.send(&echo).await.unwrap(); } tx.close_send().await.unwrap(); tokio::time::timeout(tokio::time::Duration::from_secs(10), task) .await .unwrap() .unwrap(); } #[cfg(unix)] async fn echo_default_value(cli: streaming_ttrpc::StreamingClient) { let mut stream = cli .echo_default_value(default_ctx(), &Default::default()) // send default value to verify #208 .await .unwrap(); let received = stream.recv().await.unwrap().unwrap(); assert_eq!(received.seq, 0); assert_eq!(received.msg, ""); }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `HSION` reader - HSI clock enable Set and cleared by software. Set by hardware to force the HSI to ON when the product leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. Set by hardware to force the HSI to ON when the product leaves Standby mode or in case of a failure of the HSE which is used as the system clock source. This bit cannot be cleared if the HSI is used directly (via SW mux) as system clock, or if the HSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type HSION_R = crate::BitReader; #[doc = "Field `HSION` writer - HSI clock enable Set and cleared by software. Set by hardware to force the HSI to ON when the product leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. Set by hardware to force the HSI to ON when the product leaves Standby mode or in case of a failure of the HSE which is used as the system clock source. This bit cannot be cleared if the HSI is used directly (via SW mux) as system clock, or if the HSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type HSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSIRDY` reader - HSI clock ready flag Set by hardware to indicate that the HSI oscillator is stable."] pub type HSIRDY_R = crate::BitReader; #[doc = "Field `HSIKERON` reader - HSI clock enable in Stop mode Set and reset by software to force the HSI to ON, even in Stop mode, in order to be quickly available as kernel clock for peripherals. This bit has no effect on the value of HSION."] pub type HSIKERON_R = crate::BitReader; #[doc = "Field `HSIKERON` writer - HSI clock enable in Stop mode Set and reset by software to force the HSI to ON, even in Stop mode, in order to be quickly available as kernel clock for peripherals. This bit has no effect on the value of HSION."] pub type HSIKERON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSIDIV` reader - HSI clock divider Set and reset by software. These bits allow selecting a division ratio in order to configure the wanted HSI clock frequency. The HSIDIV cannot be changed if the HSI is selected as reference clock for at least one enabled PLL (PLLxON bit set to 1). In that case, the new HSIDIV value is ignored."] pub type HSIDIV_R = crate::FieldReader; #[doc = "Field `HSIDIV` writer - HSI clock divider Set and reset by software. These bits allow selecting a division ratio in order to configure the wanted HSI clock frequency. The HSIDIV cannot be changed if the HSI is selected as reference clock for at least one enabled PLL (PLLxON bit set to 1). In that case, the new HSIDIV value is ignored."] pub type HSIDIV_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `HSIDIVF` reader - HSI divider flag Set and reset by hardware. As a write operation to HSIDIV has not an immediate effect on the frequency, this flag indicates the current status of the HSI divider. HSIDIVF goes immediately to 0 when HSIDIV value is changed, and is set back to 1 when the output frequency matches the value programmed into HSIDIV."] pub type HSIDIVF_R = crate::BitReader; #[doc = "Field `CSION` reader - CSI clock enable Set and reset by software to enable/disable CSI clock for system and/or peripheral. Set by hardware to force the CSI to ON when the system leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. This bit cannot be cleared if the CSI is used directly (via SW mux) as system clock, or if the CSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type CSION_R = crate::BitReader; #[doc = "Field `CSION` writer - CSI clock enable Set and reset by software to enable/disable CSI clock for system and/or peripheral. Set by hardware to force the CSI to ON when the system leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. This bit cannot be cleared if the CSI is used directly (via SW mux) as system clock, or if the CSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type CSION_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CSIRDY` reader - CSI clock ready flag Set by hardware to indicate that the CSI oscillator is stable. This bit is activated only if the RC is enabled by CSION (it is not activated if the CSI is enabled by CSIKERON or by a peripheral request)."] pub type CSIRDY_R = crate::BitReader; #[doc = "Field `CSIKERON` reader - CSI clock enable in Stop mode Set and reset by software to force the CSI to ON, even in Stop mode, in order to be quickly available as kernel clock for some peripherals. This bit has no effect on the value of CSION."] pub type CSIKERON_R = crate::BitReader; #[doc = "Field `CSIKERON` writer - CSI clock enable in Stop mode Set and reset by software to force the CSI to ON, even in Stop mode, in order to be quickly available as kernel clock for some peripherals. This bit has no effect on the value of CSION."] pub type CSIKERON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSI48ON` reader - HSI48 clock enable Set by software and cleared by software or by the hardware when the system enters to Stop or Standby mode."] pub type HSI48ON_R = crate::BitReader; #[doc = "Field `HSI48ON` writer - HSI48 clock enable Set by software and cleared by software or by the hardware when the system enters to Stop or Standby mode."] pub type HSI48ON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSI48RDY` reader - HSI48 clock ready flag Set by hardware to indicate that the HSI48 oscillator is stable."] pub type HSI48RDY_R = crate::BitReader; #[doc = "Field `HSEON` reader - HSE clock enable Set and cleared by software. Cleared by hardware to stop the HSE when entering Stop or Standby mode. This bit cannot be cleared if the HSE is used directly (via SW mux) as system clock, or if the HSE is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type HSEON_R = crate::BitReader; #[doc = "Field `HSEON` writer - HSE clock enable Set and cleared by software. Cleared by hardware to stop the HSE when entering Stop or Standby mode. This bit cannot be cleared if the HSE is used directly (via SW mux) as system clock, or if the HSE is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] pub type HSEON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSERDY` reader - HSE clock ready flag Set by hardware to indicate that the HSE oscillator is stable."] pub type HSERDY_R = crate::BitReader; #[doc = "Field `HSEBYP` reader - HSE clock bypass Set and cleared by software to bypass the oscillator with an external clock. The external clock must be enabled with the HSEON bit to be used by the device. The HSEBYP bit can be written only if the HSE oscillator is disabled."] pub type HSEBYP_R = crate::BitReader; #[doc = "Field `HSEBYP` writer - HSE clock bypass Set and cleared by software to bypass the oscillator with an external clock. The external clock must be enabled with the HSEON bit to be used by the device. The HSEBYP bit can be written only if the HSE oscillator is disabled."] pub type HSEBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSECSSON` reader - HSE clock security system enable Set by software to enable clock security system on HSE. This bit is “set only” (disabled by a system reset or when the system enters in Standby mode). When HSECSSON is set, the clock detector is enabled by hardware when the HSE is ready and disabled by hardware if an oscillator failure is detected."] pub type HSECSSON_R = crate::BitReader; #[doc = "Field `HSECSSON` writer - HSE clock security system enable Set by software to enable clock security system on HSE. This bit is “set only” (disabled by a system reset or when the system enters in Standby mode). When HSECSSON is set, the clock detector is enabled by hardware when the HSE is ready and disabled by hardware if an oscillator failure is detected."] pub type HSECSSON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSEEXT` reader - external high speed clock type in Bypass mode Set and reset by software to select the external clock type (analog or digital). The external clock must be enabled with the HSEON bit to be used by the device. The HSEEXT bit can be written only if the HSE oscillator is disabled."] pub type HSEEXT_R = crate::BitReader; #[doc = "Field `HSEEXT` writer - external high speed clock type in Bypass mode Set and reset by software to select the external clock type (analog or digital). The external clock must be enabled with the HSEON bit to be used by the device. The HSEEXT bit can be written only if the HSE oscillator is disabled."] pub type HSEEXT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PLL1ON` reader - PLL1 enable Set and cleared by software to enable PLL1. Cleared by hardware when entering Stop or Standby mode. Note that the hardware prevents writing this bit to 0, if the PLL1 output is used as the system clock."] pub type PLL1ON_R = crate::BitReader; #[doc = "Field `PLL1ON` writer - PLL1 enable Set and cleared by software to enable PLL1. Cleared by hardware when entering Stop or Standby mode. Note that the hardware prevents writing this bit to 0, if the PLL1 output is used as the system clock."] pub type PLL1ON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PLL1RDY` reader - PLL1 clock ready flag Set by hardware to indicate that the PLL1 is locked."] pub type PLL1RDY_R = crate::BitReader; #[doc = "Field `PLL2ON` reader - PLL2 enable Set and cleared by software to enable PLL2. Cleared by hardware when entering Stop or Standby mode."] pub type PLL2ON_R = crate::BitReader; #[doc = "Field `PLL2ON` writer - PLL2 enable Set and cleared by software to enable PLL2. Cleared by hardware when entering Stop or Standby mode."] pub type PLL2ON_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PLL2RDY` reader - PLL2 clock ready flag Set by hardware to indicate that the PLL is locked."] pub type PLL2RDY_R = crate::BitReader; impl R { #[doc = "Bit 0 - HSI clock enable Set and cleared by software. Set by hardware to force the HSI to ON when the product leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. Set by hardware to force the HSI to ON when the product leaves Standby mode or in case of a failure of the HSE which is used as the system clock source. This bit cannot be cleared if the HSI is used directly (via SW mux) as system clock, or if the HSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] pub fn hsion(&self) -> HSION_R { HSION_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - HSI clock ready flag Set by hardware to indicate that the HSI oscillator is stable."] #[inline(always)] pub fn hsirdy(&self) -> HSIRDY_R { HSIRDY_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - HSI clock enable in Stop mode Set and reset by software to force the HSI to ON, even in Stop mode, in order to be quickly available as kernel clock for peripherals. This bit has no effect on the value of HSION."] #[inline(always)] pub fn hsikeron(&self) -> HSIKERON_R { HSIKERON_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bits 3:4 - HSI clock divider Set and reset by software. These bits allow selecting a division ratio in order to configure the wanted HSI clock frequency. The HSIDIV cannot be changed if the HSI is selected as reference clock for at least one enabled PLL (PLLxON bit set to 1). In that case, the new HSIDIV value is ignored."] #[inline(always)] pub fn hsidiv(&self) -> HSIDIV_R { HSIDIV_R::new(((self.bits >> 3) & 3) as u8) } #[doc = "Bit 5 - HSI divider flag Set and reset by hardware. As a write operation to HSIDIV has not an immediate effect on the frequency, this flag indicates the current status of the HSI divider. HSIDIVF goes immediately to 0 when HSIDIV value is changed, and is set back to 1 when the output frequency matches the value programmed into HSIDIV."] #[inline(always)] pub fn hsidivf(&self) -> HSIDIVF_R { HSIDIVF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 8 - CSI clock enable Set and reset by software to enable/disable CSI clock for system and/or peripheral. Set by hardware to force the CSI to ON when the system leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. This bit cannot be cleared if the CSI is used directly (via SW mux) as system clock, or if the CSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] pub fn csion(&self) -> CSION_R { CSION_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - CSI clock ready flag Set by hardware to indicate that the CSI oscillator is stable. This bit is activated only if the RC is enabled by CSION (it is not activated if the CSI is enabled by CSIKERON or by a peripheral request)."] #[inline(always)] pub fn csirdy(&self) -> CSIRDY_R { CSIRDY_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - CSI clock enable in Stop mode Set and reset by software to force the CSI to ON, even in Stop mode, in order to be quickly available as kernel clock for some peripherals. This bit has no effect on the value of CSION."] #[inline(always)] pub fn csikeron(&self) -> CSIKERON_R { CSIKERON_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 12 - HSI48 clock enable Set by software and cleared by software or by the hardware when the system enters to Stop or Standby mode."] #[inline(always)] pub fn hsi48on(&self) -> HSI48ON_R { HSI48ON_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - HSI48 clock ready flag Set by hardware to indicate that the HSI48 oscillator is stable."] #[inline(always)] pub fn hsi48rdy(&self) -> HSI48RDY_R { HSI48RDY_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 16 - HSE clock enable Set and cleared by software. Cleared by hardware to stop the HSE when entering Stop or Standby mode. This bit cannot be cleared if the HSE is used directly (via SW mux) as system clock, or if the HSE is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - HSE clock ready flag Set by hardware to indicate that the HSE oscillator is stable."] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - HSE clock bypass Set and cleared by software to bypass the oscillator with an external clock. The external clock must be enabled with the HSEON bit to be used by the device. The HSEBYP bit can be written only if the HSE oscillator is disabled."] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - HSE clock security system enable Set by software to enable clock security system on HSE. This bit is “set only” (disabled by a system reset or when the system enters in Standby mode). When HSECSSON is set, the clock detector is enabled by hardware when the HSE is ready and disabled by hardware if an oscillator failure is detected."] #[inline(always)] pub fn hsecsson(&self) -> HSECSSON_R { HSECSSON_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - external high speed clock type in Bypass mode Set and reset by software to select the external clock type (analog or digital). The external clock must be enabled with the HSEON bit to be used by the device. The HSEEXT bit can be written only if the HSE oscillator is disabled."] #[inline(always)] pub fn hseext(&self) -> HSEEXT_R { HSEEXT_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 24 - PLL1 enable Set and cleared by software to enable PLL1. Cleared by hardware when entering Stop or Standby mode. Note that the hardware prevents writing this bit to 0, if the PLL1 output is used as the system clock."] #[inline(always)] pub fn pll1on(&self) -> PLL1ON_R { PLL1ON_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - PLL1 clock ready flag Set by hardware to indicate that the PLL1 is locked."] #[inline(always)] pub fn pll1rdy(&self) -> PLL1RDY_R { PLL1RDY_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 26 - PLL2 enable Set and cleared by software to enable PLL2. Cleared by hardware when entering Stop or Standby mode."] #[inline(always)] pub fn pll2on(&self) -> PLL2ON_R { PLL2ON_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - PLL2 clock ready flag Set by hardware to indicate that the PLL is locked."] #[inline(always)] pub fn pll2rdy(&self) -> PLL2RDY_R { PLL2RDY_R::new(((self.bits >> 27) & 1) != 0) } } impl W { #[doc = "Bit 0 - HSI clock enable Set and cleared by software. Set by hardware to force the HSI to ON when the product leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. Set by hardware to force the HSI to ON when the product leaves Standby mode or in case of a failure of the HSE which is used as the system clock source. This bit cannot be cleared if the HSI is used directly (via SW mux) as system clock, or if the HSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] #[must_use] pub fn hsion(&mut self) -> HSION_W<CR_SPEC, 0> { HSION_W::new(self) } #[doc = "Bit 2 - HSI clock enable in Stop mode Set and reset by software to force the HSI to ON, even in Stop mode, in order to be quickly available as kernel clock for peripherals. This bit has no effect on the value of HSION."] #[inline(always)] #[must_use] pub fn hsikeron(&mut self) -> HSIKERON_W<CR_SPEC, 2> { HSIKERON_W::new(self) } #[doc = "Bits 3:4 - HSI clock divider Set and reset by software. These bits allow selecting a division ratio in order to configure the wanted HSI clock frequency. The HSIDIV cannot be changed if the HSI is selected as reference clock for at least one enabled PLL (PLLxON bit set to 1). In that case, the new HSIDIV value is ignored."] #[inline(always)] #[must_use] pub fn hsidiv(&mut self) -> HSIDIV_W<CR_SPEC, 3> { HSIDIV_W::new(self) } #[doc = "Bit 8 - CSI clock enable Set and reset by software to enable/disable CSI clock for system and/or peripheral. Set by hardware to force the CSI to ON when the system leaves Stop mode, if STOPWUCK = 1 or STOPKERWUCK = 1. This bit cannot be cleared if the CSI is used directly (via SW mux) as system clock, or if the CSI is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] #[must_use] pub fn csion(&mut self) -> CSION_W<CR_SPEC, 8> { CSION_W::new(self) } #[doc = "Bit 10 - CSI clock enable in Stop mode Set and reset by software to force the CSI to ON, even in Stop mode, in order to be quickly available as kernel clock for some peripherals. This bit has no effect on the value of CSION."] #[inline(always)] #[must_use] pub fn csikeron(&mut self) -> CSIKERON_W<CR_SPEC, 10> { CSIKERON_W::new(self) } #[doc = "Bit 12 - HSI48 clock enable Set by software and cleared by software or by the hardware when the system enters to Stop or Standby mode."] #[inline(always)] #[must_use] pub fn hsi48on(&mut self) -> HSI48ON_W<CR_SPEC, 12> { HSI48ON_W::new(self) } #[doc = "Bit 16 - HSE clock enable Set and cleared by software. Cleared by hardware to stop the HSE when entering Stop or Standby mode. This bit cannot be cleared if the HSE is used directly (via SW mux) as system clock, or if the HSE is selected as reference clock for PLL1 with PLL1 enabled (PLL1ON bit set to 1)."] #[inline(always)] #[must_use] pub fn hseon(&mut self) -> HSEON_W<CR_SPEC, 16> { HSEON_W::new(self) } #[doc = "Bit 18 - HSE clock bypass Set and cleared by software to bypass the oscillator with an external clock. The external clock must be enabled with the HSEON bit to be used by the device. The HSEBYP bit can be written only if the HSE oscillator is disabled."] #[inline(always)] #[must_use] pub fn hsebyp(&mut self) -> HSEBYP_W<CR_SPEC, 18> { HSEBYP_W::new(self) } #[doc = "Bit 19 - HSE clock security system enable Set by software to enable clock security system on HSE. This bit is “set only” (disabled by a system reset or when the system enters in Standby mode). When HSECSSON is set, the clock detector is enabled by hardware when the HSE is ready and disabled by hardware if an oscillator failure is detected."] #[inline(always)] #[must_use] pub fn hsecsson(&mut self) -> HSECSSON_W<CR_SPEC, 19> { HSECSSON_W::new(self) } #[doc = "Bit 20 - external high speed clock type in Bypass mode Set and reset by software to select the external clock type (analog or digital). The external clock must be enabled with the HSEON bit to be used by the device. The HSEEXT bit can be written only if the HSE oscillator is disabled."] #[inline(always)] #[must_use] pub fn hseext(&mut self) -> HSEEXT_W<CR_SPEC, 20> { HSEEXT_W::new(self) } #[doc = "Bit 24 - PLL1 enable Set and cleared by software to enable PLL1. Cleared by hardware when entering Stop or Standby mode. Note that the hardware prevents writing this bit to 0, if the PLL1 output is used as the system clock."] #[inline(always)] #[must_use] pub fn pll1on(&mut self) -> PLL1ON_W<CR_SPEC, 24> { PLL1ON_W::new(self) } #[doc = "Bit 26 - PLL2 enable Set and cleared by software to enable PLL2. Cleared by hardware when entering Stop or Standby mode."] #[inline(always)] #[must_use] pub fn pll2on(&mut self) -> PLL2ON_W<CR_SPEC, 26> { PLL2ON_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 = "RCC clock control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0x23"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0x23; }
// https://adventofcode.com/2018/day/5 use std::fs::File; use std::io::{BufRead, BufReader}; fn reacts(x: char, y: char) -> bool { (x != y) && (x.to_lowercase().to_string() == y.to_lowercase().to_string()) } fn polymer_react(ps: &str) -> String { let mut poly: Vec<char> = vec![]; for c in ps.chars() { match poly.last() { Some(&t) => { if reacts(t, c) { poly.pop(); } else { poly.push(c); } } None => poly.push(c), } } poly.iter().collect() } pub fn day5(input: &str) { let f = File::open(input).expect("Failed to open input file"); let mut reader = BufReader::new(f); let mut line = String::new(); reader.read_line(&mut line).expect("Failed to read buffer"); let polymer = line.trim(); println!("Polymer1 length: {}", polymer_react(polymer).len()); if let Some(shortest) = shortest_polymer(polymer) { println!("Shortest polymer length: {}", shortest.len()); } else { println!("Couldn't find the shortest polymer"); } } fn filter_unit(ps: &str, u: char) -> String { ps.chars() .filter(|&c| c.to_lowercase().to_string() != u.to_lowercase().to_string()) .collect() } fn shortest_polymer(ps: &str) -> Option<String> { ('a' as u8..('z' as u8 + 1)) .map(|u| polymer_react(&filter_unit(ps, u as char))) .min_by_key(|x| x.len()) } #[test] fn test_polymer_react() { assert_eq!(polymer_react("dabAcCaCBAcCcaDA"), "dabCBAcaDA"); assert_eq!(polymer_react("aaA"), "a"); assert_eq!(polymer_react("aAa"), "a"); assert_eq!(polymer_react("aAab"), "ab"); assert_eq!(polymer_react("cAaaC"), "caC"); assert_eq!(polymer_react("cCAdDbEeC"), "AbC"); } #[test] fn test_polymer_filter() { assert_eq!(filter_unit("aaA", 'a'), ""); assert_eq!(filter_unit("aaA", 'A'), ""); assert_eq!(filter_unit("aaAbdc", 'a'), "bdc"); assert_eq!(filter_unit("aaAbdc", 'A'), "bdc"); assert_eq!(filter_unit("aaAbdc", 'b'), "aaAdc"); }
use serde::*; use serde_tuple::*; use std::time::SystemTime; use crate::util::temporal; #[derive(Clone, Debug, Serialize, Deserialize_tuple)] pub struct Aircraft { pub icao24: String, pub callsign: Option<String>, // Can be null if not received pub origin_country: String, pub time_position: Option<i64>, // Time of last position update, as unix timestamp. Can be null pub last_contact: i64, // Time of last update received, as unix timestamp pub longitude: Option<f64>, // Can be null if not received pub latitude: Option<f64>, // Can be null if not received pub baro_altitude: Option<f32>, // Barometric altitude, meters. Can be null pub on_ground: bool, pub velocity: Option<f32>, // Ground speed, m/s. Can be null if not received pub true_track: Option<f32>, // Decimal degrees clockwise from N. Can be null pub vertical_rate: Option<f32>, // m/s, positive means climbing pub sensors: Option<Vec<i32>>, // Source sensor; will not contain useful data in these queries pub geo_altitude: Option<f32>, // Geometric altitude, meters. Can be null pub squawk: Option<String>, // Transponder code. Can be null pub spi: bool, // Special purpose indicator pub position_source: i32 // 0=ADS-B, 1=ASTERIX, 2=MLAT } #[derive(Debug, Clone, Deserialize)] pub struct AircraftData { pub time: isize, // Time of data receipt #[serde(rename = "states")] pub data: Vec<Aircraft> // All state vectors } impl AircraftData { pub fn empty() -> Self { Self { time: 0, data: vec![] } } pub fn linear_search<P>(&self, pred: P) -> Option<&Aircraft> where P: FnMut(&&Aircraft) -> bool { self.data.iter() .filter(pred) .next() } } impl Aircraft { pub fn _has_position_data(&self) -> bool { self.longitude.is_some() && self.latitude.is_some() } pub fn basic_status(&self) -> String { // e.g. "AAA1234 (United States, ICAO: ab42de, Last contact: 2 seconds ago)" let last_contact = temporal::get_duration( temporal::systemtime_from_datetime( temporal::utc_datetime_from_timestamp(self.last_contact as i64)), SystemTime::now()); format!("{} ({}, ICAO: {}, Last contact: {})", self.callsign.as_ref().unwrap_or(&"[Unknown callsign]".to_string()), self.origin_country, self.icao24, last_contact.map(|x| format!("{} seconds ago", x.as_secs())).unwrap_or("[Unknown]".to_string()) ) } }
pub mod CasperMessage; pub mod DeployService; pub mod DeployService_grpc; pub mod Either; pub mod ProposeService; pub mod ProposeService_grpc; pub mod RhoTypes; pub mod routing; pub mod routing_grpc; pub mod scalapb; mod empty { pub use protobuf::well_known_types::Empty; }
use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::num::ParseIntError; use std::str::FromStr; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum Direction { Up, Down, Left, Right, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] struct Segment { direction: Direction, distance: i64, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] struct ParseDirectionError; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] struct ParseSegmentError; impl From<ParseDirectionError> for ParseSegmentError { fn from(_err: ParseDirectionError) -> Self { Self } } impl From<ParseIntError> for ParseSegmentError { fn from(_err: ParseIntError) -> Self { Self } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] struct Point(i64, i64); impl FromStr for Direction { type Err = ParseDirectionError; fn from_str(s: &str) -> Result<Self, Self::Err> { let direction = match s { "U" => Direction::Up, "D" => Direction::Down, "L" => Direction::Left, "R" => Direction::Right, _ => return Err(ParseDirectionError), }; Ok(direction) } } impl FromStr for Segment { type Err = ParseSegmentError; fn from_str(s: &str) -> Result<Self, Self::Err> { let step = { let direction: Direction = s[..1].parse()?; let distance: i64 = s[1..].parse()?; Segment { direction, distance, } }; Ok(step) } } impl Point { fn dist_from_origin(&self) -> i64 { self.0.abs() + self.1.abs() } fn step(&self, direction: Direction) -> Point { match direction { Direction::Up => Point(self.0, self.1 + 1), Direction::Down => Point(self.0, self.1 - 1), Direction::Left => Point(self.0 - 1, self.1), Direction::Right => Point(self.0 + 1, self.1), } } } pub(crate) fn day03() { let input = File::open("data/day03.txt").expect("Failed to open input"); let mut buffered = BufReader::new(input); let mut line1 = String::new(); buffered .read_line(&mut line1) .expect("Failed to read line1"); let steps1: Vec<Segment> = line1 .trim() .split(',') .map(|word| word.parse::<Segment>().unwrap()) .collect(); let mut line2 = String::new(); buffered .read_line(&mut line2) .expect("Failed to read line2"); let steps2: Vec<Segment> = line2 .trim() .split(',') .map(|word| word.parse::<Segment>().unwrap()) .collect(); let visited1 = visited(&steps1); let visited2 = visited(&steps2); let set1 = visited1.keys().collect::<HashSet<_>>(); let set2 = visited2.keys().collect::<HashSet<_>>(); let intersections = set1.intersection(&set2); let closest = intersections .clone() .map(|c| c.dist_from_origin()) .min() .unwrap(); println!("Part one answer is: {}", closest); let shortest = intersections .map(|c| visited1.get(c).unwrap() + visited2.get(c).unwrap()) .min() .unwrap(); println!("Part two answer is: {}", shortest); } // Given a path of `Segment`s, returns a `HashMap` whose keys are the points visited by that path // and whose values are the number of steps it took to reach the point. fn visited(path: &[Segment]) -> HashMap<Point, i64> { let mut visited = HashMap::new(); let mut posn = Point(0, 0); let mut steps = 0; for segment in path { for _ii in 1..=segment.distance { posn = posn.step(segment.direction); steps += 1; visited.entry(posn).or_insert(steps); } } visited }
/// Rotations in degrees #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, PartialOrd, Ord, )] pub struct Rot(usize); // Right pub const DEG_0: Rot = Rot(0); // Up pub const DEG_90: Rot = Rot(90); // Left pub const DEG_180: Rot = Rot(180); // Down pub const DEG_270: Rot = Rot(270); impl Rot { pub const fn rot_90(self, card: usize) -> Self { Rot((self.0 + 90) % card) } pub const fn opp(self) -> Self { Rot((self.0 + 180) % 360) } pub fn to(self, o: Self, card: usize) -> Self { let dest = if o.0 < self.0 { o.0 + 360 } else { o.0 }; Rot((dest - self.0) % card) } pub const fn rot_90_n(self, card: usize, n: usize) -> Self { Rot((self.0 + 90 * n) % card) } pub fn up_to(v: usize) -> impl Iterator<Item = Rot> { (0..v).step_by(90).map(Rot) } pub const fn all() -> [Rot; 4] { [DEG_0, DEG_90, DEG_180, DEG_270] } } #[test] fn to() { assert_eq!(DEG_0.to(&DEG_90, 360), DEG_90); assert_eq!(DEG_0.to(&DEG_180, 360), DEG_180); assert_eq!(DEG_0.to(&DEG_270, 360), DEG_270); assert_eq!(DEG_0.to(&DEG_270, 90), DEG_0); assert_eq!(DEG_270.to(&DEG_0, 360), DEG_90); assert_eq!(DEG_180.to(&DEG_0, 360), DEG_180); assert_eq!(DEG_180.to(&DEG_0, 180), DEG_0); assert_eq!(DEG_90.to(&DEG_0, 180), DEG_90); } #[test] fn rot_90_n() { assert_eq!(DEG_0.rot_90_n(360, 0), DEG_0); assert_eq!(DEG_0.rot_90_n(360, 1), DEG_90); } // TODO add a symmetry which is flipped x and flipped y and rotated
use nu_engine::get_full_help; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, IntoPipelineData, PipelineData, Signature, Value, }; #[derive(Clone)] pub struct Url; impl Command for Url { fn name(&self) -> &str { "url" } fn signature(&self) -> Signature { Signature::build("url").category(Category::Network) } fn usage(&self) -> &str { "Apply url function." } fn search_terms(&self) -> Vec<&str> { vec!["network", "parse"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { Ok(Value::String { val: get_full_help(&Url.signature(), &Url.examples(), engine_state, stack), span: call.head, } .into_pipeline_data()) } }
extern crate ndarray; use super::loss_layer::{LayerWithLoss, SigmodWithLoss}; use crate::functions::*; use crate::layers::{Embedding1d, Embedding2d}; use crate::model::Model; use crate::types::{Arr1d, Arr2d, Arr3d}; use crate::util::*; use itertools::izip; use ndarray::{s, Array, Array1, Array2, Array3, Axis, Ix2}; pub struct EmbeddingDot { /// 単語の表現ベクトルの束(2次元行列)を持っていて、基本的にただそこから抜き出してくるだけ embed: Embedding1d, input: Arr2d, target_w: Arr2d, } impl EmbeddingDot { /// input: (bs, ch), idx: (bs,) <- 正解インデックスを想定 fn forward(&mut self, input: Arr2d, idx: Array1<usize>) -> Arr1d { self.target_w = self.embed.forward(idx); self.input = input; (&self.input * &self.target_w).sum_axis(Axis(1)) // 要するに各列で内積を取る } fn backward(&mut self, dout: Arr1d) -> Arr2d { // let dout = dout.into_shape((dout.len(), 1)).unwrap(); let dout = dout.insert_axis(Axis(1)); let dtarget_w = &self.input * &dout; // target_wの方は、inputから勾配を得る self.embed.backward(dtarget_w); // 元のwに埋め込む &self.target_w * &dout // inputの勾配はtarget_wになる } } struct EmbeddingDot2d { /// (word_num, ch) embed: Embedding2d, /// (bs, 1, ch) input: Arr3d, /// (bs, sn, ch) target_w: Arr3d, } impl EmbeddingDot2d { /// input: (bs, ch), idx: (bs, samplnum), output: (bs, samplnum) /// 各行で、idxによりwからサンプリングして、inputと掛ける fn forward(&mut self, input: Arr2d, idx: Array2<usize>) -> Arr2d { let (batch_size, channel_num) = input.dim(); self.target_w = self.embed.forward(idx); // (bs, sn, ch) self.input = input.insert_axis(Axis(1)); let out = (&self.target_w * &self.input).sum_axis(Axis(2)); // 要するに各列で内積を取る out } fn backward(&mut self, dout: Arr2d) -> Arr2d { let dout = dout.insert_axis(Axis(2)); // let dtarget_w = self.input * dout; // target_wの方は、inputから勾配を得る // castできないので仕方なく let dtarget_w = Array::from_shape_fn(self.target_w.dim(), |(i, j, k)| { self.input[[i, 0, k]] * dout[[i, j, 0]] }); self.embed.backward(dtarget_w); // 元のwに埋め込む (&self.target_w * &dout).sum_axis(Axis(1)) // sample_num方向に潰す } fn new(w: Arr2d) -> Self { Self { embed: Embedding2d::new(w), input: Default::default(), target_w: Default::default(), } } fn params(&mut self) -> Vec<&mut Arr2d> { self.embed.params() } fn params_immut(&self) -> Vec<&Arr2d> { self.embed.params_immut() } fn grads(&self) -> Vec<Arr2d> { self.embed.grads() } } use rand::distributions::Distribution; use rand::distributions::WeightedIndex; use rand::prelude::thread_rng; struct Sampler { sample_size: usize, distribution: WeightedIndex<f32>, } impl Sampler { /// 正解であるtargetに、negativeサンプリングを加える fn negative_sampling(&self, target: Array1<usize>) -> (Array2<usize>, Array2<bool>) { let mut rng = thread_rng(); let batch_size = target.len(); let mut arr = Array2::zeros((batch_size, self.sample_size + 1)); arr.index_axis_mut(Axis(1), 0).assign(&target); let ns = Array2::from_shape_fn((batch_size, self.sample_size), |_| { self.distribution.sample(&mut rng) }); arr.slice_mut(s![.., 1..]).assign(&ns); let ans = Array::from_shape_fn(arr.dim(), |(i, j)| arr[[i, j]] == target[i]); (arr, ans) } fn new(sample_size: usize, distribution: WeightedIndex<f32>) -> Self { Self { sample_size, distribution, } } } pub trait InitWithSampler { fn new(ws: &[Arr2d], sample_size: usize, distribution: WeightedIndex<f32>) -> Self; } pub struct NegativeSamplingLoss { sample_size: usize, sampler: Sampler, loss_layer: SigmodWithLoss<Ix2>, embed: EmbeddingDot2d, } impl LayerWithLoss for NegativeSamplingLoss { fn forward2(&mut self, input: Arr2d, target: Array1<usize>) -> f32 { // let batch_size = target.shape()[0]; let (target_and_negative_sample, label) = self.sampler.negative_sampling(target); let out = self.embed.forward(input, target_and_negative_sample); self.loss_layer.forward(out, label) } fn backward(&mut self) -> Arr2d { let mut dx = self.loss_layer.backward(); dx = self.embed.backward(dx); dx } fn params(&mut self) -> Vec<&mut Arr2d> { self.embed.params() } fn grads(&self) -> Vec<Arr2d> { self.embed.grads() } } impl NegativeSamplingLoss { pub fn new(w: Arr2d, sample_size: usize, distribution: WeightedIndex<f32>) -> Self { Self { sample_size, sampler: Sampler::new(sample_size, distribution), loss_layer: Default::default(), embed: EmbeddingDot2d::new(w), } } pub fn params_immut(&self) -> Vec<&Arr2d> { self.embed.params_immut() } } use counter::Counter; pub fn get_distribution(corpus: &Vec<usize>, power: Option<f32>) -> WeightedIndex<f32> { let id_counts: Counter<_> = corpus.iter().cloned().collect(); let mut v: Vec<_> = id_counts.into_map().into_iter().collect(); v.sort(); let power = power.unwrap_or(1.0); let weights: Vec<_> = v.into_iter().map(|p| p.1 as f32 * power).collect(); WeightedIndex::new(&weights).unwrap() }
/// An enum to represent all characters in the Georgian block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Georgian { /// \u{10a0}: 'Ⴀ' CapitalLetterAn, /// \u{10a1}: 'Ⴁ' CapitalLetterBan, /// \u{10a2}: 'Ⴂ' CapitalLetterGan, /// \u{10a3}: 'Ⴃ' CapitalLetterDon, /// \u{10a4}: 'Ⴄ' CapitalLetterEn, /// \u{10a5}: 'Ⴅ' CapitalLetterVin, /// \u{10a6}: 'Ⴆ' CapitalLetterZen, /// \u{10a7}: 'Ⴇ' CapitalLetterTan, /// \u{10a8}: 'Ⴈ' CapitalLetterIn, /// \u{10a9}: 'Ⴉ' CapitalLetterKan, /// \u{10aa}: 'Ⴊ' CapitalLetterLas, /// \u{10ab}: 'Ⴋ' CapitalLetterMan, /// \u{10ac}: 'Ⴌ' CapitalLetterNar, /// \u{10ad}: 'Ⴍ' CapitalLetterOn, /// \u{10ae}: 'Ⴎ' CapitalLetterPar, /// \u{10af}: 'Ⴏ' CapitalLetterZhar, /// \u{10b0}: 'Ⴐ' CapitalLetterRae, /// \u{10b1}: 'Ⴑ' CapitalLetterSan, /// \u{10b2}: 'Ⴒ' CapitalLetterTar, /// \u{10b3}: 'Ⴓ' CapitalLetterUn, /// \u{10b4}: 'Ⴔ' CapitalLetterPhar, /// \u{10b5}: 'Ⴕ' CapitalLetterKhar, /// \u{10b6}: 'Ⴖ' CapitalLetterGhan, /// \u{10b7}: 'Ⴗ' CapitalLetterQar, /// \u{10b8}: 'Ⴘ' CapitalLetterShin, /// \u{10b9}: 'Ⴙ' CapitalLetterChin, /// \u{10ba}: 'Ⴚ' CapitalLetterCan, /// \u{10bb}: 'Ⴛ' CapitalLetterJil, /// \u{10bc}: 'Ⴜ' CapitalLetterCil, /// \u{10bd}: 'Ⴝ' CapitalLetterChar, /// \u{10be}: 'Ⴞ' CapitalLetterXan, /// \u{10bf}: 'Ⴟ' CapitalLetterJhan, /// \u{10c0}: 'Ⴠ' CapitalLetterHae, /// \u{10c1}: 'Ⴡ' CapitalLetterHe, /// \u{10c2}: 'Ⴢ' CapitalLetterHie, /// \u{10c3}: 'Ⴣ' CapitalLetterWe, /// \u{10c4}: 'Ⴤ' CapitalLetterHar, /// \u{10c5}: 'Ⴥ' CapitalLetterHoe, /// \u{10c7}: 'Ⴧ' CapitalLetterYn, /// \u{10cd}: 'Ⴭ' CapitalLetterAen, /// \u{10d0}: 'ა' LetterAn, /// \u{10d1}: 'ბ' LetterBan, /// \u{10d2}: 'გ' LetterGan, /// \u{10d3}: 'დ' LetterDon, /// \u{10d4}: 'ე' LetterEn, /// \u{10d5}: 'ვ' LetterVin, /// \u{10d6}: 'ზ' LetterZen, /// \u{10d7}: 'თ' LetterTan, /// \u{10d8}: 'ი' LetterIn, /// \u{10d9}: 'კ' LetterKan, /// \u{10da}: 'ლ' LetterLas, /// \u{10db}: 'მ' LetterMan, /// \u{10dc}: 'ნ' LetterNar, /// \u{10dd}: 'ო' LetterOn, /// \u{10de}: 'პ' LetterPar, /// \u{10df}: 'ჟ' LetterZhar, /// \u{10e0}: 'რ' LetterRae, /// \u{10e1}: 'ს' LetterSan, /// \u{10e2}: 'ტ' LetterTar, /// \u{10e3}: 'უ' LetterUn, /// \u{10e4}: 'ფ' LetterPhar, /// \u{10e5}: 'ქ' LetterKhar, /// \u{10e6}: 'ღ' LetterGhan, /// \u{10e7}: 'ყ' LetterQar, /// \u{10e8}: 'შ' LetterShin, /// \u{10e9}: 'ჩ' LetterChin, /// \u{10ea}: 'ც' LetterCan, /// \u{10eb}: 'ძ' LetterJil, /// \u{10ec}: 'წ' LetterCil, /// \u{10ed}: 'ჭ' LetterChar, /// \u{10ee}: 'ხ' LetterXan, /// \u{10ef}: 'ჯ' LetterJhan, /// \u{10f0}: 'ჰ' LetterHae, /// \u{10f1}: 'ჱ' LetterHe, /// \u{10f2}: 'ჲ' LetterHie, /// \u{10f3}: 'ჳ' LetterWe, /// \u{10f4}: 'ჴ' LetterHar, /// \u{10f5}: 'ჵ' LetterHoe, /// \u{10f6}: 'ჶ' LetterFi, /// \u{10f7}: 'ჷ' LetterYn, /// \u{10f8}: 'ჸ' LetterElifi, /// \u{10f9}: 'ჹ' LetterTurnedGan, /// \u{10fa}: 'ჺ' LetterAin, /// \u{10fb}: '჻' ParagraphSeparator, /// \u{10fc}: 'ჼ' ModifierLetterNar, /// \u{10fd}: 'ჽ' LetterAen, /// \u{10fe}: 'ჾ' LetterHardSign, } impl Into<char> for Georgian { fn into(self) -> char { match self { Georgian::CapitalLetterAn => 'Ⴀ', Georgian::CapitalLetterBan => 'Ⴁ', Georgian::CapitalLetterGan => 'Ⴂ', Georgian::CapitalLetterDon => 'Ⴃ', Georgian::CapitalLetterEn => 'Ⴄ', Georgian::CapitalLetterVin => 'Ⴅ', Georgian::CapitalLetterZen => 'Ⴆ', Georgian::CapitalLetterTan => 'Ⴇ', Georgian::CapitalLetterIn => 'Ⴈ', Georgian::CapitalLetterKan => 'Ⴉ', Georgian::CapitalLetterLas => 'Ⴊ', Georgian::CapitalLetterMan => 'Ⴋ', Georgian::CapitalLetterNar => 'Ⴌ', Georgian::CapitalLetterOn => 'Ⴍ', Georgian::CapitalLetterPar => 'Ⴎ', Georgian::CapitalLetterZhar => 'Ⴏ', Georgian::CapitalLetterRae => 'Ⴐ', Georgian::CapitalLetterSan => 'Ⴑ', Georgian::CapitalLetterTar => 'Ⴒ', Georgian::CapitalLetterUn => 'Ⴓ', Georgian::CapitalLetterPhar => 'Ⴔ', Georgian::CapitalLetterKhar => 'Ⴕ', Georgian::CapitalLetterGhan => 'Ⴖ', Georgian::CapitalLetterQar => 'Ⴗ', Georgian::CapitalLetterShin => 'Ⴘ', Georgian::CapitalLetterChin => 'Ⴙ', Georgian::CapitalLetterCan => 'Ⴚ', Georgian::CapitalLetterJil => 'Ⴛ', Georgian::CapitalLetterCil => 'Ⴜ', Georgian::CapitalLetterChar => 'Ⴝ', Georgian::CapitalLetterXan => 'Ⴞ', Georgian::CapitalLetterJhan => 'Ⴟ', Georgian::CapitalLetterHae => 'Ⴠ', Georgian::CapitalLetterHe => 'Ⴡ', Georgian::CapitalLetterHie => 'Ⴢ', Georgian::CapitalLetterWe => 'Ⴣ', Georgian::CapitalLetterHar => 'Ⴤ', Georgian::CapitalLetterHoe => 'Ⴥ', Georgian::CapitalLetterYn => 'Ⴧ', Georgian::CapitalLetterAen => 'Ⴭ', Georgian::LetterAn => 'ა', Georgian::LetterBan => 'ბ', Georgian::LetterGan => 'გ', Georgian::LetterDon => 'დ', Georgian::LetterEn => 'ე', Georgian::LetterVin => 'ვ', Georgian::LetterZen => 'ზ', Georgian::LetterTan => 'თ', Georgian::LetterIn => 'ი', Georgian::LetterKan => 'კ', Georgian::LetterLas => 'ლ', Georgian::LetterMan => 'მ', Georgian::LetterNar => 'ნ', Georgian::LetterOn => 'ო', Georgian::LetterPar => 'პ', Georgian::LetterZhar => 'ჟ', Georgian::LetterRae => 'რ', Georgian::LetterSan => 'ს', Georgian::LetterTar => 'ტ', Georgian::LetterUn => 'უ', Georgian::LetterPhar => 'ფ', Georgian::LetterKhar => 'ქ', Georgian::LetterGhan => 'ღ', Georgian::LetterQar => 'ყ', Georgian::LetterShin => 'შ', Georgian::LetterChin => 'ჩ', Georgian::LetterCan => 'ც', Georgian::LetterJil => 'ძ', Georgian::LetterCil => 'წ', Georgian::LetterChar => 'ჭ', Georgian::LetterXan => 'ხ', Georgian::LetterJhan => 'ჯ', Georgian::LetterHae => 'ჰ', Georgian::LetterHe => 'ჱ', Georgian::LetterHie => 'ჲ', Georgian::LetterWe => 'ჳ', Georgian::LetterHar => 'ჴ', Georgian::LetterHoe => 'ჵ', Georgian::LetterFi => 'ჶ', Georgian::LetterYn => 'ჷ', Georgian::LetterElifi => 'ჸ', Georgian::LetterTurnedGan => 'ჹ', Georgian::LetterAin => 'ჺ', Georgian::ParagraphSeparator => '჻', Georgian::ModifierLetterNar => 'ჼ', Georgian::LetterAen => 'ჽ', Georgian::LetterHardSign => 'ჾ', } } } impl std::convert::TryFrom<char> for Georgian { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { 'Ⴀ' => Ok(Georgian::CapitalLetterAn), 'Ⴁ' => Ok(Georgian::CapitalLetterBan), 'Ⴂ' => Ok(Georgian::CapitalLetterGan), 'Ⴃ' => Ok(Georgian::CapitalLetterDon), 'Ⴄ' => Ok(Georgian::CapitalLetterEn), 'Ⴅ' => Ok(Georgian::CapitalLetterVin), 'Ⴆ' => Ok(Georgian::CapitalLetterZen), 'Ⴇ' => Ok(Georgian::CapitalLetterTan), 'Ⴈ' => Ok(Georgian::CapitalLetterIn), 'Ⴉ' => Ok(Georgian::CapitalLetterKan), 'Ⴊ' => Ok(Georgian::CapitalLetterLas), 'Ⴋ' => Ok(Georgian::CapitalLetterMan), 'Ⴌ' => Ok(Georgian::CapitalLetterNar), 'Ⴍ' => Ok(Georgian::CapitalLetterOn), 'Ⴎ' => Ok(Georgian::CapitalLetterPar), 'Ⴏ' => Ok(Georgian::CapitalLetterZhar), 'Ⴐ' => Ok(Georgian::CapitalLetterRae), 'Ⴑ' => Ok(Georgian::CapitalLetterSan), 'Ⴒ' => Ok(Georgian::CapitalLetterTar), 'Ⴓ' => Ok(Georgian::CapitalLetterUn), 'Ⴔ' => Ok(Georgian::CapitalLetterPhar), 'Ⴕ' => Ok(Georgian::CapitalLetterKhar), 'Ⴖ' => Ok(Georgian::CapitalLetterGhan), 'Ⴗ' => Ok(Georgian::CapitalLetterQar), 'Ⴘ' => Ok(Georgian::CapitalLetterShin), 'Ⴙ' => Ok(Georgian::CapitalLetterChin), 'Ⴚ' => Ok(Georgian::CapitalLetterCan), 'Ⴛ' => Ok(Georgian::CapitalLetterJil), 'Ⴜ' => Ok(Georgian::CapitalLetterCil), 'Ⴝ' => Ok(Georgian::CapitalLetterChar), 'Ⴞ' => Ok(Georgian::CapitalLetterXan), 'Ⴟ' => Ok(Georgian::CapitalLetterJhan), 'Ⴠ' => Ok(Georgian::CapitalLetterHae), 'Ⴡ' => Ok(Georgian::CapitalLetterHe), 'Ⴢ' => Ok(Georgian::CapitalLetterHie), 'Ⴣ' => Ok(Georgian::CapitalLetterWe), 'Ⴤ' => Ok(Georgian::CapitalLetterHar), 'Ⴥ' => Ok(Georgian::CapitalLetterHoe), 'Ⴧ' => Ok(Georgian::CapitalLetterYn), 'Ⴭ' => Ok(Georgian::CapitalLetterAen), 'ა' => Ok(Georgian::LetterAn), 'ბ' => Ok(Georgian::LetterBan), 'გ' => Ok(Georgian::LetterGan), 'დ' => Ok(Georgian::LetterDon), 'ე' => Ok(Georgian::LetterEn), 'ვ' => Ok(Georgian::LetterVin), 'ზ' => Ok(Georgian::LetterZen), 'თ' => Ok(Georgian::LetterTan), 'ი' => Ok(Georgian::LetterIn), 'კ' => Ok(Georgian::LetterKan), 'ლ' => Ok(Georgian::LetterLas), 'მ' => Ok(Georgian::LetterMan), 'ნ' => Ok(Georgian::LetterNar), 'ო' => Ok(Georgian::LetterOn), 'პ' => Ok(Georgian::LetterPar), 'ჟ' => Ok(Georgian::LetterZhar), 'რ' => Ok(Georgian::LetterRae), 'ს' => Ok(Georgian::LetterSan), 'ტ' => Ok(Georgian::LetterTar), 'უ' => Ok(Georgian::LetterUn), 'ფ' => Ok(Georgian::LetterPhar), 'ქ' => Ok(Georgian::LetterKhar), 'ღ' => Ok(Georgian::LetterGhan), 'ყ' => Ok(Georgian::LetterQar), 'შ' => Ok(Georgian::LetterShin), 'ჩ' => Ok(Georgian::LetterChin), 'ც' => Ok(Georgian::LetterCan), 'ძ' => Ok(Georgian::LetterJil), 'წ' => Ok(Georgian::LetterCil), 'ჭ' => Ok(Georgian::LetterChar), 'ხ' => Ok(Georgian::LetterXan), 'ჯ' => Ok(Georgian::LetterJhan), 'ჰ' => Ok(Georgian::LetterHae), 'ჱ' => Ok(Georgian::LetterHe), 'ჲ' => Ok(Georgian::LetterHie), 'ჳ' => Ok(Georgian::LetterWe), 'ჴ' => Ok(Georgian::LetterHar), 'ჵ' => Ok(Georgian::LetterHoe), 'ჶ' => Ok(Georgian::LetterFi), 'ჷ' => Ok(Georgian::LetterYn), 'ჸ' => Ok(Georgian::LetterElifi), 'ჹ' => Ok(Georgian::LetterTurnedGan), 'ჺ' => Ok(Georgian::LetterAin), '჻' => Ok(Georgian::ParagraphSeparator), 'ჼ' => Ok(Georgian::ModifierLetterNar), 'ჽ' => Ok(Georgian::LetterAen), 'ჾ' => Ok(Georgian::LetterHardSign), _ => Err(()), } } } impl Into<u32> for Georgian { 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 Georgian { 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 Georgian { 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 Georgian { /// The character with the lowest index in this unicode block pub fn new() -> Self { Georgian::CapitalLetterAn } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("Georgian{:#?}", self); string_morph::to_sentence_case(&s) } }
pub struct IsDisabled; pub struct IsEnabled; pub struct IsInput; pub struct IsOutput; pub struct Unknown; pub struct Pin<STATE, DIRECTION> { pub state: STATE, pub direction: DIRECTION, pub pin_mask: u32 } pub trait PinWrite { fn set_high(&self); fn set_low(&self); } pub trait PinRead { fn get_state(&self) -> bool; } impl<STATE, DIRECTION> Pin<STATE, DIRECTION> { fn to_input(&self) -> Pin<IsEnabled, IsInput> { // Enable pin and set to input. Pin { state: IsEnabled, direction: IsInput, pin_mask: self.pin_mask } } fn to_output(&self) -> Pin<IsEnabled, IsOutput> { // Enable pin and set to output. Pin { state: IsEnabled, direction: IsOutput, pin_mask: self.pin_mask } } } impl PinWrite for Pin<IsEnabled, IsOutput> { fn set_high(&self) {} fn set_low(&self) {} } impl PinRead for Pin<IsEnabled, IsInput> { fn get_state(&self) -> bool { false } } fn new_pin(_pin_mask: u32) -> Pin<IsDisabled, Unknown> { Pin { state: IsDisabled, direction: Unknown, pin_mask: _pin_mask } }
// use std::fmt; use std::io; use thiserror::Error; // #[derive(Debug)] // pub struct StatsError { // pub msg: String, // } // // impl fmt::Display for StatsError { // fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // write!(f, "Display: {}", self) // } // } // // impl From<&str> for StatsError { // fn from(line: &str) -> Self { // StatsError { msg: line.to_string(), } // } // } // // impl From<io::Error> for StatsError { // fn from(err: io::Error) -> Self { // StatsError { // msg: err.to_string(), // } // } // } // // impl From<std::num::TryFromIntError> for StatsError { // fn from(_: std::num::TryFromIntError) -> Self { // StatsError { // msg: "Num conversion error".to_string(), // } // } // } #[derive(Debug, Error)] pub enum StatsError { #[error("Num conversion error")] NumConversion(#[from] std::num::TryFromIntError), #[error("Wrong directory")] DirectoryIO(#[from] io::Error) }
use super::contracts::ContractedFunctionExt; use super::options::ApplyContract; use super::options::ApplyContracts; use super::options::UseCallback; use super::options::UseCallbacks; use super::{ heap::UpValueHeap, stack::{Stack, StackFrame}, }; use crate::{ compiler::{ constants::{ConstantMap, ConstantTable}, program::Program, }, core::{instructions::DenseInstruction, opcode::OpCode}, rvals::{FutureResult, UpValue}, values::contracts::ContractedFunction, }; use crate::{ env::Env, gc::Gc, parser::{ ast::ExprKind, parser::{ParseError, Parser}, span::Span, }, primitives::ListOperations, rerrs::{ErrorKind, SteelErr}, rvals::{ByteCodeLambda, Result, SteelVal}, stop, values::structs::SteelStruct, }; use std::{ cell::RefCell, collections::HashMap, convert::TryFrom, iter::Iterator, rc::{Rc, Weak}, result, }; use super::evaluation_progress::EvaluationProgress; use log::error; const STACK_LIMIT: usize = 1000; pub struct VirtualMachineCore { global_env: Env, global_upvalue_heap: UpValueHeap, callback: EvaluationProgress, stack: StackFrame, function_stack: Vec<Gc<ByteCodeLambda>>, stack_index: Stack<usize>, } impl VirtualMachineCore { pub fn new() -> VirtualMachineCore { VirtualMachineCore { global_env: Env::root(), global_upvalue_heap: UpValueHeap::new(), callback: EvaluationProgress::new(), stack: StackFrame::with_capacity(256), function_stack: Vec::with_capacity(64), stack_index: Stack::with_capacity(64), } } pub fn insert_binding(&mut self, idx: usize, value: SteelVal) { self.global_env.add_root_value(idx, value); } pub fn extract_value(&self, idx: usize) -> Option<SteelVal> { self.global_env.extract(idx) } pub fn on_progress<FN: Fn(usize) -> bool + 'static>(&mut self, callback: FN) { &self.callback.with_callback(Box::new(callback)); } pub fn execute_program<U: UseCallbacks, A: ApplyContracts>( &mut self, program: Program, use_callbacks: U, apply_contracts: A, ) -> Result<Vec<SteelVal>> { let Program { instructions, constant_map, } = program; let output = instructions .into_iter() .map(|x| { self.execute( Rc::from(x.into_boxed_slice()), &constant_map, use_callbacks, apply_contracts, ) }) .collect(); output } pub fn _execute_program_by_ref(&mut self, program: &Program) -> Result<Vec<SteelVal>> { let Program { instructions, constant_map, } = program; let instructions: Vec<_> = instructions .clone() .into_iter() .map(|x| Rc::from(x.into_boxed_slice())) .collect(); instructions .into_iter() .map(|code| self.execute(code, &constant_map, UseCallback, ApplyContract)) .collect() } pub fn execute<U: UseCallbacks, A: ApplyContracts>( &mut self, instructions: Rc<[DenseInstruction]>, constant_map: &ConstantMap, use_callbacks: U, apply_contracts: A, ) -> Result<SteelVal> { let result = vm( instructions, &mut self.stack, &mut self.global_env, constant_map, &self.callback, &mut self.global_upvalue_heap, &mut self.function_stack, &mut self.stack_index, use_callbacks, apply_contracts, ); // Clean up self.stack.clear(); self.stack_index.clear(); self.function_stack.clear(); result } } #[derive(Debug, Clone)] pub struct InstructionPointer(usize, Rc<[DenseInstruction]>); impl InstructionPointer { pub fn _new_raw() -> Self { InstructionPointer(0, Rc::from(Vec::new().into_boxed_slice())) } #[inline(always)] pub fn new(ip: usize, instrs: Rc<[DenseInstruction]>) -> Self { InstructionPointer(ip, instrs) } pub fn instrs_ref(&self) -> &Rc<[DenseInstruction]> { &self.1 } #[inline(always)] pub fn instrs(self) -> Rc<[DenseInstruction]> { self.1 } } #[derive(Clone, Debug)] pub struct Continuation { pub(crate) stack: StackFrame, instructions: Rc<[DenseInstruction]>, instruction_stack: Stack<InstructionPointer>, stack_index: Stack<usize>, ip: usize, pop_count: usize, function_stack: Vec<Gc<ByteCodeLambda>>, upvalue_head: Option<Weak<RefCell<UpValue>>>, } #[inline(always)] fn validate_closure_for_call_cc(function: &SteelVal, span: Span) -> Result<()> { match function { SteelVal::Closure(c) => { if c.arity() != 1 { stop!(Generic => "function arity in call/cc must be 1"; span) } } SteelVal::ContinuationFunction(_) => {} _ => { stop!(Generic => "call/cc expects a function"; span) } } Ok(()) } pub(crate) struct VmCore<'a, CT: ConstantTable, U: UseCallbacks, A: ApplyContracts> { pub(crate) instructions: Rc<[DenseInstruction]>, pub(crate) stack: &'a mut StackFrame, pub(crate) global_env: &'a mut Env, pub(crate) instruction_stack: Stack<InstructionPointer>, pub(crate) stack_index: &'a mut Stack<usize>, pub(crate) callback: &'a EvaluationProgress, pub(crate) constants: &'a CT, pub(crate) ip: usize, pub(crate) pop_count: usize, pub(crate) upvalue_head: Option<Weak<RefCell<UpValue>>>, pub(crate) upvalue_heap: &'a mut UpValueHeap, pub(crate) function_stack: &'a mut Vec<Gc<ByteCodeLambda>>, pub(crate) use_callbacks: U, pub(crate) apply_contracts: A, } impl<'a, CT: ConstantTable, U: UseCallbacks, A: ApplyContracts> VmCore<'a, CT, U, A> { fn new( instructions: Rc<[DenseInstruction]>, stack: &'a mut StackFrame, global_env: &'a mut Env, constants: &'a CT, callback: &'a EvaluationProgress, upvalue_heap: &'a mut UpValueHeap, function_stack: &'a mut Vec<Gc<ByteCodeLambda>>, stack_index: &'a mut Stack<usize>, use_callbacks: U, apply_contracts: A, ) -> Result<VmCore<'a, CT, U, A>> { if instructions.is_empty() { stop!(Generic => "empty stack!") } Ok(VmCore { instructions: Rc::clone(&instructions), stack, global_env, instruction_stack: Stack::new(), stack_index, callback, constants, ip: 0, pop_count: 1, upvalue_head: None, upvalue_heap, function_stack, use_callbacks, apply_contracts, }) } fn capture_upvalue(&mut self, local_idx: usize) -> Weak<RefCell<UpValue>> { let mut prev_up_value: Option<Weak<RefCell<UpValue>>> = None; let mut upvalue = self.upvalue_head.clone(); while upvalue.is_some() && upvalue .as_ref() .unwrap() .upgrade() .expect("Upvalue freed too early") .borrow() .index() .map(|x| x > local_idx) .unwrap_or(false) { prev_up_value = upvalue.clone(); upvalue = upvalue .map(|x| { x.upgrade() .expect("Upvalue freed too early") .borrow() .next .clone() }) .flatten(); } if upvalue.is_some() && upvalue .as_ref() .unwrap() .upgrade() .expect("Upvalue freed too early") .borrow() .index() .map(|x| x == local_idx) .unwrap_or(false) { return upvalue.unwrap(); } let created_up_value: Weak<RefCell<UpValue>> = self.upvalue_heap.new_upvalue( local_idx, upvalue, self.stack .0 .iter() .chain(self.global_env.bindings_vec.iter()), self.function_stack.iter(), ); if prev_up_value.is_none() { self.upvalue_head = Some(created_up_value.clone()); } else { let prev_up_value = prev_up_value.unwrap().upgrade().unwrap(); prev_up_value .borrow_mut() .set_next(created_up_value.clone()); } created_up_value } fn close_upvalues(&mut self, last: usize) { while self.upvalue_head.is_some() && self .upvalue_head .as_ref() .unwrap() .upgrade() .unwrap() .borrow() .index() .map(|x| x >= last) .unwrap_or(false) { let upvalue = self.upvalue_head.as_ref().unwrap().upgrade().unwrap(); let value = upvalue.borrow().get_value(&self.stack); upvalue.borrow_mut().set_value(value); self.upvalue_head = upvalue.borrow_mut().next.clone(); } } #[inline(always)] fn new_continuation_from_state(&self) -> Continuation { Continuation { stack: self.stack.clone(), instructions: Rc::clone(&self.instructions), instruction_stack: self.instruction_stack.clone(), stack_index: self.stack_index.clone(), ip: self.ip, pop_count: self.pop_count, function_stack: self.function_stack.clone(), upvalue_head: self.upvalue_head.clone(), } } #[inline(always)] fn set_state_from_continuation(&mut self, continuation: Continuation) { *self.stack = continuation.stack; self.instructions = continuation.instructions; self.instruction_stack = continuation.instruction_stack; self.ip = continuation.ip; self.pop_count = continuation.pop_count; *self.stack_index = continuation.stack_index; *self.function_stack = continuation.function_stack; self.upvalue_head = continuation.upvalue_head; } #[inline(always)] fn construct_continuation_function(&self) -> SteelVal { let captured_continuation = self.new_continuation_from_state(); SteelVal::ContinuationFunction(Gc::new(captured_continuation)) } fn vm(mut self) -> Result<SteelVal> { let mut cur_inst; while self.ip < self.instructions.len() { cur_inst = self.instructions[self.ip]; match cur_inst.op_code { OpCode::PANIC => self.handle_panic(cur_inst.span)?, OpCode::EVAL => { let _expr_to_eval = self.stack.pop().unwrap(); panic!("eval not yet supported - internal compiler error"); } OpCode::PASS => { println!("Hitting a pass - this shouldn't happen"); self.ip += 1; } OpCode::VOID => { self.stack.push(SteelVal::Void); self.ip += 1; } OpCode::STRUCT => { // For now, only allow structs at the top level // In the future, allow structs to be also available in a nested scope self.handle_struct(cur_inst.payload_size as usize)?; self.stack.push(SteelVal::Void); self.ip += 1; // return Ok(SteelVal::Void); } OpCode::INNERSTRUCT => { self.handle_inner_struct(cur_inst.payload_size as usize)?; self.stack.push(SteelVal::Void); self.ip += 1; } OpCode::CALLCC => { /* - Construct the continuation - Get the function that has been passed in (off the stack) - Apply the function with the continuation - Handle continuation function call separately in the handle_func_call */ let function = self.stack.pop().unwrap(); validate_closure_for_call_cc(&function, cur_inst.span)?; let continuation = self.construct_continuation_function(); match function { SteelVal::Closure(closure) => { if self.stack_index.len() == STACK_LIMIT { println!("stack frame at exit: {:?}", self.stack); stop!(Generic => "stack overflowed!"; cur_inst.span); } if closure.arity() != 1 { stop!(Generic => "call/cc expects a function with arity 1"); } self.stack_index.push(self.stack.len()); // Put the continuation as the argument self.stack.push(continuation); // self.global_env = inner_env; self.instruction_stack.push(InstructionPointer::new( self.ip + 1, Rc::clone(&self.instructions), )); self.pop_count += 1; self.instructions = closure.body_exp(); self.function_stack.push(closure); self.ip = 0; } SteelVal::ContinuationFunction(cc) => { self.set_state_from_continuation(cc.unwrap()); self.ip += 1; self.stack.push(continuation); } _ => { stop!(Generic => "call/cc expects a function"); } } } OpCode::READ => self.handle_read(&cur_inst.span)?, OpCode::COLLECT => self.handle_collect(&cur_inst.span)?, OpCode::COLLECTTO => self.handle_collect_to(&cur_inst.span)?, OpCode::TRANSDUCE => self.handle_transduce(&cur_inst.span)?, OpCode::SET => self.handle_set(cur_inst.payload_size as usize)?, OpCode::PUSHCONST => { let val = self.constants.get(cur_inst.payload_size as usize); self.stack.push(val); self.ip += 1; } OpCode::PUSH => self.handle_push(cur_inst.payload_size as usize)?, OpCode::READLOCAL => self.handle_local(cur_inst.payload_size as usize)?, OpCode::SETLOCAL => self.handle_set_local(cur_inst.payload_size as usize), OpCode::READUPVALUE => self.handle_upvalue(cur_inst.payload_size as usize), OpCode::SETUPVALUE => self.handle_set_upvalue(cur_inst.payload_size as usize), OpCode::APPLY => self.handle_apply(cur_inst.span)?, OpCode::CLEAR => { self.ip += 1; } OpCode::LOADINT1 => { self.stack.push(SteelVal::INT_ONE); self.ip += 1; } OpCode::LOADINT2 => { self.stack.push(SteelVal::INT_TWO); self.ip += 1; } OpCode::CGLOCALCONST => { let read_local = self.instructions[self.ip + 1]; let push_const = self.instructions[self.ip + 2]; // Snag the function let func = self .global_env .repl_lookup_idx(cur_inst.payload_size as usize)?; // get the local let offset = self.stack_index.last().copied().unwrap_or(0); let local_value = self.stack[read_local.payload_size as usize + offset].clone(); // get the const let const_val = self.constants.get(push_const.payload_size as usize); self.handle_lazy_function_call(func, local_value, const_val, &cur_inst.span)?; } OpCode::CALLGLOBAL => { let next_inst = self.instructions[self.ip + 1]; self.handle_call_global( cur_inst.payload_size as usize, next_inst.payload_size as usize, &next_inst.span, )?; } OpCode::CALLGLOBALTAIL => { let next_inst = self.instructions[self.ip + 1]; self.handle_tail_call_global( cur_inst.payload_size as usize, next_inst.payload_size as usize, &next_inst.span, )?; } OpCode::FUNC => { let func = self.stack.pop().unwrap(); self.handle_function_call( func, cur_inst.payload_size as usize, &cur_inst.span, )?; } // Tail call basically says "hey this function is exiting" // In the closure case, transfer ownership of the stack to the called function OpCode::TAILCALL => { let func = self.stack.pop().unwrap(); self.handle_tail_call(func, cur_inst.payload_size as usize, &cur_inst.span)? } OpCode::IF => { // change to truthy... if self.stack.pop().unwrap().is_truthy() { self.ip = cur_inst.payload_size as usize; } else { self.ip = self.instructions[self.ip + 1].payload_size as usize // self.ip += 1; } } OpCode::TCOJMP => { let current_arity = self.instructions[self.ip + 1].payload_size as usize; self.ip = cur_inst.payload_size as usize; // HACK COME BACK TO THIS // if self.ip == 0 && self.heap.len() > self.heap.limit() { // TODO collect here // self.heap.collect_garbage(); // } let offset = self.stack_index.last().copied().unwrap_or(0); // We should have arity at this point, drop the stack up to this point // take the last arity off the stack, go back and replace those in order let back = self.stack.len() - current_arity; for i in 0..current_arity { self.stack.set_idx(offset + i, self.stack[back + i].clone()); } self.stack.truncate(offset + current_arity); } OpCode::JMP => { self.ip = cur_inst.payload_size as usize; } OpCode::POP => { if let Some(r) = self.handle_pop(cur_inst.payload_size, &cur_inst.span) { return r; } } OpCode::BIND => self.handle_bind(cur_inst.payload_size as usize), OpCode::SCLOSURE => self.handle_start_closure(cur_inst.payload_size as usize), OpCode::SDEF => self.handle_start_def(), OpCode::EDEF => { self.ip += 1; } _ => { // crate::core::instructions::pretty_print_dense_instructions(&self.instructions); panic!("Unhandled opcode: {:?} @ {}", cur_inst.op_code, self.ip); } } // Put callbacks behind generic if self.use_callbacks.use_callbacks() { match self.callback.call_and_increment() { Some(b) if !b => stop!(Generic => "Callback forced quit of function!"), _ => {} } } } error!( "Out of bounds instruction!: instruction pointer: {}, instruction length: {}", self.ip, self.instructions.len() ); panic!("Out of bounds instruction") } #[inline(always)] fn handle_pop(&mut self, payload: u32, span: &Span) -> Option<Result<SteelVal>> { self.pop_count -= 1; // unwrap just because we want to see if we have something here // rolling back the function stack self.function_stack.pop(); if self.pop_count == 0 { let ret_val = self.stack.try_pop().ok_or_else(|| { SteelErr::new(ErrorKind::Generic, "stack empty at pop".to_string()).with_span(*span) }); // Roll back if needed if let Some(rollback_index) = self.stack_index.pop() { self.stack.truncate(rollback_index); } Some(ret_val) } else { let ret_val = self.stack.pop().unwrap(); let rollback_index = self.stack_index.pop().unwrap(); // Snatch the value to close from the payload size let value_count_to_close = payload; // Move forward past the pop self.ip += 1; for i in 0..value_count_to_close { let instr = self.instructions[self.ip]; match (instr.op_code, instr.payload_size) { (OpCode::CLOSEUPVALUE, 1) => { self.close_upvalues(rollback_index + i as usize); } (OpCode::CLOSEUPVALUE, 0) => { // do nothing explicitly, just a normal pop } (op, _) => panic!( "Closing upvalues failed with instruction: {:?} @ {}", op, self.ip ), } self.ip += 1; } self.stack.truncate(rollback_index); self.stack.push(ret_val); if !self .instruction_stack .last() .unwrap() .instrs_ref() .is_empty() { let prev_state = self.instruction_stack.pop().unwrap(); self.ip = prev_state.0; self.instructions = prev_state.instrs(); } else { self.ip += 1; } None } } #[inline(always)] fn handle_transduce(&mut self, span: &Span) -> Result<()> { let list = self.stack.pop().unwrap(); let initial_value = self.stack.pop().unwrap(); let reducer = self.stack.pop().unwrap(); let transducer = self.stack.pop().unwrap(); if let SteelVal::IterV(transducer) = &transducer { let ret_val = self.transduce(&transducer.ops, list, initial_value, reducer, span); self.stack.push(ret_val?); } else { stop!(Generic => "Transduce must take an iterable"); } self.ip += 1; Ok(()) } #[inline(always)] fn handle_collect_to(&mut self, span: &Span) -> Result<()> { let output_type = self.stack.pop().unwrap(); let list = self.stack.pop().unwrap(); let transducer = self.stack.pop().unwrap(); if let SteelVal::IterV(transducer) = &transducer { let ret_val = self.run(&transducer.ops, list, Some(output_type), span); self.stack.push(ret_val?); } else { stop!(Generic => "Transducer execute takes a list"; *span); } self.ip += 1; Ok(()) } #[inline(always)] fn handle_collect(&mut self, span: &Span) -> Result<()> { let list = self.stack.pop().unwrap(); let transducer = self.stack.pop().unwrap(); if let SteelVal::IterV(transducer) = &transducer { let ret_val = self.run(&transducer.ops, list, None, span); self.stack.push(ret_val?); } else { stop!(Generic => "Transducer execute takes a list"; *span); } self.ip += 1; Ok(()) } #[inline(always)] fn handle_panic(&mut self, span: Span) -> Result<()> { let error_message = self.stack.pop().unwrap(); stop!(Generic => error_message.to_string(); span); } #[inline(always)] fn handle_struct(&mut self, offset: usize) -> Result<()> { let val = self.constants.get(offset); let mut iter = SteelVal::iter(val); // List of indices e.g. '(25 26 27 28) to bind struct functions to let indices = iter.next().unwrap(); // The name of the struct let name: String = if let SteelVal::StringV(s) = iter.next().unwrap() { s.to_string() } else { stop!( Generic => "ICE: Struct expected a string name") }; // The fields of the structs let fields: Vec<Gc<String>> = iter .map(|x| { if let SteelVal::StringV(s) = x { Ok(s) } else { stop!(Generic => "ICE: Struct encoded improperly with non string fields") } }) .collect::<Result<Vec<_>>>()?; // Get them as &str for now let other_fields: Vec<&str> = fields.iter().map(|x| x.as_str()).collect(); // Generate the functions, but they immediately override them with the names // Store them with the indices let funcs = SteelStruct::generate_from_name_fields(name.as_str(), &other_fields)?; for ((_, func), idx) in funcs.into_iter().zip(SteelVal::iter(indices)) { let idx = if let SteelVal::IntV(idx) = idx { idx as usize } else { stop!(Generic => "Index wrong in structs") }; self.global_env.repl_define_idx(idx, func); } Ok(()) } #[inline(always)] fn handle_inner_struct(&mut self, offset: usize) -> Result<()> { let val = self.constants.get(offset); let mut iter = SteelVal::iter(val); // List of indices e.g. '(25 26 27 28) to bind struct functions to let _ = iter.next().unwrap(); // The name of the struct let name: String = if let SteelVal::StringV(s) = iter.next().unwrap() { s.to_string() } else { stop!( Generic => "ICE: Struct expected a string name") }; // The fields of the structs let fields: Vec<Gc<String>> = iter .map(|x| { if let SteelVal::StringV(s) = x { Ok(s) } else { stop!(Generic => "ICE: Struct encoded improperly with non string fields") } }) .collect::<Result<Vec<_>>>()?; // Get them as &str for now let other_fields: Vec<&str> = fields.iter().map(|x| x.as_str()).collect(); // Generate the functions, but they immediately override them with the names // Store them with the indices let funcs = SteelStruct::generate_from_name_fields(name.as_str(), &other_fields)?; // We've mapped in the compiler _where_ locals are going to be (on the stack), just put them there for (_, func) in funcs { self.stack.push(func); } Ok(()) } #[inline(always)] fn handle_read(&mut self, span: &Span) -> Result<()> { // this needs to be a string let expression_to_parse = self.stack.pop().unwrap(); if let SteelVal::StringV(expr) = expression_to_parse { // dummy interning hashmap because the parser is bad // please don't judge I'm working on fixing it // TODO let mut intern = HashMap::new(); let parsed: result::Result<Vec<ExprKind>, ParseError> = Parser::new(expr.as_str(), &mut intern).collect(); match parsed { Ok(v) => { let converted: Result<Vec<SteelVal>> = v.into_iter().map(SteelVal::try_from).collect(); // let converted = Gc::new(SteelVal::try_from(v[0].clone())?); self.stack .push(ListOperations::built_in_list_func_flat_non_gc(converted?)?); self.ip += 1; } Err(e) => stop!(Generic => format!("{}", e); *span), } } else { stop!(TypeMismatch => "read expects a string"; *span) } Ok(()) } #[inline(always)] fn handle_set(&mut self, index: usize) -> Result<()> { let value_to_assign = self.stack.pop().unwrap(); if let SteelVal::Closure(_) = &value_to_assign { // println!("Closing upvalue here"); self.close_upvalues(*self.stack_index.last().unwrap_or(&0)); } let value = self.global_env.repl_set_idx(index, value_to_assign)?; self.stack.push(value); self.ip += 1; Ok(()) } #[inline(always)] fn handle_call_global(&mut self, index: usize, payload_size: usize, span: &Span) -> Result<()> { let func = self.global_env.repl_lookup_idx(index)?; self.ip += 1; self.handle_function_call(func, payload_size, span) } #[inline(always)] fn handle_tail_call_global( &mut self, index: usize, payload_size: usize, span: &Span, ) -> Result<()> { let func = self.global_env.repl_lookup_idx(index)?; self.ip += 1; self.handle_tail_call(func, payload_size, span) } #[inline(always)] fn handle_push(&mut self, index: usize) -> Result<()> { let value = self.global_env.repl_lookup_idx(index)?; self.stack.push(value); self.ip += 1; Ok(()) } #[inline(always)] fn handle_local(&mut self, index: usize) -> Result<()> { let offset = self.stack_index.last().copied().unwrap_or(0); let value = self.stack[index + offset].clone(); self.stack.push(value); self.ip += 1; Ok(()) } #[inline(always)] fn handle_upvalue(&mut self, index: usize) { let value = self .function_stack .last() .map(|x| { x.upvalues()[index] .upgrade() .expect("Upvalue dropped too early!") .borrow() .get_value(&self.stack) }) .unwrap(); self.stack.push(value); self.ip += 1; } #[inline(always)] fn handle_start_closure(&mut self, offset: usize) { self.ip += 1; let forward_jump = offset - 1; // Snag the number of upvalues here let ndefs = self.instructions[self.ip].payload_size; self.ip += 1; // TODO preallocate size let mut upvalues = Vec::with_capacity(ndefs as usize); // TODO clean this up a bit // hold the spot for where we need to jump aftwards let forward_index = self.ip + forward_jump; // Insert metadata for _ in 0..ndefs { let instr = self.instructions[self.ip]; match (instr.op_code, instr.payload_size) { (OpCode::FILLUPVALUE, n) => { upvalues.push( self.function_stack .last() .map(|x| x.upvalues()[n as usize].clone()) .unwrap(), ); } (OpCode::FILLLOCALUPVALUE, n) => { upvalues.push( self.capture_upvalue(self.stack_index.last().unwrap_or(&0) + n as usize), ); } (l, _) => { panic!( "Something went wrong in closure construction!, found: {:?} @ {}", l, self.ip, ); } } self.ip += 1; } // Construct the closure body using the offsets from the payload // used to be - 1, now - 2 let closure_body = self.instructions[self.ip..(self.ip + forward_jump - 1)].to_vec(); // snag the arity from the eclosure instruction let arity = self.instructions[forward_index - 1].payload_size; let constructed_lambda = ByteCodeLambda::new(closure_body, arity as usize, upvalues); self.stack .push(SteelVal::Closure(Gc::new(constructed_lambda))); self.ip = forward_index; } #[inline(always)] fn handle_bind(&mut self, payload_size: usize) { self.global_env .repl_define_idx(payload_size, self.stack.pop().unwrap()); self.ip += 1; } #[inline(always)] fn handle_set_local(&mut self, index: usize) { let value_to_set = self.stack.pop().unwrap(); let offset = self.stack_index.last().copied().unwrap_or(0); let old_value = self.stack[index + offset].clone(); // Modify the stack and change the value to the new one self.stack.set_idx(index + offset, value_to_set); self.stack.push(old_value); self.ip += 1; } #[inline(always)] fn handle_set_upvalue(&mut self, index: usize) { let new = self.stack.pop().unwrap(); let last_func = self.function_stack.last().unwrap(); let upvalue = last_func.upvalues()[index].upgrade().unwrap(); let value = upvalue.borrow_mut().mutate_value(&mut self.stack.0, new); self.stack.push(value); self.ip += 1; } #[inline(always)] fn handle_tail_call_closure( &mut self, closure: &Gc<ByteCodeLambda>, payload_size: usize, span: &Span, ) -> Result<()> { // Snag the current functions arity & remove the last function call let current_executing = self.function_stack.pop(); // TODO self.function_stack.push(Gc::clone(&closure)); if self.stack_index.len() == STACK_LIMIT { // println!("stacks at exit: {:?}", self.stacks); println!("stack frame at exit: {:?}", self.stack); stop!(Generic => "stack overflowed!"; *span); } if closure.arity() != payload_size { stop!(ArityMismatch => format!("function expected {} arguments, found {}", closure.arity(), payload_size); *span); } // println!("stack index before: {:?}", self.stack_index); // jump back to the beginning at this point let offset = *(self.stack_index.last().unwrap_or(&0)); if !current_executing .map(|x| x.upvalues().is_empty()) .unwrap_or(true) { self.close_upvalues(offset); } // Find the new arity from the payload let new_arity = payload_size; // We should have arity at this point, drop the stack up to this point // take the last arity off the stack, go back and replace those in order let back = self.stack.len() - new_arity; for i in 0..new_arity { self.stack.set_idx(offset + i, self.stack[back + i].clone()); } // TODO self.stack.truncate(offset + new_arity); // // TODO // self.heap // .gather_mark_and_sweep_2(&self.global_env, &inner_env); // self.heap.collect_garbage(); // Added this one as well // self.heap.add(Rc::clone(&self.global_env)); // self.global_env = inner_env; self.instructions = closure.body_exp(); self.ip = 0; Ok(()) } #[inline(always)] fn handle_tail_call( &mut self, stack_func: SteelVal, payload_size: usize, span: &Span, ) -> Result<()> { use SteelVal::*; match &stack_func { BoxedFunction(f) => self.call_boxed_func(f, payload_size, span)?, FuncV(f) => self.call_primitive_func(f, payload_size, span)?, FutureFunc(f) => self.call_future_func(f, payload_size)?, ContractedFunction(cf) => { self.call_contracted_function_tail_call(cf, payload_size, span)? } ContinuationFunction(cc) => self.call_continuation(cc)?, Closure(closure) => self.handle_tail_call_closure(closure, payload_size, span)?, _ => { stop!(BadSyntax => "TailCall - Application not a procedure or function type not supported"; *span); } } Ok(()) } #[inline(always)] fn call_boxed_func( &mut self, func: &Rc<dyn Fn(&[SteelVal]) -> Result<SteelVal>>, payload_size: usize, span: &Span, ) -> Result<()> { let result = func(self.stack.peek_range(self.stack.len() - payload_size..)) .map_err(|x| x.set_span(*span))?; self.stack.truncate(self.stack.len() - payload_size); self.stack.push(result); self.ip += 1; Ok(()) } #[inline(always)] fn call_primitive_func( &mut self, f: &fn(&[SteelVal]) -> Result<SteelVal>, payload_size: usize, span: &Span, ) -> Result<()> { let result = f(self.stack.peek_range(self.stack.len() - payload_size..)) .map_err(|x| x.set_span(*span))?; self.stack.truncate(self.stack.len() - payload_size); self.stack.push(result); self.ip += 1; Ok(()) } #[inline(always)] fn call_contracted_function( &mut self, cf: &ContractedFunction, payload_size: usize, span: &Span, ) -> Result<()> { if cf.arity() != payload_size { stop!(ArityMismatch => format!("function expected {} arguments, found {}", cf.arity(), payload_size); *span); } if self.apply_contracts.enforce_contracts() { let args = self.stack.split_off(self.stack.len() - payload_size); let result = cf.apply( args, self.constants, span, self.callback, &mut self.upvalue_heap, self.global_env, &mut self.stack, &mut self.function_stack, &mut self.stack_index, self.use_callbacks, self.apply_contracts, )?; self.stack.push(result); self.ip += 1; Ok(()) } else { self.handle_function_call_closure(&cf.function, payload_size, span) } } #[inline(always)] fn call_contracted_function_tail_call( &mut self, cf: &ContractedFunction, payload_size: usize, span: &Span, ) -> Result<()> { if cf.arity() != payload_size { stop!(ArityMismatch => format!("function expected {} arguments, found {}", cf.arity(), payload_size); *span); } if self.apply_contracts.enforce_contracts() { let args = self.stack.split_off(self.stack.len() - payload_size); let result = cf.apply( args, self.constants, span, self.callback, &mut self.upvalue_heap, self.global_env, &mut self.stack, &mut self.function_stack, &mut self.stack_index, self.use_callbacks, self.apply_contracts, )?; self.stack.push(result); self.ip += 1; Ok(()) } else { self.handle_tail_call_closure(&cf.function, payload_size, span) } } #[inline(always)] fn call_future_func( &mut self, f: &Rc<dyn Fn(&[SteelVal]) -> Result<FutureResult>>, payload_size: usize, ) -> Result<()> { let result = SteelVal::FutureV(Gc::new(f(self .stack .peek_range(self.stack.len() - payload_size..))?)); self.stack.truncate(self.stack.len() - payload_size); self.stack.push(result); self.ip += 1; Ok(()) } #[inline(always)] fn call_continuation(&mut self, continuation: &Continuation) -> Result<()> { let last = self .stack .pop() .ok_or_else(throw!(ArityMismatch => "continuation expected 1 argument, found none"))?; self.set_state_from_continuation(continuation.clone()); self.ip += 1; self.stack.push(last); Ok(()) } #[inline(always)] fn handle_lazy_closure( &mut self, closure: &Gc<ByteCodeLambda>, local: SteelVal, const_value: SteelVal, span: &Span, ) -> Result<()> { // push them onto the stack if we need to self.stack.push(local); self.stack.push(const_value); // Push on the function stack so we have access to it later self.function_stack.push(Gc::clone(closure)); if closure.arity() != 2 { stop!(ArityMismatch => format!("function expected {} arguments, found {}", closure.arity(), 2); *span); } // self.current_arity = Some(closure.arity()); if self.stack_index.len() == STACK_LIMIT { println!("stack frame at exit: {:?}", self.stack); stop!(Generic => "stack overflowed!"; *span); } self.stack_index.push(self.stack.len() - 2); // TODO use new heap // self.heap // .gather_mark_and_sweep_2(&self.global_env, &inner_env); // self.heap.collect_garbage(); self.instruction_stack.push(InstructionPointer::new( self.ip + 4, Rc::clone(&self.instructions), )); self.pop_count += 1; // Move args into the stack, push stack onto stacks // let stack = std::mem::replace(&mut self.stack, args.into()); // self.stacks.push(stack); self.instructions = closure.body_exp(); self.ip = 0; Ok(()) } #[inline(always)] fn handle_lazy_function_call( &mut self, stack_func: SteelVal, local: SteelVal, const_value: SteelVal, span: &Span, ) -> Result<()> { use SteelVal::*; match &stack_func { BoxedFunction(f) => { self.stack .push(f(&[local, const_value]).map_err(|x| x.set_span(*span))?); self.ip += 4; } FuncV(f) => { self.stack .push(f(&[local, const_value]).map_err(|x| x.set_span(*span))?); self.ip += 4; } FutureFunc(f) => { let result = SteelVal::FutureV(Gc::new( f(&[local, const_value]).map_err(|x| x.set_span(*span))?, )); self.stack.push(result); self.ip += 4; } ContractedFunction(cf) => { if cf.arity() != 2 { stop!(ArityMismatch => format!("function expected {} arguments, found {}", cf.arity(), 2); *span); } if self.apply_contracts.enforce_contracts() { let result = cf.apply( vec![local, const_value], self.constants, span, self.callback, &mut self.upvalue_heap, self.global_env, &mut self.stack, &mut self.function_stack, &mut self.stack_index, self.use_callbacks, self.apply_contracts, )?; self.stack.push(result); self.ip += 4; } else { self.handle_lazy_closure(&cf.function, local, const_value, span)?; } } ContinuationFunction(_cc) => { unimplemented!("calling continuation lazily not yet handled"); } Closure(closure) => self.handle_lazy_closure(closure, local, const_value, span)?, _ => { println!("{:?}", stack_func); stop!(BadSyntax => "Function application not a procedure or function type not supported"; *span); } } Ok(()) } #[inline(always)] fn handle_function_call_closure( &mut self, closure: &Gc<ByteCodeLambda>, payload_size: usize, span: &Span, ) -> Result<()> { // println!("Calling normal function"); // Push on the function stack so we have access to it later self.function_stack.push(Gc::clone(closure)); if closure.arity() != payload_size { stop!(ArityMismatch => format!("function expected {} arguments, found {}", closure.arity(), payload_size); *span); } // self.current_arity = Some(closure.arity()); if self.stack_index.len() == STACK_LIMIT { println!("stack frame at exit: {:?}", self.stack); stop!(Generic => "stack overflowed!"; *span); } self.stack_index.push(self.stack.len() - payload_size); // TODO use new heap // self.heap // .gather_mark_and_sweep_2(&self.global_env, &inner_env); // self.heap.collect_garbage(); self.instruction_stack.push(InstructionPointer::new( self.ip + 1, Rc::clone(&self.instructions), )); self.pop_count += 1; // Move args into the stack, push stack onto stacks // let stack = std::mem::replace(&mut self.stack, args.into()); // self.stacks.push(stack); self.instructions = closure.body_exp(); self.ip = 0; Ok(()) } #[inline(always)] fn handle_function_call( &mut self, stack_func: SteelVal, payload_size: usize, span: &Span, ) -> Result<()> { use SteelVal::*; match &stack_func { BoxedFunction(f) => self.call_boxed_func(f, payload_size, span)?, FuncV(f) => self.call_primitive_func(f, payload_size, span)?, FutureFunc(f) => self.call_future_func(f, payload_size)?, ContractedFunction(cf) => self.call_contracted_function(cf, payload_size, span)?, ContinuationFunction(cc) => self.call_continuation(cc)?, Closure(closure) => self.handle_function_call_closure(closure, payload_size, span)?, _ => { println!("{:?}", stack_func); stop!(BadSyntax => "Function application not a procedure or function type not supported"; *span); } } Ok(()) } #[inline(always)] fn handle_start_def(&mut self) { self.ip += 1; } #[inline(always)] fn handle_apply(&mut self, span: Span) -> Result<()> { let list = self.stack.pop().unwrap(); let func = self.stack.pop().unwrap(); let mut args = match ListOperations::collect_into_vec(&list) { Ok(args) => args, Err(_) => stop!(TypeMismatch => "apply expected a list"; span), }; match &func { SteelVal::FuncV(f) => { let result = f(&args).map_err(|x| x.set_span(span))?; self.stack.push(result); self.ip += 1; } SteelVal::BoxedFunction(f) => { let result = f(&args).map_err(|x| x.set_span(span))?; self.stack.push(result); self.ip += 1; } SteelVal::Closure(closure) => { if self.stack_index.len() == STACK_LIMIT { // println!("stacks at exit: {:?}", stacks); println!("stack frame at exit: {:?}", self.stack); stop!(Generic => "stack overflowed!"; span); } // self.global_env = inner_env; self.instruction_stack.push(InstructionPointer::new( self.ip + 1, Rc::clone(&self.instructions), )); self.pop_count += 1; self.function_stack.push(Gc::clone(closure)); let payload_size = args.len(); // Append the arguments to the function self.stack.append_vec(&mut args); self.stack_index.push(self.stack.len() - payload_size); self.instructions = closure.body_exp(); self.ip = 0; } _ => { stop!(BadSyntax => "Apply - Application not a procedure or function type not supported"; span); } } Ok(()) } } #[inline(always)] pub(crate) fn vm<CT: ConstantTable, U: UseCallbacks, A: ApplyContracts>( instructions: Rc<[DenseInstruction]>, stack: &mut StackFrame, global_env: &mut Env, constants: &CT, callback: &EvaluationProgress, upvalue_heap: &mut UpValueHeap, function_stack: &mut Vec<Gc<ByteCodeLambda>>, stack_index: &mut Stack<usize>, use_callbacks: U, apply_contracts: A, ) -> Result<SteelVal> { VmCore::new( instructions, stack, global_env, constants, callback, upvalue_heap, function_stack, stack_index, use_callbacks, apply_contracts, )? .vm() }
#![warn(clippy::pedantic)] #![warn(clippy::nursery)] #![forbid(unsafe_code)] // #![warn(clippy::restriction)] /** * MIT License * * termail - Copyright (c) 2021 Larry Hao * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ mod app; mod config; mod ui; mod utils; use app::App; use config::TermailConfig; use std::path::Path; const VERSION: &str = env!("CARGO_PKG_VERSION"); fn main() { let mut config = TermailConfig::default(); config.load().unwrap_or_default(); let mut args: Vec<String> = std::env::args().collect(); // match args.len() {} args.remove(0); let mut should_exit = false; for i in args { let i = i.as_str(); match i { "-v" | "--version" => { println!("Termusic version is: {}", VERSION); should_exit = true; } "-h" | "--help" => { println!( r"Termusic help: Usage: termusic [DIRECTORY] [OPTIONS] -v or --version print version and exit. -h or --help print this message and exit. directory: start termusic with directory. no arguments: start termusic with ~/.config/termusic/config.toml" ); should_exit = true; } _ => { let p = Path::new(i); let mut p_string = String::new(); if p.exists() { if p.has_root() { if let Ok(p1) = p.canonicalize() { p_string = p1.as_path().to_string_lossy().to_string(); } } else if let Ok(p_base) = std::env::current_dir() { let p2 = p_base.join(&p); if let Ok(p3) = p2.canonicalize() { p_string = p3.as_path().to_string_lossy().to_string(); } } config.mail_dir_from_cli = Some(p_string); } else { println!( r"Unknown arguments Termusic help: Usage: termusic [DIRECTORY] [OPTIONS] -v or --version print version and exit. -h or --help print this message and exit. directory: start termusic with directory. no arguments: start termusic with ~/.config/termusic/config.toml" ); should_exit = true; } } } } if should_exit { return; } // glib::set_application_name("termusic"); // glib::set_prgname(Some("termusic")); let mut app: App = App::new(config); app.run(); }
fn main() { let mut num = String::new(); std::io::stdin().read_line(&mut num).unwrap(); let num = num.trim().parse::<u32>().unwrap(); println!("{}:{}:{}", num / 3600, (num % 3600) / 60, num % 60); }
use core::{ops, slice}; use stable_deref_trait::StableDeref; use crate::{ sealed, traits::{IntoSlice, IntoSliceFrom, IntoSliceTo, Truncate}, AsMutSlice, AsSlice, OwningSlice, }; /// Owning slice of a `BUFFER` where `start == 0` #[derive(Clone, Copy)] pub struct OwningSliceTo<BUFFER, INDEX> where BUFFER: AsSlice, INDEX: sealed::Index, { pub(crate) buffer: BUFFER, pub(crate) end: INDEX, } /// Equivalent to `buffer[..end]` but by value #[allow(non_snake_case)] pub fn OwningSliceTo<B, I>(buffer: B, end: I) -> OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { let slen = buffer.as_slice().len(); let uend = end.into(); assert!(uend <= slen); OwningSliceTo { buffer, end } } impl<B, I> OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { /// Destroys the owning slice and returns the original buffer pub fn unslice(self) -> B { self.buffer } } impl<B, I> AsSlice for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { type Element = B::Element; fn as_slice(&self) -> &[B::Element] { unsafe { let p = self.buffer.as_slice().as_ptr(); let len = self.end.into(); slice::from_raw_parts(p, len) } } } impl<B, I> AsMutSlice for OwningSliceTo<B, I> where B: AsMutSlice, I: sealed::Index, { fn as_mut_slice(&mut self) -> &mut [B::Element] { unsafe { let p = self.buffer.as_mut_slice().as_mut_ptr(); let len = self.end.into(); slice::from_raw_parts_mut(p, len) } } } impl<B, I> ops::Deref for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { type Target = [B::Element]; fn deref(&self) -> &[B::Element] { self.as_slice() } } impl<B, I> ops::DerefMut for OwningSliceTo<B, I> where B: AsMutSlice, I: sealed::Index, { fn deref_mut(&mut self) -> &mut [B::Element] { self.as_mut_slice() } } unsafe impl<B, I> StableDeref for OwningSliceTo<B, I> where B: AsSlice + StableDeref, I: sealed::Index, { } impl<B, I> IntoSlice<I> for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { type Slice = OwningSlice<B, I>; fn into_slice(self, start: I, length: I) -> Self::Slice { let len = self.len(); let ustart = start.into(); let ulength = length.into(); assert!(ustart + ulength <= len); OwningSlice { buffer: self.buffer, start, length, } } } impl<B> IntoSlice<u16> for OwningSliceTo<B, u8> where B: AsSlice, { type Slice = OwningSlice<B, u8>; fn into_slice(self, start: u16, length: u16) -> Self::Slice { let len = self.len(); assert!(usize::from(start) + usize::from(length) <= len); // NOTE(cast) start, length < self.len() (self.end) <= u8::MAX OwningSlice { buffer: self.buffer, start: start as u8, length: length as u8, } } } impl<B> IntoSlice<u8> for OwningSliceTo<B, u16> where B: AsSlice, { type Slice = OwningSlice<B, u16>; fn into_slice(self, start: u8, length: u8) -> Self::Slice { let len = self.len(); assert!(usize::from(start) + usize::from(length) <= len); // NOTE(cast) start, length < self.len() (self.end) <= u8::MAX OwningSlice { buffer: self.buffer, start: u16::from(start), length: u16::from(length), } } } impl<B, I> IntoSliceFrom<I> for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { type SliceFrom = OwningSlice<B, I>; fn into_slice_from(self, start: I) -> Self::SliceFrom { let len = self.len(); assert!(start.into() <= len); OwningSlice { buffer: self.buffer, start, length: self.end - start, } } } impl<B> IntoSliceFrom<u16> for OwningSliceTo<B, u8> where B: AsSlice, { type SliceFrom = OwningSlice<B, u8>; fn into_slice_from(self, start: u16) -> Self::SliceFrom { let len = self.len(); assert!(usize::from(start) <= len); // NOTE(cast) start < self.len() (self.end) <= u8::MAX OwningSlice { buffer: self.buffer, start: start as u8, length: self.end - start as u8, } } } impl<B> IntoSliceFrom<u8> for OwningSliceTo<B, u16> where B: AsSlice, { type SliceFrom = OwningSlice<B, u16>; fn into_slice_from(self, start: u8) -> Self::SliceFrom { let len = self.len(); assert!(usize::from(start) <= len); OwningSlice { buffer: self.buffer, start: u16::from(start), length: self.end - u16::from(start), } } } impl<B, I> IntoSliceTo<I> for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { type SliceTo = OwningSliceTo<B, I>; fn into_slice_to(self, end: I) -> Self::SliceTo { let len = self.len(); assert!(end.into() <= len); OwningSliceTo { buffer: self.buffer, end, } } } impl<B> IntoSliceTo<u16> for OwningSliceTo<B, u8> where B: AsSlice, { type SliceTo = OwningSliceTo<B, u8>; fn into_slice_to(self, end: u16) -> Self::SliceTo { let len = self.len(); assert!(usize::from(end) <= len); // NOTE(cast) end <= self.len() (self.end) <= u8::MAX OwningSliceTo { buffer: self.buffer, end: end as u8, } } } impl<B> IntoSliceTo<u8> for OwningSliceTo<B, u16> where B: AsSlice, { type SliceTo = OwningSliceTo<B, u16>; fn into_slice_to(self, end: u8) -> Self::SliceTo { let len = self.len(); assert!(usize::from(end) <= len); OwningSliceTo { buffer: self.buffer, end: u16::from(end), } } } impl<B, I> Truncate<I> for OwningSliceTo<B, I> where B: AsSlice, I: sealed::Index, { fn truncate(&mut self, len: I) { if len < self.end { self.end = len; } } } impl<B> Truncate<u16> for OwningSliceTo<B, u8> where B: AsSlice, { fn truncate(&mut self, len: u16) { if len < u16::from(self.end) { self.end = len as u8; } } } impl<B> Truncate<u8> for OwningSliceTo<B, u16> where B: AsSlice, { fn truncate(&mut self, len: u8) { let len = u16::from(len); if len < self.end { self.end = len; } } }
fn main() { enum Continent { Europe, Asia, Africa, America, Oceania, } let continent = Continent::Asia; match continent { Continent::Europe => let a = 7;, Continent::Asia => let a = 7, Continent::Africa => fn aaa() {}, Continent::America => println!("am"), Continent::Oceania => println!("o"), } }
#[doc = "Register `WKUPCR` reader"] pub type R = crate::R<WKUPCR_SPEC>; #[doc = "Register `WKUPCR` writer"] pub type W = crate::W<WKUPCR_SPEC>; #[doc = "Field `WKUPC1` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC1_R = crate::BitReader; #[doc = "Field `WKUPC1` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC2` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC2_R = crate::BitReader; #[doc = "Field `WKUPC2` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC3` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC3_R = crate::BitReader; #[doc = "Field `WKUPC3` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC4` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC4_R = crate::BitReader; #[doc = "Field `WKUPC4` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC5` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC5_R = crate::BitReader; #[doc = "Field `WKUPC5` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC6` reader - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC6_R = crate::BitReader; #[doc = "Field `WKUPC6` writer - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] pub type WKUPC6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc1(&self) -> WKUPC1_R { WKUPC1_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc2(&self) -> WKUPC2_R { WKUPC2_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc3(&self) -> WKUPC3_R { WKUPC3_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc4(&self) -> WKUPC4_R { WKUPC4_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc5(&self) -> WKUPC5_R { WKUPC5_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] pub fn wkupc6(&self) -> WKUPC6_R { WKUPC6_R::new(((self.bits >> 5) & 1) != 0) } } impl W { #[doc = "Bit 0 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc1(&mut self) -> WKUPC1_W<WKUPCR_SPEC, 0> { WKUPC1_W::new(self) } #[doc = "Bit 1 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc2(&mut self) -> WKUPC2_W<WKUPCR_SPEC, 1> { WKUPC2_W::new(self) } #[doc = "Bit 2 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc3(&mut self) -> WKUPC3_W<WKUPCR_SPEC, 2> { WKUPC3_W::new(self) } #[doc = "Bit 3 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc4(&mut self) -> WKUPC4_W<WKUPCR_SPEC, 3> { WKUPC4_W::new(self) } #[doc = "Bit 4 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc5(&mut self) -> WKUPC5_W<WKUPCR_SPEC, 4> { WKUPC5_W::new(self) } #[doc = "Bit 5 - Clear Wakeup pin flag for WKUP. These bits are always read as 0."] #[inline(always)] #[must_use] pub fn wkupc6(&mut self) -> WKUPC6_W<WKUPCR_SPEC, 5> { WKUPC6_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 = "reset only by system reset, not reset by wakeup from Standby mode5 wait states are required when writing this register (when clearing a WKUPF bit in PWR_WKUPFR, the AHB write access will complete after the WKUPF has been cleared).\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`wkupcr::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 [`wkupcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct WKUPCR_SPEC; impl crate::RegisterSpec for WKUPCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`wkupcr::R`](R) reader structure"] impl crate::Readable for WKUPCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`wkupcr::W`](W) writer structure"] impl crate::Writable for WKUPCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets WKUPCR to value 0"] impl crate::Resettable for WKUPCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::errors; use json; use snailquote; // Get the esbuild arguments from the esbuild.config.json data structure pub fn args_from_config_json_value( json: json::JsonValue, ) -> Result<String, errors::ConfigParseError> { let mut args: Vec<String> = vec![]; let mut entries: Vec<String> = vec![]; let mut options: Vec<String> = vec![]; if !json.is_object() { return Err(errors::ConfigParseError::JsonError(json::Error::WrongType( String::from("The JSON main type must be an object."), ))); } for (key, value) in json.entries() { if key == "entry" { match entries_from_config(value) { Some(result) => entries = result, None => (), } continue; } match option_from_config(key, value) { Some(param) => options.push(param), None => (), } } args.append(&mut options); args.append(&mut entries); Ok(args.join(" ")) } // Get the esbuild arguments from the data structure of the package.json esbuild field pub fn args_from_package_json_value( json: json::JsonValue, ) -> Result<String, errors::ConfigParseError> { if !json.is_object() { return Err(errors::ConfigParseError::JsonError(json::Error::WrongType( String::from("The package.json seems malformed."), ))); } args_from_config_json_value(json["esbuild"].clone()) } // Get the entries in the config file pub fn entries_from_config(value: &json::JsonValue) -> Option<Vec<String>> { if value.is_string() { return Some(vec![quote_value(value.as_str().unwrap())]); } if value.is_array() { let entries: Vec<String> = value .members() .filter_map(|entry| match entry.as_str() { Some(value) => Some(quote_value(value)), None => None, }) .collect(); return match entries.is_empty() { false => Some(entries), true => None, }; } None } // Parse a single config value from esbuild.config.json pub fn option_from_config(key: &str, value: &json::JsonValue) -> Option<String> { if value.is_boolean() { return option_from_bool(key, value); } if value.is_string() { return option_from_string(key, value); } if value.is_array() { return option_from_array(key, value); } if value.is_object() { return option_from_object(key, value); } None } // Parse a bool config value pub fn option_from_bool(key: &str, value: &json::JsonValue) -> Option<String> { match value.as_bool() { Some(value) => { if value { Some(["--", key].concat()) } else { None } } None => None, } } // Parse a string config value pub fn option_from_string(key: &str, value: &json::JsonValue) -> Option<String> { match value.as_str() { Some(value) => Some(["--", key, "=", &quote_value(value)].concat()), None => None, } } // Parse an object config value pub fn option_from_object(key: &str, value: &json::JsonValue) -> Option<String> { let mut options: Vec<String> = vec![]; for (k, v) in value.entries() { match v.as_str() { Some(value) => options.push(["--", key, ":", k, "=", &quote_value(value)].concat()), None => (), } } if options.len() > 0 { Some(options.join(" ")) } else { None } } // Parse an array config value pub fn option_from_array(key: &str, value: &json::JsonValue) -> Option<String> { let mut options: Vec<String> = vec![]; for param_value in value.members() { match param_value.as_str() { Some(value) => options.push(["--", key, ":", &quote_value(value)].concat()), None => (), } } if options.len() > 0 { Some(options.join(" ")) } else { None } } // Quote a value if it contains a space pub fn quote_value(value: &str) -> String { let value = snailquote::escape(&value).to_string(); if value == "" { String::from("''") } else { value } } #[cfg(test)] mod tests { use super::*; #[test] fn test_args_from_json_value() { let value = json::parse( r#"{ "entry": "index.js", "a": true, "b": "abc", "c": ["def", "ghi"], "d": { "e": "jkl", "f": "mno" } }"#, ) .unwrap(); assert_eq!( args_from_config_json_value(value).unwrap(), "--a --b=abc --c:def --c:ghi --d:e=jkl --d:f=mno index.js" ); } #[test] fn test_entries_from_config() { let value = json::parse("\"path/to/some/file.js\"").unwrap(); let entries = entries_from_config(&value).unwrap(); assert_eq!(entries[0], "path/to/some/file.js"); let value = json::parse("[\"path/to/some/file.js\"]").unwrap(); let entries = entries_from_config(&value).unwrap(); assert_eq!(entries[0], "path/to/some/file.js"); let value = json::parse( r#"[ "path/to/some/file.js", "./path with spaces.js", true ]"#, ) .unwrap(); let entries = entries_from_config(&value).unwrap(); assert_eq!(entries[0], "path/to/some/file.js"); assert_eq!(entries[1], "'./path with spaces.js'"); assert!(entries.get(2).is_none()); let value = json::parse("[]").unwrap(); assert!(entries_from_config(&value).is_none()); let value = json::parse("true").unwrap(); assert!(entries_from_config(&value).is_none()); } #[test] fn test_option_from_config() { let value = json::parse("true").unwrap(); assert!(!option_from_config("name", &value).is_none()); let value = json::parse("false").unwrap(); assert!(option_from_config("name", &value).is_none()); let value = json::parse("\"a\"").unwrap(); assert!(!option_from_config("name", &value).is_none()); let value = json::parse("[\"a\"]").unwrap(); assert!(!option_from_config("name", &value).is_none()); let value = json::parse("{\"a\": \"abc\"}").unwrap(); assert!(!option_from_config("name", &value).is_none()); let value = json::parse("null").unwrap(); assert!(option_from_config("name", &value).is_none()); } #[test] fn test_option_from_bool() { let value = json::parse("true").unwrap(); assert_eq!(option_from_bool("name", &value).unwrap(), "--name"); let value = json::parse("false").unwrap(); assert!(option_from_bool("name", &value).is_none()); // Wrong types get ignored let value = json::parse("1").unwrap(); assert!(option_from_bool("name", &value).is_none()); } #[test] fn test_option_from_string() { let value = json::parse("\"a\"").unwrap(); assert_eq!(option_from_string("name", &value).unwrap(), "--name=a"); // Wrong types get ignored let value = json::parse("1").unwrap(); assert!(option_from_string("name", &value).is_none()); // Empty value let value = json::parse("\"\"").unwrap(); assert_eq!(option_from_string("name", &value).unwrap(), "--name=''"); } #[test] fn test_option_from_object() { let value = json::parse("{ \"a\": \"abc\", \"b\": \"def\" }").unwrap(); assert_eq!( option_from_object("name", &value).unwrap(), "--name:a=abc --name:b=def" ); let value = json::parse("{}").unwrap(); assert!(option_from_object("name", &value).is_none()); // Wrong types in the object get ignored let value = json::parse("{ \"a\": \"abc\", \"b\": 123 }").unwrap(); assert_eq!(option_from_object("name", &value).unwrap(), "--name:a=abc"); } #[test] fn test_option_from_array() { let value = json::parse("[\"a\", \"b\", \"c\"]").unwrap(); assert_eq!( option_from_array("name", &value).unwrap(), "--name:a --name:b --name:c" ); // Empty arrays let value = json::parse("[]").unwrap(); assert!(option_from_array("name", &value).is_none()); // Wrong types in the array get ignored let value = json::parse("[\"a\", 1, \"b\"]").unwrap(); assert_eq!( option_from_array("name", &value).unwrap(), "--name:a --name:b" ); } #[test] fn test_quote_value() { assert_eq!(quote_value("value"), "value"); // Having a space should return the value with quotes assert_eq!(quote_value("with space"), "'with space'"); // Having a quote should return the value with quotes assert_eq!(quote_value("with\"quote"), "'with\"quote'"); assert_eq!(quote_value("with'quote"), "\"with'quote\""); } }
use core::cmp::min; use core::marker::PhantomData; use core::mem; use core::pin::Pin; use core::sync::atomic::{compiler_fence, Ordering}; use core::task::{Context, Poll}; use embassy::interrupt::InterruptExt; use embassy::io::{AsyncBufRead, AsyncWrite, Result}; use embassy::util::{Unborrow, WakerRegistration}; use embassy_extras::peripheral::{PeripheralMutex, PeripheralState}; use embassy_extras::ring_buffer::RingBuffer; use embassy_extras::{low_power_wait_until, unborrow}; use crate::gpio::sealed::Pin as _; use crate::gpio::{OptionalPin as GpioOptionalPin, Pin as GpioPin}; use crate::pac; use crate::ppi::{AnyConfigurableChannel, ConfigurableChannel, Event, Ppi, Task}; use crate::timer::Instance as TimerInstance; use crate::uarte::{Config, Instance as UarteInstance}; // Re-export SVD variants to allow user to directly set values pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity}; #[derive(Copy, Clone, Debug, PartialEq)] enum RxState { Idle, Receiving, } #[derive(Copy, Clone, Debug, PartialEq)] enum TxState { Idle, Transmitting(usize), } struct State<'d, U: UarteInstance, T: TimerInstance> { phantom: PhantomData<&'d mut U>, timer: T, _ppi_ch1: Ppi<'d, AnyConfigurableChannel>, _ppi_ch2: Ppi<'d, AnyConfigurableChannel>, rx: RingBuffer<'d>, rx_state: RxState, rx_waker: WakerRegistration, tx: RingBuffer<'d>, tx_state: TxState, tx_waker: WakerRegistration, } /// Interface to a UARTE instance /// /// This is a very basic interface that comes with the following limitations: /// - The UARTE instances share the same address space with instances of UART. /// You need to make sure that conflicting instances /// are disabled before using `Uarte`. See product specification: /// - nrf52832: Section 15.2 /// - nrf52840: Section 6.1.2 pub struct BufferedUarte<'d, U: UarteInstance, T: TimerInstance> { inner: PeripheralMutex<State<'d, U, T>>, } impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> { /// unsafe: may not leak self or futures pub unsafe fn new( _uarte: impl Unborrow<Target = U> + 'd, timer: impl Unborrow<Target = T> + 'd, ppi_ch1: impl Unborrow<Target = impl ConfigurableChannel> + 'd, ppi_ch2: impl Unborrow<Target = impl ConfigurableChannel> + 'd, irq: impl Unborrow<Target = U::Interrupt> + 'd, rxd: impl Unborrow<Target = impl GpioPin> + 'd, txd: impl Unborrow<Target = impl GpioPin> + 'd, cts: impl Unborrow<Target = impl GpioOptionalPin> + 'd, rts: impl Unborrow<Target = impl GpioOptionalPin> + 'd, config: Config, rx_buffer: &'d mut [u8], tx_buffer: &'d mut [u8], ) -> Self { unborrow!(timer, ppi_ch1, ppi_ch2, irq, rxd, txd, cts, rts); let r = U::regs(); let rt = timer.regs(); rxd.conf().write(|w| w.input().connect().drive().h0h1()); r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) }); txd.set_high(); txd.conf().write(|w| w.dir().output().drive().h0h1()); r.psel.txd.write(|w| unsafe { w.bits(txd.psel_bits()) }); if let Some(pin) = rts.pin_mut() { pin.set_high(); pin.conf().write(|w| w.dir().output().drive().h0h1()); } r.psel.cts.write(|w| unsafe { w.bits(cts.psel_bits()) }); if let Some(pin) = cts.pin_mut() { pin.conf().write(|w| w.input().connect().drive().h0h1()); } r.psel.rts.write(|w| unsafe { w.bits(rts.psel_bits()) }); r.baudrate.write(|w| w.baudrate().variant(config.baudrate)); r.config.write(|w| w.parity().variant(config.parity)); // Configure let hardware_flow_control = match (rts.pin().is_some(), cts.pin().is_some()) { (false, false) => false, (true, true) => true, _ => panic!("RTS and CTS pins must be either both set or none set."), }; r.config.write(|w| { w.hwfc().bit(hardware_flow_control); w.parity().variant(config.parity); w }); r.baudrate.write(|w| w.baudrate().variant(config.baudrate)); // Enable interrupts r.intenset.write(|w| w.endrx().set().endtx().set()); // Disable the irq, let the Registration enable it when everything is set up. irq.disable(); irq.pend(); // Enable UARTE instance r.enable.write(|w| w.enable().enabled()); // BAUDRATE register values are `baudrate * 2^32 / 16000000` // source: https://devzone.nordicsemi.com/f/nordic-q-a/391/uart-baudrate-register-values // // We want to stop RX if line is idle for 2 bytes worth of time // That is 20 bits (each byte is 1 start bit + 8 data bits + 1 stop bit) // This gives us the amount of 16M ticks for 20 bits. let timeout = 0x8000_0000 / (config.baudrate as u32 / 40); rt.tasks_stop.write(|w| unsafe { w.bits(1) }); rt.bitmode.write(|w| w.bitmode()._32bit()); rt.prescaler.write(|w| unsafe { w.prescaler().bits(0) }); rt.cc[0].write(|w| unsafe { w.bits(timeout) }); rt.mode.write(|w| w.mode().timer()); rt.shorts.write(|w| { w.compare0_clear().set_bit(); w.compare0_stop().set_bit(); w }); let mut ppi_ch1 = Ppi::new(ppi_ch1.degrade_configurable()); ppi_ch1.set_event(Event::from_reg(&r.events_rxdrdy)); ppi_ch1.set_task(Task::from_reg(&rt.tasks_clear)); ppi_ch1.set_fork_task(Task::from_reg(&rt.tasks_start)); ppi_ch1.enable(); let mut ppi_ch2 = Ppi::new(ppi_ch2.degrade_configurable()); ppi_ch2.set_event(Event::from_reg(&rt.events_compare[0])); ppi_ch2.set_task(Task::from_reg(&r.tasks_stoprx)); ppi_ch2.enable(); BufferedUarte { inner: PeripheralMutex::new( State { phantom: PhantomData, timer, _ppi_ch1: ppi_ch1, _ppi_ch2: ppi_ch2, rx: RingBuffer::new(rx_buffer), rx_state: RxState::Idle, rx_waker: WakerRegistration::new(), tx: RingBuffer::new(tx_buffer), tx_state: TxState::Idle, tx_waker: WakerRegistration::new(), }, irq, ), } } pub fn set_baudrate(self: Pin<&mut Self>, baudrate: Baudrate) { let mut inner = self.inner(); inner.as_mut().register_interrupt(); inner.with(|state, _irq| { let r = U::regs(); let rt = state.timer.regs(); let timeout = 0x8000_0000 / (baudrate as u32 / 40); rt.cc[0].write(|w| unsafe { w.bits(timeout) }); rt.tasks_clear.write(|w| unsafe { w.bits(1) }); r.baudrate.write(|w| w.baudrate().variant(baudrate)); }); } fn inner(self: Pin<&mut Self>) -> Pin<&mut PeripheralMutex<State<'d, U, T>>> { unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) } } } impl<'d, U: UarteInstance, T: TimerInstance> AsyncBufRead for BufferedUarte<'d, U, T> { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> { let mut inner = self.inner(); inner.as_mut().register_interrupt(); inner.with(|state, _irq| { // Conservative compiler fence to prevent optimizations that do not // take in to account actions by DMA. The fence has been placed here, // before any DMA action has started compiler_fence(Ordering::SeqCst); trace!("poll_read"); // We have data ready in buffer? Return it. let buf = state.rx.pop_buf(); if !buf.is_empty() { trace!(" got {:?} {:?}", buf.as_ptr() as u32, buf.len()); let buf: &[u8] = buf; let buf: &[u8] = unsafe { mem::transmute(buf) }; return Poll::Ready(Ok(buf)); } trace!(" empty"); state.rx_waker.register(cx.waker()); Poll::<Result<&[u8]>>::Pending }) } fn consume(self: Pin<&mut Self>, amt: usize) { let mut inner = self.inner(); inner.as_mut().register_interrupt(); inner.with(|state, irq| { trace!("consume {:?}", amt); state.rx.pop(amt); irq.pend(); }) } } impl<'d, U: UarteInstance, T: TimerInstance> AsyncWrite for BufferedUarte<'d, U, T> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> { let mut inner = self.inner(); inner.as_mut().register_interrupt(); inner.with(|state, irq| { trace!("poll_write: {:?}", buf.len()); let tx_buf = state.tx.push_buf(); if tx_buf.is_empty() { trace!("poll_write: pending"); state.tx_waker.register(cx.waker()); return Poll::Pending; } let n = min(tx_buf.len(), buf.len()); tx_buf[..n].copy_from_slice(&buf[..n]); state.tx.push(n); trace!("poll_write: queued {:?}", n); // Conservative compiler fence to prevent optimizations that do not // take in to account actions by DMA. The fence has been placed here, // before any DMA action has started compiler_fence(Ordering::SeqCst); irq.pend(); Poll::Ready(Ok(n)) }) } } impl<'a, U: UarteInstance, T: TimerInstance> Drop for State<'a, U, T> { fn drop(&mut self) { let r = U::regs(); let rt = self.timer.regs(); // TODO this probably deadlocks. do like Uarte instead. rt.tasks_stop.write(|w| unsafe { w.bits(1) }); if let RxState::Receiving = self.rx_state { r.tasks_stoprx.write(|w| unsafe { w.bits(1) }); } if let TxState::Transmitting(_) = self.tx_state { r.tasks_stoptx.write(|w| unsafe { w.bits(1) }); } if let RxState::Receiving = self.rx_state { low_power_wait_until(|| r.events_endrx.read().bits() == 1); } if let TxState::Transmitting(_) = self.tx_state { low_power_wait_until(|| r.events_endtx.read().bits() == 1); } } } impl<'a, U: UarteInstance, T: TimerInstance> PeripheralState for State<'a, U, T> { type Interrupt = U::Interrupt; fn on_interrupt(&mut self) { trace!("irq: start"); let r = U::regs(); let rt = self.timer.regs(); loop { match self.rx_state { RxState::Idle => { trace!(" irq_rx: in state idle"); let buf = self.rx.push_buf(); if !buf.is_empty() { trace!(" irq_rx: starting {:?}", buf.len()); self.rx_state = RxState::Receiving; // Set up the DMA read r.rxd.ptr.write(|w| // The PTR field is a full 32 bits wide and accepts the full range // of values. unsafe { w.ptr().bits(buf.as_ptr() as u32) }); r.rxd.maxcnt.write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to `u8` is also fine. // // The MAXCNT field is at least 8 bits wide and accepts the full // range of values. unsafe { w.maxcnt().bits(buf.len() as _) }); trace!(" irq_rx: buf {:?} {:?}", buf.as_ptr() as u32, buf.len()); // Start UARTE Receive transaction r.tasks_startrx.write(|w| // `1` is a valid value to write to task registers. unsafe { w.bits(1) }); } break; } RxState::Receiving => { trace!(" irq_rx: in state receiving"); if r.events_endrx.read().bits() != 0 { rt.tasks_stop.write(|w| unsafe { w.bits(1) }); let n: usize = r.rxd.amount.read().amount().bits() as usize; trace!(" irq_rx: endrx {:?}", n); self.rx.push(n); r.events_endrx.reset(); self.rx_waker.wake(); self.rx_state = RxState::Idle; } else { break; } } } } loop { match self.tx_state { TxState::Idle => { trace!(" irq_tx: in state Idle"); let buf = self.tx.pop_buf(); if !buf.is_empty() { trace!(" irq_tx: starting {:?}", buf.len()); self.tx_state = TxState::Transmitting(buf.len()); // Set up the DMA write r.txd.ptr.write(|w| // The PTR field is a full 32 bits wide and accepts the full range // of values. unsafe { w.ptr().bits(buf.as_ptr() as u32) }); r.txd.maxcnt.write(|w| // We're giving it the length of the buffer, so no danger of // accessing invalid memory. We have verified that the length of the // buffer fits in an `u8`, so the cast to `u8` is also fine. // // The MAXCNT field is 8 bits wide and accepts the full range of // values. unsafe { w.maxcnt().bits(buf.len() as _) }); // Start UARTE Transmit transaction r.tasks_starttx.write(|w| // `1` is a valid value to write to task registers. unsafe { w.bits(1) }); } break; } TxState::Transmitting(n) => { trace!(" irq_tx: in state Transmitting"); if r.events_endtx.read().bits() != 0 { r.events_endtx.reset(); trace!(" irq_tx: endtx {:?}", n); self.tx.pop(n); self.tx_waker.wake(); self.tx_state = TxState::Idle; } else { break; } } } } trace!("irq: end"); } }
use core::str::from_utf8_unchecked; use alloc::borrow::Cow; use alloc::string::String; use alloc::vec::Vec; #[cfg(feature = "std")] use std::io::{self, Write}; use crate::functions::*; use crate::utf8_width; /// Encode text used in an unquoted attribute. Except for alphanumeric characters, escape all characters which are less than 128. /// /// The following characters are escaped to named entities: /// /// * `&` => `&amp;` /// * `<` => `&lt;` /// * `>` => `&gt;` /// * `"` => `&quot;` /// /// Other non-alphanumeric characters are escaped to `&#xHH;`. pub fn encode_unquoted_attribute<S: ?Sized + AsRef<str>>(text: &S) -> Cow<str> { let text = text.as_ref(); let text_bytes = text.as_bytes(); let text_length = text_bytes.len(); let mut p = 0; let mut e; loop { if p == text_length { return Cow::from(text); } e = text_bytes[p]; if utf8_width::is_width_1(e) && !is_alphanumeric(e) { break; } p += 1; } let mut v = Vec::with_capacity(text_length); v.extend_from_slice(&text_bytes[..p]); write_html_entity_to_vec(e, &mut v); encode_unquoted_attribute_to_vec( unsafe { from_utf8_unchecked(&text_bytes[(p + 1)..]) }, &mut v, ); Cow::from(unsafe { String::from_utf8_unchecked(v) }) } /// Write text used in an unquoted attribute to a mutable `String` reference and return the encoded string slice. Except for alphanumeric characters, escape all characters which are less than 128. /// /// The following characters are escaped to named entities: /// /// * `&` => `&amp;` /// * `<` => `&lt;` /// * `>` => `&gt;` /// * `"` => `&quot;` /// /// Other non-alphanumeric characters are escaped to `&#xHH;`. #[inline] pub fn encode_unquoted_attribute_to_string<S: AsRef<str>>(text: S, output: &mut String) -> &str { unsafe { from_utf8_unchecked(encode_unquoted_attribute_to_vec(text, output.as_mut_vec())) } } /// Write text used in an unquoted attribute to a mutable `Vec<u8>` reference and return the encoded data slice. Except for alphanumeric characters, escape all characters which are less than 128. /// /// The following characters are escaped to named entities: /// /// * `&` => `&amp;` /// * `<` => `&lt;` /// * `>` => `&gt;` /// * `"` => `&quot;` /// /// Other non-alphanumeric characters are escaped to `&#xHH;`. pub fn encode_unquoted_attribute_to_vec<S: AsRef<str>>(text: S, output: &mut Vec<u8>) -> &[u8] { let text = text.as_ref(); let text_bytes = text.as_bytes(); let text_length = text_bytes.len(); output.reserve(text_length); let current_length = output.len(); let mut p = 0; let mut e; let mut start = 0; while p < text_length { e = text_bytes[p]; if utf8_width::is_width_1(e) && !is_alphanumeric(e) { output.extend_from_slice(&text_bytes[start..p]); start = p + 1; write_html_entity_to_vec(e, output); } p += 1; } output.extend_from_slice(&text_bytes[start..p]); &output[current_length..] } #[cfg(feature = "std")] /// Write text used in an unquoted attribute to a writer. Except for alphanumeric characters, escape all characters which are less than 128. /// /// The following characters are escaped to named entities: /// /// * `&` => `&amp;` /// * `<` => `&lt;` /// * `>` => `&gt;` /// * `"` => `&quot;` /// /// Other non-alphanumeric characters are escaped to `&#xHH;`. pub fn encode_unquoted_attribute_to_writer<S: AsRef<str>, W: Write>( text: S, output: &mut W, ) -> Result<(), io::Error> { let text = text.as_ref(); let text_bytes = text.as_bytes(); let text_length = text_bytes.len(); let mut p = 0; let mut e; let mut start = 0; while p < text_length { e = text_bytes[p]; if utf8_width::is_width_1(e) && !is_alphanumeric(e) { output.write_all(&text_bytes[start..p])?; start = p + 1; write_html_entity_to_writer(e, output)?; } p += 1; } output.write_all(&text_bytes[start..p]) }
use std::collections::HashMap; use std::fmt::Formatter; use std::net::IpAddr; use std::str::FromStr; use serde::de::{Unexpected, Visitor}; use serde::ser::*; use serde::Serializer; use serde::{Deserializer, Serialize}; use sqlx::types::ipnetwork::IpNetwork; use sqlx::types::Uuid; use crate::common::SideType; use crate::get5::basic::*; impl Serialize for Spectators { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("name", &self.name)?; let player_map: HashMap<String, String> = self .players .iter() .map(|player| { let name: String = match &player.name { None => "".to_string(), Some(n) => n.clone(), }; (player.steamID.clone(), name) }) .collect(); map.serialize_entry("players", &player_map)?; map.end() } } impl Serialize for Team { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let mut map = serializer.serialize_map(None)?; map.serialize_entry("name", &self.name)?; if let Some(tag) = &self.tag { map.serialize_entry("tag", tag)?; } if let Some(flag) = &self.flag { map.serialize_entry("flag", &flag)?; } if let Some(logo) = &self.logo { map.serialize_entry("logo", logo)?; } if !self.players.is_empty() { let player_map: HashMap<String, String> = self .players .iter() .map(|player| { let name: String = match &player.name { None => "".to_string(), Some(n) => n.clone(), }; (player.steamID.clone(), name) }) .collect(); map.serialize_entry("players", &player_map)?; } if let Some(series_score) = self.series_score { map.serialize_entry("series_score", &series_score)?; } if let Some(match_text) = &self.match_text { map.serialize_entry("match_text", match_text)?; } map.end() } } impl Serialize for Match { fn serialize<G>(&self, serializer: G) -> Result<G::Ok, G::Error> where G: Serializer, { let mut map = serializer.serialize_map(None)?; if let Some(matchid) = &self.matchid { map.serialize_entry("matchid", matchid)?; } if let Some(num_maps) = self.num_maps { map.serialize_entry("num_maps", &num_maps)?; } if let Some(maplist) = &self.maplist { map.serialize_entry("maplist", maplist)?; } if let Some(skip_veto) = self.skip_veto { map.serialize_entry("skip_veto", &skip_veto)?; } if let Some(side_type) = &self.side_type { map.serialize_entry("side_type", side_type)?; } if let Some(players_per_team) = self.players_per_team { map.serialize_entry("players_per_team", &players_per_team)?; } if let Some(min_players_to_ready) = self.min_players_to_ready { map.serialize_entry("min_players_to_ready", &min_players_to_ready)?; } if let Some(favored_percentage_team1) = self.favored_percentage_team1 { map.serialize_entry("favored_percentage_team1", &favored_percentage_team1)?; } if let Some(favored_percentage_text) = &self.favored_percentage_text { map.serialize_entry("favored_percentage_text", favored_percentage_text)?; } if let Some(cvars) = &self.cvars { map.serialize_entry("cvars", cvars)?; } if let Some(spectators) = &self.spectators { map.serialize_entry("spectators", spectators)?; } map.serialize_entry("team1", &self.team1)?; map.serialize_entry("team2", &self.team2)?; if let Some(match_title) = &self.match_title { map.serialize_entry("match_title", match_title)?; } map.end() } } impl Serialize for SideType { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { match self { SideType::Standard => serializer.serialize_str("standard"), SideType::NeverKnife => serializer.serialize_str("never_knife"), SideType::AlwaysKnife => serializer.serialize_str("always_knife"), } } } pub(crate) fn serialize_ipnetwork<S>(addr: &IpNetwork, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { s.serialize_str(addr.ip().to_string().as_str()) } pub(crate) fn deserialize_ipnetwork<'de, D>(d: D) -> Result<IpNetwork, D::Error> where D: Deserializer<'de>, { d.deserialize_str(IpNetworkVisitor {}) } struct IpNetworkVisitor {} impl<'de> Visitor<'de> for IpNetworkVisitor { type Value = IpNetwork; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { formatter.write_str("IPv4 or IPv6 address") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { let addr = IpAddr::from_str(v).map_err(|err| { serde::de::Error::invalid_value(Unexpected::Other(err.to_string().as_str()), &self) })?; Ok(IpNetwork::from(addr)) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: serde::de::Error, { let addr = IpAddr::from_str(v.as_str()).map_err(|err| { serde::de::Error::invalid_value(Unexpected::Other(err.to_string().as_str()), &self) })?; Ok(IpNetwork::from(addr)) } } pub(crate) fn serialize_uuid<S>(uuid: &Uuid, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { s.serialize_str(uuid.to_string().as_str()) } pub(crate) fn deserialize_uuid<'de, D>(d: D) -> Result<Uuid, D::Error> where D: Deserializer<'de>, { d.deserialize_str(UuidVisitor {}) } struct UuidVisitor {} impl<'de> Visitor<'de> for UuidVisitor { type Value = Uuid; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { formatter.write_str("string of hexadecimal digits with optional hyphens") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Uuid::parse_str(v).map_err(|err| { serde::de::Error::invalid_value(Unexpected::Other(err.to_string().as_str()), &self) }) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: serde::de::Error, { Uuid::parse_str(v.as_str()).map_err(|err| { serde::de::Error::invalid_value(Unexpected::Other(err.to_string().as_str()), &self) }) } }
use super::program::ShaderData; use crate::engine::base::*; #[derive(Debug)] pub struct Frame { pub width: usize, pub height: usize, pub buffer: Vec<PixelBuffer>, } #[derive(Debug)] pub struct PixelBuffer { pub coord: Vec2, pub color: (u8, u8, u8, u8), pub z: u8, //z buffer pub varying: Option<Vec<ShaderData>>, } impl Frame { pub fn clear(&mut self) { for i in 0..self.buffer.len() { self.buffer[i].color = (0, 0, 0, 0); self.buffer[i].varying = None; self.buffer[i].z = 0; } } pub fn get(&self, coord: &(usize, usize)) -> Option<&PixelBuffer> { if coord.0 >= self.width || coord.1 >= self.height { None } else { self.buffer.get(coord.1 * self.width + coord.0) } } pub fn get_mut(&mut self, coord: &(usize, usize)) -> Option<&mut PixelBuffer> { if coord.0 >= self.width || coord.1 >= self.height { None } else { self.buffer.get_mut(coord.1 * self.width + coord.0) } } pub fn new(width: usize, height: usize) -> Self { let mut buffer = vec![]; for y in 0..height { for x in 0..width { buffer.push(PixelBuffer { coord: Vec2::new(x as f64, y as f64), color: (0, 0, 0, 0), z: 0, varying: None, }) } } Frame { buffer, width, height, } } }
#[cfg(test)] mod tests { use crate::intcode::{Intcode, Interrupt}; use crate::util; use crate::util::ListInput; #[test] fn test_advent_puzzle_1() { let mut output = None; let ListInput(rom) = util::load_input_file("day09.txt").unwrap(); let mut program = Intcode::new(&rom); loop { match program.run() { Interrupt::WaitingForInput => program.set_input(1), Interrupt::Output(o) => output = Some(o), _ => break, } } assert_eq!(output, Some(3765554916)); } #[test] fn test_advent_puzzle_2() { let mut output = None; let ListInput(rom) = util::load_input_file("day09.txt").unwrap(); let mut program = Intcode::new(&rom); loop { match program.run() { Interrupt::WaitingForInput => program.set_input(2), Interrupt::Output(o) => output = Some(o), _ => break, } } assert_eq!(output, Some(76642)); } #[test] fn smoke_simple_program_1() { let mut program = Intcode::new(&vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ]); loop { match program.run() { _ => break, } } assert_eq!( program.dump_memory(), String::from( "[109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" ) ); } #[test] fn smoke_simple_program_2() { let mut output = None; let mut program = Intcode::new(&vec![1102, 34915192, 34915192, 7, 4, 7, 99, 0]); loop { match program.run() { Interrupt::Output(o) => output = Some(o), Interrupt::WaitingForInput => program.set_input(5), _ => break, } } assert_eq!( output.map(|o| util::number_of_digits(o as f64) as i64), Some(16) ); } #[test] fn smoke_simple_program_3() { let mut output = None; let mut program = Intcode::new(&vec![104, 1125899906842624, 99]); loop { match program.run() { Interrupt::Output(o) => output = Some(o), Interrupt::WaitingForInput => program.set_input(5), _ => break, } } assert_eq!(output, Some(1125899906842624)); } }
use std::{path::PathBuf, str::FromStr}; use tts::{ backend::{ gcp::{ GcpAudioConfigRequest, GcpConfig, GcpTts, GcpVoiceRequest, GenderCode, LanguageCode, VoiceCode, }, openjtalk::{OpenJTalk, OpenJTalkConfig}, }, error::TtsError, TtsEngine, }; pub enum TtsType { OpenJTalkMeiNormal, GcpJpFemaleNormalA(String), GcpJpFemaleNormalB(String), GcpJpFemalePremiumA(String), GcpJpFemalePremiumB(String), GcpJpMaleNormalA(String), GcpJpMaleNormalB(String), GcpJpMalePremiumA(String), GcpJpMalePremiumB(String), } pub enum TtsKind { OpenJTalk(OpenJTalk), Gcp(GcpTts), } impl TtsKind { pub fn ensure_ojtalk(self) -> OpenJTalk { match self { TtsKind::OpenJTalk(e) => e, _ => unreachable!(), } } pub fn ensure_gcp(self) -> GcpTts { match self { TtsKind::Gcp(e) => e, _ => unreachable!(), } } } macro_rules! gcp_voice { ($token:expr => {lang: $lang:expr, name: $name:expr, gender: $gender:expr}) => {{ let voice = GcpVoiceRequest { language_code: $lang.to_string(), name: $name.to_string(), ssml_gender: $gender.to_string(), }; let audio_config = GcpAudioConfigRequest { audio_encoding: "MP3".to_string(), ..Default::default() }; let config = GcpConfig::new(&$token, voice, audio_config); let engine = GcpTts::from_config(config)?; Ok(TtsKind::Gcp(engine)) }}; } pub fn create_tts_engine(tts_type: TtsType) -> Result<TtsKind, TtsError> { match tts_type { TtsType::OpenJTalkMeiNormal => { let dictionary = PathBuf::from_str("/usr/local/dic/").unwrap(); let hts_path = PathBuf::from_str("/root/.config/resources/voice/mei_normal.htsvoice").unwrap(); let config = OpenJTalkConfig { dictionary, hts_path, all_pass: Some(0.54), postfilter_coef: 0.8, ..Default::default() }; let engine = OpenJTalk::from_config(config)?; Ok(TtsKind::OpenJTalk(engine)) } TtsType::GcpJpFemaleNormalA(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPStandardA, gender: GenderCode::Female }) } TtsType::GcpJpFemaleNormalB(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPStandardB, gender: GenderCode::Female }) } TtsType::GcpJpFemalePremiumA(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPWavenetA, gender: GenderCode::Female }) } TtsType::GcpJpFemalePremiumB(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPWavenetB, gender: GenderCode::Female }) } TtsType::GcpJpMaleNormalA(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPStandardC, gender: GenderCode::Male }) } TtsType::GcpJpMaleNormalB(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPStandardD, gender: GenderCode::Male }) } TtsType::GcpJpMalePremiumA(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPWavenetC, gender: GenderCode::Male }) } TtsType::GcpJpMalePremiumB(token) => { gcp_voice!(token => { lang: LanguageCode::JaJP, name: VoiceCode::JaJPWavenetD, gender: GenderCode::Male }) } } }
use amethyst::{ assets::Handle, core::transform::Transform, ecs::{Component, DenseVecStorage, Entity}, prelude::*, renderer::{SpriteRender, SpriteSheet}, }; use super::ai::AI; use crate::pong::{ARENA_HEIGHT, ARENA_WIDTH}; pub const PADDLE_HEIGHT: f32 = 16.0; pub const PADDLE_WIDTH: f32 = 4.0; pub const PADDLE_VELOCITY: f32 = 180.0; #[derive(PartialEq, Eq, Clone, Debug)] pub enum Side { Left, Right, } pub struct Paddle { pub side: Side, pub width: f32, pub height: f32, pub velocity: f32, } impl Paddle { fn new(side: Side) -> Paddle { Paddle { side, width: PADDLE_WIDTH, height: PADDLE_HEIGHT, velocity: 0.0, } } } impl Component for Paddle { type Storage = DenseVecStorage<Self>; } pub fn init_paddles(world: &mut World, sprite_sheet_handle: Handle<SpriteSheet>, num_players: u8) { let mut left_transform = Transform::default(); let mut right_transform = Transform::default(); let y = ARENA_HEIGHT / 2.0; left_transform.set_translation_xyz(PADDLE_WIDTH * 0.5, y, 0.0); right_transform.set_translation_xyz(ARENA_WIDTH - PADDLE_WIDTH * 0.5, y, 0.0); let sprite_render = SpriteRender::new(sprite_sheet_handle, 0); if num_players == 0 { get_ai_paddle(world, sprite_render.clone(), left_transform, Side::Left) } else { get_paddle(world, sprite_render.clone(), left_transform, Side::Left) }; if num_players <= 1 { get_ai_paddle(world, sprite_render, right_transform, Side::Right) } else { get_paddle(world, sprite_render, right_transform, Side::Right) }; } fn get_ai_paddle( world: &mut World, sprite_render: SpriteRender, transform: Transform, side: Side, ) -> Entity { world .create_entity() .with(sprite_render) .with(Paddle::new(side)) .with(transform) .with(AI) .build() } fn get_paddle( world: &mut World, sprite_render: SpriteRender, transform: Transform, side: Side, ) -> Entity { world .create_entity() .with(sprite_render) .with(Paddle::new(side)) .with(transform) .build() }
mod resend; mod service; use crate::{resend::Resender, service::OutboxServiceConfig}; use actix::Actor; use anyhow::Context; use async_trait::async_trait; use dotenv::dotenv; use drogue_cloud_registry_events::{ sender::{KafkaEventSender, KafkaSenderConfig}, stream::{EventHandler, KafkaEventStream, KafkaStreamConfig}, Event, }; use drogue_cloud_service_common::{ config::ConfigFromEnv, defaults, health::{HealthServer, HealthServerConfig}, }; use serde::Deserialize; use std::{sync::Arc, time::Duration}; #[derive(Clone, Debug, Deserialize)] struct Config { #[serde(default = "defaults::bind_addr")] pub bind_addr: String, #[serde(default = "resend_period")] #[serde(with = "humantime_serde")] /// Scan every x seconds for resending events. pub resend_period: Duration, #[serde(default = "before")] #[serde(with = "humantime_serde")] /// Send events older than x seconds. pub before: Duration, #[serde(default)] pub health: HealthServerConfig, pub kafka_sender: KafkaSenderConfig, pub kafka_source: KafkaStreamConfig, } const fn resend_period() -> Duration { Duration::from_secs(60) } const fn before() -> Duration { Duration::from_secs(5 * 60) } struct OutboxHandler(Arc<service::OutboxService>); #[async_trait] impl EventHandler for OutboxHandler { type Event = Event; type Error = anyhow::Error; async fn handle(&self, event: &Self::Event) -> Result<(), anyhow::Error> { log::debug!("Outbox event: {:?}", event); self.0.mark_seen(event.clone()).await?; Ok(()) } } #[actix::main] async fn main() -> anyhow::Result<()> { env_logger::init(); dotenv().ok(); let config = Config::from_env()?; let service = Arc::new(service::OutboxService::new( OutboxServiceConfig::from_env()? )?); // create event sender let sender = KafkaEventSender::new(config.kafka_sender) .context("Unable to create Kafka event sender")?; // start resender Resender { interval: config.resend_period, before: chrono::Duration::from_std(config.before)?, service: service.clone(), sender: Arc::new(sender), } .start(); // event source let source = KafkaEventStream::new(config.kafka_source)?; let source = source.run(OutboxHandler(service)); // health server let health = HealthServer::new(config.health, vec![]); // run futures::try_join!(health.run(), source)?; // exiting Ok(()) }
//! Translation state. use cranelift_codegen::ir; use cranelift_frontend; use cranelift_frontend::Variable; use llvm_sys::prelude::*; use llvm_sys::target::*; use std::collections::HashMap; /// Information about Ebbs that we'll create. pub struct EbbInfo { pub num_preds_left: usize, } impl Default for EbbInfo { fn default() -> Self { Self { num_preds_left: 0 } } } /// Data structures used throughout translation. pub struct Context<'a> { /// Builder for emitting instructions. pub builder: cranelift_frontend::FunctionBuilder<'a>, /// Map from LLVM Values to `Variable`s. pub value_map: HashMap<LLVMValueRef, Variable>, /// Map from LLVM BasicBlocks to bookkeeping data. pub ebb_info: HashMap<LLVMBasicBlockRef, EbbInfo>, /// Map from LLVM BasicBlocks to Cranelift `Ebb`s. Only contains entries for /// blocks that correspond to `Ebb` headers. pub ebb_map: HashMap<LLVMBasicBlockRef, ir::Ebb>, /// The LLVM DataLayout (formerly known as TargetData, the name still used /// in the C API). pub dl: LLVMTargetDataRef, } impl<'a> Context<'a> { pub fn new( func: &'a mut ir::Function, il_builder: &'a mut cranelift_frontend::FunctionBuilderContext, dl: LLVMTargetDataRef, ) -> Self { Self { builder: cranelift_frontend::FunctionBuilder::new(func, il_builder), value_map: HashMap::new(), ebb_info: HashMap::new(), ebb_map: HashMap::new(), dl, } } }
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0 mod pool; pub use pool::*;
extern "C" { pub fn esp_task_wdt_reset(); }
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; pub type Env = HashMap<String, String>; pub fn init_env() -> Env { let file = File::open(".env").expect("couldn't open file: .env"); let mut env = HashMap::new(); for line in BufReader::new(file).lines() { let key_values: Vec<String> = line.unwrap().split("=").map(str::to_string).collect(); env.insert(key_values[0].clone(), key_values[1].clone()); } env }
use super::{Asset, Processor}; use crate::bundler::Emitter; /// Simply skip any incoming assets #[derive(Default)] pub struct SkipProcessor {} impl Processor for SkipProcessor { fn process(&mut self, _asset: Asset, _emitter: &mut Emitter) -> anyhow::Result<()> { Ok(()) } }
use std::fs::File; use std::io::prelude::*; use std::io::{copy, BufReader, Error, ErrorKind, Result}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc; use std::thread; use std::time::Duration; enum Message { Connected(TcpStream), Quit, } fn main() -> Result<()> { let (host, port) = ("127.0.0.1", 7878); let tcplistener = TcpListener::bind((host, port))?; // 多个sender,单个receiver let (sender, receiver) = mpsc::channel(); let sender_stream = sender.clone(); // 开启新线程用来接受信息 let accept_loop = thread::spawn(move || { while let Ok((stream, addr)) = tcplistener.accept() { // 受到的话就send给handler sender_stream.send(Message::Connected(stream)); } }); // 主线程用来处理连接,如果发来的信息是退出,就break while let Ok(message) = receiver.recv() { match message { Message::Connected(stream) => { let sender_quit = sender.clone(); // 开启新线程处理信息 thread::spawn(move || { // 如果handler检测到退出请求,就send一个退出信号 if let Ok(HandleResult::Quit) = handle_connection(stream) { sender_quit.send(Message::Quit).unwrap(); } }); } Message::Quit => { break; } } } // accept_loop.join(); Ok(()) } enum HandleResult { Ok, Quit, } fn handle_connection(mut stream: TcpStream) -> Result<HandleResult> { let mut stream_str = String::new(); // read_line只能获取第一行 BufReader::new(&stream).read_line(&mut stream_str)?; let stream_subs: Vec<&str> = stream_str.split(" ").collect(); println!("#1: {}", stream_str); let stream_subs: Vec<&str> = stream_str.split(" ").collect(); let (method, path) = (stream_subs[0], stream_subs[1]); let (path, query) = match path.find("?") { Some(pos) => (&path[0..pos], &path[(pos + 1)..]), None => (path, ""), }; println!("#3{}, {}", path, query); if query == "sleep" { thread::sleep(Duration::from_secs(5)); } if path == "/" { stream.write(b"HTTP/1.1 200 OK\r\n\r\n<html><body>Welcome</body></html>")?; // write!(stream, "HTTP/1.1 200 OK\r\n\r\n<html><body>Welcome</body></html>")?; } else { let relative_path = match path.strip_prefix("/") { Some(p) => p, None => path, }; match File::open(relative_path) { Ok(mut f) => { write!(stream, "HTTP/1.1 200 OK\r\n\r\n")?; copy(&mut f, &mut stream)?; } Err(err) => { write!( stream, "HTTP/1.1 404 NOT FOUND\r\n\r\n<html><body>Not Found {}</body></html>", path )?; } } } stream.flush()?; if query == "quit" { return Ok(HandleResult::Quit); } Ok(HandleResult::Ok) }
//! A collection of objects for the Rainfusion website. pub mod rainfusion; use redis::{FromRedisValue, ToRedisArgs}; use std::collections::HashMap; /// A generic trait to allow objects to be used easily with /// database backends in glass. pub trait Sortable { type DataType: FromRedisValue + ToRedisArgs + Clone; fn object_to_index() -> &'static str; #[cfg(feature = "redis_backend")] #[cfg(feature = "json_backend")] fn map_to_object(map: HashMap<String, Self::DataType>) -> Self; #[cfg(feature = "redis_backend")] #[cfg(feature = "json_backend")] fn object_to_map(&self) -> Vec<(String, Self::DataType)>; }