text
stringlengths
8
4.13M
// Copyright 2020 Datafuse Labs. // // 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::cell::RefCell; use std::thread::sleep; use std::time::Duration; use clap::App; use clap::AppSettings; use clap::Arg; use clap::ArgMatches; use serde::Deserialize; use serde::Serialize; use crate::cmds::queries::query::QueryCommand; use crate::cmds::ClusterCommand; use crate::cmds::PackageCommand; use crate::cmds::Status; use crate::cmds::VersionCommand; use crate::cmds::Writer; use crate::error::CliError; const GITHUB_BASE_URL: &str = "https://github.com"; const GITHUB_DATABEND_URL: &str = "https://github.com/datafuselabs/databend/releases/download"; const GITHUB_DATABEND_TAG_URL: &str = "https://api.github.com/repos/datafuselabs/databend/tags"; const GITHUB_CLIENT_URL: &str = "https://github.com/ZhiHanZ/usql/releases/download"; #[derive(Clone, Debug)] pub struct Config { //(TODO(zhihanz) remove those field as they already mentioned in Clap global flag) pub group: String, pub databend_dir: String, pub mirror: CustomMirror, pub clap: RefCell<ArgMatches>, } pub trait MirrorAsset { fn is_ok(&self) -> bool { if let Ok(res) = ureq::get(self.get_base_url().as_str()).call() { return res.status() % 100 != 4 && res.status() % 100 != 5; } false } fn get_base_url(&self) -> String; fn get_databend_url(&self) -> String; fn get_databend_tag_url(&self) -> String; fn get_client_url(&self) -> String; fn to_mirror(&self) -> CustomMirror { CustomMirror { base_url: self.get_base_url(), databend_url: self.get_databend_url(), databend_tag_url: self.get_databend_tag_url(), client_url: self.get_client_url(), } } } #[derive(PartialEq, Debug, Clone)] pub struct GithubMirror {} impl MirrorAsset for GithubMirror { fn get_base_url(&self) -> String { GITHUB_BASE_URL.to_string() } fn get_databend_url(&self) -> String { GITHUB_DATABEND_URL.to_string() } fn get_databend_tag_url(&self) -> String { GITHUB_DATABEND_TAG_URL.to_string() } fn get_client_url(&self) -> String { GITHUB_CLIENT_URL.to_string() } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct CustomMirror { pub(crate) base_url: String, pub(crate) databend_url: String, pub(crate) databend_tag_url: String, pub(crate) client_url: String, } impl CustomMirror { fn new( base_url: String, databend_url: String, databend_tag_url: String, client_url: String, ) -> Self { CustomMirror { base_url, databend_url, databend_tag_url, client_url, } } } impl MirrorAsset for CustomMirror { fn get_base_url(&self) -> String { self.base_url.clone() } fn get_databend_url(&self) -> String { self.databend_url.clone() } fn get_databend_tag_url(&self) -> String { self.databend_tag_url.clone() } fn get_client_url(&self) -> String { self.client_url.clone() } } // choose one mirror which could be connected // if the mirror user provided works, it would choose it as default mirror, otherwise it would panic // if user have not provided a mirror, it would validate on mirror stored in status and warn // user if it could not be connected. // in default situation(no mirror stored in status), we provided a pool of possible mirrors to use. // it would select one working mirror as default mirror pub fn choose_mirror(conf: &Config) -> Result<CustomMirror, CliError> { // try user defined mirror source at first let conf = conf.clone(); let default = GithubMirror {}; if default.to_mirror() != conf.mirror { let custom: CustomMirror = conf.mirror.clone(); for _ in 0..5 { let custom: CustomMirror = conf.mirror.clone(); if custom.is_ok() { let mut status = Status::read(conf).expect("cannot configure status"); status.mirrors = Some(custom.to_mirror()); status.write()?; return Ok(custom); } else { sleep(Duration::from_secs(1)); } } return Err(CliError::Unknown(format!( "cannot connect to the provided mirror {:?}", custom ))); } let status = Status::read(conf).expect("cannot configure status"); let mut writer = Writer::create(); if let Some(mirror) = status.mirrors { let custom: CustomMirror = mirror.clone(); if !custom.is_ok() { writer.write_err(&*format!( "Mirror error: cannot connect to current mirror {:?}", mirror )) } else { return Ok(mirror); } } let default_mirrors: Vec<Box<dyn MirrorAsset>> = vec![Box::new(GithubMirror {})]; for _ in 0..5 { for i in &default_mirrors { if i.is_ok() { return Ok(i.to_mirror()); } else { sleep(Duration::from_secs(1)); } } } Err(CliError::Unknown( "cannot find possible mirror to connect".to_string(), )) } impl Config { pub(crate) fn build_cli() -> App<'static> { App::new("bendctl") .setting(AppSettings::ColoredHelp) .arg( Arg::new("group") .long("group") .about("Sets the group name for configuration") .default_value("test") .env("DATABEND_GROUP") .global(true) .takes_value(true), ) .arg( Arg::new("databend_dir") .long("databend_dir") .about("Sets the directory to store databend binaries(query and store)") .default_value("~/.databend") .env("databend_dir") .global(true) .takes_value(true) .value_hint(clap::ValueHint::DirPath), ) .arg( Arg::new("download_url") .long("download_url") .about("Sets the url to download databend binaries") .default_value("https://github.com/datafuselabs/databend/releases/download") .env("DOWNLOAD_URL") .global(true) .takes_value(true), ) .arg( Arg::new("tag_url") .long("tag_url") .about("Sets the url to for databend tags") .default_value("https://api.github.com/repos/datafuselabs/databend/tags") .env("DOWNLOAD_URL") .global(true) .takes_value(true), ) .arg( Arg::new("client_url") .long("client_url") .about("Sets the url to fetch databend query client") .env("DOWNLOAD_CLIENT_URL") .default_value("https://github.com/ZhiHanZ/usql/releases/download") .global(true) .takes_value(true), ) .arg( Arg::new("validation_url") .long("validation_url") .about("Sets the url to validate on custom download network connection") .env("DOWNLOAD_VALIDATION_URL") .default_value("https://github.com") .global(true) .takes_value(true), ) .subcommand( App::new("completion") .setting(AppSettings::ColoredHelp) .setting(AppSettings::DisableVersionFlag) .about("Generate auto completion scripts for bash or zsh terminal") .arg( Arg::new("completion") .takes_value(true) .possible_values(&["bash", "zsh"]), ), ) .subcommand(PackageCommand::generate()) .subcommand(VersionCommand::generate()) .subcommand(ClusterCommand::generate()) .subcommand(QueryCommand::generate()) } pub fn create() -> Self { let clap = RefCell::new(Config::build_cli().get_matches()); let config = Config { group: clap .clone() .into_inner() .value_of("group") .unwrap() .parse() .unwrap(), databend_dir: clap .clone() .into_inner() .value_of("databend_dir") .unwrap() .parse() .unwrap(), mirror: CustomMirror::new( clap.clone() .into_inner() .value_of("validation_url") .unwrap() .parse() .unwrap(), clap.clone() .into_inner() .value_of("download_url") .unwrap() .parse() .unwrap(), clap.clone() .into_inner() .value_of("tag_url") .unwrap() .parse() .unwrap(), clap.clone() .into_inner() .value_of("client_url") .unwrap() .parse() .unwrap(), ), clap, }; Config::build(config) } fn build(mut conf: Config) -> Self { let home_dir = dirs::home_dir().unwrap(); let databend_dir = home_dir.join(".databend"); if conf.databend_dir == "~/.databend" { conf.databend_dir = format!("{}/{}", databend_dir.to_str().unwrap(), conf.group); } else { conf.databend_dir = format!("{}/{}", conf.databend_dir, conf.group); } let res = choose_mirror(&conf); if let Ok(mirror) = res { conf.mirror = mirror.clone(); let mut status = Status::read(conf.clone()).expect("cannot read status"); status.mirrors = Some(mirror); status.write().expect("cannot write status"); } else { panic!("{}", format!("{:?}", res.unwrap_err())) } conf } }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" The CCI (commodity channel index) is calculated as the difference between the typical price of a commodity and its simple moving average, divided by the mean absolute deviation of the typical price. The index is scaled by an inverse factor of 0.015 to provide more readable numbers "#; const PINE_FN_ARGUMENTS: &'static str = " **source (series(float))** Series of values to process. **length (int)** Number of bars (length). "; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "cci", signatures: vec![], description: DESCRIPTION, example: "", returns: "Commodity channel index of x for y bars back.", arguments: PINE_FN_ARGUMENTS, remarks: "", links: "", }; vec![fn_doc] }
mod disassembler; mod cpu; use std::env; use cpu::Cpu; use disassembler::disassemble; use raylib::prelude::*; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { panic!("rom path not provided"); } let instructions = disassemble(&args[1]); let mut cpu = Cpu { memory: [0; 4096], registers: [0; 16], stack: [0; 16], i: 0, vf: 0, delay_timer: 0, sound_timer: 0, pc: 0, sp: 0 }; cpu.load_program(&instructions); let (mut rl, thread) = raylib::init() .size(640, 320) .title("chipmyst") .build(); while !rl.window_should_close() { let mut d = rl.begin_drawing(&thread); d.clear_background(Color::WHITE); let x: i32 = 10; let mut y: i32 = 10; for instr in &instructions { d.draw_text(&instr.asm, x, y, 8, Color::BLACK); y += 10; } } }
extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect::HdbResult; use log::*; use std::time::Instant; #[test] fn test_012_connect_other_user() -> HdbResult<()> { let mut log_handle = test_utils::init_logger(); let start = Instant::now(); connect_other_user(&mut log_handle)?; info!("Elapsed time: {:?}", Instant::now().duration_since(start)); Ok(()) } fn connect_other_user(_log_handle: &mut LoggerHandle) -> HdbResult<()> { // _log_handle.parse_and_push_temp_spec("test = debug, info"); let other_user = "THEOTHERONE".to_string(); let sys_conn = test_utils::get_um_connection().unwrap(); sys_conn.multiple_statements_ignore_err(vec![ &format!("drop user {other_user}",), &format!( "create user {other_user} password \"Theother1234\" NO FORCE_FIRST_PASSWORD_CHANGE", ), ]); let before: String = sys_conn .query("SELECT CURRENT_USER FROM DUMMY")? .try_into()?; assert_eq!(before, "SYSTEM".to_string()); let response = sys_conn.statement(format!("CONNECT {other_user} PASSWORD Theother1234",))?; debug!("Response: {response:?}",); let after: String = sys_conn .query("SELECT CURRENT_USER FROM DUMMY")? .try_into()?; assert_eq!(after, "THEOTHERONE".to_string()); // _log_handle.pop_temp_spec(); Ok(()) }
pub mod names; pub mod sectors; pub mod business; pub mod world; pub mod stocks;
use super::super::class::class::Class; use super::super::gc::gc::GcType; use super::jit::*; use super::{ frame::{Array, ObjectBody, VariableType}, vm::RuntimeEnvironment, }; use llvm; use llvm::{core::*, prelude::*}; use rustc_hash::FxHashMap; use std::ffi::CString; #[rustfmt::skip] pub unsafe fn native_functions( module: LLVMModuleRef, context: LLVMContextRef, ) -> FxHashMap<String, LLVMValueRef> { let mut map = FxHashMap::default(); macro_rules! parse_ty { (void ) => { VariableType::Void. to_llvmty(context) }; (int ) => { VariableType::Int. to_llvmty(context) }; (dbl) => { VariableType::Double. to_llvmty(context) }; (ptr) => { VariableType::Pointer.to_llvmty(context) }; } macro_rules! define_native_function { ($ret_ty:ident, [ $($param_ty:ident),* ], $name:expr) => { let mut params_ty = vec![$(parse_ty!($param_ty)),*]; let func_ty = LLVMFunctionType( parse_ty!($ret_ty), params_ty.as_mut_ptr(), params_ty.len() as u32, 0); let func = LLVMAddFunction( module, CString::new($name).unwrap().as_ptr(), func_ty); map.insert($name.to_string(), func); } } define_native_function!(void, [ptr, ptr, int], "java/io/PrintStream.println:(I)V"); define_native_function!(void, [ptr, ptr, ptr], "java/io/PrintStream.println:(Ljava/lang/String;)V"); define_native_function!(void, [ptr, ptr, ptr], "java/io/PrintStream.print:(Ljava/lang/String;)V"); define_native_function!(ptr, [ptr, ptr, int ],"java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;"); define_native_function!(ptr, [ptr, ptr, ptr], "java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;"); define_native_function!(ptr, [ptr, ptr], "java/lang/StringBuilder.toString:()Ljava/lang/String;"); define_native_function!(dbl, [ptr], "java/lang/Math.random:()D"); define_native_function!(dbl, [ptr, dbl], "java/lang/Math.sqrt:(D)D"); define_native_function!(dbl, [ptr, dbl], "java/lang/Math.sin:(D)D"); define_native_function!(dbl, [ptr, dbl], "java/lang/Math.cos:(D)D"); define_native_function!(dbl, [ptr, dbl], "java/lang/Math.tan:(D)D"); define_native_function!(dbl, [ptr, dbl, dbl], "java/lang/Math.pow:(DD)D"); define_native_function!(dbl, [ptr, dbl], "java/lang/Math.abs:(D)D"); define_native_function!(ptr, [ptr, ptr], "ferrugo_internal_new"); define_native_function!(int, [ptr, ptr, int], "ferrugo_internal_baload"); define_native_function!(ptr, [ptr, ptr, int], "ferrugo_internal_aaload"); define_native_function!(void, [ptr, ptr, int, int], "ferrugo_internal_bastore"); map } pub unsafe fn add_native_functions( native_functions: &FxHashMap<String, LLVMValueRef>, ee: llvm::execution_engine::LLVMExecutionEngineRef, ) { for (name, func) in &[ ( "java/io/PrintStream.println:(I)V", java_io_printstream_println_i_v as *mut libc::c_void, ), ( "java/io/PrintStream.println:(Ljava/lang/String;)V", java_io_printstream_println_string_v as *mut libc::c_void, ), ( "java/io/PrintStream.print:(Ljava/lang/String;)V", java_io_printstream_print_string_v as *mut libc::c_void, ), ( "java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;", java_lang_stringbuilder_append_string_stringbuilder as *mut libc::c_void, ), ( "java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;", java_lang_stringbuilder_append_i_stringbuilder as *mut libc::c_void, ), ( "java/lang/StringBuilder.toString:()Ljava/lang/String;", java_lang_stringbuilder_tostring_string as *mut libc::c_void, ), ( "java/lang/Math.random:()D", java_lang_math_random_d as *mut libc::c_void, ), ( "java/lang/Math.sin:(D)D", java_lang_math_sin_d_d as *mut libc::c_void, ), ( "java/lang/Math.pow:(DD)D", java_lang_math_pow_dd_d as *mut libc::c_void, ), ( "ferrugo_internal_new", ferrugo_internal_new as *mut libc::c_void, ), ( "ferrugo_internal_baload", ferrugo_internal_baload as *mut libc::c_void, ), ( "ferrugo_internal_aaload", ferrugo_internal_aaload as *mut libc::c_void, ), ( "ferrugo_internal_bastore", ferrugo_internal_bastore as *mut libc::c_void, ), ] { llvm::execution_engine::LLVMAddGlobalMapping( ee, *native_functions.get(*name).unwrap(), *func, ); } } // Builtin Native Functions #[no_mangle] pub extern "C" fn java_io_printstream_println_i_v( _renv: *mut RuntimeEnvironment, _obj: *mut ObjectBody, i: i32, ) { println!("{}", i); } #[no_mangle] pub extern "C" fn java_io_printstream_println_string_v( _renv: *mut RuntimeEnvironment, _obj: *mut ObjectBody, s: *mut ObjectBody, ) { let string = unsafe { &mut *s }; println!("{}", string.get_string_mut()); } #[no_mangle] pub extern "C" fn java_io_printstream_print_string_v( _renv: *mut RuntimeEnvironment, _obj: *mut ObjectBody, s: *mut ObjectBody, ) { print!("{}", unsafe { &mut *s }.get_string_mut()); } #[no_mangle] pub extern "C" fn java_lang_stringbuilder_append_i_stringbuilder( renv: *mut RuntimeEnvironment, obj: *mut ObjectBody, i: i32, ) -> *mut ObjectBody { unsafe { let renv = &mut *renv; let string_builder = &mut *obj; let string_obj = &mut string_builder.variables[0]; // TODO: Currently, JIT doesn't support 'invokespecial'. Therefore StringBuilder newly // created in JIT-compiled code is not initialized. That's why the code below is needed. if *string_obj == 0 { *string_obj = (&mut *renv.objectheap).create_string_object("".to_string(), renv.classheap) } let mut string = (&mut *(*string_obj as GcType<ObjectBody>)) .get_string_mut() .clone(); string.push_str(format!("{}", i).as_str()); *string_obj = (&mut *renv.objectheap).create_string_object(string.to_string(), renv.classheap); } obj } #[no_mangle] pub extern "C" fn java_lang_stringbuilder_append_string_stringbuilder( renv: *mut RuntimeEnvironment, obj: *mut ObjectBody, s: *mut ObjectBody, ) -> *mut ObjectBody { unsafe { let renv = &mut *renv; let string_builder = &mut *obj; let string_obj = &mut string_builder.variables[0]; // TODO: Currently, JIT doesn't support 'invokespecial'. Therefore StringBuilder newly // created in JIT-compiled code is not initialized. That's why the code below is needed. if *string_obj == 0 { *string_obj = (&mut *renv.objectheap).create_string_object("".to_string(), renv.classheap) } let mut str1 = (&mut *(*string_obj as GcType<ObjectBody>)) .get_string_mut() .clone(); let str2 = (&mut *s).get_string_mut(); str1.push_str(str2); *string_obj = (&mut *renv.objectheap).create_string_object(str1.to_string(), renv.classheap); } obj } #[no_mangle] pub extern "C" fn java_lang_stringbuilder_tostring_string( _renv: *mut RuntimeEnvironment, obj: *mut ObjectBody, ) -> *mut ObjectBody { let string_builder = unsafe { &mut *obj }; let s = string_builder.variables[0]; s as GcType<ObjectBody> } #[no_mangle] pub extern "C" fn java_lang_math_random_d(_renv: *mut RuntimeEnvironment) -> f64 { use rand::random; random::<f64>() } #[no_mangle] pub extern "C" fn java_lang_math_sqrt_d_d(_renv: *mut RuntimeEnvironment, x: f64) -> f64 { x.sqrt() } #[no_mangle] pub extern "C" fn java_lang_math_sin_d_d(_renv: *mut RuntimeEnvironment, x: f64) -> f64 { x.sin() } #[no_mangle] pub extern "C" fn java_lang_math_cos_d_d(_renv: *mut RuntimeEnvironment, x: f64) -> f64 { x.cos() } #[no_mangle] pub extern "C" fn java_lang_math_tan_d_d(_renv: *mut RuntimeEnvironment, x: f64) -> f64 { x.tan() } #[no_mangle] pub extern "C" fn java_lang_math_abs_d_d(_renv: *mut RuntimeEnvironment, x: f64) -> f64 { x.abs() } #[no_mangle] pub extern "C" fn java_lang_math_pow_dd_d(_renv: *mut RuntimeEnvironment, x: f64, y: f64) -> f64 { x.powf(y) } // Internal Functions #[no_mangle] pub extern "C" fn ferrugo_internal_new( renv: *mut RuntimeEnvironment, class: *mut Class, ) -> *mut ObjectBody { let renv = unsafe { &mut *renv }; let object = unsafe { &mut *renv.objectheap }.create_object(class); object as GcType<ObjectBody> } #[no_mangle] pub extern "C" fn ferrugo_internal_baload( _renv: *mut RuntimeEnvironment, array: *mut Array, index: u32, ) -> u32 { unsafe { &*array }.at::<u8>(index as isize) as u32 } #[no_mangle] pub extern "C" fn ferrugo_internal_aaload( _renv: *mut RuntimeEnvironment, array: *mut Array, index: u32, ) -> u64 { unsafe { &*array }.at::<u64>(index as isize) as u64 } #[no_mangle] pub extern "C" fn ferrugo_internal_bastore( _renv: *mut RuntimeEnvironment, array: *mut Array, index: u32, val: u32, ) { unsafe { &mut *array }.store(index as isize, val as u8) }
extern crate amethyst; use amethyst::prelude::*; struct MenuState { } impl SimpleState for MenuState { }
//! libc syscalls supporting `rustix::rand`. #[cfg(linux_kernel)] use {crate::backend::c, crate::backend::conv::ret_usize, crate::io, crate::rand::GetRandomFlags}; #[cfg(linux_kernel)] pub(crate) fn getrandom(buf: &mut [u8], flags: GetRandomFlags) -> io::Result<usize> { // `getrandom` wasn't supported in glibc until 2.25. weak_or_syscall! { fn getrandom(buf: *mut c::c_void, buflen: c::size_t, flags: c::c_uint) via SYS_getrandom -> c::ssize_t } unsafe { ret_usize(getrandom(buf.as_mut_ptr().cast(), buf.len(), flags.bits())) } }
use crate::libbb::getopt32::getopt32; use libc; use libc::getutxent; use libc::localtime; use libc::sysinfo; use libc::time; // When reading the utmp entries with getuxent, this identifies // a user entry. const UTMP_USER_PROCESS: libc::c_short = 7; fn get_users() -> u32 { let mut users = 0; unsafe { while let Some(ut) = getutxent().as_mut() { if ut.ut_type == UTMP_USER_PROCESS && ut.ut_user[0] != 0 { users += 1 } } } users } /* nr of bits of precision */ /* 1.0 as fixed-point */ pub fn uptime_main(_argc: libc::c_int, argv: *mut *mut libc::c_char) -> libc::c_int { let opts = unsafe { getopt32(argv, b"s\x00" as *const u8 as *const libc::c_char) }; let mut current_secs = unsafe { time(std::ptr::null_mut()) }; let mut info = unsafe { let mut info: sysinfo = std::mem::zeroed(); sysinfo(&mut info); info }; if opts != 0 { // -s current_secs -= info.uptime } let current_time = unsafe { *localtime(&current_secs) }; if opts != 0 { // -s println!( "{:04}-{:02}-{:02} {:02}:{:02}:{:02}", current_time.tm_year + 1900, current_time.tm_mon + 1, current_time.tm_mday, current_time.tm_hour, current_time.tm_min, current_time.tm_sec, ); /* The above way of calculating boot time is wobbly, * info.uptime has only 1 second precision, which makes * "uptime -s" wander +- one second. * /proc/uptime may be better, it has 0.01s precision. */ return 0; } print!( " {:02}:{:02}:{:02} up ", current_time.tm_hour, current_time.tm_min, current_time.tm_sec, ); let updays = info.uptime / (60 * 60 * 24); if updays > 0 { print!("{} day{}, ", updays, if updays != 1 { "s" } else { "" },); } let upminutes_total = info.uptime / 60; let uphours = (upminutes_total / 60) % 24; let upminutes = upminutes_total % 60; if uphours > 0 { print!("{:2}:{:02}", uphours, upminutes); } else { print!("{} min", upminutes); } println!( ", {} users, load average: {}.{:02}, {}.{:02}, {}.{:02}", get_users(), info.loads[0] >> 16, ((info.loads[0] & ((1 << 16) - 1)) * 100) >> 16, info.loads[1] >> 16, ((info.loads[1] & ((1 << 16) - 1)) * 100) >> 16, info.loads[2] >> 16, ((info.loads[2] & ((1 << 16) - 1)) * 100) >> 16, ); 0 }
mod api; mod components; mod containers; mod router; mod state; mod ui; mod utils; use common::User; use seed::{prelude::*, App}; use crate::containers::app; use crate::state::{update, Model, ModelEvent}; #[wasm_bindgen] pub fn start() { seed::log!("Booting client application."); let mut model = Model::default(); model.is_initializing = true; let app = App::builder(update, app) .routes(router::router) .build_and_start(); // Attempt to load any session data. match utils::get_session_item("user") { Ok(user_json) => match serde_json::from_str::<User>(&user_json) { Ok(user) => app.update(state::ModelEvent::Initialized(Some(user))), Err(_) => app.update(state::ModelEvent::Initialized(None)), } Err(_) => app.update(state::ModelEvent::Initialized(None)), } }
#![cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use crate::detail::sse::{rcp_nr1}; use crate::detail::sandwich::{sw02, sw32, sw_l2}; use crate::util::ApplyTo; use crate::{Line, Plane, Point}; /// \defgroup translator Translators /// /// A translator represents a rigid-body displacement along a normalized axis. /// To apply the translator to a supported entity, the call operator is /// available. /// /// !!! example /// /// ```c++ /// // Initialize a point at (1, 3, 2) /// kln::point p{1.f, 3.f, 2.f}; /// /// // Create a normalized translator representing a 4-unit /// // displacement along the xz-axis. /// kln::translator r{4.f, 1.f, 0.f, 1.f}; /// /// // Displace our point using the created translator /// kln::point translated = r(p); /// ``` /// We can translate lines and planes as well using the translator's call /// operator. /// /// Translators can be multiplied to one another with the `*` operator to create /// a new translator equivalent to the application of each factor. /// /// !!! example /// /// ```c++ /// // Suppose we have 3 translators t1, t2, and t3 /// /// // The translator t created here represents the combined action of /// // t1, t2, and t3. /// kln::translator t = t3 * t2 * t1; /// ``` /// /// The same `*` operator can be used to compose the translator's action with /// other rotors and motors. //pub type Translator = IdealLine; #[derive(Copy, Clone)] pub struct Translator { pub p2_: __m128 } impl Translator { pub fn new(delta: f32, x: f32, y: f32, z: f32) -> Translator { let norm = f32::sqrt(x * x + y * y + z * z); let inv_norm: f32 = 1. / norm; let half_d: f32 = -0.5 * delta; unsafe { let mut p2_ = _mm_mul_ps(_mm_set1_ps(half_d), _mm_set_ps(z, y, x, 0.)); p2_ = _mm_mul_ps(p2_, _mm_set_ps(inv_norm, inv_norm, inv_norm, 0.)); Translator::from(p2_) } } pub fn load_normalized(&mut self, data: &f32) { unsafe { self.p2_ = _mm_loadu_ps(data); } } pub fn default() -> Translator { unsafe { Translator::from(_mm_setzero_ps()) } } pub fn invert(&mut self) { unsafe { self.p2_ = _mm_xor_ps(_mm_set_ps(-0., -0., -0., 0.), self.p2_); } } pub fn normalize(self) -> Self { unimplemented!() } pub fn inverse(self) -> Translator { let mut out = Translator::from(self.p2_); out.invert(); out } } /// Conjugates a plane $p$ with this translator and returns the result /// $tp\widetilde{t}$. impl ApplyTo<Plane> for Translator { fn apply_to(self, p: Plane) -> Plane { unsafe { let tmp: __m128; if is_x86_feature_detected!("sse4.1") { tmp = _mm_blend_ps(self.p2_, _mm_set_ss(1.), 1); } else { tmp = _mm_add_ps(self.p2_, _mm_set_ss(1.)); } Plane::from(sw02(p.p0_, tmp)) } } } common_operations!(Translator, p2_); impl Translator { get_basis_blade_fn!(e01, e10, p2_, 1); get_basis_blade_fn!(e02, e20, p2_, 2); get_basis_blade_fn!(e03, e30, p2_, 3); } /// Conjugates a line $\ell$ with this translator and returns the result /// $t\ell\widetilde{t}$. impl ApplyTo<Line> for Translator { fn apply_to(self, l: Line) -> Line { Line::from(l.p1_, sw_l2(l.p1_, l.p2_, self.p2_)) } } /// Conjugates a point $p$ with this translator and returns the result /// $tp\widetilde{t}$. impl ApplyTo<Point> for Translator { fn apply_to(self, p: Point) -> Point { Point::from(sw32(p.p3_, self.p2_)) } } #[cfg(test)] mod tests { #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; #[allow(dead_code)] fn approx_eq(a: f32, b: f32) { assert!((a - b).abs() < 1e-6) } use crate::{ApplyTo, Line, Point, Translator}; #[test] fn translator_point() { let t = Translator::new(1., 0., 0., 1.); let p1 = Point::new(1., 0., 0.); let p2: Point = t.apply_to(p1); assert_eq!(p2.x(), 1.); assert_eq!(p2.y(), 0.); assert_eq!(p2.z(), 1.); } #[test] fn translator_line() { let data: [f32; 4] = [0., -5., -2., 2.]; let mut t = Translator::default(); t.load_normalized(&data[0]); // a*e01 + b*e01 + c*e02 + d*e23 + e*e31 + f*e12 let l1 = Line::new(-1., 2., -3., -6., 5., 4.); let l2: Line = t.apply_to(l1); assert_eq!(l2.e01(), 35.); assert_eq!(l2.e02(), -14.); assert_eq!(l2.e03(), 71.); assert_eq!(l2.e12(), 4.); assert_eq!(l2.e31(), 5.); assert_eq!(l2.e23(), -6.); } use crate::detail::sandwich::sw02; #[test] fn simd_sandwich() { let mut ab = <[f32; 4]>::default(); unsafe { let a = _mm_set_ps(4., 3., 2., 1.); let b = _mm_set_ps(-1., -2., -3., -4.); _mm_store_ps(&mut ab[0], sw02(a, b)); } assert_eq!(ab[0], 9.); assert_eq!(ab[1], 2.); assert_eq!(ab[2], 3.); assert_eq!(ab[3], 4.); } }
use crate::linked_list::{LinkedList, Node}; use crate::loom::sync::atomic::{AtomicIsize, Ordering}; use crate::loom::sync::Mutex; use crate::loom::thread; use crate::parker::Parker; use crate::tag::Tag; use std::mem; use std::ptr; /// The type of the prelude function. pub(super) type Prelude = dyn Fn() + Send + 'static; // Shared state between the worker thread and [Thread]. pub(super) struct Shared { modifiers: AtomicIsize, queue: Mutex<LinkedList<Entry>>, parker: Parker, } impl Shared { /// Construct new shared state. pub(super) fn new() -> Self { Self { modifiers: AtomicIsize::new(0), queue: Mutex::new(LinkedList::new()), parker: Parker::new(), } } /// Construct a guard which while held ensures that the system knows someone /// is modifying the worker queue. /// /// Interior cleanup of the worker queue will only be considered complete /// once modifiers reaches 0, because otherwise we run the risk of another /// thread being in the middle of a modification while we are cleaning up /// and we leave that thread in a blocked state. pub(super) fn lock_queue(&self) -> Option<ModifierGuard<'_>> { let value = self.modifiers.fetch_add(1, Ordering::SeqCst); if value == isize::MAX { // We don't have much choice here. Wrapping around is very unlikely // to happen because the number of threads required for it to happen // is so big. We eprintln in an attempt to get some information out // but we really need to abort to maintain the safety of the system. eprintln!("ste: modifiers invariant breached, aborting"); std::process::abort(); } if value < 0 { self.modifiers.fetch_sub(1, Ordering::SeqCst); return None; } Some(ModifierGuard { modifiers: &self.modifiers, }) } // Release all shared state, this will hang until the number of modifiers is // zero, after which it will pop all elements from the queue and release // them. unsafe fn panic_join(&self) { let modifiers = self.modifiers.fetch_add(isize::MIN, Ordering::SeqCst); // It's not possible for the state to be anything but empty // here, because the worker thread takes the state before // executing user code which might panic. debug_assert!(modifiers >= 0); let mut local = self.queue.lock().unwrap().steal(); release_local_queue(&mut local); while self.modifiers.load(Ordering::Acquire) != isize::MIN { thread::yield_now(); } let mut local = self.queue.lock().unwrap().steal(); release_local_queue(&mut local); } /// Process the given entry on the remote thread. /// /// # Safety /// /// We're sending the entry to be executed on a remote thread, the caller /// must assure that anything being referenced in it is owned by the caller /// and will not be dropped or deallocated for the duration of this call. pub(super) unsafe fn schedule_in_place(&self, parker: ptr::NonNull<Parker>, entry: Entry) { let mut node = Node::new(entry); let first = { let _guard = match self.lock_queue() { Some(guard) => guard, None => panic!("background thread ended"), }; self.queue .lock() .unwrap() .push_front(ptr::NonNull::from(&mut node)) }; if first { self.parker.unpark(); } // NB: We must park here until the remote task wakes us up to allow // the task to access things from the environment in the other // thread safely. // // We also know fully that the parker is balanced - i.e. there are // no sporadic wakes that can happen because we contrl the state of // the submitted task exactly above. parker.as_ref().park(); } /// What should happen when the shared state is joined. /// /// We mark the modifiers count as negative to signal any entering threads /// that they are no longer permitted to push tasks onto the task set. pub(super) fn outer_join(&self) { // We get the thread to shut down by disallowing the queue to be // modified. If the thread has already shut down (due to a panic) // this will already have been set to `isize::MIN` and will wrap // around or do some other nonsense we can ignore. self.modifiers.fetch_add(isize::MIN, Ordering::SeqCst); self.parker.unpark(); } } pub(super) struct ModifierGuard<'a> { modifiers: &'a AtomicIsize, } impl Drop for ModifierGuard<'_> { fn drop(&mut self) { self.modifiers.fetch_sub(1, Ordering::SeqCst); } } /// Worker thread. pub(super) fn run(prelude: Option<Box<Prelude>>, shared: ptr::NonNull<Shared>) { unsafe { let shared = shared.as_ref(); let tag = Tag(shared as *const _ as usize); if let Some(prelude) = prelude { let guard = PoisonGuard { shared }; prelude(); mem::forget(guard); } while let Some(guard) = shared.lock_queue() { let mut local = shared.queue.lock().unwrap().steal(); drop(guard); if local.is_empty() { shared.parker.park(); continue; } while let Some(mut entry) = local.pop_front() { let entry = &mut entry.as_mut().value; entry.task.as_mut()(tag); entry.parker.as_ref().unpark(); } } } /// Guard used to mark the state of the executed as "panicked". This is /// accomplished by asserting that the only reason this destructor would /// be called would be due to an unwinding panic. struct PoisonGuard<'a> { shared: &'a Shared, } impl Drop for PoisonGuard<'_> { fn drop(&mut self) { unsafe { self.shared.panic_join(); } } } } /// A task submitted to the executor. #[derive(Debug)] pub(super) struct Entry { task: ptr::NonNull<dyn FnMut(Tag) + Send + 'static>, parker: ptr::NonNull<Parker>, } impl Entry { pub(super) unsafe fn new( task: &mut (impl FnMut(Tag) + Send), parker: ptr::NonNull<Parker>, ) -> Self { Self { task: ptr::NonNull::new_unchecked(mem::transmute::<&mut (dyn FnMut(Tag) + Send), _>( task, )), parker, } } /// Release all resources associated with the entry. unsafe fn release(&self) { self.parker.as_ref().unpark(); } } /// Helper function to release a local queue. /// /// This is useful when a queue is stolen, because it disassociates the stolen /// part of the queue from the rest. unsafe fn release_local_queue(queue: &mut LinkedList<Entry>) { while let Some(entry) = queue.pop_back() { entry.as_ref().value.release(); } }
pub mod rectangable; pub mod relative;
use legion::prelude::Entity; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Attacking { pub range: f32, pub reload_time: f32, pub wind_up_time: f32, pub state: AttackingState, pub attacking_type: AttackingType, pub timer: f32, pub target: Option<Entity>, } impl Attacking { pub fn new( range: f32, reload_time: f32, wind_up_time: f32, attacking_type: AttackingType, ) -> Self { Self { range, reload_time, wind_up_time, state: AttackingState::Ready, attacking_type, timer: 0., target: None, } } } #[derive(Clone, Copy, Debug, PartialEq)] #[allow(dead_code)] pub enum AttackingState { Ready, WindingUp, Cooldown, } #[derive(Clone, Copy, Debug, PartialEq)] #[allow(dead_code)] pub enum AttackingType { Instant, Projectile, //TODO } #[allow(dead_code)] impl Attacking { pub fn attacks_per_second(&self) -> f32 { todo!() } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type SpatialGestureRecognizer = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpatialGestureSettings(pub u32); impl SpatialGestureSettings { pub const None: Self = Self(0u32); pub const Tap: Self = Self(1u32); pub const DoubleTap: Self = Self(2u32); pub const Hold: Self = Self(4u32); pub const ManipulationTranslate: Self = Self(8u32); pub const NavigationX: Self = Self(16u32); pub const NavigationY: Self = Self(32u32); pub const NavigationZ: Self = Self(64u32); pub const NavigationRailsX: Self = Self(128u32); pub const NavigationRailsY: Self = Self(256u32); pub const NavigationRailsZ: Self = Self(512u32); } impl ::core::marker::Copy for SpatialGestureSettings {} impl ::core::clone::Clone for SpatialGestureSettings { fn clone(&self) -> Self { *self } } pub type SpatialHoldCanceledEventArgs = *mut ::core::ffi::c_void; pub type SpatialHoldCompletedEventArgs = *mut ::core::ffi::c_void; pub type SpatialHoldStartedEventArgs = *mut ::core::ffi::c_void; pub type SpatialInteraction = *mut ::core::ffi::c_void; pub type SpatialInteractionController = *mut ::core::ffi::c_void; pub type SpatialInteractionControllerProperties = *mut ::core::ffi::c_void; pub type SpatialInteractionDetectedEventArgs = *mut ::core::ffi::c_void; pub type SpatialInteractionManager = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpatialInteractionPressKind(pub i32); impl SpatialInteractionPressKind { pub const None: Self = Self(0i32); pub const Select: Self = Self(1i32); pub const Menu: Self = Self(2i32); pub const Grasp: Self = Self(3i32); pub const Touchpad: Self = Self(4i32); pub const Thumbstick: Self = Self(5i32); } impl ::core::marker::Copy for SpatialInteractionPressKind {} impl ::core::clone::Clone for SpatialInteractionPressKind { fn clone(&self) -> Self { *self } } pub type SpatialInteractionSource = *mut ::core::ffi::c_void; pub type SpatialInteractionSourceEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpatialInteractionSourceHandedness(pub i32); impl SpatialInteractionSourceHandedness { pub const Unspecified: Self = Self(0i32); pub const Left: Self = Self(1i32); pub const Right: Self = Self(2i32); } impl ::core::marker::Copy for SpatialInteractionSourceHandedness {} impl ::core::clone::Clone for SpatialInteractionSourceHandedness { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct SpatialInteractionSourceKind(pub i32); impl SpatialInteractionSourceKind { pub const Other: Self = Self(0i32); pub const Hand: Self = Self(1i32); pub const Voice: Self = Self(2i32); pub const Controller: Self = Self(3i32); } impl ::core::marker::Copy for SpatialInteractionSourceKind {} impl ::core::clone::Clone for SpatialInteractionSourceKind { fn clone(&self) -> Self { *self } } pub type SpatialInteractionSourceLocation = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct SpatialInteractionSourcePositionAccuracy(pub i32); impl SpatialInteractionSourcePositionAccuracy { pub const High: Self = Self(0i32); pub const Approximate: Self = Self(1i32); } impl ::core::marker::Copy for SpatialInteractionSourcePositionAccuracy {} impl ::core::clone::Clone for SpatialInteractionSourcePositionAccuracy { fn clone(&self) -> Self { *self } } pub type SpatialInteractionSourceProperties = *mut ::core::ffi::c_void; pub type SpatialInteractionSourceState = *mut ::core::ffi::c_void; pub type SpatialManipulationCanceledEventArgs = *mut ::core::ffi::c_void; pub type SpatialManipulationCompletedEventArgs = *mut ::core::ffi::c_void; pub type SpatialManipulationDelta = *mut ::core::ffi::c_void; pub type SpatialManipulationStartedEventArgs = *mut ::core::ffi::c_void; pub type SpatialManipulationUpdatedEventArgs = *mut ::core::ffi::c_void; pub type SpatialNavigationCanceledEventArgs = *mut ::core::ffi::c_void; pub type SpatialNavigationCompletedEventArgs = *mut ::core::ffi::c_void; pub type SpatialNavigationStartedEventArgs = *mut ::core::ffi::c_void; pub type SpatialNavigationUpdatedEventArgs = *mut ::core::ffi::c_void; pub type SpatialPointerInteractionSourcePose = *mut ::core::ffi::c_void; pub type SpatialPointerPose = *mut ::core::ffi::c_void; pub type SpatialRecognitionEndedEventArgs = *mut ::core::ffi::c_void; pub type SpatialRecognitionStartedEventArgs = *mut ::core::ffi::c_void; pub type SpatialTappedEventArgs = *mut ::core::ffi::c_void;
use dataflow::ops::filter::FilterCondition; use node::{MirNode, MirNodeType}; use query::MirQuery; use MirNodeRef; use std::collections::HashMap; pub fn optimize(q: MirQuery) -> MirQuery { //remove_extraneous_projections(&mut q); q } pub fn optimize_post_reuse(_q: &mut MirQuery) { // find_and_merge_filter_chains(q); } #[allow(dead_code)] fn find_and_merge_filter_chains(q: &MirQuery) { let mut chained_filters = Vec::new(); // depth first search let mut node_stack = Vec::new(); node_stack.extend(q.roots.iter().cloned()); let mut visited_nodes = HashMap::new(); while !node_stack.is_empty() { let n = node_stack.pop().unwrap(); let node_name = n.borrow().versioned_name(); let mut end_chain = false; if visited_nodes.contains_key(&node_name) { continue; } visited_nodes.insert(node_name, true); match n.borrow().inner { MirNodeType::Filter { .. } => { try_add_node_to_chain(&n, &mut chained_filters); } _ => { // we need this because n most likely will be a children of // last_node. if that's the case, mutably borrowing the // child in end_filter_chain will cause a BorrowMutError // because it was already borrowed in the match. end_chain = true; } } if end_chain { end_filter_chain(&mut chained_filters); } for child in n.borrow().children.iter() { node_stack.push(child.clone()); } } } fn try_add_node_to_chain(node: &MirNodeRef, chained_filters: &mut Vec<MirNodeRef>) { // any filter node can start a new chain if chained_filters.is_empty() || node.borrow().ancestors.len() == 1 { chained_filters.push(node.clone()); } else { end_filter_chain(chained_filters); return; } if node.borrow().children.len() != 1 { end_filter_chain(chained_filters); } } fn end_filter_chain(chained_filters: &mut Vec<MirNodeRef>) { use std::cmp::max; if chained_filters.len() < 2 { chained_filters.clear(); return; } { let first_node = chained_filters.first().unwrap(); let last_node = chained_filters.last().unwrap(); let schema_version = first_node.borrow().from_version; let name = chained_filters .iter() .fold("merged_filter_".to_string(), |mut acc, ref node| { acc.push_str(node.borrow().name()); acc }); let prev_node = first_node.borrow().ancestors.first().unwrap().clone(); let fields = prev_node.borrow().columns().to_vec(); let width = chained_filters.iter().fold(0, |mut acc, ref node| { let w = match node.borrow().inner { MirNodeType::Filter { ref conditions } => conditions.len(), _ => 0, }; acc = max(acc, w); acc }); let merged_conditions = to_conditions(chained_filters, width); let merged_filter = MirNode::new( name.as_str(), schema_version, fields, MirNodeType::Filter { conditions: merged_conditions.clone(), }, vec![prev_node], vec![], ); for ancestor in &first_node.borrow().ancestors { ancestor.borrow_mut().remove_child(first_node.clone()); } first_node.borrow_mut().ancestors.clear(); for child in &last_node.borrow().children { merged_filter.borrow_mut().add_child(child.clone()); child.borrow_mut().add_ancestor(merged_filter.clone()); child.borrow_mut().remove_ancestor(last_node.clone()); } } chained_filters.clear(); } fn to_conditions( chained_filters: &[MirNodeRef], num_columns: usize, ) -> Vec<Option<FilterCondition>> { let mut merged_conditions = vec![None; num_columns]; for filter in chained_filters { match filter.borrow().inner { MirNodeType::Filter { ref conditions } => { // Note that this assumes that there is only ever one column being filtered on for // each filter that is being merged. let i = conditions.iter().position(Option::is_some).unwrap(); merged_conditions[i] = conditions[i].clone(); } _ => unreachable!(), } } merged_conditions } // currently unused #[allow(dead_code)] fn remove_extraneous_projections(_q: &mut MirQuery) { unimplemented!() }
use base64::Engine; pub mod options; pub fn basic_header(username: &str, password: &str)->String{ base64::engine::general_purpose::STANDARD.encode( format!( "{}:{}", username, password ) ) }
fn main(){ proconio::input!{n:u64,m:i64,l:[(i64,i64);n]} println!("{}",l.iter().filter(|(x,y)|x*x+y*y<=m*m).count()) }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::Hash; use fuchsia_async as fasync; use futures::channel::mpsc::UnboundedSender; use futures::future::{AbortHandle, Abortable}; use futures::TryFutureExt; use super::ZxTime; /// A possible timer event that may be fulfilled by calling /// [`TimerDispatcher::commit_timer`] #[derive(Debug)] pub struct TimerEvent<T> { inner: T, id: u64, } /// Internal information to keep tabs on timers. struct TimerInfo { id: u64, instant: ZxTime, abort_handle: AbortHandle, } /// Helper struct to keep track of timers for the event loop. pub(super) struct TimerDispatcher<T: Hash + Eq, E> { sender: UnboundedSender<E>, // Invariant: TimerDispatcher uses a HashMap keyed on an external identifier // T and assigns an internal "versioning" ID every time a timer is // scheduled. The "versioning" ID is just monotonically incremented and it // is used to disambiguate different scheduling events of the same timer T. // TimerInfo in the HashMap will always hold the latest allocated // "versioning" identifier, meaning that: // - When a timer is rescheduled, we update TimerInfo::id to a new value // - To "commit" a timer firing (through commit_timer), the TimerEvent // given must carry the same "versioning" identifier as the one currently // held by the HashMap in TimerInfo::id. // For external users, the only way to obtain T from a TimerEvent<T> is to // give it to TimerDispatcher::commit_timer, so that we can further the // invariant into: only ONE version of T that was scheduled by // TimerDispatcher is "valid" at a given point in time. timers: HashMap<T, TimerInfo>, next_id: u64, } impl<T, E> TimerDispatcher<T, E> where T: Hash + Eq + Clone, E: 'static + From<TimerEvent<T>> + Sync + Send, { /// Creates a new `TimerDispatcher` that sends [`TimerEvent`]s over /// `sender`. pub(super) fn new(sender: UnboundedSender<E>) -> Self { Self { timers: HashMap::new(), sender, next_id: 0 } } /// Schedule a new timer with identifier `timer_id` at `time`. /// /// If a timer with the same `timer_id` was already scheduled, the old timer is /// unscheduled and its expiry time is returned. pub(super) fn schedule_timer(&mut self, timer_id: T, time: ZxTime) -> Option<ZxTime> { let next_id = self.next_id; // Overflowing next_id should be safe enough to hold TimerDispatcher's // invariant about around "versioning" timer identifiers. We'll // overlflow after 2^64 timers are scheduled (which can take a while) // and, even then, for it to break the invariant we'd need to still // have a timer scheduled from long ago and be unlucky enough that // ordering ends up giving it the same ID. That seems unlikely, so we // just wrap around and overflow next_id. self.next_id = self.next_id.overflowing_add(1).0; let timer_send = self.sender.clone(); let event = E::from(TimerEvent { inner: timer_id.clone(), id: next_id }); let timeout = async move { fasync::Timer::new(fasync::Time::from_zx(time.0)).await; timer_send.unbounded_send(event).unwrap(); }; let (abort_handle, abort_registration) = AbortHandle::new_pair(); let timeout = Abortable::new(timeout, abort_registration); // An Abortable future's Output type is Result<_,Aborted>, but // spawn_local wants a future whose Output type is (). We achieve that // by discarding the abort information with unwrap_or_else below: let timeout = timeout.unwrap_or_else(|_| ()); fasync::spawn_local(timeout); match self.timers.entry(timer_id) { Entry::Vacant(e) => { // If we don't have any currently scheduled timers with this // timer_id, we're just going to insert a new value into the // vacant entry, marking it with next_id. e.insert(TimerInfo { id: next_id, instant: time, abort_handle }); None } Entry::Occupied(mut e) => { // If we already have a scheduled timer with this timer_id, we // must... let info = e.get_mut(); // ...call the abort handle on the old timer, to prevent it from // firing if it hasn't already: info.abort_handle.abort(); // ...update the abort handle with the new one: info.abort_handle = abort_handle; // ...store the new "versioning" timer_id next_id, effectively // marking this newest version as the only valid one, in case // the old timer had already fired as is currently waiting to be // commited. info.id = next_id; // ...finally, we get the old instant information to be returned // and update the TimerInfo entry with the new time value: let old = Some(info.instant); info.instant = time; old } } } /// Cancels a timer with identifier `timer_id`. /// /// If a timer with the provided `timer_id` was scheduled, returns the /// expiry time for it after having cancelled it. pub(super) fn cancel_timer(&mut self, timer_id: &T) -> Option<ZxTime> { if let Some(t) = self.timers.remove(timer_id) { // call the abort handle, in case the future hasn't fired yet: t.abort_handle.abort(); Some(t.instant) } else { None } } /// Cancels all timers with given filter. /// /// `f` will be called sequentially for all the currently scheduled timers. /// If `f(id)` returns `true`, the timer with `id` will be cancelled. pub(super) fn cancel_timers_with<F: FnMut(&T) -> bool>(&mut self, mut f: F) { self.timers.retain(|id, info| { let discard = f(&id); if discard { info.abort_handle.abort(); } !discard }); } /// Gets the time a timer with identifier `timer_id` will be invoked. /// /// If a timer with the provided `timer_id` exists, returns the expiry /// time for it; `None` otherwise. pub(super) fn scheduled_time(&self, timer_id: &T) -> Option<ZxTime> { self.timers.get(timer_id).map(|t| t.instant) } /// Retrieves the internal timer value of a [`TimerEvent`]. /// /// `commit_timer` will "commit" `event` for consumption, if `event` is /// still valid to be triggered. If `commit_timer` returns `Some`, then /// `TimerDispatcher` will "forget" about the timer identifier contained in /// `event`, meaning subsequent calls to [`cancel_timer`] or /// [`schedule_timer`] will return `None`. /// /// [`cancel_timer`]: TimerDispatcher::cancel_timer /// [`schedule_timer`]: TimerDispatcher::schedule_timer pub(super) fn commit_timer(&mut self, event: TimerEvent<T>) -> Option<T> { match self.timers.entry(event.inner.clone()) { Entry::Occupied(e) => { // The event is only valid if its id matches the one in the // HashMap: if e.get().id == event.id { e.remove(); Some(event.inner) } else { None } } _ => None, } } } #[cfg(test)] mod tests { use super::*; use fuchsia_zircon as zx; use futures::channel::mpsc; use futures::StreamExt; struct OuterEvent(TimerEvent<usize>); impl From<TimerEvent<usize>> for OuterEvent { fn from(i: TimerEvent<usize>) -> Self { OuterEvent(i) } } fn nanos_from_now(nanos: i64) -> ZxTime { ZxTime(zx::Time::from_nanos(zx::Time::get(zx::ClockId::Monotonic).into_nanos() + nanos)) } // NOTE(brunodalbo): In the tests below, we rely on the order of the tests // that come out, but the timers are scheduled just nanoseconds apart. // What's effectively giving us the ordering of the events coming out the // UnboundedReceiver is the scheduling order, and not really the actual time // value that we set on each timer. This is deterministic enough to avoid // flakiness with the singlethreaded and very controlled approach used in // the tests, but it stands to note that the spawn_local strategy that is // being used by TimerDispatcher does *not* 100% guarantee that timers will // actually be operated in order based on their scheduled times. #[fasync::run_singlethreaded(test)] async fn test_timers_fire() { let (snd, mut rcv) = mpsc::unbounded(); let mut d = TimerDispatcher::<usize, OuterEvent>::new(snd); assert!(d.schedule_timer(1, nanos_from_now(1)).is_none()); assert!(d.schedule_timer(2, nanos_from_now(2)).is_none()); let t1 = rcv.next().await.unwrap(); assert_eq!(d.commit_timer(t1.0).unwrap(), 1); let t2 = rcv.next().await.unwrap(); assert_eq!(d.commit_timer(t2.0).unwrap(), 2); } #[fasync::run_singlethreaded(test)] async fn test_get_scheduled_instant() { let (snd, _rcv) = mpsc::unbounded(); let mut d = TimerDispatcher::<usize, OuterEvent>::new(snd); // Timer 1 is scheduled. let time1 = nanos_from_now(1); assert!(d.schedule_timer(1, time1).is_none()); assert_eq!(d.scheduled_time(&1).unwrap(), time1); // Timer 2 does not exist yet. assert!(d.scheduled_time(&2).is_none()); // Timer 1 is scheduled. let time2 = nanos_from_now(2); assert!(d.schedule_timer(2, time2).is_none()); assert_eq!(d.scheduled_time(&1).unwrap(), time1); assert_eq!(d.scheduled_time(&2).unwrap(), time2); // Cancel Timer 1. assert_eq!(d.cancel_timer(&1).unwrap(), time1); assert!(d.scheduled_time(&1).is_none()); // Timer 2 should still be scheduled. assert_eq!(d.scheduled_time(&2).unwrap(), time2); } #[fasync::run_singlethreaded(test)] async fn test_cancel() { let (snd, mut rcv) = mpsc::unbounded(); let mut d = TimerDispatcher::<usize, OuterEvent>::new(snd); // timer 1 and 2 are scheduled. // timer 1 is going to be cancelled even before we allow the loop to // run, while timer 2 will be cancelled AFTER we retrieve it from // the event stream. let time1 = nanos_from_now(1); let time2 = nanos_from_now(2); assert!(d.schedule_timer(1, time1).is_none()); assert!(d.schedule_timer(2, time2).is_none()); assert_eq!(d.cancel_timer(&1).unwrap(), time1); let t = rcv.next().await.unwrap(); assert_eq!(d.cancel_timer(&2).unwrap(), time2); // only event 2 should come out: assert_eq!(t.0.inner, 2); // Resolving it should fail: assert!(d.commit_timer(t.0).is_none()); // schedule another timer and wait for it, just to prove that timer 1's // event never gets fired: assert!(d.schedule_timer(3, nanos_from_now(5)).is_none()); let t = rcv.next().await.unwrap(); assert_eq!(t.0.inner, 3); } #[fasync::run_singlethreaded(test)] async fn test_reschedule() { let (snd, mut rcv) = mpsc::unbounded(); let mut d = TimerDispatcher::<usize, OuterEvent>::new(snd); // timer 1 and 2 are scheduled. // timer 1 is going to be rescheduled even before we allow the loop to // run, while timer 2 will be rescheduled AFTER we retrieve it from // the event stream. let time1 = nanos_from_now(1); let time2 = nanos_from_now(2); let resched1 = nanos_from_now(3); let resched2 = nanos_from_now(4); assert!(d.schedule_timer(1, time1).is_none()); assert!(d.schedule_timer(2, time2).is_none()); assert_eq!(d.schedule_timer(1, resched1).unwrap(), time1); let t = rcv.next().await.unwrap(); assert_eq!(d.schedule_timer(2, resched2).unwrap(), time2); // only event 2 should come out: assert_eq!(t.0.inner, 2); // Resolving it should fail (because we rescheduled it): assert!(d.commit_timer(t.0).is_none()); // now we can go at it again and get the rescheduled timer 1...: let t = rcv.next().await.unwrap(); assert_eq!(t.0.inner, 1); assert_eq!(d.commit_timer(t.0).unwrap(), 1); // ... and timer 2: let t = rcv.next().await.unwrap(); assert_eq!(t.0.inner, 2); assert_eq!(d.commit_timer(t.0).unwrap(), 2); } #[fasync::run_singlethreaded(test)] async fn test_cancel_with() { let (snd, mut rcv) = mpsc::unbounded(); let mut d = TimerDispatcher::<usize, OuterEvent>::new(snd); // schedule 4 timers: assert!(d.schedule_timer(1, nanos_from_now(1)).is_none()); assert!(d.schedule_timer(2, nanos_from_now(2)).is_none()); assert!(d.schedule_timer(3, nanos_from_now(3)).is_none()); assert!(d.schedule_timer(4, nanos_from_now(4)).is_none()); // cancel timers 1, 3, and 4. d.cancel_timers_with(|id| *id != 2); // check that only one timer remains assert_eq!(d.timers.len(), 1); // get the timer and assert that it is the timer with id == 2. let t = rcv.next().await.unwrap(); assert_eq!(t.0.inner, 2); assert_eq!(d.commit_timer(t.0).unwrap(), 2); } }
//! Delay use crate::hal::blocking::delay::{DelayMs, DelayUs}; use crate::hal::timer::{Cancel, CountDown}; use crate::pac::hstimer::HSTIMER; use crate::{ ccu::{Ccu, Clocks}, timer::Timer, }; use cortex_a::asm; use embedded_time::{ duration::{Duration, Microseconds, Milliseconds}, rate::Hertz, }; use nb::block; /// High-speed timer (HSTIMER) as a delay provider pub struct Delay { timer: Timer<HSTIMER>, } impl Delay { pub fn new(timer: HSTIMER, clocks: Clocks, ccu: &mut Ccu) -> Self { Delay { timer: Timer::hstimer(timer, clocks, ccu), } } } impl DelayUs<Microseconds> for Delay { fn delay_us(&mut self, us: Microseconds) { self.timer.start(us.to_rate::<Hertz>().unwrap()); block!(self.timer.wait()).unwrap(); self.timer.cancel().unwrap(); } } impl DelayMs<Milliseconds> for Delay { fn delay_ms(&mut self, ms: Milliseconds) { self.timer.start(ms.to_rate::<Hertz>().unwrap()); block!(self.timer.wait()).unwrap(); self.timer.cancel().unwrap(); } } // TODO - rm these or make a NoOpDelay type that uses Clocks... pub(crate) fn delay_ms(ms: usize) { delay_us(ms * 1000); } pub(crate) fn delay_us(us: usize) { for _ in 0..us { for _ in 0..(24 + 10) { asm::nop(); } } }
use std::sync::mpsc::Receiver; use crate::backup_file::BackupFile; use crate::chunk::Chunk; pub fn run(destinations: &mut Vec<BackupFile>, write_queue_consume: Receiver<(usize, Chunk)>) { while let Ok((device_number, chunk)) = write_queue_consume.recv() { destinations[device_number].write_chunk(chunk); } }
/* * @lc app=leetcode.cn id=93 lang=rust * * [93] 复原IP地址 * * https://leetcode-cn.com/problems/restore-ip-addresses/description/ * * algorithms * Medium (42.77%) * Total Accepted: 6.3K * Total Submissions: 14.7K * Testcase Example: '"25525511135"' * * 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 * * 示例: * * 输入: "25525511135" * 输出: ["255.255.11.135", "255.255.111.35"] * */ impl Solution { pub fn restore_ip_addresses(s: String) -> Vec<String> { fn dfs<'a>(res: &mut Vec<String>, s: &'a String, idx: usize, temp: &mut Vec<&'a str>) { if temp.len() == 4 { if idx == s.len() { res.push(temp.join(".")); } return; } for i in 1..=3 { if idx + i > s.len() { continue; } let v = &s[idx..(idx + i)]; if v.len() == 3 && v > "255" { continue; } if v.len() != 1 && v.starts_with('0') { continue; } temp.push(v); dfs(res, s, idx + i, temp); temp.pop(); } } let mut res = vec![]; dfs(&mut res, &s, 0, &mut vec![]); res } } fn main() { fn check(s: &str) { let res = Solution::restore_ip_addresses(s.to_string()); dbg!(res); } check("010010"); check("192168102"); } struct Solution {}
use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::str::FromStr; use std::hash::{Hash, Hasher}; use crate::class_file::validated::Instruction; use crate::class_file::unvalidated::AccessFlags; use crate::class_file::unvalidated::{ClassFile as UnvalidatedClassFile}; use crate::class_file::validated::ClassFile; use crate::class_file::validated::ClassFileRef; use crate::class_file::unvalidated::{Constant as UnvalidatedConstant}; use crate::class_file::validated::Constant; use crate::class_file::unvalidated::ConstantIdx; use crate::class_file::unvalidated::FieldAccessFlags; use crate::class_file::unvalidated::FieldInfo; use crate::class_file::unvalidated::MethodAccessFlags; use crate::class_file::validated::MethodBody; use crate::class_file::validated::MethodHandle; use crate::class_file::unvalidated::MethodInfo; struct CallFrame { offset: u32, arguments: Vec<Value>, body: Rc<MethodBody>, enclosing_class: Rc<ClassFile>, operand_stack: Vec<Value>, } impl CallFrame { pub fn new( body: Rc<MethodBody>, enclosing_class: Rc<ClassFile>, mut arguments: Vec<Value>, ) -> Self { while arguments.len() < (body.max_locals as usize) { arguments.push(Value::Integer(0)); } CallFrame { offset: 0, arguments, body, enclosing_class, operand_stack: Vec::new(), } } } pub struct VMState { // Attribute is actually a Code (anything else is an error) call_stack: Vec<CallFrame>, } #[allow(dead_code)] impl VMState { pub fn new( code: Rc<MethodBody>, method_class: Rc<ClassFile>, initial_args: Vec<Value>, ) -> Self { let mut state = VMState { call_stack: Vec::new(), }; state .call_stack .push(CallFrame::new(code, method_class, initial_args)); state } fn current_frame(&self) -> &CallFrame { self.call_stack.iter().rev().next().unwrap() } fn current_frame_mut(&mut self) -> &mut CallFrame { self.call_stack.iter_mut().rev().next().unwrap() } fn next_instruction(&mut self) -> Option<Instruction> { if self.call_stack.len() == 0 { return None; } let frame = self.current_frame_mut(); let mut inst_iter = frame.body.iter_from(frame.offset); let inst = inst_iter.next(); frame.offset = inst_iter.offset as u32; inst } pub fn enter( &mut self, body: Rc<MethodBody>, enclosing_class: Rc<ClassFile>, arguments: Vec<Value>, ) { self.call_stack .push(CallFrame::new(body, enclosing_class, arguments)); } pub fn leave(&mut self) { self.call_stack.pop().expect("stack is non-empty"); } fn interpret_iload(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let argument: Option<&Value> = frame_mut.arguments.get(idx as usize); let operand = match argument { Some(argument) => match argument { Value::Integer(v) => Value::Integer(*v), _ => { return Err(VMError::BadClass("iload but not integer")); } }, None => { return Err(VMError::BadClass("iload but insufficient arguments")); } }; frame_mut.operand_stack.push(operand); Ok(None) } fn interpret_istore(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let value = frame_mut .operand_stack .pop() .expect("operand stack has value"); frame_mut.arguments[idx as usize] = value.clone(); Ok(None) } fn interpret_lload(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let argument: Option<&Value> = frame_mut.arguments.get(idx as usize); let operand = match argument { Some(argument) => match argument { Value::Long(v) => Value::Long(*v), _ => { return Err(VMError::BadClass("lload but not long")); } }, None => { return Err(VMError::BadClass("lload but insufficient arguments")); } }; frame_mut.operand_stack.push(operand); Ok(None) } fn interpret_lstore(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let value = frame_mut .operand_stack .pop() .expect("operand stack has value"); frame_mut.arguments[idx as usize] = value.clone(); Ok(None) } fn interpret_fload(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let argument: Option<&Value> = frame_mut.arguments.get(idx as usize); let operand = match argument { Some(argument) => match argument { Value::Float(v) => Value::Float(*v), _ => { return Err(VMError::BadClass("fload but not float")); } }, None => { return Err(VMError::BadClass("fload but insufficient arguments")); } }; frame_mut.operand_stack.push(operand); Ok(None) } fn interpret_fstore(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let value = frame_mut .operand_stack .pop() .expect("operand stack has value"); frame_mut.arguments[idx as usize] = value.clone(); Ok(None) } fn interpret_dload(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let argument: Option<&Value> = frame_mut.arguments.get(idx as usize); let operand = match argument { Some(argument) => match argument { Value::Double(v) => Value::Double(*v), _ => { return Err(VMError::BadClass("dload but not double")); } }, None => { return Err(VMError::BadClass("dload but insufficient arguments")); } }; frame_mut.operand_stack.push(operand); Ok(None) } fn interpret_dstore(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let value = frame_mut .operand_stack .pop() .expect("operand stack has value"); frame_mut.arguments[idx as usize] = value.clone(); Ok(None) } fn interpret_aload(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let argument: Option<&Value> = frame_mut.arguments.get(idx as usize); let operand = match argument { // TODO: type check argument as an object? Some(argument) => argument.clone(), None => { return Err(VMError::BadClass("dload but insufficient arguments")); } }; frame_mut.operand_stack.push(operand); Ok(None) } fn interpret_astore(&mut self, idx: u16) -> Result<Option<Value>, VMError> { let frame_mut = self.current_frame_mut(); let value = frame_mut .operand_stack .pop() .expect("operand stack has value"); frame_mut.arguments[idx as usize] = value.clone(); Ok(None) } fn execute( &mut self, instruction: &Instruction, vm: &mut VirtualMachine, ) -> Result<Option<Value>, VMError> { match instruction { Instruction::InvokeVirtual(method_ref) => { let target_class = vm.resolve_class(&method_ref.class_name).unwrap(); let method = target_class .get_method(&method_ref.name, &method_ref.desc) .expect("method exists"); // get method by name `method_name` if method.access().is_native() { if let Some(native_method) = target_class.native_methods.get(&method_ref.name) { native_method(self, vm)?; Ok(None) } else if let Some(native_method) = target_class .native_methods .get(&format!("{}{}", &method_ref.name, &method_ref.desc)) { native_method(self, vm)?; Ok(None) } else { panic!("attempted to call native method with no implementation: {} - note, JNI resolution is not yet supported.", &method_ref.name); } } else { interpreted_method_call(self, vm, method, target_class, &method_ref.desc)?; Ok(None) } } Instruction::InvokeStatic(method_ref) => { let target_class = vm.resolve_class(&method_ref.class_name).unwrap(); let method = target_class .get_method(&method_ref.name, &method_ref.desc) .expect("method exists"); // get method by name `method_name` if method.access().is_native() { if let Some(native_method) = target_class.native_methods.get(&method_ref.name) { native_method(self, vm)?; Ok(None) } else if let Some(native_method) = target_class .native_methods .get(&format!("{}{}", &method_ref.name, &method_ref.desc)) { native_method(self, vm)?; Ok(None) } else { panic!("attempted to call native method with no implementation: {} - note, JNI resolution is not yet supported.", &method_ref.name); } } else { interpreted_method_call(self, vm, method, target_class, &method_ref.desc)?; Ok(None) } } Instruction::GetStatic(field_ref) => { let target_class = vm.resolve_class(&field_ref.class_name).unwrap(); let value = vm .get_static_field(&target_class, &field_ref.name, &field_ref.desc) .unwrap(); self.current_frame_mut().operand_stack.push(value); Ok(None) } Instruction::PutStatic(field_ref) => { let target_class = vm.resolve_class(&field_ref.class_name).unwrap(); let value = if let Some(value) = self.current_frame_mut().operand_stack.pop() { value } else { return Err(VMError::BadClass("putstatic but insufficient arguments")); }; vm.put_static_field(&target_class, &field_ref.name, &field_ref.desc, value); Ok(None) } Instruction::InvokeSpecial(method_ref) => { let target_class = vm.resolve_class(&method_ref.class_name).unwrap(); let method = target_class .get_method(&method_ref.name, &method_ref.desc) .expect("method exists"); // get method by name `method_name` if method.access().is_native() { if let Some(native_method) = target_class.native_methods.get(&method_ref.name) { native_method(self, vm)?; Ok(None) } else if let Some(native_method) = target_class .native_methods .get(&format!("{}{}", &method_ref.name, &method_ref.desc)) { native_method(self, vm)?; Ok(None) } else { panic!("attempted to call native method with no implementation: {} - note, JNI resolution is not yet supported.", &method_ref.name); } } else { interpreted_method_call(self, vm, method, target_class, &method_ref.desc)?; Ok(None) } } Instruction::NewArray(_tpe) => { let top = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let mut elems = Vec::new(); if let Value::Integer(size) = top { for _ in 0..size { elems.push(Value::Integer(0)); } } self.current_frame_mut() .operand_stack .push(Value::Array( Rc::new(RefCell::new(elems.into_boxed_slice())), )); Ok(None) } Instruction::New(tpe) => { self.current_frame_mut() .operand_stack .push(Value::new_inst( vm.resolve_class(tpe)?, )); Ok(None) } Instruction::BIPush(b) => { self.current_frame_mut() .operand_stack .push(Value::Integer(*b as i32)); Ok(None) } Instruction::SIPush(s) => { self.current_frame_mut() .operand_stack .push(Value::Integer(*s as i32)); Ok(None) } Instruction::Dup => { let top = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); self.current_frame_mut().operand_stack.push(top.clone()); self.current_frame_mut().operand_stack.push(top); Ok(None) } Instruction::Dup2 => { // ok this one is trickier // TODO: handle longs/doubles properly let top = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let next = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); self.current_frame_mut().operand_stack.push(next.clone()); self.current_frame_mut().operand_stack.push(top.clone()); self.current_frame_mut().operand_stack.push(next); self.current_frame_mut().operand_stack.push(top); Ok(None) } Instruction::BALoad => { // ok this one is trickier // TODO: handle longs/doubles properly let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays if let Some(value) = elements.borrow().get(index as usize) { self.current_frame_mut() .operand_stack .push(value.clone()); } else { panic!("array index out of bounds exceptions!!"); } } else { panic!("getting element out of non-array"); } Ok(None) } Instruction::BAStore => { // ok this one is trickier // TODO: handle longs/doubles properly let value = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays elements.borrow_mut()[index as usize] = value; } else { panic!("storing element into non-array"); } Ok(None) } Instruction::CAStore => { // ok this one is trickier // TODO: handle longs/doubles properly let value = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays elements.borrow_mut()[index as usize] = value; } else { panic!("storing element into non-array"); } Ok(None) } Instruction::CALoad => { // ok this one is trickier // TODO: handle longs/doubles properly let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays self .current_frame_mut() .operand_stack .push(elements.borrow()[index as usize].clone()); } else { panic!("storing element into non-array"); } Ok(None) } Instruction::SAStore => { // ok this one is trickier // TODO: handle longs/doubles properly let value = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays elements.borrow_mut()[index as usize] = value; } else { panic!("storing element into non-array"); } Ok(None) } Instruction::SALoad => { // ok this one is trickier // TODO: handle longs/doubles properly let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays self .current_frame_mut() .operand_stack .push(elements.borrow()[index as usize].clone()); } else { panic!("storing element into non-array"); } Ok(None) } Instruction::IAStore => { // ok this one is trickier // TODO: handle longs/doubles properly let value = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays elements.borrow_mut()[index as usize] = value; } else { panic!("storing element into non-array"); } Ok(None) } Instruction::IALoad => { // ok this one is trickier // TODO: handle longs/doubles properly let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Integer(index)) = (array, index) { // TODO: homogeneously typed arrays self .current_frame_mut() .operand_stack .push(elements.borrow()[index as usize].clone()); } else { panic!("storing element into non-array"); } Ok(None) } Instruction::LAStore => { // ok this one is trickier // TODO: handle longs/doubles properly let value = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Long(index)) = (array, index) { // TODO: homogeneously typed arrays elements.borrow_mut()[index as usize] = value; } else { panic!("storing element into non-array"); } Ok(None) } Instruction::LALoad => { // ok this one is trickier // TODO: handle longs/doubles properly let index = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); let array = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let (Value::Array(elements), Value::Long(index)) = (array, index) { // TODO: homogeneously typed arrays self .current_frame_mut() .operand_stack .push(elements.borrow()[index as usize].clone()); } else { panic!("storing element into non-array"); } Ok(None) } Instruction::ArrayLength => { let top = self .current_frame_mut() .operand_stack .pop() .expect("stack has a value"); if let Value::Array(elems) = top { self.current_frame_mut() .operand_stack .push(Value::Integer(elems.borrow().len() as i32)); Ok(None) } else { panic!("arraylength but value is not array"); } } Instruction::LConst0 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Long(0)); Ok(None) } Instruction::LConst1 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Long(1)); Ok(None) } Instruction::IConst0 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(0)); Ok(None) } Instruction::IConst1 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(1)); Ok(None) } Instruction::IConst2 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(2)); Ok(None) } Instruction::IConst3 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(3)); Ok(None) } Instruction::IConst4 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(4)); Ok(None) } Instruction::IConst5 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(5)); Ok(None) } Instruction::IConstM1 => { let frame_mut = self.current_frame_mut(); frame_mut .operand_stack .push(Value::Integer(-1)); Ok(None) } Instruction::Goto(offset) => { let frame_mut = self.current_frame_mut(); frame_mut.offset = frame_mut.offset.wrapping_add(*offset as i32 as u32 - 3); Ok(None) } Instruction::IfGe(offset) => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match value { Value::Integer(v) => { if v >= 0 { frame_mut.offset += *offset as i32 as u32 - 3; Ok(None) } else { Ok(None) } } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::IfLe(offset) => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ifle but insufficient arguments")); }; match value { Value::Integer(v) => { if v <= 0 { frame_mut.offset += *offset as i32 as u32 - 3; Ok(None) } else { Ok(None) } } _ => Err(VMError::BadClass("ifle but invalid operand types")), } } Instruction::IfEq(offset) => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ifeq but insufficient arguments")); }; match value { Value::Integer(v) => { if v == 0 { frame_mut.offset += *offset as i32 as u32 - 3; Ok(None) } else { Ok(None) } } _ => Err(VMError::BadClass("ifeq but invalid operand types")), } } Instruction::IfNe(offset) => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ifne but insufficient arguments")); }; match value { Value::Integer(v) => { if v != 0 { frame_mut.offset += *offset as i32 as u32 - 3; Ok(None) } else { Ok(None) } } _ => Err(VMError::BadClass("ifne but invalid operand types")), } } Instruction::IfIcmpNe(offset) => { let frame_mut = self.current_frame_mut(); let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match (left, right) { (Value::Integer(l), Value::Integer(r)) => { if l != r { frame_mut.offset += *offset as i32 as u32 - 3; Ok(None) } else { Ok(None) } } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::ILoad0 => self.interpret_iload(0), Instruction::ILoad1 => self.interpret_iload(1), Instruction::ILoad2 => self.interpret_iload(2), Instruction::ILoad3 => self.interpret_iload(3), Instruction::ILoad(idx) => self.interpret_iload(*idx), Instruction::IStore0 => self.interpret_istore(0), Instruction::IStore1 => self.interpret_istore(1), Instruction::IStore2 => self.interpret_istore(2), Instruction::IStore3 => self.interpret_istore(3), Instruction::IStore(idx) => self.interpret_istore(*idx), Instruction::LLoad0 => self.interpret_lload(0), Instruction::LLoad1 => self.interpret_lload(1), Instruction::LLoad2 => self.interpret_lload(2), Instruction::LLoad3 => self.interpret_lload(3), Instruction::LLoad(idx) => self.interpret_lload(*idx), Instruction::LStore0 => self.interpret_lstore(0), Instruction::LStore1 => self.interpret_lstore(1), Instruction::LStore2 => self.interpret_lstore(2), Instruction::LStore3 => self.interpret_lstore(3), Instruction::LStore(idx) => self.interpret_lstore(*idx), Instruction::FLoad0 => self.interpret_fload(0), Instruction::FLoad1 => self.interpret_fload(1), Instruction::FLoad2 => self.interpret_fload(2), Instruction::FLoad3 => self.interpret_fload(3), Instruction::FLoad(idx) => self.interpret_fload(*idx), Instruction::FStore0 => self.interpret_fstore(0), Instruction::FStore1 => self.interpret_fstore(1), Instruction::FStore2 => self.interpret_fstore(2), Instruction::FStore3 => self.interpret_fstore(3), Instruction::FStore(idx) => self.interpret_fstore(*idx), Instruction::DLoad0 => self.interpret_dload(0), Instruction::DLoad1 => self.interpret_dload(1), Instruction::DLoad2 => self.interpret_dload(2), Instruction::DLoad3 => self.interpret_dload(3), Instruction::DLoad(idx) => self.interpret_dload(*idx), Instruction::DStore0 => self.interpret_dstore(0), Instruction::DStore1 => self.interpret_dstore(1), Instruction::DStore2 => self.interpret_dstore(2), Instruction::DStore3 => self.interpret_dstore(3), Instruction::DStore(idx) => self.interpret_dstore(*idx), Instruction::ALoad0 => self.interpret_aload(0), Instruction::ALoad1 => self.interpret_aload(1), Instruction::ALoad2 => self.interpret_aload(2), Instruction::ALoad3 => self.interpret_aload(3), Instruction::ALoad(idx) => self.interpret_aload(*idx), Instruction::AStore0 => self.interpret_astore(0), Instruction::AStore1 => self.interpret_astore(1), Instruction::AStore2 => self.interpret_astore(2), Instruction::AStore3 => self.interpret_astore(3), Instruction::AStore(idx) => self.interpret_astore(*idx), Instruction::IAdd => { let frame_mut = self.current_frame_mut(); let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match (left, right) { (Value::Integer(l), Value::Integer(r)) => { frame_mut .operand_stack .push(Value::Integer(l.wrapping_add(r))); Ok(None) } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::LAdd => { let frame_mut = self.current_frame_mut(); let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ladd but insufficient arguments")); }; let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ladd but insufficient arguments")); }; match (left, right) { (Value::Long(l), Value::Long(r)) => { frame_mut .operand_stack .push(Value::Long(l.wrapping_add(r))); Ok(None) } _ => Err(VMError::BadClass("ladd but invalid operand types")), } } Instruction::ISub => { let frame_mut = self.current_frame_mut(); let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match (left, right) { (Value::Integer(l), Value::Integer(r)) => { frame_mut .operand_stack .push(Value::Integer(l.wrapping_sub(r))); Ok(None) } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::IAnd => { let frame_mut = self.current_frame_mut(); let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iand but insufficient arguments")); }; let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iand but insufficient arguments")); }; match (left, right) { (Value::Integer(l), Value::Integer(r)) => { frame_mut .operand_stack .push(Value::Integer(l & r)); Ok(None) } _ => Err(VMError::BadClass("iand but invalid operand types")), } } Instruction::IOr => { let frame_mut = self.current_frame_mut(); let left = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ior but insufficient arguments")); }; let right = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ior but insufficient arguments")); }; match (left, right) { (Value::Integer(l), Value::Integer(r)) => { frame_mut .operand_stack .push(Value::Integer(l | r)); Ok(None) } _ => Err(VMError::BadClass("ior but invalid operand types")), } } Instruction::IShr => { let frame_mut = self.current_frame_mut(); let value2 = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ishr but insufficient arguments")); }; let value1 = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ishr but insufficient arguments")); }; match (value1, value2) { (Value::Integer(v1), Value::Integer(v2)) => { frame_mut .operand_stack .push(Value::Integer(v1 >> (v2 & 0x1f))); Ok(None) } _ => Err(VMError::BadClass("ishr but invalid operand types")), } } Instruction::IShl => { let frame_mut = self.current_frame_mut(); let value2 = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ishl but insufficient arguments")); }; let value1 = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ishl but insufficient arguments")); }; match (value1, value2) { (Value::Integer(v1), Value::Integer(v2)) => { frame_mut .operand_stack .push(Value::Integer(v1 << (v2 & 0x1f))); Ok(None) } _ => Err(VMError::BadClass("ishl but invalid operand types")), } } Instruction::I2B => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match value { Value::Integer(l) => { frame_mut .operand_stack .push(Value::Integer(l as i8 as i32)); Ok(None) } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::I2C => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("iadd but insufficient arguments")); }; match value { Value::Integer(l) => { frame_mut .operand_stack .push(Value::Integer(l as i16 as u16 as i32)); Ok(None) } _ => Err(VMError::BadClass("iadd but invalid operand types")), } } Instruction::IReturn => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ireturn but insufficient arguments")); }; match value { Value::Integer(_) => { self.leave(); Ok(Some(value)) } _ => Err(VMError::BadClass("ireturn but invalid operand types")), } } Instruction::AReturn => { let frame_mut = self.current_frame_mut(); let value = if let Some(value) = frame_mut.operand_stack.pop() { value } else { return Err(VMError::BadClass("ireturn but insufficient arguments")); }; match value { Value::Array(_) => { self.leave(); Ok(Some(value)) } _ => Err(VMError::BadClass("ireturn but invalid operand types")), } } Instruction::Ldc(c) => { let value = match &**c { Constant::Integer(i) => Value::Integer(*i as i32), Constant::Long(l) => Value::Long(*l as i64), Constant::String(s) => { Value::String(Rc::new(s.bytes().collect())) } _ => { return Err(VMError::Unsupported("unsupported constant type for ldc")); } }; self.current_frame_mut().operand_stack.push(value); Ok(None) } Instruction::Return => { self.leave(); Ok(None) } _ => { unimplemented!(); } } } #[allow(dead_code)] fn return_value(&mut self) -> Option<Value> { // panic!("Hello there"); None } } #[derive(Debug)] pub enum Value { Integer(i32), Long(i64), Float(f32), Double(f64), Array(Rc<RefCell<Box<[Value]>>>), String(Rc<Vec<u8>>), Object(Rc<RefCell<HashMap<String, Value>>>, Rc<ClassFile>), Null(String), // Null, of type `String` } impl Clone for Value { fn clone(&self) -> Self { match self { Value::Integer(v) => Value::Integer(*v), Value::Long(v) => Value::Long(*v), Value::Float(v) => Value::Float(*v), Value::Double(v) => Value::Double(*v), Value::Array(v) => Value::Array(Rc::clone(v)), Value::String(v) => Value::String(Rc::clone(v)), Value::Object(v1, v2) => Value::Object(Rc::clone(v1), Rc::clone(v2)), Value::Null(v) => Value::Null(v.clone()), } } } impl Value { pub fn new_inst(class_file: Rc<ClassFile>) -> Value { let mut fields = HashMap::new(); // TODO: respect type and access flags of fields for field in class_file.fields.iter() { fields.insert( field.name.clone(), Value::default_of( &field.desc, ), ); } Value::Object(Rc::new(RefCell::new(fields)), class_file) } pub fn default_of(s: &str) -> Value { match s { "J" => Value::Long(0), "B" | "C" | "S" | "Z" | "I" => Value::Integer(0), "F" => Value::Float(0.0), "D" => Value::Double(0.0), // Lasdf; reference type // [ array // [[Lasdf; asdf[][] other => Value::Null(other.to_string()), } } pub fn parse_from(s: &str) -> Option<Value> { if s == "null" { return Some(Value::Null("Object".to_string())); } if let Ok(v) = i64::from_str(s) { return Some(Value::Integer(v as i32)); } if let Ok(v) = f64::from_str(s) { return Some(Value::Double(v)); } if s.len() >= 2 && s.starts_with("\"") && s.ends_with("\"") { return Some(Value::String(Rc::new(s[1..][..s.len() - 2].bytes().collect()))); } return None; } } pub(crate) struct ValueRef(Value); impl ValueRef { pub fn of(reference: &Value) -> Self { ValueRef(reference.clone()) } } impl Hash for ValueRef { fn hash<H: Hasher>(&self, state: &mut H) { match &self.0 { Value::Integer(v) => v.hash(state), Value::Long(v) => v.hash(state), Value::Float(v) => v.to_bits().hash(state), Value::Double(v) => v.to_bits().hash(state), Value::Array(v) => { unsafe { let ptr = Rc::into_raw(Rc::clone(v)); ptr.hash(state); Rc::from_raw(ptr); } }, Value::String(v) => { unsafe { let ptr = Rc::into_raw(Rc::clone(v)); ptr.hash(state); Rc::from_raw(ptr); } }, Value::Object(v1, v2) => { unsafe { let ptr = Rc::into_raw(Rc::clone(v1)); ptr.hash(state); Rc::from_raw(ptr); let ptr = Rc::into_raw(Rc::clone(v2)); ptr.hash(state); Rc::from_raw(ptr); } } Value::Null(v) => v.hash(state), } } } impl Eq for ValueRef {} impl PartialEq for ValueRef { fn eq(&self, other: &ValueRef) -> bool { match (&self.0, &other.0) { (Value::Integer(v1), Value::Integer(v2)) => { v1 == v2 }, (Value::Long(v1), Value::Long(v2)) => { v1 == v2 }, (Value::Float(v1), Value::Float(v2)) => { v1 == v2 }, (Value::Double(v1), Value::Double(v2)) => { v1 == v2 }, (Value::Array(v1), Value::Array(v2)) => { Rc::ptr_eq(v1, v2) }, (Value::Object(v1, _), Value::Object(v2, _)) => { Rc::ptr_eq(v1, v2) }, (Value::String(v1), Value::String(v2)) => { Rc::ptr_eq(v1, v2) }, (Value::Null(v1), Value::Null(v2)) => { v1 == v2 }, _ => false, } } } #[allow(dead_code)] enum NativeObject { StringBuilder(Vec<u16>), Unknown, } pub struct VirtualMachine { classes: HashMap<String, Rc<ClassFile>>, static_instances: HashMap<ClassFileRef, HashMap<String, Value>>, native_instances: HashMap<ValueRef, RefCell<NativeObject>>, } #[derive(Debug)] pub enum VMError { TypeError, NameResolutionError, ClassLoadError, AccessError(&'static str), BadClass(&'static str), Unsupported(&'static str), } impl VirtualMachine { pub fn new() -> Self { VirtualMachine { classes: HashMap::new(), static_instances: HashMap::new(), native_instances: HashMap::new(), } } fn get_static_field( &mut self, class_ref: &Rc<ClassFile>, name: &str, ty: &str, ) -> Option<Value> { let fields = self .static_instances .entry(ClassFileRef::of(class_ref)) .or_insert_with(|| HashMap::new()); if class_ref.has_static_field(name) { Some(fields.entry(name.to_string()).or_insert_with( || Value::default_of(ty) ).clone()) } else { None } } fn put_static_field( &mut self, class_ref: &Rc<ClassFile>, name: &str, ty: &str, value: Value, ) { let fields = self .static_instances .entry(ClassFileRef::of(class_ref)) .or_insert_with(|| HashMap::new()); if class_ref.has_static_field(name) { fields.insert(name.to_owned(), value); } else { panic!("no field {} on {}", name, ty); } } pub fn resolve_class(&mut self, referent: &str) -> Result<Rc<ClassFile>, VMError> { if let Some(class_file) = self.classes.get(referent) { return Ok(Rc::clone(class_file)); } let new_class = match referent { "java/lang/String" => { let constants = vec![ UnvalidatedConstant::Utf8(b"java/lang/String".to_vec()), UnvalidatedConstant::Utf8(b"<init>".to_vec()), UnvalidatedConstant::Utf8(b"hashCode".to_vec()), UnvalidatedConstant::Utf8(b"()I".to_vec()), UnvalidatedConstant::Utf8(b"(Ljava/lang/String;)".to_vec()), UnvalidatedConstant::Utf8(b"([B)V".to_vec()), UnvalidatedConstant::Utf8(b"[B".to_vec()), UnvalidatedConstant::Utf8(b"value".to_vec()), UnvalidatedConstant::Utf8(b"(Ljava/lang/String;)Ljava/lang/String;".to_vec()), UnvalidatedConstant::Utf8(b"concat".to_vec()), ]; let mut native_methods: HashMap< String, fn(&mut VMState, &mut VirtualMachine) -> Result<(), VMError>, > = HashMap::new(); native_methods.insert("<init>(Ljava/lang/String;)".to_string(), string_init_string); native_methods.insert("<init>([B)V".to_string(), string_init_bytearray); native_methods.insert("hashCode()I".to_string(), string_hashcode); native_methods.insert( "concat(Ljava/lang/String;)Ljava/lang/String;".to_string(), string_concat, ); let synthetic_class = ClassFile::validate(&UnvalidatedClassFile { major_version: 55, minor_version: 0, constant_pool: constants, access_flags: AccessFlags { flags: 0x0001 }, this_class: ConstantIdx::new(1).unwrap(), super_class: None, interfaces: Vec::new(), fields: vec![FieldInfo { access_flags: FieldAccessFlags { flags: 0x0001 }, name_index: ConstantIdx::new(8).unwrap(), descriptor_index: ConstantIdx::new(7).unwrap(), attributes: Vec::new(), }], methods: vec![ MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(5).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(6).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(3).unwrap(), descriptor_index: ConstantIdx::new(4).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(10).unwrap(), descriptor_index: ConstantIdx::new(9).unwrap(), attributes: Vec::new(), }, ], attributes: vec![], native_methods, }).unwrap(); synthetic_class } "java/lang/StringBuilder" => { let constants = vec![ UnvalidatedConstant::Utf8(b"java/lang/StringBuilder".to_vec()), UnvalidatedConstant::Utf8(b"<init>".to_vec()), UnvalidatedConstant::Utf8(b"()V".to_vec()), UnvalidatedConstant::Utf8(b"(Ljava/lang/String;)V".to_vec()), UnvalidatedConstant::Utf8(b"append".to_vec()), // UnvalidatedConstant::Utf8(b"(B)Ljava/lang/String;".to_vec()), // UnvalidatedConstant::Utf8(b"(C)Ljava/lang/String;".to_vec()), // UnvalidatedConstant::Utf8(b"([C)Ljava/lang/String;".to_vec()), UnvalidatedConstant::Utf8(b"(Ljava/lang/String;)Ljava/lang/StringBuilder;".to_vec()), UnvalidatedConstant::Utf8(b"toString".to_vec()), UnvalidatedConstant::Utf8(b"()Ljava/lang/String;".to_vec()), ]; let mut native_methods: HashMap< String, fn(&mut VMState, &mut VirtualMachine) -> Result<(), VMError>, > = HashMap::new(); native_methods.insert("<init>()V".to_string(), stringbuilder_init); native_methods.insert("<init>(Ljava/lang/String;)V".to_string(), string_init_string); native_methods.insert("append(Ljava/lang/String;)Ljava/lang/StringBuilder;".to_string(), stringbuilder_append_string); // native_methods.insert("append([C)Ljava/lang/StringBuilder".to_string(), stringbuilder_append_chars); native_methods.insert("toString()Ljava/lang/String;".to_string(), stringbuilder_tostring); let synthetic_class = ClassFile::validate(&UnvalidatedClassFile { major_version: 55, minor_version: 0, constant_pool: constants, access_flags: AccessFlags { flags: 0x0001 }, this_class: ConstantIdx::new(1).unwrap(), super_class: None, interfaces: Vec::new(), fields: vec![], methods: vec![ MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(3).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(4).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(5).unwrap(), descriptor_index: ConstantIdx::new(6).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(7).unwrap(), descriptor_index: ConstantIdx::new(8).unwrap(), attributes: Vec::new(), }, ], attributes: vec![], native_methods, }).unwrap(); synthetic_class } "java/lang/System" => { let constants = vec![ UnvalidatedConstant::Utf8(b"java/lang/System".to_vec()), UnvalidatedConstant::Utf8(b"out".to_vec()), UnvalidatedConstant::Utf8(b"Ljava/io/PrintStream;".to_vec()), UnvalidatedConstant::Utf8(b"exit".to_vec()), UnvalidatedConstant::Utf8(b"(I)V".to_vec()), ]; let mut native_methods: HashMap< String, fn(&mut VMState, &mut VirtualMachine) -> Result<(), VMError>, > = HashMap::new(); native_methods.insert("exit(I)V".to_string(), system_exit); let synthetic_class = ClassFile::validate(&UnvalidatedClassFile { major_version: 55, minor_version: 0, constant_pool: constants, access_flags: AccessFlags { flags: 0x0001 }, this_class: ConstantIdx::new(1).unwrap(), super_class: None, interfaces: Vec::new(), fields: vec![FieldInfo { access_flags: FieldAccessFlags { flags: 0x0009 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(3).unwrap(), attributes: Vec::new(), }], methods: vec![ MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(4).unwrap(), descriptor_index: ConstantIdx::new(5).unwrap(), attributes: Vec::new(), }, ], attributes: vec![], native_methods, }).unwrap(); synthetic_class } "java/io/PrintStream" => { let constants = vec![ UnvalidatedConstant::Utf8(b"java/io/PrintStream".to_vec()), UnvalidatedConstant::Utf8(b"println".to_vec()), UnvalidatedConstant::Utf8(b"(Ljava/lang/String;)V".to_vec()), UnvalidatedConstant::Utf8(b"(I)V".to_vec()), UnvalidatedConstant::Utf8(b"(J)V".to_vec()), ]; let mut native_methods: HashMap< String, fn(&mut VMState, &mut VirtualMachine) -> Result<(), VMError>, > = HashMap::new(); native_methods.insert("println(Ljava/lang/String;)V".to_string(), system_out_println_string); native_methods.insert("println(I)V".to_string(), system_out_println_int); native_methods.insert("println(J)V".to_string(), system_out_println_long); let synthetic_class = ClassFile::validate(&UnvalidatedClassFile { major_version: 55, minor_version: 0, constant_pool: constants, access_flags: AccessFlags { flags: 0x0001 }, this_class: ConstantIdx::new(1).unwrap(), super_class: None, interfaces: Vec::new(), fields: vec![], methods: vec![ MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(3).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(4).unwrap(), attributes: Vec::new(), }, MethodInfo { access_flags: MethodAccessFlags { flags: 0x0101 }, name_index: ConstantIdx::new(2).unwrap(), descriptor_index: ConstantIdx::new(5).unwrap(), attributes: Vec::new(), }, ], attributes: vec![], native_methods, }).unwrap(); synthetic_class } class_name => { // println!("Looking up class {}", class_name); return match self.classes.get(class_name) { Some(class_ref) => Ok(Rc::clone(class_ref)), None => Err(VMError::BadClass("unknown class, cannot dynamically ")), }; } }; self.register(referent.to_string(), new_class) } pub fn register( &mut self, class_name: String, class_file: ClassFile, ) -> Result<Rc<ClassFile>, VMError> { // println!("Registering class {}", class_name);; let rc = Rc::new(class_file); self.classes.insert(class_name, Rc::clone(&rc)); if let Some(method) = rc.get_method("<clinit>", "()V") { let mut state = VMState::new( Rc::clone(method.body.as_ref().expect("clinit has a body")), Rc::clone(&rc), vec![], ); let clinit_res = self .interpret(&mut state) .expect("clinit executes successfully"); if clinit_res.is_some() { panic!("clinit should not return values"); } } // else no static initializer Ok(rc) } pub fn execute( &mut self, method: Rc<MethodHandle>, class_ref: &Rc<ClassFile>, args: Vec<Value>, ) -> Result<Option<Value>, VMError> { if !method.access().is_static() { return Err(VMError::AccessError( "attempted to call an instance method without an instance", )); } if !method.access().is_public() { return Err(VMError::AccessError( "attempted to initiate VM with non-public function", )); } let code = method.body.as_ref().ok_or(VMError::AccessError( "attempted to initiate VM with function that has no body", ))?; // TODO: verify arguments? verify that `method` does not take arguments?? let mut state = VMState::new(Rc::clone(code), Rc::clone(class_ref), args); self.interpret(&mut state) } fn interpret(&mut self, state: &mut VMState) -> Result<Option<Value>, VMError> { // magic incantation to awaken the machine println!("zoom zoom"); while let Some(instruction) = state.next_instruction() { // println!("Executing {:?}", instruction); // let enc = &*state.current_frame().enclosing_class; // println!("Executing {}", instruction); if let Some(value) = state.execute(&instruction, self)? { // TODO: type check the return value if state.call_stack.len() == 0 { // this was a return from the first call frame, so it's the result of the // entire interpreter execution return Ok(Some(value)); } else { // this was an inner return, so push it onto the caller's operand stack state.current_frame_mut().operand_stack.push(value); } } // println!("Complete!"); } Ok(None) // Ok(state.return_value()) } } fn interpreted_method_call( state: &mut VMState, _vm: &mut VirtualMachine, method: Rc<MethodHandle>, method_class: Rc<ClassFile>, method_type: &str, ) -> Result<(), VMError> { // TODO: parse out arguments from method type, check against available operands, do the call // // today: [...], do the call if method_type == "(I)I" { let frame = state.current_frame_mut(); let arg = frame.operand_stack.pop().expect("argument is present"); state.enter( Rc::clone(method.body.as_ref().expect("method has a body")), method_class, vec![arg], ); } else if method_type == "(I)V" { let frame = state.current_frame_mut(); let arg = frame.operand_stack.pop().expect("argument is present"); state.enter( Rc::clone(method.body.as_ref().expect("method has a body")), method_class, vec![arg], ); } else { state.enter( Rc::clone(method.body.as_ref().expect("method has a body")), method_class, vec![], ); } Ok(()) } fn system_out_println_string(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let _receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let Value::String(data) = argument { if let Ok(string) = std::str::from_utf8(data.as_slice()) { println!("{}", string); } else { panic!("executing System.out.println(\"{:?}\")", data); } } else if let Value::Object(fields, _) = argument { if let Value::Array(elements) = &fields.borrow()["value"] { for el in elements.borrow().iter() { if let Value::Integer(v) = el { print!("{}", *v as u8 as char); } else { panic!("string contains non-byte element") } } print!("\n"); } else { panic!("string does not contain value"); } } else { panic!("type error, expected string, got {:?}", argument); } Ok(()) } fn system_out_println_int(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let _receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let Value::Integer(v) = argument { println!("{}", v); } else { panic!("type error, expected string, got {:?}", argument); } Ok(()) } fn system_out_println_long(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let _receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let Value::Long(v) = argument { println!("{}", v); } else { panic!("type error, expected string, got {:?}", argument); } Ok(()) } // "<init>()V" fn stringbuilder_init(state: &mut VMState, vm: &mut VirtualMachine) -> Result<(), VMError> { let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let data = RefCell::new(NativeObject::StringBuilder(Vec::new())); vm.native_instances.insert(ValueRef::of(&receiver), data); Ok(()) } // "append(Ljava/lang/String;);Ljava/lang/StringBuilder" fn stringbuilder_append_string(state: &mut VMState, vm: &mut VirtualMachine) -> Result<(), VMError> { let appendee = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let data = vm.native_instances.get(&ValueRef::of(&receiver)).expect("stringbuilder receiver has associated native data"); if let NativeObject::StringBuilder(data) = &mut *data.borrow_mut() { if let Value::String(str_data) = appendee { // do thing for el in str_data.iter() { data.push(*el as u16); } } else if let Value::Object(fields, _) = appendee { // do thing if let Value::Array(str_data) = &fields.borrow()["value"] { let str_data = str_data.borrow(); for el in str_data.iter() { if let Value::Integer(i) = el { data.push(*i as u16); } } } else { panic!("appendee of stringbuilder is a non-string object"); } } else { panic!("appendee of stringbuilder append is not a string"); } } else { panic!("native object corresponding to stringbuilder receiver is not stringbuilder data"); } state.current_frame_mut().operand_stack.push(receiver); Ok(()) } // "toString()Ljava/lang/String" fn stringbuilder_tostring(state: &mut VMState, vm: &mut VirtualMachine) -> Result<(), VMError> { // really just consume the argument let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let data = vm.native_instances.get(&ValueRef::of(&receiver)).expect("stringbuilder receiver has associated native data"); let mut str_data: Vec<Value> = Vec::new(); if let NativeObject::StringBuilder(data) = &*data.borrow() { for el in data.iter() { str_data.push(Value::Integer(*el as i32)); } } else { panic!("native object corresponding to stringbuilder receiver is not stringbuilder data"); } // now make the string to return... let mut string_fields = HashMap::new(); string_fields.insert("value".to_string(), Value::Array(Rc::new(RefCell::new(str_data.into_boxed_slice())))); let s = Value::Object(Rc::new(RefCell::new(string_fields)), vm.resolve_class("java/lang/String")?); state.current_frame_mut().operand_stack.push(s); Ok(()) } /* native_methods.insert("<init>(Ljava/lang/String;)V".to_string(), string_init_string); native_methods.insert("append(Ljava/lang/String;)Ljava/lang/StringBuilder".to_string(), stringbuilder_append_string); // native_methods.insert("append([C)Ljava/lang/StringBuilder".to_string(), stringbuilder_append_chars); native_methods.insert("toString()Ljava/lang/String".to_string(), stringbuilder_tostring); */ // "<init>(Ljava/lang/String;)V" fn string_init_string(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let (Value::Object(argument, _), Value::Object(receiver, _)) = (&argument, &receiver) { let new_value = argument.borrow()["value"].clone(); receiver.borrow_mut().insert("value".to_string(), new_value); } else { panic!("type error, expected string, got {:?}", argument); } Ok(()) } // "<init>([B)" fn string_init_bytearray(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let (Value::Array(new_elems), Value::Object(fields, _)) = (&argument, &receiver) { let mut str_elems = Vec::new(); for el in new_elems.borrow().iter() { if let Value::Integer(i) = el { if (*i as u8) < 128 { str_elems.push(Value::Integer(*i)); } else { str_elems.push(Value::Integer(0xfffd)); } } else { panic!("bad string"); } } fields.borrow_mut().insert( "value".to_string(), Value::Array(Rc::new(RefCell::new(str_elems.into_boxed_slice()))), ); } else { panic!("type error, expected string, got {:?}", argument); } Ok(()) } // "hashCode()I" fn string_hashcode(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let Value::String(data) = receiver { let mut hashcode: i32 = 0; for c in data.iter().cloned() { // value is actually a char array hashcode = hashcode.wrapping_mul(31).wrapping_add(c as u16 as i32); } state .current_frame_mut() .operand_stack .push(Value::Integer(hashcode)); } else if let Value::Object(fields, _) = receiver { let mut hashcode: i32 = 0; if let Value::Array(elems) = &fields.borrow()["value"] { for c in elems.borrow().iter() { if let Value::Integer(v) = c { // value is actually a char array hashcode = hashcode.wrapping_mul(31).wrapping_add(*v as u16 as i32); } else { panic!("string contains non-byte element"); } } state .current_frame_mut() .operand_stack .push(Value::Integer(hashcode)); } else { panic!("string does not have a value?"); } } else { panic!("type error, expected string, got {:?}", receiver); } Ok(()) } // "concat(Ljava/lang/String;)Ljava/lang/String;" fn string_concat(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); let receiver = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let (Value::String(base), Value::String(ext)) = (&receiver, &argument) { state .current_frame_mut() .operand_stack .push(Value::String( Rc::new(base.iter().cloned().chain(ext.iter().cloned()).collect()), )); } else { panic!("type error, expected string, string, got {:?}", argument); } Ok(()) } fn system_exit(state: &mut VMState, _vm: &mut VirtualMachine) -> Result<(), VMError> { let argument = state .current_frame_mut() .operand_stack .pop() .expect("argument available"); if let Value::Integer(i) = argument { std::process::exit(i); } else { panic!("attempted to exit with non-int operand"); } }
use super::VarResult; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::err_msgs::*; use crate::helper::str_replace; use crate::helper::{ move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64, pine_ref_to_string, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::output::{OutputData, OutputInfo, PlotInfo, StrOptionsData}; use crate::types::{ Bool, Callable, CallableObject, Color, DataType, Float, Int, Object, ParamCollectCall, PineClass, PineFrom, PineRef, PineType, RefData, RuntimeErr, SecondType, Series, SeriesCall, NA, }; use std::collections::BTreeMap; use std::rc::Rc; struct PlotProps; pub const YLOC_PRICE: &'static str = "price"; pub const YLOC_ABOVEBAR: &'static str = "abovebar"; pub const YLOC_BELOWBAR: &'static str = "belowbar"; impl<'a> PineClass<'a> for PlotProps { fn custom_type(&self) -> &str { "yloc" } fn get(&self, _ctx: &mut dyn Ctx<'a>, name: &str) -> Result<PineRef<'a>, RuntimeErr> { match name { "price" => Ok(PineRef::new_rc(String::from(YLOC_PRICE))), "abovebar" => Ok(PineRef::new_rc(String::from(YLOC_ABOVEBAR))), "belowbar" => Ok(PineRef::new_rc(String::from(YLOC_BELOWBAR))), _ => Err(RuntimeErr::NotImplement(str_replace( NO_FIELD_IN_OBJECT, vec![String::from(name), String::from("yloc")], ))), } } fn copy(&self) -> Box<dyn PineClass<'a> + 'a> { Box::new(PlotProps) } } pub const VAR_NAME: &'static str = "yloc"; pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(Object::new(Box::new(PlotProps))); let mut obj_type = BTreeMap::new(); obj_type.insert("price", SyntaxType::string()); obj_type.insert("abovebar", SyntaxType::string()); obj_type.insert("belowbar", SyntaxType::string()); let syntax_type = SyntaxType::Object(Rc::new(obj_type)); VarResult::new(value, syntax_type, VAR_NAME) } #[cfg(test)] mod tests { use super::*; use crate::runtime::{AnySeries, NoneCallback}; use crate::{LibInfo, PineParser, PineRunner}; #[test] fn xloc_test() { use crate::ast::stat_expr_types::VarIndex; use crate::runtime::VarOperate; use crate::types::{downcast_pf, Tuple}; let lib_info = LibInfo::new( vec![declare_var()], vec![("close", SyntaxType::float_series())], ); let src = r"m = [ yloc.abovebar, yloc.belowbar, yloc.price ]"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![("close", AnySeries::from_float_vec(vec![Some(1f64)]))], None, ) .unwrap(); let tuple_res = downcast_pf::<Tuple>(runner.get_context().move_var(VarIndex::new(0, 0)).unwrap()); let tuple_vec = tuple_res.unwrap().into_inner().0; assert_eq!( tuple_vec, vec![ PineRef::new_rc(String::from("abovebar")), PineRef::new_rc(String::from("belowbar")), PineRef::new_rc(String::from("price")), ] ); } }
use crate::{Fields, Field, Value}; use std::fmt; pub trait Structable { fn fields(&self) -> Fields; // fn field_by_name(&self, name: &str) -> Option<Field>; fn get(&self, field: &Field) -> Option<Value<'_>>; } pub(crate) fn debug(value: &dyn Structable, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut f = fmt.debug_struct(""); for field in value.fields().iter() { f.field(field.name(), &value.get(&field).unwrap()); } f.finish() }
use std::net::Ipv4Addr; use std::net::SocketAddrV6; use ed25519_dalek::PublicKey; use tokio_util::codec::{Decoder, Encoder}; use bytes::BytesMut; use nanocurrency_types::*; use Message; use NanoCurrencyCodec; /// A list of blocks for testing fn get_test_blocks() -> Vec<Block> { let header = BlockHeader { signature: Signature::from_bytes(&[1u8; 64] as _).unwrap(), work: 4, }; vec![ Block { header: header.clone(), inner: BlockInner::Send { previous: BlockHash([2; 32]), destination: Account([3; 32]), balance: 1234567890_1234567890_u128, }, }, Block { header: header.clone(), inner: BlockInner::Receive { previous: BlockHash([2; 32]), source: BlockHash([3; 32]), }, }, Block { header: header.clone(), inner: BlockInner::Open { source: BlockHash([2; 32]), account: Account([3; 32]), representative: Account([4; 32]), }, }, Block { header: header.clone(), inner: BlockInner::Change { previous: BlockHash([2; 32]), representative: Account([3; 32]), }, }, Block { header: header.clone(), inner: BlockInner::State { previous: BlockHash([2; 32]), link: [3; 32], account: Account([4; 32]), representative: Account([5; 32]), balance: 1234567890_1234567890_u128, }, }, ] } fn encode_decode(msg: Message) -> Message { let mut codec = NanoCurrencyCodec(Network::Beta); let mut bytes = BytesMut::new(); assert!(codec.encode(msg.clone(), &mut bytes).is_ok()); let decode = codec .decode(&mut bytes) .expect("Failed to decode generated message") .expect("Codec returned no message"); assert_eq!(decode.0.network, Network::Beta); assert_eq!(decode.1, msg); decode.1 } #[test] fn keepalive() { let mut addrs = [zero_v6_addr!(); 8]; addrs[0] = SocketAddrV6::new(Ipv4Addr::new(22, 33, 44, 55).to_ipv6_mapped(), 1357, 0, 0); addrs[7] = SocketAddrV6::new(Ipv4Addr::new(44, 55, 66, 77).to_ipv6_mapped(), 3579, 0, 0); encode_decode(Message::Keepalive(addrs)); } #[test] fn blocks() { for block in get_test_blocks() { let msg = encode_decode(Message::Publish(block.clone())); if let Message::Publish(msg_block) = msg { assert_eq!(block.header, msg_block.header); } else { unreachable!(); } } } #[test] fn confirm_req() { for block in get_test_blocks() { encode_decode(Message::ConfirmReq(block.clone())); } } #[test] fn confirm_ack() { let mut hashes = Vec::new(); for block in get_test_blocks() { hashes.push(block.get_hash()); encode_decode(Message::ConfirmAck(Vote { account: Account([5; 32]), signature: Signature::from_bytes(&[6u8; 64] as _).unwrap(), sequence: 123456, inner: VoteInner::Block(block.clone()), })); } encode_decode(Message::ConfirmAck(Vote { account: Account([10; 32]), signature: Signature::from_bytes(&[12u8; 64] as _).unwrap(), sequence: 6545321, inner: VoteInner::Hashes(hashes), })); } #[test] fn node_id_handshake() { let query = [1u8; 32]; let response = ( PublicKey::from_bytes(&[2u8; 32]).unwrap(), Signature::from_bytes(&[3u8; 64]).unwrap(), ); encode_decode(Message::NodeIdHandshake(None, None)); encode_decode(Message::NodeIdHandshake(Some(query), None)); encode_decode(Message::NodeIdHandshake(None, Some(response))); encode_decode(Message::NodeIdHandshake(Some(query), Some(response))); }
use gccjit::{RValue, ToRValue, Type}; use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_codegen_ssa::mir::operand::OperandValue; use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::{AsmBuilderMethods, AsmMethods, BaseTypeMethods, BuilderMethods, GlobalAsmOperandRef, InlineAsmOperandRef}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::LlvmInlineAsmInner; use rustc_middle::bug; use rustc_span::Span; use rustc_target::asm::*; use crate::builder::Builder; use crate::context::CodegenCx; use crate::type_of::LayoutGccExt; impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { fn codegen_llvm_inline_asm(&mut self, _ia: &LlvmInlineAsmInner, _outputs: Vec<PlaceRef<'tcx, RValue<'gcc>>>, mut _inputs: Vec<RValue<'gcc>>, _span: Span) -> bool { // TODO return true; /*let mut ext_constraints = vec![]; let mut output_types = vec![]; // Prepare the output operands let mut indirect_outputs = vec![]; for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() { if out.is_rw { let operand = self.load_operand(place); if let OperandValue::Immediate(_) = operand.val { inputs.push(operand.immediate()); } ext_constraints.push(i.to_string()); } if out.is_indirect { let operand = self.load_operand(place); if let OperandValue::Immediate(_) = operand.val { indirect_outputs.push(operand.immediate()); } } else { output_types.push(place.layout.gcc_type(self.cx())); } } if !indirect_outputs.is_empty() { indirect_outputs.extend_from_slice(&inputs); inputs = indirect_outputs; } let clobbers = ia.clobbers.iter().map(|s| format!("~{{{}}}", &s)); // Default per-arch clobbers // Basically what clang does let arch_clobbers = match &self.sess().target.target.arch[..] { "x86" | "x86_64" => vec!["~{dirflag}", "~{fpsr}", "~{flags}"], "mips" | "mips64" => vec!["~{$1}"], _ => Vec::new(), }; let all_constraints = ia .outputs .iter() .map(|out| out.constraint.to_string()) .chain(ia.inputs.iter().map(|s| s.to_string())) .chain(ext_constraints) .chain(clobbers) .chain(arch_clobbers.iter().map(|s| (*s).to_string())) .collect::<Vec<String>>() .join(","); debug!("Asm Constraints: {}", &all_constraints); // Depending on how many outputs we have, the return type is different let num_outputs = output_types.len(); let output_type = match num_outputs { 0 => self.type_void(), 1 => output_types[0], _ => self.type_struct(&output_types, false), }; let asm = ia.asm.as_str(); let r = inline_asm_call( self, &asm, &all_constraints, &inputs, output_type, ia.volatile, ia.alignstack, ia.dialect, ); if r.is_none() { return false; } let r = r.unwrap(); // Again, based on how many outputs we have let outputs = ia.outputs.iter().zip(&outputs).filter(|&(ref o, _)| !o.is_indirect); for (i, (_, &place)) in outputs.enumerate() { let v = if num_outputs == 1 { r } else { self.extract_value(r, i as u64) }; OperandValue::Immediate(v).store(self, place); } // Store mark in a metadata node so we can map LLVM errors // back to source locations. See #17552. unsafe { let key = "srcloc"; let kind = llvm::LLVMGetMDKindIDInContext( self.llcx, key.as_ptr() as *const c_char, key.len() as c_uint, ); let val: &'ll Value = self.const_i32(span.ctxt().outer_expn().as_u32() as i32); llvm::LLVMSetMetadata(r, kind, llvm::LLVMMDNodeInContext(self.llcx, &val, 1)); } true*/ } fn codegen_inline_asm(&mut self, template: &[InlineAsmTemplatePiece], operands: &[InlineAsmOperandRef<'tcx, Self>], options: InlineAsmOptions, span: &[Span]) { let asm_arch = self.tcx.sess.asm_arch.unwrap(); let intel_dialect = match asm_arch { InlineAsmArch::X86 | InlineAsmArch::X86_64 if !options.contains(InlineAsmOptions::ATT_SYNTAX) => true, _ => false, }; // Collect the types of output operands // FIXME: we do this here instead of later because of a bug in libgccjit where creating the // variable after the extended asm expression causes a segfault: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100380 let mut output_vars = FxHashMap::default(); let mut operand_numbers = FxHashMap::default(); let mut current_number = 0; for (idx, op) in operands.iter().enumerate() { match *op { InlineAsmOperandRef::Out { reg, late, place } => { let ty = match place { Some(place) => place.layout.gcc_type(self.cx, false), None => { // If the output is discarded, we don't really care what // type is used. We're just using this to tell GCC to // reserve the register. //dummy_output_type(self.cx, reg.reg_class()) // NOTE: if no output value, we should not create one (it will be a // clobber). continue; }, }; let var = self.current_func().new_local(None, ty, "output_register"); operand_numbers.insert(idx, current_number); current_number += 1; output_vars.insert(idx, var); } InlineAsmOperandRef::InOut { reg, late, out_place, .. } => { let ty = match out_place { Some(place) => place.layout.gcc_type(self.cx, false), None => { // If the output is discarded, we don't really care what // type is used. We're just using this to tell GCC to // reserve the register. //dummy_output_type(self.cx, reg.reg_class()) // NOTE: if no output value, we should not create one. continue; }, }; operand_numbers.insert(idx, current_number); current_number += 1; let var = self.current_func().new_local(None, ty, "output_register"); output_vars.insert(idx, var); } _ => {} } } // All output operands must come before the input operands, hence the 2 loops. for (idx, op) in operands.iter().enumerate() { match *op { InlineAsmOperandRef::In { .. } | InlineAsmOperandRef::InOut { .. } => { operand_numbers.insert(idx, current_number); current_number += 1; }, _ => (), } } // Build the template string let mut template_str = String::new(); for piece in template { match *piece { InlineAsmTemplatePiece::String(ref string) => { if string.contains('%') { for c in string.chars() { if c == '%' { template_str.push_str("%%"); } else { template_str.push(c); } } } else { template_str.push_str(string) } } InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => { match operands[operand_idx] { InlineAsmOperandRef::Out { reg, place: Some(_), .. } => { let modifier = modifier_to_gcc(asm_arch, reg.reg_class(), modifier); if let Some(modifier) = modifier { template_str.push_str(&format!("%{}{}", modifier, operand_numbers[&operand_idx])); } else { template_str.push_str(&format!("%{}", operand_numbers[&operand_idx])); } }, InlineAsmOperandRef::Out { reg, place: None, .. } => { unimplemented!("Out None"); }, InlineAsmOperandRef::In { reg, .. } | InlineAsmOperandRef::InOut { reg, .. } => { let modifier = modifier_to_gcc(asm_arch, reg.reg_class(), modifier); if let Some(modifier) = modifier { template_str.push_str(&format!("%{}{}", modifier, operand_numbers[&operand_idx])); } else { template_str.push_str(&format!("%{}", operand_numbers[&operand_idx])); } } InlineAsmOperandRef::Const { ref string } => { // Const operands get injected directly into the template template_str.push_str(string); } InlineAsmOperandRef::SymFn { .. } | InlineAsmOperandRef::SymStatic { .. } => { unimplemented!(); // Only emit the raw symbol name //template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx])); } } } } } let block = self.llbb(); let template_str = if intel_dialect { template_str } else { // FIXME: this might break the "m" memory constraint: // https://stackoverflow.com/a/9347957/389119 // TODO: only set on x86 platforms. format!(".att_syntax noprefix\n\t{}\n\t.intel_syntax noprefix", template_str) }; let extended_asm = block.add_extended_asm(None, &template_str); // Collect the types of output operands let mut output_types = vec![]; for (idx, op) in operands.iter().enumerate() { match *op { InlineAsmOperandRef::Out { reg, late, place } => { let ty = match place { Some(place) => place.layout.gcc_type(self.cx, false), None => { // If the output is discarded, we don't really care what // type is used. We're just using this to tell GCC to // reserve the register. dummy_output_type(self.cx, reg.reg_class()) }, }; output_types.push(ty); //op_idx.insert(idx, constraints.len()); let prefix = if late { "=" } else { "=&" }; let constraint = format!("{}{}", prefix, reg_to_gcc(reg)); if place.is_some() { let var = output_vars[&idx]; extended_asm.add_output_operand(None, &constraint, var); } else { // NOTE: reg.to_string() returns the register name with quotes around it so // remove them. extended_asm.add_clobber(reg.to_string().trim_matches('"')); } } InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => { let ty = match out_place { Some(out_place) => out_place.layout.gcc_type(self.cx, false), None => dummy_output_type(self.cx, reg.reg_class()) }; output_types.push(ty); //op_idx.insert(idx, constraints.len()); // TODO: prefix of "+" for reading and writing? let prefix = if late { "=" } else { "=&" }; let constraint = format!("{}{}", prefix, reg_to_gcc(reg)); if out_place.is_some() { let var = output_vars[&idx]; // TODO: also specify an output operand when out_place is none: that would // be the clobber but clobbers do not support general constraint like reg; // they only support named registers. // Not sure how we can do this. And the LLVM backend does not seem to add a // clobber. extended_asm.add_output_operand(None, &constraint, var); } let constraint = reg_to_gcc(reg); extended_asm.add_input_operand(None, &constraint, in_value.immediate()); } InlineAsmOperandRef::In { reg, value } => { let constraint = reg_to_gcc(reg); extended_asm.add_input_operand(None, &constraint, value.immediate()); } _ => {} } } // Collect input operands //let mut constraints = vec![]; //let mut op_idx = FxHashMap::default(); //let mut inputs = vec![]; for (idx, op) in operands.iter().enumerate() { match *op { InlineAsmOperandRef::In { reg, value } => { //inputs.push(value.immediate()); //op_idx.insert(idx, constraints.len()); //constraints.push(reg_to_gcc(reg)); } InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => { //inputs.push(in_value.immediate()); //constraints.push(format!("{}", op_idx[&idx])); } InlineAsmOperandRef::SymFn { instance } => { //inputs.push(self.cx.get_fn(instance)); //op_idx.insert(idx, constraints.len()); //constraints.push("s".to_string()); } InlineAsmOperandRef::SymStatic { def_id } => { //inputs.push(self.cx.get_static(def_id)); //op_idx.insert(idx, constraints.len()); //constraints.push("s".to_string()); } _ => {} } } /*if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) { match asm_arch { InlineAsmArch::AArch64 | InlineAsmArch::Arm => { constraints.push("~{cc}".to_string()); } InlineAsmArch::X86 | InlineAsmArch::X86_64 => { constraints.extend_from_slice(&[ "~{dirflag}".to_string(), "~{fpsr}".to_string(), "~{flags}".to_string(), ]); } InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {} } } if !options.contains(InlineAsmOptions::NOMEM) { // This is actually ignored by LLVM, but it's probably best to keep // it just in case. LLVM instead uses the ReadOnly/ReadNone // attributes on the call instruction to optimize. constraints.push("~{memory}".to_string()); } let volatile = !options.contains(InlineAsmOptions::PURE); let alignstack = !options.contains(InlineAsmOptions::NOSTACK); let output_type = match &output_types[..] { [] => self.type_void(), [ty] => ty, tys => self.type_struct(&tys, false), };*/ /*let result = inline_asm_call( self, &template_str, &constraints.join(","), &inputs, output_type, volatile, alignstack, dialect, span, ) .unwrap_or_else(|| span_bug!(span, "LLVM asm constraint validation failed")); if options.contains(InlineAsmOptions::PURE) { if options.contains(InlineAsmOptions::NOMEM) { llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result); } else if options.contains(InlineAsmOptions::READONLY) { llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result); } } else { if options.contains(InlineAsmOptions::NOMEM) { llvm::Attribute::InaccessibleMemOnly .apply_callsite(llvm::AttributePlace::Function, result); } else { // LLVM doesn't have an attribute to represent ReadOnly + SideEffect } }*/ // Write results to outputs for (idx, op) in operands.iter().enumerate() { if let InlineAsmOperandRef::Out { reg, place: Some(place), .. } | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op { OperandValue::Immediate(output_vars[&idx].to_rvalue()).store(self, place); } } } } /// Converts a register class to a GCC constraint code. // TODO: return &'static str instead? fn reg_to_gcc(reg: InlineAsmRegOrRegClass) -> String { match reg { // For vector registers LLVM wants the register name to match the type size. InlineAsmRegOrRegClass::Reg(reg) => { // TODO: add support for vector register. let constraint = match reg.name() { "ax" => "a", "bx" => "b", "cx" => "c", "dx" => "d", "si" => "S", "di" => "D", // TODO: for registers like r11, we have to create a register variable: https://stackoverflow.com/a/31774784/389119 // TODO: in this case though, it's a clobber, so it should work as r11. // Recent nightly supports clobber() syntax, so update to it. It does not seem // like it's implemented yet. name => name, // FIXME: probably wrong. }; constraint.to_string() }, InlineAsmRegOrRegClass::RegClass(reg) => match reg { InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => unimplemented!(), InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => unimplemented!(), InlineAsmRegClass::Bpf(_) => unimplemented!(), InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => unimplemented!(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => unimplemented!(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => unimplemented!(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => unimplemented!(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => unimplemented!(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => unimplemented!(), InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => unimplemented!(), InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r", InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg) | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => unimplemented!(), InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => unimplemented!(), InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => { bug!("GCC backend does not support SPIR-V") } InlineAsmRegClass::Err => unreachable!(), } .to_string(), } } /// Type to use for outputs that are discarded. It doesn't really matter what /// the type is, as long as it is valid for the constraint code. fn dummy_output_type<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, reg: InlineAsmRegClass) -> Type<'gcc> { match reg { InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(), InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => { unimplemented!() } InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => { unimplemented!() } InlineAsmRegClass::Bpf(_) => unimplemented!(), InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(), InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(), InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(), InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(), InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(), InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(), InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(), InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(), InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(), InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg) | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(), InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(), InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(), InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => { bug!("LLVM backend does not support SPIR-V") }, InlineAsmRegClass::Err => unreachable!(), } } impl<'gcc, 'tcx> AsmMethods for CodegenCx<'gcc, 'tcx> { fn codegen_global_asm(&self, template: &[InlineAsmTemplatePiece], operands: &[GlobalAsmOperandRef], options: InlineAsmOptions, _line_spans: &[Span]) { let asm_arch = self.tcx.sess.asm_arch.unwrap(); // Default to Intel syntax on x86 let intel_syntax = matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64) && !options.contains(InlineAsmOptions::ATT_SYNTAX); // Build the template string let mut template_str = String::new(); for piece in template { match *piece { InlineAsmTemplatePiece::String(ref string) => { for line in string.lines() { // NOTE: gcc does not allow inline comment, so remove them. let line = if let Some(index) = line.rfind("//") { &line[..index] } else { line }; template_str.push_str(line); template_str.push('\n'); } }, InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span: _ } => { match operands[operand_idx] { GlobalAsmOperandRef::Const { ref string } => { // Const operands get injected directly into the // template. Note that we don't need to escape $ // here unlike normal inline assembly. template_str.push_str(string); } } } } } let template_str = if intel_syntax { format!("{}\n\t.intel_syntax noprefix", template_str) } else { format!(".att_syntax\n\t{}\n\t.intel_syntax noprefix", template_str) }; // NOTE: seems like gcc will put the asm in the wrong section, so set it to .text manually. let template_str = format!(".pushsection .text\n{}\n.popsection", template_str); self.context.add_top_level_asm(None, &template_str); } } fn modifier_to_gcc(arch: InlineAsmArch, reg: InlineAsmRegClass, modifier: Option<char>) -> Option<char> { match reg { InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier, InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => { unimplemented!() //if modifier == Some('v') { None } else { modifier } } InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => unimplemented!(), InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => { unimplemented!() /*if modifier.is_none() { Some('q') } else { modifier }*/ } InlineAsmRegClass::Bpf(_) => unimplemented!(), InlineAsmRegClass::Hexagon(_) => unimplemented!(), InlineAsmRegClass::Mips(_) => unimplemented!(), InlineAsmRegClass::Nvptx(_) => unimplemented!(), InlineAsmRegClass::PowerPC(_) => unimplemented!(), InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => unimplemented!(), InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier { None if arch == InlineAsmArch::X86_64 => Some('q'), None => Some('k'), Some('l') => Some('b'), Some('h') => Some('h'), Some('x') => Some('w'), Some('e') => Some('k'), Some('r') => Some('q'), _ => unreachable!(), }, InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => unimplemented!(), InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg) | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg) | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => unimplemented!() /*match (reg, modifier) { (X86InlineAsmRegClass::xmm_reg, None) => Some('x'), (X86InlineAsmRegClass::ymm_reg, None) => Some('t'), (X86InlineAsmRegClass::zmm_reg, None) => Some('g'), (_, Some('x')) => Some('x'), (_, Some('y')) => Some('t'), (_, Some('z')) => Some('g'), _ => unreachable!(), }*/, InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => unimplemented!(), InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => unimplemented!(), InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => { bug!("LLVM backend does not support SPIR-V") }, InlineAsmRegClass::Err => unreachable!(), } }
use std::str::FromStr; use argonautica::{ self, config::{Variant, Version}, {Hasher, Verifier}, input::SecretKey, }; use crate::error::{Error, ErrorKind, ParseError}; use failure::format_err; const SALT_SIZE : usize = 32; enum HashVersion { V1, } /// Hash Version v1 impl HashVersion { pub fn from_hash(hash: &str) -> Option<HashVersion> { let version: String = hash.chars().take_while(|c| c != &'$').collect(); match version.as_ref() { "1" => Some(HashVersion::V1), _ => None, } } } /// Hashing algorithm v1, using Argon2id variant with 256-bit salt. struct V1Hash { pub salt: [u8; SALT_SIZE], pub hash: [u8; 32], } impl V1Hash { /// String hash method. #[allow(dead_code)] pub fn hash_password(password: &str) -> Result<Self, Error> { use crate::random; let salt = random::generate_random_byte_array(); let slen = salt.len(); // validate salt size if !(slen == 32) { return Err( ErrorKind::Msg(format!( "Expected salt size (32), got salt size({})", slen)).into()) } let encrypt = argon2id(password, &salt)?; let mut hash = [0u8; 32]; for (&x, p) in encrypt.into_bytes() .iter().zip(hash.iter_mut()){ *p = x; } Ok (V1Hash { salt, hash }) } /// Checks password with Argon2. pub fn check(&self, password: &str) -> Result<bool, Error> { let key = load_env_var("SECRET_KEY")?; let mut verifier = Verifier::new(); let is_valid = if verifier .with_secret_key(&key) .with_password(password) .verify() .is_ok() { true } else { false }; Ok(is_valid) } /// takes in &[u8] and validates len size on `salt`, `hash` types of V1Hash. pub fn from_bytes<B: AsRef<[u8]>, C: AsRef<[u8]>>(b0: B, b1: C) -> Result<Self, ParseError> { let salt_byte = b0.as_ref(); let hash_byte= b1.as_ref(); validate!( salt_byte.len() != 32 || hash_byte.len() != 32, ParseError::InvalidLen ); let mut salt = [0u8; 32]; let mut hash = [0u8; 32]; salt.copy_from_slice(salt_byte); hash.copy_from_slice(hash_byte); Ok(V1Hash { salt, hash } ) } } impl FromStr for V1Hash { type Err = ParseError; fn from_str(s: &str) -> Result<Self, ParseError> { let parts: Vec<_> = s.split('$').collect(); validate!(parts.len() != 3, ParseError::InvalidVecLen); validate!(parts[0] != "1", ParseError::InvalidSlice); let vec_salt = base64::decode(parts[1]) .map_err(|e| ParseError::DecodeError(e))?; let vec_hash = base64::decode(parts[2]) .map_err(|e| ParseError::DecodeError(e))?; let v1hash_from_bytes = V1Hash::from_bytes(&vec_salt, &vec_hash)?; let salt = v1hash_from_bytes.salt; let hash = v1hash_from_bytes.hash; Ok(Self { salt, hash }) } } /// ToString implementation for V1Hash impl ToString for V1Hash { fn to_string(&self) -> String { let as_str = format!( "1${}${}", // base64::encode(&self.salt).as_ref(), base64::encode(&self.salt), // base64::encode(&self.hash).as_ref(), base64::encode(&self.hash), ); as_str } } /// Into() String implementation for V1Hash impl Into<String> for V1Hash { fn into(self) -> String { self.to_string() } } /// argon2id algorithm hashes a password for login sessions pub fn argon2id(pwd: &str, salt: &[u8]) -> Result<String, Error> { let key = load_env_var("SECRET_KEY")?; let mut a2id = Hasher::default(); let raw_hash = a2id .configure_hash_len(32) .configure_variant(Variant::Argon2id) .configure_version(Version::_0x13) .with_password(pwd) .with_salt(salt) .with_secret_key(key); let hash_encoded = raw_hash.hash()?; Ok(hash_encoded) } /// Check a password against a hash which has been generated by this crate. pub fn check_password(pwd: &str, hash: &str) -> bool { match HashVersion::from_hash(hash) { Some(HashVersion::V1) => { let v1_hash: V1Hash = match hash.parse() { Ok(v1_hash) => v1_hash, Err(_) => return false, }; v1_hash.check(pwd).unwrap() } None => false, } } /// gets environment variable /// /// TODO: Use thread-safe cell for static reference of jwt_key and secret_key. pub fn load_env_var(env: &str) -> Result<SecretKey<'static>, Error> { let _path = dotenv::from_path("../sentry.env") .map_err(|e| format_err!( "Failed to load env file. Cause: {}", e ))?; let env_var = std::env::var(env) .expect("Please inspect env variable exists"); Ok(SecretKey::from_base64_encoded(&env_var)?) } #[cfg(test)] mod test { use super::*; #[test] pub fn known_hash() { // In order to test the argon2id function we must make nonce deterministic. // Nonce should always be random bytes in production. let nonce = [66, 67, 80, 97, 35, 48, 7, 89, 112, 112, 32, 225, 83, 134, 76, 117, 159, 143, 191, 83, 140, 8, 239, 14, 53, 253, 105, 206, 71, 108, 116, 12]; let crypt = argon2id("WY5cpFbAY0ns", &nonce).unwrap(); let encrypted: String = base64::encode(&crypt).into(); assert_eq!( encrypted, "JGFyZ29uMmlkJHY9MTkkbT00MDk2LHQ9MTkyLHA9OCRRa05RWVNNd0IxbHdjQ0RoVTRaTWRaK1B2MU9NQ084T05mMXB6a2RzZEF3JFcxYW5VQlBaUnUvYlFJR3E2aHBqMkorNytCOVg2SmtzZUY0dUpBM0xid0E=" ); } #[test] pub fn hash_roundtrip() { use crate::random; for _ in 0..10 { let password: String = random::password(); let v1_hash: String = V1Hash::hash_password(&password).unwrap().into(); eprintln!("{:?}", v1_hash); assert!(true, check_password(&password, &v1_hash)) } } }
use cpu::CPU; use std::mem::swap; /// Swap the contents of register pairs HL with DE /// /// # Cycles /// /// 5 /// /// # Arguments /// /// * `cpu` - The cpu to perform the swap in /// pub fn xchg(cpu: &mut CPU) -> u8 { swap(&mut cpu.h, &mut cpu.d); swap(&mut cpu.l, &mut cpu.e); 5 } /// Swap the contents of register pairs HL with the top of the stack /// /// # Cycles /// /// 18 /// /// # Arguments /// /// * `cpu` - The cpu to perform the swap in /// pub fn xthl(cpu: &mut CPU) -> u8 { swap(&mut cpu.h, &mut cpu.memory[(cpu.sp + 1) as usize]); swap(&mut cpu.l, &mut cpu.memory[cpu.sp as usize]); 18 } #[cfg(test)] mod test { use super::*; #[test] fn xchg_exchanges_h_l_pair_with_d_e_pair() { let mut cpu = CPU { d: 0xDE, e: 0xAD, h: 0xBE, l: 0xEF, ..CPU::default() }; xchg(&mut cpu); assert_eq!(cpu.d, 0xBE); assert_eq!(cpu.e, 0xEF); assert_eq!(cpu.h, 0xDE); assert_eq!(cpu.l, 0xAD); } #[test] fn xthl_exchanges_h_l_pair_with_bytes_on_stack() { let mut cpu = CPU { memory: vec![0, 0xDE, 0xAD], h: 0xBE, l: 0xEF, sp: 1, ..CPU::default() }; xthl(&mut cpu); assert_eq!(cpu.h, 0xAD); assert_eq!(cpu.l, 0xDE); assert_eq!(cpu.memory, vec![0, 0xEF, 0xBE]); } }
use chrono::{DateTime, Duration, TimeZone, Utc}; use std::fmt; use std::str::FromStr; use {Error, Result}; /// A UTC timestamp. Used for serialization to and from the plist date type. #[derive(Clone, Debug, PartialEq)] pub struct Date { inner: DateTime<Utc>, } impl Date { #[doc(hidden)] pub fn from_seconds_since_plist_epoch(timestamp: f64) -> Result<Date> { // Seconds since 1/1/2001 00:00:00. if timestamp.is_nan() { return Err(Error::InvalidData); } let millis = timestamp * 1_000.0; // Chrono's Duration can only millisecond values between ::std::i64::MIN and // ::std::i64::MAX. if millis > ::std::i64::MAX as f64 || millis < ::std::i64::MIN as f64 { return Err(Error::InvalidData); } let whole_millis = millis.floor(); let submilli_nanos = ((millis - whole_millis) * 1_000_000.0).floor(); let dur = Duration::milliseconds(whole_millis as i64); let dur = dur + Duration::nanoseconds(submilli_nanos as i64); let plist_epoch = Utc.ymd(2001, 1, 1).and_hms(0, 0, 0); let date = plist_epoch.checked_add_signed(dur).ok_or(Error::InvalidData)?; Ok(Date { inner: date }) } } impl From<DateTime<Utc>> for Date { fn from(date: DateTime<Utc>) -> Self { Date { inner: date } } } impl Into<DateTime<Utc>> for Date { fn into(self) -> DateTime<Utc> { self.inner } } impl fmt::Display for Date { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.inner) } } impl FromStr for Date { type Err = (); fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let date = DateTime::parse_from_rfc3339(s).map_err(|_| ())?; Ok(Date { inner: date.with_timezone(&Utc) }) } } #[cfg(feature = "serde")] pub mod serde_impls { use serde_base::de::{Deserialize, Deserializer, Error, Visitor, Unexpected}; use serde_base::ser::{Serialize, Serializer}; use std::fmt; use std::str::FromStr; use Date; pub const DATE_NEWTYPE_STRUCT_NAME: &'static str = "PLIST-DATE"; impl Serialize for Date { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { let date_str = self.to_string(); serializer.serialize_newtype_struct(DATE_NEWTYPE_STRUCT_NAME, &date_str) } } struct DateNewtypeVisitor; impl<'de> Visitor<'de> for DateNewtypeVisitor { type Value = Date; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a plist date newtype") } fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de> { deserializer.deserialize_str(DateStrVisitor) } } struct DateStrVisitor; impl<'de> Visitor<'de> for DateStrVisitor { type Value = Date; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a plist date string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error { Date::from_str(v).map_err(|_| E::invalid_value(Unexpected::Str(v), &self)) } } impl<'de> Deserialize<'de> for Date { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { deserializer.deserialize_newtype_struct(DATE_NEWTYPE_STRUCT_NAME, DateNewtypeVisitor) } } }
#![feature(rustc_attrs)] #![feature(c_unwind)] mod atoms; mod symbols; extern "C" { /// The target-defined entry point for the generated executable. /// /// Each target has its own runtime crate, with its own entry point /// exposed as `firefly_entry`, the core runtime (this crate) calls /// into that entry after global initialization of target-agnostic /// resources is complete. #[link_name = "firefly_entry"] fn firefly_entry() -> i32; #[allow(improper_ctypes)] #[link_name = env!("LANG_START_SYMBOL_NAME")] fn lang_start(main: &dyn Fn() -> i32, argc: isize, argv: *const *const i8) -> isize; } #[no_mangle] pub extern "C" fn main(argc: i32, argv: *const *const std::os::raw::c_char) -> i32 { unsafe { lang_start(&move || main_internal(), argc as isize, argv) as i32 } } /// The primary entry point for the Firefly runtime /// /// This function is responsible for setting up any core functionality required /// by the higher-level runtime, e.g. initializing the atom table. Once initialized, /// this function invokes the platform-specific entry point which handles starting /// up the schedulers and other high-level runtime functionality. #[rustc_main] pub fn main_internal() -> i32 { // Initialize atom table if unsafe { atoms::init(atoms::start(), atoms::end()) } == false { return 102; } // Initialize the dispatch table if unsafe { symbols::init(symbols::start(), symbols::end()) } == false { return 103; } // Invoke platform-specific entry point unsafe { firefly_entry() } }
use bigneon_db::models::UserEditableAttributes; use validator::Validate; #[derive(Default, Deserialize, Validate)] pub struct UserProfileAttributes { pub first_name: Option<String>, pub last_name: Option<String>, #[validate(email)] pub email: Option<String>, pub phone: Option<String>, #[validate(url)] pub profile_pic_url: Option<String>, #[validate(url)] pub thumb_profile_pic_url: Option<String>, #[validate(url)] pub cover_photo_url: Option<String>, } impl From<UserProfileAttributes> for UserEditableAttributes { fn from(attributes: UserProfileAttributes) -> Self { UserEditableAttributes { first_name: attributes.first_name, last_name: attributes.last_name, email: attributes.email, phone: attributes.phone, profile_pic_url: attributes.profile_pic_url, thumb_profile_pic_url: attributes.thumb_profile_pic_url, cover_photo_url: attributes.cover_photo_url, ..Default::default() } } }
extern crate proconio; use proconio::input; mod mint { use std::ops::{Add, Div, Mul, Sub}; type Int = i64; pub const MOD: Int = 1_000_000_000 + 7; #[derive(Clone, Copy)] pub struct Mint { x: Int, } impl Mint { pub fn new(x: Int) -> Mint { Mint { x: (x % MOD + MOD) % MOD, } } pub fn val(&self) -> Int { self.x } } impl Add<Int> for Mint { type Output = Mint; fn add(self, rhs: Int) -> Mint { Mint::new(self.val() + (rhs % MOD)) } } impl Add for Mint { type Output = Mint; fn add(self, rhs: Mint) -> Mint { self + rhs.val() } } impl Sub<Int> for Mint { type Output = Mint; fn sub(self, rhs: Int) -> Mint { Mint::new(self.val() - (rhs % MOD)) } } impl Sub for Mint { type Output = Mint; fn sub(self, rhs: Mint) -> Mint { self - rhs.val() } } impl Mul<Int> for Mint { type Output = Mint; fn mul(self, rhs: Int) -> Mint { Mint::new(self.val() * (rhs % MOD)) } } impl Mul for Mint { type Output = Mint; fn mul(self, rhs: Mint) -> Mint { self * rhs.val() } } impl Mint { pub fn pow(x: Mint, y: Int) -> Mint { assert!(y >= 0); let mut res = Mint::new(1); let mut base = x; let mut exp = y; while exp > 0 { if (exp & 1) == 1 { res = res * base; } base = base * base; exp = exp / 2; } res } pub fn inv(self) -> Mint { Mint::pow(self, MOD - 2) } } impl Div<Int> for Mint { type Output = Mint; fn div(self, rhs: Int) -> Mint { self * Mint::new(rhs).inv() } } impl Div for Mint { type Output = Mint; fn div(self, rhs: Mint) -> Mint { self * rhs.val() } } impl std::fmt::Display for Mint { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.val()) } } } use mint::Mint; struct Cmb { fac: Vec<Mint>, fac_inv: Vec<Mint>, } impl Cmb { pub fn new(n: usize) -> Cmb { let mut fac = vec![Mint::new(0); n]; let mut fac_inv = vec![Mint::new(0); n]; fac[0] = Mint::new(1); for i in 1..n { fac[i] = fac[i - 1] * (i as i64); } fac_inv[n - 1] = fac[n - 1].inv(); for i in (0..n - 1).rev() { fac_inv[i] = fac_inv[i + 1] * ((i + 1) as i64) } Cmb { fac, fac_inv } } pub fn binom(&self, a: usize, b: usize) -> Mint { if a < b { return Mint::new(0); } self.fac[a] * self.fac_inv[b] * self.fac_inv[a - b] } } fn main() { // ....... // ....... // ....... // ....... // ....... // ....... // ....... // ####... // ####... // ####... input! { h: usize, w: usize, a: usize, b: usize, } let cmb = Cmb::new(h + w); let count = |x: usize, y: usize| cmb.binom(x + y, x); let mut ans = Mint::new(0); ans = ans + count(h - 1, w - 1); for j in 1..=b { // (1, 1) -> (h - a, j) // (h - a + 1, j) -> (h, w) let s = count(h - a - 1, j - 1) * count(a - 1, w - j); ans = ans - s; } println!("{}", ans); }
pub mod extract; use std::collections::HashMap; use crate::datastore::prelude::*; use crate::datastore::value::ValueType; use chrono::prelude::*; use googapis::google::datastore::v1::Value; use juniper::ID; use prost_types::Timestamp; pub enum DbValue<'a> { /// ID of the entity Id(&'a Entity), /// field-Entity -> ID Key(&'a str, &'a Entity), /// field-Entity -> String Str(&'a str, &'a Entity), /// field-Entity -> String Blob(&'a str, &'a Entity), /// field-Entity -> DateTime<Utc> Timestamp(&'a str, &'a Entity), /// field-Entity -> bool Bool(&'a str, &'a Entity), } impl<'a> Into<ID> for DbValue<'a> { fn into(self) -> ID { match self { DbValue::Id(e) => extract::id(e), DbValue::Key(key, entity) => match &extract::field(entity, key) { Some(ValueType::KeyValue(key)) => extract::id_from_key(key), _ => ID::new(""), }, _ => ID::new(""), } } } impl<'a> Into<String> for DbValue<'a> { fn into(self) -> String { match self { DbValue::Str(key, entity) => match extract::field(entity, key) { Some(ValueType::StringValue(v)) => v, _ => "".to_string(), }, DbValue::Blob(key, entity) => match extract::field(entity, key) { Some(ValueType::BlobValue(v)) => match std::str::from_utf8(&v) { Ok(v) => v.to_string(), _ => "".to_string(), }, _ => "".to_string(), }, _ => "".to_string(), } } } impl<'a> Into<bool> for DbValue<'a> { fn into(self) -> bool { match self { DbValue::Bool(key, entity) => match extract::field(entity, key) { Some(ValueType::BooleanValue(v)) => v, _ => false, }, _ => false, } } } impl<'a> Into<DateTime<Utc>> for DbValue<'a> { fn into(self) -> DateTime<Utc> { let default_datetime = extract::timestamp_to_datetime(&Timestamp { nanos: 0, seconds: 0, }); match self { DbValue::Timestamp(key, entity) => match &extract::field(entity, key) { Some(ValueType::TimestampValue(v)) => extract::timestamp_to_datetime(v), _ => default_datetime, }, _ => default_datetime, } } } pub type DbProperties = HashMap<String, Value>;
//! A minheap that separates values from priorities. //! Intended for use in astar. use std::cmp::Ordering; use std::collections::BinaryHeap; pub struct MinHeap<V: Eq, P: Ord>(BinaryHeap<MinHeapItem<V, P>>); #[derive(Eq, PartialEq)] struct MinHeapItem<V: Eq, P: Ord> { value: V, priority: P, } impl<V: Eq, P: Ord> MinHeap<V, P> { pub fn new() -> Self { MinHeap(BinaryHeap::new()) } pub fn push(&mut self, value: V, priority: P) { self.0.push(MinHeapItem { value, priority }) } pub fn pop(&mut self) -> Option<V> { match self.0.pop() { Some(item) => Some(item.value), None => None, } } } impl<V: Eq, P: Ord> Ord for MinHeapItem<V, P> { fn cmp(&self, other: &Self) -> Ordering { match self.priority.cmp(&other.priority) { Ordering::Equal => Ordering::Equal, Ordering::Greater => Ordering::Less, Ordering::Less => Ordering::Greater, } } } impl<V: Eq, P: Ord> PartialOrd for MinHeapItem<V, P> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }
#![cfg(feature = "macros")] #![allow(clippy::let_unit_value)] use std::{ pin::Pin, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, task::{Context as StdContext, Poll}, time::Duration, }; use actix::prelude::*; use actix_rt::time::{interval_at, sleep, Instant}; use futures_core::stream::Stream; use futures_util::stream::once; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver}; #[derive(Debug, PartialEq)] enum Op { Cancel, Timeout, TimeoutStop, RunAfter, RunAfterStop, } struct StreamRx { rx: UnboundedReceiver<Ping>, } impl Stream for StreamRx { type Item = Ping; fn poll_next(self: Pin<&mut Self>, cx: &mut StdContext<'_>) -> Poll<Option<Self::Item>> { let this = self.get_mut(); Pin::new(&mut this.rx).poll_recv(cx) } } struct MyActor { op: Op, } impl Actor for MyActor { type Context = actix::Context<Self>; fn started(&mut self, ctx: &mut Context<MyActor>) { match self.op { Op::Cancel => { let handle0 = ctx.notify_later(TimeoutMessage, Duration::new(0, 100)); let handle1 = ctx.notify_later(TimeoutMessage, Duration::new(0, 100)); assert!(ctx.cancel_future(handle1)); assert!(ctx.cancel_future(handle0)); } Op::Timeout => { ctx.notify_later(TimeoutMessage, Duration::new(0, 1000)); } Op::TimeoutStop => { ctx.notify_later(TimeoutMessage, Duration::new(0, 1_000_000)); ctx.stop(); } Op::RunAfter => { ctx.run_later(Duration::new(0, 100), |_, _| { System::current().stop(); }); } Op::RunAfterStop => { ctx.run_later(Duration::new(1, 0), |_, _| { panic!("error"); }); ctx.stop(); } } } fn stopped(&mut self, _: &mut Context<MyActor>) { System::current().stop(); } } struct TimeoutMessage; impl Message for TimeoutMessage { type Result = (); } impl Handler<TimeoutMessage> for MyActor { type Result = (); fn handle(&mut self, _: TimeoutMessage, _: &mut Self::Context) { if self.op != Op::Timeout { panic!("should not happen {:?}", self.op); } System::current().stop(); } } #[test] fn test_add_timeout() { System::new().block_on(async { let _addr = MyActor { op: Op::Timeout }.start(); }); } #[test] fn test_add_timeout_cancel() { System::new().block_on(async { let _addr = MyActor { op: Op::Cancel }.start(); actix_rt::spawn(async move { sleep(Duration::new(0, 1000)).await; System::current().stop(); }); }); } #[test] // delayed notification should be dropped after context stop fn test_add_timeout_stop() { System::new().block_on(async { let _addr = MyActor { op: Op::TimeoutStop, } .start(); }); } #[test] fn test_run_after() { System::new().block_on(async { let _addr = MyActor { op: Op::RunAfter }.start(); }); } #[test] fn test_run_after_stop() { System::new().block_on(async { let _addr = MyActor { op: Op::RunAfterStop, } .start(); }); } struct ContextWait { cnt: Arc<AtomicUsize>, } impl Actor for ContextWait { type Context = actix::Context<Self>; } struct Ping; impl Message for Ping { type Result = (); } impl Handler<Ping> for ContextWait { type Result = (); fn handle(&mut self, _: Ping, ctx: &mut Self::Context) { let cnt = self.cnt.load(Ordering::Relaxed); self.cnt.store(cnt + 1, Ordering::Relaxed); let fut = sleep(Duration::from_secs(1)); fut.into_actor(self).wait(ctx); System::current().stop(); } } #[test] fn test_wait_context() { let m = Arc::new(AtomicUsize::new(0)); let cnt = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let addr = ContextWait { cnt }.start(); addr.do_send(Ping); addr.do_send(Ping); addr.do_send(Ping); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), 1); } #[test] fn test_message_stream_wait_context() { let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let _addr = ContextWait::create(move |ctx| { let (tx, rx) = unbounded_channel(); let _ = tx.send(Ping); let _ = tx.send(Ping); let _ = tx.send(Ping); let actor = ContextWait { cnt: m2 }; ctx.add_message_stream(StreamRx { rx }); actor }); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), 1); } #[test] fn test_stream_wait_context() { let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let _addr = ContextWait::create(move |ctx| { let (tx, rx) = unbounded_channel(); let _ = tx.send(Ping); let _ = tx.send(Ping); let _ = tx.send(Ping); let actor = ContextWait { cnt: m2 }; ctx.add_message_stream(StreamRx { rx }); actor }); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), 1); } struct ContextNoWait { cnt: Arc<AtomicUsize>, } impl Actor for ContextNoWait { type Context = actix::Context<Self>; } impl Handler<Ping> for ContextNoWait { type Result = (); fn handle(&mut self, _: Ping, _: &mut Self::Context) { let cnt = self.cnt.load(Ordering::Relaxed); self.cnt.store(cnt + 1, Ordering::Relaxed); } } #[actix::test] async fn test_nowait_context() { let m = Arc::new(AtomicUsize::new(0)); let cnt = Arc::clone(&m); actix_rt::spawn(async move { let addr = ContextNoWait { cnt }.start(); addr.do_send(Ping); addr.do_send(Ping); addr.do_send(Ping); }); sleep(Duration::from_millis(200)).await; assert_eq!(m.load(Ordering::Relaxed), 3); } #[actix::test] async fn test_message_stream_nowait_context() { let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); actix_rt::spawn(async move { let _addr = ContextNoWait::create(move |ctx| { let (tx, rx) = unbounded_channel(); let _ = tx.send(Ping); let _ = tx.send(Ping); let _ = tx.send(Ping); let actor = ContextNoWait { cnt: m2 }; ctx.add_message_stream(StreamRx { rx }); actor }); }); sleep(Duration::from_millis(200)).await; assert_eq!(m.load(Ordering::Relaxed), 3); } #[test] fn test_stream_nowait_context() { let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let _addr = ContextNoWait::create(move |ctx| { let (tx, rx) = unbounded_channel(); let _ = tx.send(Ping); let _ = tx.send(Ping); let _ = tx.send(Ping); let actor = ContextNoWait { cnt: m2 }; ctx.add_message_stream(StreamRx { rx }); actor }); actix_rt::spawn(async move { sleep(Duration::from_millis(200)).await; System::current().stop(); }); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), 3); } #[test] fn test_notify() { let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let addr = ContextNoWait::create(move |ctx| { ctx.notify(Ping); ctx.notify(Ping); ContextNoWait { cnt: Arc::clone(&m), } }); addr.do_send(Ping); actix_rt::spawn(async move { sleep(Duration::from_millis(200)).await; System::current().stop(); }); }); sys.run().unwrap(); assert_eq!(m2.load(Ordering::Relaxed), 3); } struct ContextHandle { h: Arc<AtomicUsize>, } impl Actor for ContextHandle { type Context = Context<Self>; } impl StreamHandler<Ping> for ContextHandle { fn handle(&mut self, _: Ping, ctx: &mut Self::Context) { self.h.store(ctx.handle().into_usize(), Ordering::Relaxed); System::current().stop(); } } #[test] fn test_current_context_handle() { let h = Arc::new(AtomicUsize::new(0)); let h2 = Arc::clone(&h); let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let _addr = ContextHandle::create(move |ctx| { h2.store( ContextHandle::add_stream(once(async { Ping }), ctx).into_usize(), Ordering::Relaxed, ); ContextHandle { h: m2 } }); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), h.load(Ordering::Relaxed)); } #[test] fn test_start_from_context() { let h = Arc::new(AtomicUsize::new(0)); let h2 = Arc::clone(&h); let m = Arc::new(AtomicUsize::new(0)); let m2 = Arc::clone(&m); let sys = System::new(); sys.block_on(async move { let _addr = ContextHandle::create(move |ctx| { h2.store( ctx.add_stream(once(async { Ping })).into_usize(), Ordering::Relaxed, ); ContextHandle { h: m2 } }); }); sys.run().unwrap(); assert_eq!(m.load(Ordering::Relaxed), h.load(Ordering::Relaxed)); } struct CancelHandler { source: SpawnHandle, } impl Actor for CancelHandler { type Context = Context<Self>; fn stopped(&mut self, _: &mut Context<Self>) { System::current().stop(); } } struct CancelPacket; impl StreamHandler<CancelPacket> for CancelHandler { fn handle(&mut self, _: CancelPacket, ctx: &mut Context<Self>) { ctx.cancel_future(self.source); } } #[test] fn test_cancel_handler() { actix::System::new().block_on(async { struct WtfStream { interval: actix_rt::time::Interval, } impl Stream for WtfStream { type Item = CancelPacket; fn poll_next( self: Pin<&mut Self>, cx: &mut StdContext<'_>, ) -> Poll<Option<Self::Item>> { self.get_mut() .interval .poll_tick(cx) .map(|_| Some(CancelPacket)) } } CancelHandler::create(|ctx| CancelHandler { source: ctx.add_stream(WtfStream { interval: interval_at(Instant::now(), Duration::from_millis(1)), }), }); }); } struct CancelLater { handle: Option<SpawnHandle>, } impl Actor for CancelLater { type Context = Context<Self>; fn started(&mut self, ctx: &mut Context<Self>) { // nothing spawned other than the future to be canceled after completion self.handle = Some(ctx.spawn(async {}.into_actor(self))); } } struct CancelMessage; impl Message for CancelMessage { type Result = (); } impl Handler<CancelMessage> for CancelLater { type Result = (); fn handle(&mut self, _: CancelMessage, ctx: &mut Self::Context) { ctx.cancel_future(self.handle.take().unwrap()); } } #[test] fn test_cancel_completed_with_no_context_item() { actix::System::new().block_on(async { // first, spawn future that will complete immediately let addr = CancelLater { handle: None }.start(); // then, cancel the future which would already be completed actix_rt::spawn(async move { sleep(Duration::from_millis(100)).await; addr.do_send(CancelMessage); }); // finally, terminate the actor, which shouldn't be blocked unless // the actor context ate up CPU time actix_rt::spawn(async { sleep(Duration::from_millis(200)).await; System::current().stop(); }); }); } mod scheduled_task_is_cancelled_properly { use tokio::{sync::oneshot, task::yield_now, time::timeout}; use super::*; struct TestActor; impl Actor for TestActor { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.spawn(yield_now().into_actor(self)); } } #[derive(Message)] #[rtype(result = "()")] struct Msg(Option<oneshot::Sender<()>>); impl Drop for Msg { fn drop(&mut self) { self.0.take().unwrap().send(()).unwrap(); } } impl Handler<Msg> for TestActor { type Result = (); fn handle(&mut self, msg: Msg, ctx: &mut Self::Context) -> Self::Result { let handle = ctx.run_later(Duration::from_millis(0), |_, _| { let _msg = msg; System::current().stop_with_code(1); panic!("This closure must not be executed"); }); ctx.cancel_future(handle); } } #[test] fn cancels() { let sys = System::new(); sys.block_on(async { let addr = TestActor.start(); let (tx, rx) = oneshot::channel(); addr.do_send(Msg(Some(tx))); timeout(Duration::from_millis(500), rx) .await .unwrap() .unwrap(); System::current().stop(); }); sys.run().unwrap(); } }
use std::collections::HashMap; // The base data and measure of "completed-ness" required to be // useable inside of a lattice machine pub trait NodeType { // returns the UUID of the NodeType to be used by the NodeOpt fn uuid(&self) -> String; // returns if the base data type is completed fn is_completed(&self) -> bool; } pub trait ReadNode<T>: NodeType { // new creates a new NodeOpt out of the base data type // and list of relations it depends on. fn new(base_data: T, depends_on: Vec<String>, required_by: Vec<String>) -> Self; // returns a hashmap where keys are the LatNode who this LatNode depends on being // complete before becoming active and a bool indicating whether that LatNode // is active or not fn depends_on(&self) -> &HashMap<String, ()>; // returns a hashmap where keys are the LatNodes who require this LatNode fn required_by(&self) -> &HashMap<String, ()>; // returns a hashmap where keys are the completed LatNodes this depended on. fn fulfilled_by(&self) -> &HashMap<String, ()>; // returns whether this LatNode should be active. fn is_active(&self) -> bool { !(!self.is_completed() && self.depends_on().is_empty()) } fn is_pending(&self) -> bool { !self.depends_on().is_empty() || !self.is_completed() } } pub struct BasicNode<T> where T: NodeType, { base_data: T, depends_on: HashMap<String, ()>, required_by: HashMap<String, ()>, fulfilled_by: HashMap<String, ()>, } impl<T: NodeType> NodeType for BasicNode<T> { fn uuid(&self) -> String { self.base_data.uuid() } fn is_completed(&self) -> bool { self.base_data.is_completed() } } impl<T: NodeType> ReadNode<T> for BasicNode<T> { fn new(t: T, depends_on: Vec<String>, required_by: Vec<String>) -> Self { let mut s = Self { base_data: t, depends_on: HashMap::new(), fulfilled_by: HashMap::new(), required_by: HashMap::new(), }; for v in depends_on { s.depends_on.insert(v, ()); } for v in required_by { s.required_by.insert(v, ()); } s } fn depends_on(&self) -> &HashMap<String, ()> { &self.depends_on } fn required_by(&self) -> &HashMap<String, ()> { &self.required_by } fn fulfilled_by(&self) -> &HashMap<String, ()> { &self.fulfilled_by } } pub trait WriteNode<T>: ReadNode<T> { // returns a mutable reference to a hashmap where keys are the // LatNode who this LatNode depends on being // complete before becoming active and a bool indicating whether // that LatNode is active or not fn get_depends_on(&mut self) -> &mut HashMap<String, ()>; // returns a mutable reference to a hashmap where keys are the // LatNodes who require this LatNode fn get_required_by(&mut self) -> &mut HashMap<String, ()>; // returns a hashmap where keys are the completed LatNodes this // depended on fn get_fulfilled_by(&mut self) -> &mut HashMap<String, ()>; // returns a hashmap where keys are the completed LatNodes this // depended on. // add_depends_on takes a LatNode's UUID and adds it to the relations fn add_depends_on(&mut self, key: String) { self.get_depends_on().insert(key, ()); } // add_required_by takes a LatNode's UUID and adds it to the relations fn add_required_by(&mut self, key: String) { self.get_required_by().insert(key, ()); } fn depend_fulfilled(&mut self, key: String) -> Result<(), ()> { match self.get_depends_on().remove(&key) { None => Err(()), Some(_) => { self.get_fulfilled_by().insert(key, ()); Ok(()) } } } fn update(&mut self, t: T) -> Result<(), ()>; } impl<T: NodeType> WriteNode<T> for BasicNode<T> { fn get_depends_on(&mut self) -> &mut HashMap<String, ()> { &mut self.depends_on } fn get_required_by(&mut self) -> &mut HashMap<String, ()> { &mut self.required_by } fn get_fulfilled_by(&mut self) -> &mut HashMap<String, ()> { &mut self.fulfilled_by } fn update(&mut self, t: T) -> Result<(), ()> { self.base_data = t; Ok(()) } } pub trait LatMachine<T, U> where T: WriteNode<U>, { // default impl? fn new() -> Self; // If embedding as a LatNode, then we get this for free. fn is_completed(&self) -> bool { self.read_pending().is_empty() } fn read_pending(&self) -> &HashMap<String, T>; fn read_fulfilled(&self) -> &HashMap<String, T>; fn get_pending(&mut self) -> &mut HashMap<String, T>; fn get_fulfilled(&mut self) -> &mut HashMap<String, T>; fn append_pending(&mut self, t: T) { self.get_pending().insert(t.uuid(), t); } fn append_fulfilled(&mut self, t: T) { self.get_fulfilled().insert(t.uuid(), t); } fn append(&mut self, t: T) { if t.is_pending() { self.append_pending(t); } else { self.append_fulfilled(t); }; } // Always public below here: fn fulfill(&mut self, key: String) -> Result<(), ()> { let mut cascasde = Vec::<String>::new(); let pending = self.get_pending(); match pending.remove(&key) { None => Err(()), Some(mut target) => { let r_map = target.get_required_by(); for (k, _) in r_map { match pending.get_mut(k) { None => return Err(()), Some(x) => match x.depend_fulfilled(key.clone()) { Ok(()) => { if !x.is_pending() { cascasde.push(x.uuid()); } } Err(()) => return Err(()), }, }; } self.get_fulfilled().insert(key, target); for v in cascasde { match self.fulfill(v) { Err(()) => return Err(()), Ok(()) => {} }; } Ok(()) } } } // TODO: IMPLEMENT fn unfulfill(&mut self, key: String) -> Result<(), ()> { Ok(()) // let mut cascasde = Vec::<String>::new(); // let pending = self.get_pending(); // match pending.remove(&key) { // None => Err(()), // Some(mut target) => { // let r_map = target.get_required_by(); // for (k, _) in r_map { // match pending.get_mut(k) { // None => return Err(()), // Some(x) => match x.depend_fulfilled(key.clone()) { // Ok(()) => { // if !x.is_pending() { // cascasde.push(x.uuid()); // } // } // Err(()) => return Err(()), // }, // }; // } // self.get_fulfilled().insert(key, target); // for v in cascasde { // match self.fulfill(v) { // Err(()) => return Err(()), // Ok(()) => {} // }; // } // Ok(()) // } // } } fn update_value(&mut self, key: String, update: U) -> Result<(), ()> { let m = self.get_pending(); // TODO: REPORT ERRS, DYING HERE WOULD BE AWFUL. let x = m.get_mut(&key); match x { None => Err(()), Some(t) => match t.update(update) { Err(()) => Err(()), Ok(()) => { if t.is_completed() { match self.fulfill(key) { Err(()) => return Err(()), Ok(()) => return Ok(()), }; }; Ok(()) } }, } } // boolean indicates whether this relationship blocks the value at is_required_by fn update_required_by(&mut self, target: String, is_required_by: String) -> Result<bool, ()> { // Is the required elm in pending? match self.get_pending().get_mut(&target) { Some(t) => { t.add_required_by(is_required_by); // It IS blocking Ok(true) } // The required elm must be fulfilled: None => match self.get_fulfilled().get_mut(&target) { // if not err. None => Err(()), Some(t) => { t.add_required_by(is_required_by); // It is NOT blocking. Ok(false) } }, } } fn update_depends_on(&mut self, target: String, depends_on: String) -> Result<(), ()> { // Is the required elm in pending? match self.get_pending().get_mut(&target) { Some(t) => { t.add_depends_on(depends_on); Ok(()) } // The required elm must be fulfilled: None => match self.get_fulfilled().remove(&target) { // Unknown key in either map. None => Err(()), Some(mut t) => { t.add_depends_on(depends_on); self.append(t); Ok(()) } }, } } fn add_requirement(&mut self, requires: String, is_required: String) -> Result<(), ()> { // search for requires let mut is_still_required = false; match self.get_pending().get_mut(&is_required) { Some(is_req) => { is_still_required = true; is_req.add_required_by(requires.clone()); } None => match self.get_fulfilled().get_mut(&is_required) { None => return Err(()), Some(is_req) => { is_req.add_required_by(requires.clone()); } }, }; match self.get_pending().get_mut(&requires) { Some(req) => { req.add_depends_on(is_required.clone()); if !is_still_required { req.depend_fulfilled(is_required).unwrap(); } } None => { if is_still_required { match self.get_fulfilled().remove(&requires) { None => return Err(()), Some(mut req) => { req.add_depends_on(is_required); self.append(req); } } } else { match self.get_fulfilled().get_mut(&requires) { None => return Err(()), Some(req) => { req.add_depends_on(is_required.clone()); req.depend_fulfilled(is_required).unwrap(); } } } } }; Ok(()) } } pub struct BasicLattice<T> { pending: HashMap<String, T>, fulfilled: HashMap<String, T>, } impl<T: NodeType> BasicLattice<BasicNode<T>> where T: NodeType, { pub fn from_node_list(v: Vec<BasicNode<T>>) -> BasicLattice<BasicNode<T>> { let mut s = BasicLattice::new(); let mut keys = Vec::<String>::new(); for node in v { if !node.is_pending() { keys.push(node.uuid().to_string()); } s.append_pending(node); } for key in keys { s.fulfill(key); } s } } // Why doesn't this work? // impl<T: WriteNode<U>, U> BasicLattice<T> // where // T: WriteNode<U>, // { // pub fn from_node_list(v: Vec<T>) -> BasicLattice<BasicNode<T>> { // let mut s = BasicLattice::new(); // let mut full_map = HashMap::<String, ()>::new(); // for node in v { // full_map.insert(node.uuid(), ()); // if node.depends_on().is_empty() { // s.append(node); // }; // } // s // } // } impl<T, U> LatMachine<T, U> for BasicLattice<T> where T: WriteNode<U>, { fn new() -> Self { BasicLattice { pending: HashMap::new(), fulfilled: HashMap::new(), } } fn read_pending(&self) -> &HashMap<String, T> { &self.pending } fn read_fulfilled(&self) -> &HashMap<String, T> { &self.fulfilled } fn get_pending(&mut self) -> &mut HashMap<String, T> { &mut self.pending } fn get_fulfilled(&mut self) -> &mut HashMap<String, T> { &mut self.fulfilled } }
use crate::heap::{ DisplayWithSymbolTable, Function, HirId, InlineData, InlineObject, SymbolId, SymbolTable, }; use crate::{fiber::InstructionPointer, heap::Heap}; use candy_frontend::hir; use candy_frontend::rich_ir::ReferenceKey; use candy_frontend::{ mir::Id, module::Module, rich_ir::{RichIr, RichIrBuilder, ToRichIr, TokenType}, TracingConfig, }; use enumset::EnumSet; use extension_trait::extension_trait; use itertools::Itertools; use pad::{Alignment, PadStr}; use rustc_hash::FxHashSet; use std::ops::Range; use strum::{EnumDiscriminants, IntoStaticStr}; pub struct Lir { pub module: Module, pub constant_heap: Heap, pub symbol_table: SymbolTable, pub instructions: Vec<Instruction>, pub(super) origins: Vec<FxHashSet<hir::Id>>, pub module_function: Function, pub responsible_module: HirId, } pub type StackOffset = usize; // 0 is the last item, 1 the one before that, etc. #[derive(Clone, Debug, EnumDiscriminants, Eq, Hash, IntoStaticStr, PartialEq)] #[strum_discriminants(derive(Hash, IntoStaticStr), strum(serialize_all = "camelCase"))] pub enum Instruction { /// Pops 1 argument, pushes a tag. /// /// a, value -> a, tag CreateTag { symbol_id: SymbolId, }, /// Pops num_items items, pushes a list. /// /// a, item, item, ..., item -> a, pointer to list CreateList { num_items: usize, }, /// Pops 2 * num_fields items, pushes a struct. /// /// a, key, value, key, value, ..., key, value -> a, pointer to struct CreateStruct { num_fields: usize, }, /// Pushes a function. /// /// a -> a, pointer to function CreateFunction { captured: Vec<StackOffset>, num_args: usize, // excluding responsible parameter body: InstructionPointer, }, /// Pushes a pointer onto the stack. MIR instructions that create /// compile-time known values are compiled to this instruction. PushConstant(InlineObject), /// Pushes an item from back in the stack on the stack again. PushFromStack(StackOffset), /// Leaves the top stack item untouched, but removes n below. PopMultipleBelowTop(usize), /// Sets up the data stack for a function execution and then changes the /// instruction pointer to the first instruction. /// /// a, function, arg1, arg2, ..., argN, responsible -> a, caller, captured vars, arg1, arg2, ..., argN, responsible /// /// Later, when the function returns (perhaps many instructions after this /// one), the stack will contain the result: /// /// a, function, arg1, arg2, ..., argN, responsible ~> a, return value from function Call { num_args: usize, // excluding the responsible argument }, /// Like `Call`, but after popping the stack entries for the call itself, it /// also pops the given number of local stack entries before actually /// executing the call. TailCall { num_locals_to_pop: usize, num_args: usize, // excluding the responsible argument }, /// Returns from the current function to the original caller. Leaves the /// data stack untouched, but pops a caller from the call stack and returns /// the instruction pointer to continue where the current function was /// called. Return, /// Panics. Because the panic instruction only occurs inside the generated /// needs function, the reason is already guaranteed to be a text. /// /// a, reason, responsible -> 💥 Panic, /// a, HIR ID, function, arg1, arg2, ..., argN, responsible -> a TraceCallStarts { num_args: usize, }, // a, return value -> a TraceCallEnds, /// a, HIR ID, value -> a TraceExpressionEvaluated, /// a, HIR ID, function -> a TraceFoundFuzzableFunction, } impl Instruction { /// Applies the instruction's effect on the stack. After calling it, the /// stack will be in the same state as when the control flow continues after /// this instruction. pub fn apply_to_stack(&self, stack: &mut Vec<Id>, result: Id) { match self { Instruction::CreateTag { .. } => { stack.pop(); stack.push(result); } Instruction::CreateList { num_items } => { stack.pop_multiple(*num_items); stack.push(result); } Instruction::CreateStruct { num_fields } => { stack.pop_multiple(2 * num_fields); // fields stack.push(result); } Instruction::CreateFunction { .. } => { stack.push(result); } Instruction::PushConstant(_) => { stack.push(result); } Instruction::PushFromStack(_) => { stack.push(result); } Instruction::PopMultipleBelowTop(n) => { let top = stack.pop().unwrap(); stack.pop_multiple(*n); stack.push(top); } Instruction::Call { num_args } => { stack.pop(); // responsible stack.pop_multiple(*num_args); stack.pop(); // function/builtin stack.push(result); // return value } Instruction::TailCall { num_locals_to_pop, num_args, } => { stack.pop(); // responsible stack.pop_multiple(*num_args); stack.pop(); // function/builtin stack.pop_multiple(*num_locals_to_pop); stack.push(result); // return value } Instruction::Return => { // Only modifies the call stack and the instruction pointer. // Leaves the return value untouched on the stack. } Instruction::Panic => { stack.pop(); // responsible stack.pop(); // reason stack.push(result); } Instruction::TraceCallStarts { num_args } => { stack.pop(); // HIR ID stack.pop(); // responsible stack.pop_multiple(*num_args); stack.pop(); // callee } Instruction::TraceCallEnds => { stack.pop(); // return value } Instruction::TraceExpressionEvaluated => { stack.pop(); // HIR ID stack.pop(); // value } Instruction::TraceFoundFuzzableFunction => { stack.pop(); // HIR ID stack.pop(); // value } } } } trait StackExt { fn pop_multiple(&mut self, n: usize); } impl StackExt for Vec<Id> { fn pop_multiple(&mut self, n: usize) { for _ in 0..n { self.pop(); } } } impl Lir { pub fn functions_behind(&self, ip: InstructionPointer) -> &FxHashSet<hir::Id> { &self.origins[*ip] } pub fn range_of_function(&self, function: &hir::Id) -> Range<InstructionPointer> { let start = self .origins .iter() .position(|origins| origins.contains(function)) .unwrap(); let end = start + self .origins .iter() .skip(start) .take_while(|origins| origins.contains(function)) .count(); start.into()..end.into() } } impl ToRichIr for Lir { fn build_rich_ir(&self, builder: &mut RichIrBuilder) { builder.push("# Symbol Table", TokenType::Comment, EnumSet::empty()); for (symbol_id, symbol) in self.symbol_table.ids_and_symbols() { builder.push_newline(); builder.push( format!("{:?}", symbol_id), TokenType::Address, EnumSet::empty(), ); builder.push(": ", None, EnumSet::empty()); let symbol_range = builder.push(symbol, TokenType::Symbol, EnumSet::empty()); builder.push_reference(ReferenceKey::Symbol(symbol.to_string()), symbol_range) } builder.push_newline(); builder.push_newline(); builder.push("# Constant heap", TokenType::Comment, EnumSet::empty()); for constant in self.constant_heap.iter() { builder.push_newline(); builder.push( format!("{:p}", constant.address()), TokenType::Address, EnumSet::empty(), ); builder.push(": ", None, EnumSet::empty()); builder.push( format!("{constant:?}"), TokenType::Constant, EnumSet::empty(), ); } builder.push_newline(); builder.push_newline(); builder.push("# Instructions", TokenType::Comment, EnumSet::empty()); let instruction_index_width = (self.instructions.len() * 10 - 1).ilog10() as usize; let mut previous_origins = &FxHashSet::default(); for (i, instruction) in self.instructions.iter().enumerate() { builder.push_newline(); let origins = &self.origins[i]; if origins != previous_origins { builder.push( format!("# {}", origins.iter().join(", ")), TokenType::Comment, EnumSet::empty(), ); builder.push_newline(); previous_origins = origins; } builder.push( format!( "{}: ", ToString::to_string(&i) .pad_to_width_with_alignment(instruction_index_width, Alignment::Right), ), TokenType::Comment, EnumSet::empty(), ); instruction.build_rich_ir(builder, &self.symbol_table); } } } impl Instruction { fn build_rich_ir(&self, builder: &mut RichIrBuilder, symbol_table: &SymbolTable) { let discriminant: InstructionDiscriminants = self.into(); builder.push( Into::<&'static str>::into(discriminant), None, EnumSet::empty(), ); match self { Instruction::CreateTag { symbol_id } => { builder.push(" ", None, EnumSet::empty()); let symbol_range = builder.push( DisplayWithSymbolTable::to_string(symbol_id, symbol_table), None, EnumSet::empty(), ); builder.push_reference( ReferenceKey::Symbol(symbol_table.get(*symbol_id).to_string()), symbol_range, ); } Instruction::CreateList { num_items } => { builder.push(" ", None, EnumSet::empty()); builder.push(ToString::to_string(num_items), None, EnumSet::empty()); } Instruction::CreateStruct { num_fields } => { builder.push(" ", None, EnumSet::empty()); builder.push(ToString::to_string(num_fields), None, EnumSet::empty()); } Instruction::CreateFunction { captured, num_args, body, } => { builder.push( format!( " with {num_args} {} capturing {} starting at {body:?}", arguments_plural(*num_args), if captured.is_empty() { "nothing".to_string() } else { captured.iter().join(", ") }, ), None, EnumSet::empty(), ); } Instruction::PushConstant(constant) => { builder.push(" ", None, EnumSet::empty()); if let InlineData::Pointer(pointer) = InlineData::from(*constant) { builder.push( format!("{:?}", pointer.get().address()), TokenType::Address, EnumSet::empty(), ); } else { builder.push("inline", TokenType::Address, EnumSet::empty()); } builder.push(" ", None, EnumSet::empty()); builder.push( format!("{constant:?}"), TokenType::Constant, EnumSet::empty(), ); } Instruction::PushFromStack(offset) => { builder.push(" ", None, EnumSet::empty()); builder.push(ToString::to_string(offset), None, EnumSet::empty()); } Instruction::PopMultipleBelowTop(count) => { builder.push(" ", None, EnumSet::empty()); builder.push(ToString::to_string(count), None, EnumSet::empty()); } Instruction::Call { num_args } => { builder.push( format!(" with {num_args} {}", arguments_plural(*num_args)), None, EnumSet::empty(), ); } Instruction::TailCall { num_locals_to_pop, num_args, } => { builder.push( format!( " with {num_locals_to_pop} locals and {num_args} {}", arguments_plural(*num_args), ), None, EnumSet::empty(), ); } Instruction::Return => {} Instruction::Panic => {} Instruction::TraceCallStarts { num_args } => { builder.push( format!(" ({num_args} {})", arguments_plural(*num_args)), None, EnumSet::empty(), ); } Instruction::TraceCallEnds => {} Instruction::TraceExpressionEvaluated => {} Instruction::TraceFoundFuzzableFunction => {} } } } fn arguments_plural(num_args: usize) -> &'static str { if num_args == 1 { "argument" } else { "arguments" } } #[extension_trait] pub impl RichIrForLir for RichIr { fn for_byte_code(module: &Module, byte_code: &Lir, tracing_config: &TracingConfig) -> RichIr { let mut builder = RichIrBuilder::default(); builder.push( format!("# VM Byte Code for module {module}"), TokenType::Comment, EnumSet::empty(), ); builder.push_newline(); builder.push_tracing_config(tracing_config); builder.push_newline(); byte_code.build_rich_ir(&mut builder); builder.finish(true) } }
use super::grouped::{GroupedOperation, GroupedOperator}; use nom_sql::SqlType; use serde::Deserialize; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use prelude::*; // Grouping UDF third attempt // // Grouping udf second attempt // Ohua UDF, first attempt
pub use functional_tests::compiler::*;
use crate::compiling::v1::assemble::prelude::*; use crate::query::BuiltInMacro; /// Compile an expression. impl Assemble for ast::Expr { fn assemble(&self, c: &mut Compiler<'_>, needs: Needs) -> CompileResult<Asm> { let span = self.span(); log::trace!("Expr => {:?}", c.source.source(span)); let asm = match self { ast::Expr::Path(path) => path.assemble(c, needs)?, ast::Expr::While(expr_while) => expr_while.assemble(c, needs)?, ast::Expr::For(expr_for) => expr_for.assemble(c, needs)?, ast::Expr::Loop(expr_loop) => expr_loop.assemble(c, needs)?, ast::Expr::Let(expr_let) => expr_let.assemble(c, needs)?, ast::Expr::Group(expr) => expr.expr.assemble(c, needs)?, ast::Expr::Unary(expr_unary) => expr_unary.assemble(c, needs)?, ast::Expr::Assign(expr_assign) => expr_assign.assemble(c, needs)?, ast::Expr::Binary(expr_binary) => expr_binary.assemble(c, needs)?, ast::Expr::If(expr_if) => expr_if.assemble(c, needs)?, ast::Expr::Index(expr_index_get) => expr_index_get.assemble(c, needs)?, ast::Expr::Break(expr_break) => expr_break.assemble(c, needs)?, ast::Expr::Continue(expr_continue) => expr_continue.assemble(c, needs)?, ast::Expr::Yield(expr_yield) => expr_yield.assemble(c, needs)?, ast::Expr::Block(expr_block) => expr_block.assemble(c, needs)?, ast::Expr::Return(expr_return) => expr_return.assemble(c, needs)?, ast::Expr::Match(expr_match) => expr_match.assemble(c, needs)?, ast::Expr::Await(expr_await) => expr_await.assemble(c, needs)?, ast::Expr::Try(expr_try) => expr_try.assemble(c, needs)?, ast::Expr::Select(expr_select) => expr_select.assemble(c, needs)?, ast::Expr::Call(expr_call) => expr_call.assemble(c, needs)?, ast::Expr::FieldAccess(expr_field_access) => expr_field_access.assemble(c, needs)?, ast::Expr::Closure(expr_closure) => expr_closure.assemble(c, needs)?, ast::Expr::Lit(expr_lit) => expr_lit.lit.assemble(c, needs)?, ast::Expr::ForceSemi(force_semi) => force_semi.expr.assemble(c, needs)?, ast::Expr::Tuple(expr_tuple) => expr_tuple.assemble(c, needs)?, ast::Expr::Vec(expr_vec) => expr_vec.assemble(c, needs)?, ast::Expr::Object(expr_object) => expr_object.assemble(c, needs)?, ast::Expr::Range(expr_range) => expr_range.assemble(c, needs)?, ast::Expr::MacroCall(expr_call_macro) => { let internal_macro = c.query.builtin_macro_for(&**expr_call_macro)?; match &*internal_macro { BuiltInMacro::Template(template) => template.assemble(c, needs)?, BuiltInMacro::Format(format) => format.assemble(c, needs)?, BuiltInMacro::Line(line) => line.value.assemble(c, needs)?, BuiltInMacro::File(file) => file.value.assemble(c, needs)?, } } // NB: declarations are not used in this compilation stage. // They have been separately indexed and will be built when queried // for. ast::Expr::Item(decl) => { let span = decl.span(); if needs.value() { c.asm.push(Inst::unit(), span); } Asm::top(span) } }; Ok(asm) } }
//! A compositor that can composite [`source`](crate::source)s mod compositor_2d; pub use compositor_2d::Compositor2D;
use super::attributes::{AttributeSchema, BUILTIN_SCHEMAS}; use super::errors::Error; use super::*; use crate::lexer::Span; use regex::Regex; use std::collections::HashMap; use std::convert::TryFrom; pub fn validate_file(file: &File) -> Vec<Error> { let mut validator = Validator::new(); validator.validate(file); return validator.errors; } pub fn validate_attributes(attrs: &Attributes, placement: FidlType) -> Vec<Error> { let mut validator = Validator::new(); validator.validate_attributes(attrs, placement); return validator.errors; } /// This struct exists mainly to keep track of some internal state (i.e. the /// list of errors) while doing validation on a File. See raw::errors for the /// things that are checked at this stage. pub struct Validator { errors: Vec<Error>, attribute_schemas: &'static HashMap<String, AttributeSchema>, } // TODO: shouldn't have to need to specify FidlTypes explicitly. They should be automatically // associated with their corresponding raw:: type impl Validator { pub fn new() -> Validator { // TODO: construct as not often as possible Validator { errors: Vec::new(), attribute_schemas: &BUILTIN_SCHEMAS, } } pub fn validate(&mut self, file: &File) { self.validate_attributes(&file.attributes, FidlType::Library); self.validate_library_name(&file.name); // self.validate_imports(&file.imports); for decl in file.decls.iter() { let span = decl.span; match &decl.value { Decl::Alias(decl) => self.validate_alias(decl), Decl::Const(decl) => self.validate_const(&decl), Decl::Bits(decl) => self.validate_bits(&decl), Decl::Enum(decl) => self.validate_enum(&decl), Decl::Struct(decl) => self.validate_struct(&decl), Decl::Table(decl) => self.validate_table(&decl, span), Decl::Union(decl) => self.validate_union(&decl, span), Decl::Protocol(decl) => self.validate_protocol(&decl), Decl::Service(decl) => self.validate_service(&decl), } } } fn validate_attributes(&mut self, attrs: &Attributes, placement: FidlType) { self.check_for_duplicates(attrs, FidlType::Attribute); for attr in attrs { self.validate_attribute(&attr, placement); } } fn validate_attribute(&mut self, attr: &Spanned<Attribute>, placement: FidlType) { if let Some(ref schema) = self.attribute_schemas.get(&attr.value.name.value) { if !schema.is_placement_valid(placement) { self.errors.push(Error::InvalidAttributePlacement { name: attr.value.name.clone(), placement: placement, }); } if !schema.is_value_valid(&attr.value.value) { self.errors.push(Error::InvalidAttributeValue { name: attr.value.name.clone(), value: attr.value.value.clone().unwrap_or(Spanned { value: "".to_string(), span: attr.span, }), }); } } } fn validate_library_name(&mut self, name: &LibraryName) { let re = Regex::new(r"^[a-z][a-z0-9]*$").unwrap(); for component in name.iter() { if !re.is_match(&component.value) { self.errors.push(Error::InvalidLibraryName(component.span)); // just show the first error break; } } } fn validate_alias(&mut self, decl: &Alias) { self.validate_attributes(&decl.attributes, FidlType::Alias); } fn validate_const(&mut self, decl: &Const) { self.validate_attributes(&decl.attributes, FidlType::ConstDecl); } fn validate_bits(&mut self, decl: &Bits) { self.check_for_duplicates(&decl.members, FidlType::BitsMember); self.validate_attributes(&decl.attributes, FidlType::BitsDecl); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::BitsMember); } } fn validate_enum(&mut self, decl: &Enum) { self.check_for_duplicates(&decl.members, FidlType::EnumMember); self.validate_attributes(&decl.attributes, FidlType::EnumDecl); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::EnumMember); } } fn validate_struct(&mut self, decl: &Struct) { self.check_for_duplicates(&decl.members, FidlType::StructMember); self.validate_attributes(&decl.attributes, FidlType::StructDecl); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::StructMember); } } fn validate_table(&mut self, decl: &Table, span: Span) { self.check_for_duplicates(&decl.members, FidlType::TableMember); self.validate_attributes(&decl.attributes, FidlType::TableDecl); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::TableMember); } self.check_ordinals(&decl.members, span, decl.name.span); } fn validate_union(&mut self, decl: &Union, span: Span) { self.validate_attributes(&decl.attributes, FidlType::UnionDecl); self.check_for_duplicates(&decl.members, FidlType::UnionMember); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::UnionMember); } self.check_ordinals(&decl.members, span, decl.name.span); } fn validate_protocol(&mut self, decl: &Protocol) { self.validate_attributes(&decl.attributes, FidlType::ProtocolDecl); // Note: we check for duplicate compose statements after name resolution, once we // know which protocols each name points to. self.check_for_duplicates(&decl.methods, FidlType::ProtocolDecl); for method in &decl.methods { self.validate_attributes(&method.value.attributes, FidlType::Method); if let Some(request) = &method.value.request { self.check_for_duplicates(request, FidlType::Parameter); for param in request { self.validate_attributes(&param.value.attributes, FidlType::Parameter); } } if let Some(response) = &method.value.response { self.check_for_duplicates(response, FidlType::Parameter); for param in response { self.validate_attributes(&param.value.attributes, FidlType::Parameter); } } } } fn validate_service(&mut self, decl: &Service) { self.validate_attributes(&decl.attributes, FidlType::ServiceDecl); for member in &decl.members { self.validate_attributes(&member.value.attributes, FidlType::ServiceMember); } } // TODO: spans are not completely correct here fn check_for_duplicates<T>(&mut self, values: &Vec<Spanned<T>>, decltype: FidlType) where T: Nameable, { let mut seen: HashMap<String, usize> = HashMap::new(); for (i, val) in values.iter().enumerate() { match val.name() { None => continue, Some(ref name) => { if let Some(index) = seen.get(*name) { self.errors.push(Error::DuplicateDefinition { original: values[*index].span, duplicate: val.span, decl_type: decltype, decl_name: name.to_string(), }); } else { seen.insert(name.to_string(), i); } } }; } } /// Checks that a set of ordinal members are valid: /// - at least one non reserved member /// - not out of bounds ordinals (i.e. they all fall in [1, 0xffff_ffff]) /// - they form a dense space starting at 1 fn check_ordinals<T>(&mut self, values: &Vec<Spanned<T>>, decl_span: Span, decl_name_span: Span) where T: HasOrdinal, { let is_empty = values .iter() .filter(|&member| !member.value.is_reserved()) .peekable() .peek() .is_none(); if is_empty { self.errors.push(Error::EmptyTableOrUnion(decl_span)); } let (ordinals, oob_ordinals): (Vec<_>, Vec<_>) = values .iter() .map(|member| { let IntLiteral { value, is_negative } = member.value.ordinal().value; let ord_val = u32::try_from(value); if is_negative || value == 0 || ord_val.is_err() { Err(member.span) } else { Ok(ord_val.unwrap()) } }) .partition(Result::is_ok); if !oob_ordinals.is_empty() { self.errors.push(Error::OobOrdinals { decl_span, ordinal_spans: oob_ordinals.into_iter().map(Result::unwrap_err).collect(), }); } let mut ordinals: Vec<u32> = ordinals.into_iter().map(Result::unwrap).collect(); ordinals.sort(); let mut missing_ranges: Vec<(u32, u32)> = Vec::new(); let mut next_expected = 1; for ord in ordinals { if ord != next_expected { missing_ranges.push((next_expected, ord - 1)); } next_expected = ord + 1; } if !missing_ranges.is_empty() { self.errors.push(Error::NonDenseOrdinals { decl_span, name_span: decl_name_span, missing_ranges: missing_ranges, }); } } } trait Nameable { fn name(&self) -> Option<&String>; } impl<T> Nameable for Spanned<T> where T: Nameable, { fn name(&self) -> Option<&String> { self.value.name() } } impl Nameable for Attribute { fn name(&self) -> Option<&String> { Some(&self.name.value) } } impl Nameable for StructMember { fn name(&self) -> Option<&String> { Some(&self.name.value) } } impl Nameable for BitsMember { fn name(&self) -> Option<&String> { Some(&self.name.value) } } impl Nameable for EnumMember { fn name(&self) -> Option<&String> { Some(&self.name.value) } } impl Nameable for TableMember { fn name(&self) -> Option<&String> { match &self.inner { TableMemberInner::Reserved => None, TableMemberInner::Used { ty: _, name } => Some(&name.value), } } } impl Nameable for UnionMember { fn name(&self) -> Option<&String> { match &self.inner { UnionMemberInner::Reserved => None, UnionMemberInner::Used { ty: _, name } => Some(&name.value), } } } impl Nameable for Method { fn name(&self) -> Option<&String> { Some(&self.name.value) } } impl Nameable for Parameter { fn name(&self) -> Option<&String> { Some(&self.name.value) } } trait HasOrdinal { fn is_reserved(&self) -> bool; fn ordinal(&self) -> Spanned<IntLiteral>; } impl HasOrdinal for TableMember { fn is_reserved(&self) -> bool { match &self.inner { TableMemberInner::Reserved => true, _ => false, } } fn ordinal(&self) -> Spanned<IntLiteral> { self.ordinal } } impl HasOrdinal for UnionMember { fn is_reserved(&self) -> bool { match &self.inner { UnionMemberInner::Reserved => true, _ => false, } } fn ordinal(&self) -> Spanned<IntLiteral> { self.ordinal } }
#[doc = "Reader of register RGCFR"] pub type R = crate::R<u32, super::RGCFR>; #[doc = "Writer for register RGCFR"] pub type W = crate::W<u32, super::RGCFR>; #[doc = "Register RGCFR `reset()`'s with value 0"] impl crate::ResetValue for super::RGCFR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CSOF0`"] pub type CSOF0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSOF0`"] pub struct CSOF0_W<'a> { w: &'a mut W, } impl<'a> CSOF0_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) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `CSOF1`"] pub type CSOF1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSOF1`"] pub struct CSOF1_W<'a> { w: &'a mut W, } impl<'a> CSOF1_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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `CSOF2`"] pub type CSOF2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSOF2`"] pub struct CSOF2_W<'a> { w: &'a mut W, } impl<'a> CSOF2_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 `CSOF3`"] pub type CSOF3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSOF3`"] pub struct CSOF3_W<'a> { w: &'a mut W, } impl<'a> CSOF3_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 } } impl R { #[doc = "Bit 0 - Generator Clear Overrun Flag 0"] #[inline(always)] pub fn csof0(&self) -> CSOF0_R { CSOF0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Generator Clear Overrun Flag 1"] #[inline(always)] pub fn csof1(&self) -> CSOF1_R { CSOF1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Generator Clear Overrun Flag 2"] #[inline(always)] pub fn csof2(&self) -> CSOF2_R { CSOF2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Generator Clear Overrun Flag 3"] #[inline(always)] pub fn csof3(&self) -> CSOF3_R { CSOF3_R::new(((self.bits >> 3) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Generator Clear Overrun Flag 0"] #[inline(always)] pub fn csof0(&mut self) -> CSOF0_W { CSOF0_W { w: self } } #[doc = "Bit 1 - Generator Clear Overrun Flag 1"] #[inline(always)] pub fn csof1(&mut self) -> CSOF1_W { CSOF1_W { w: self } } #[doc = "Bit 2 - Generator Clear Overrun Flag 2"] #[inline(always)] pub fn csof2(&mut self) -> CSOF2_W { CSOF2_W { w: self } } #[doc = "Bit 3 - Generator Clear Overrun Flag 3"] #[inline(always)] pub fn csof3(&mut self) -> CSOF3_W { CSOF3_W { w: self } } }
use super::*; impl<A: Array> iter::Extend<A::Item> for StackVec<A> { #[inline] fn extend<Iterable: IntoIterator<Item = A::Item>> ( self: &mut Self, iterable: Iterable, ) { // This is currently the most optimized `extend` implementation, // branching-prediction-wise let mut len = self.len; debug_assert!(len <= Self::CAPACITY); if len == Self::CAPACITY { return }; unsafe { for value in iterable { debug_assert!(len < Self::CAPACITY); ptr::write( self.array.as_mut_ptr() .offset(len as isize), value, ); len += 1; self.len = len; if len == Self::CAPACITY { break }; }; }; // // This version was less optimized: // let mut iterator = iterable.into_iter(); // let mut len = self.len; // while len < Self::CAPACITY { // if let Some(value) = iterator.next() { // unsafe { // ptr::write( // self.array.as_mut_ptr() // .offset(len as isize), // value, // ); // len += 1; // } // } else { // break // }; // }; // self.len = len; // // And this one even worse o_O // iterable.into_iter() // .take(Self::CAPACITY - self.len) // .for_each(|value| unsafe { // self.push_unchecked(value) // }) } } impl<A: Array> iter::FromIterator<A::Item> for StackVec<A> { #[inline(always)] fn from_iter<Iterable: IntoIterator<Item = A::Item>> ( iterable: Iterable, ) -> Self { let mut slf = Self::new(); slf.extend(iterable); slf } }
#![warn(clippy::all)] #![warn(clippy::pedantic)] fn main() { run(); } #[allow(clippy::cast_possible_truncation)] fn run() { let start = std::time::Instant::now(); // code goes here let limit = 28123; let abundants: Vec<u64> = (1..=limit).filter(|&v| d(v) > v).collect(); let mut abundant_sums = vec![false; (limit + 1) as usize]; for i in 0..abundants.len() - 1 { for j in i..abundants.len() { let sum = abundants[i] + abundants[j]; if sum <= limit { abundant_sums[sum as usize] = true; } } } let res = abundant_sums .into_iter() .enumerate() .filter(|(_, v)| !*v) .fold(0, |acc, (i, _)| acc + i) as u64; let span = start.elapsed().as_nanos(); println!("{} {}", res, span); } fn d(n: u64) -> u64 { let mut limit = sqrt(n); let mut sum = 1; if limit * limit == n { limit -= 1; sum += limit; } for i in 2..=limit { if n % i == 0 { sum += i + (n / i); } } sum } #[allow(clippy::similar_names)] fn sqrt(a: u64) -> u64 { let val = a; let mut min = 0; let mut max = a; while min < max { let mid = (min + max + 1) / 2; let mid_sq = mid * mid; match mid_sq.cmp(&val) { | std::cmp::Ordering::Equal => return mid, | std::cmp::Ordering::Less => min = mid, | std::cmp::Ordering::Greater => max = mid - 1, } } min }
extern crate sdl2; extern crate cgmath; use cgmath::Vector2; use cgmath::Vector3; use cgmath::InnerSpace; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::rect::Rect; use sdl2::keyboard::Keycode; use std::collections::HashSet; use crate::data::WorldMap; use crate::textures::TextureManager; use crate::sprites::Entity; use crate::sprites::SpriteManager; use crate::sprites::EntityManager; use crate::data::EntityJSON; use crate::animation::AnimationManager; const SCREEN_HEIGHT: i32 = 600; const SCREEN_WIDTH: i32 = 800; const TEX_WIDTH: u32 = 64; const TEX_HEIGHT: u32 = 64; const WALL_HEIGHT_SCALE: f64 = 1.0; const MOVE_SPEED: f64 = 4.0; const ROT_SPEED: f64 = 2.0; const ACCELERATION: f64 = 0.1; const DRAG: f64 = 3.0; const PLAYER_RADIUS: f64 = 0.2; struct Player { pos: Vector3<f64>, dir: Vector2<f64>, velocity: Vector3<f64>, camera_plane: Vector2<f64>, } #[derive(PartialEq)] enum WallSide { X, Y, } #[derive(Debug)] struct SpriteSortable<'a> { entity: &'a Entity, distance: f64, } pub struct Game<'a, 'b, 'c> { player: Player, world_map: WorldMap, entities: Vec<Entity>, texture_manager: &'a TextureManager<'a>, sprite_manager: &'c SpriteManager<'c>, entity_manager: &'c mut EntityManager<'c>, // Mutable because it increments itself each time it spawns animation_manager: &'c AnimationManager, floor_texture: &'b mut Texture<'a>, z_buffer: [f64; SCREEN_WIDTH as usize], } impl<'a, 'b, 'c> Game<'a, 'b, 'c> { pub fn new(map: WorldMap, manager: &'a TextureManager, s_manager: &'c SpriteManager, e_manager: &'c mut EntityManager<'c>, a_manager: &'c AnimationManager, floor_tex: &'b mut Texture<'a>) -> Game<'a, 'b, 'c> { // Init Player and Camera let player = Player { pos: Vector3::new(6.5, 3.5, 0.0), dir: Vector2::new(-1.0, 0.0), velocity: Vector3::new(0.0, 0.0, 0.0), camera_plane: Vector2::new(0.0, 0.66), }; let mut g = Game { player: player, world_map: map, entities: vec![], texture_manager: manager, sprite_manager: s_manager, entity_manager: e_manager, animation_manager: a_manager, floor_texture: floor_tex, z_buffer: [0.0; SCREEN_WIDTH as usize], }; // Spawn all entities defined on the map g.init_entities(&g.world_map.entities.clone()); return g; } pub fn draw(&mut self, canvas: &mut Canvas<sdl2::video::Window>, frame_time: f64) { self.render_floor(canvas); self.render_walls(canvas); self.render_sprites(canvas); self.tick_animations(frame_time); } // Actually renders the floor AND ceiling // Horizontally raycasts fn render_floor(&mut self, canvas: &mut sdl2::render::Canvas<sdl2::video::Window>) { let new_data = &mut vec![128; (SCREEN_WIDTH * SCREEN_HEIGHT * 4) as usize]; let left_ray = self.player.dir - self.player.camera_plane; let right_ray = self.player.dir + self.player.camera_plane; for y in SCREEN_HEIGHT / 2..SCREEN_HEIGHT { // Current y distance to middle of screen let p = y - SCREEN_HEIGHT / 2; // Height of camera let pos_z = 0.5 * SCREEN_HEIGHT as f64; // Horizontal distance from camera to floor for current row let row_dist = pos_z / p as f64; let floor_step = (right_ray - left_ray) * row_dist / SCREEN_WIDTH as f64; let mut floor_pos = Vector2::new( self.player.pos.x + row_dist * left_ray.x, self.player.pos.y + row_dist * left_ray.y, ); for x in 0..SCREEN_WIDTH { // Take integer portion for cell # let floor_cell = Vector2::new( floor_pos.x as i32, floor_pos.y as i32, ); let f_cell = self.world_map.get_cell(floor_cell.x as u32 & (self.world_map.width - 1), floor_cell.y as u32 & (self.world_map.height - 1)).floor_tex - 1; let c_cell = self.world_map.get_cell(floor_cell.x as u32 & (self.world_map.width - 1), floor_cell.y as u32 & (self.world_map.height - 1)).ceil_tex - 1; // Get fractional part of coordiate (how far in cell) let tex_x = (TEX_WIDTH as f64 * (floor_pos.x - floor_cell.x as f64)) as u32 & (TEX_WIDTH - 1); let tex_y = (TEX_HEIGHT as f64 * (floor_pos.y - floor_cell.y as f64)) as u32 & (TEX_HEIGHT - 1); floor_pos = floor_pos + floor_step; // Yeah I gotta copy 4 bytes at a time here so for efficiency's sake we gotta go unsafe for the memcpy :O // One RGBA pixel = 4 bytes, so we copy 4 bytes from src texture to destination // Trust me... unsafe { if f_cell > -1 { // Floor let tex_start = &self.texture_manager.get_raw_tex(f_cell as u32)[((TEX_WIDTH * tex_y + tex_x) * 4) as usize] as *const u8; let floor_start = &mut new_data[((y * SCREEN_WIDTH + x) * 4) as usize] as *mut u8; std::ptr::copy(tex_start, floor_start, 4); } if c_cell > -1 { // Ceiling let tex_start = &self.texture_manager.get_raw_tex(c_cell as u32)[((TEX_WIDTH * tex_y + tex_x) * 4) as usize] as *const u8; let ceil_start = &mut new_data[(((SCREEN_HEIGHT - y) * SCREEN_WIDTH + x) * 4) as usize] as *mut u8; std::ptr::copy(tex_start, ceil_start, 4); } } } } // Faster than texture.update? self.floor_texture.with_lock(None, |dat, _| { dat.copy_from_slice(new_data); }).unwrap(); canvas.copy(self.floor_texture, None, None).unwrap(); } // Vertical raycast walls fn render_walls(&mut self, canvas: &mut sdl2::render::Canvas<sdl2::video::Window>) { for i in 0..SCREEN_WIDTH { // Calculate incoming ray position/direction let camera_x: f64 = 2.0 * i as f64 / SCREEN_WIDTH as f64 - 1.0; let ray_hit_pos = camera_x * self.player.camera_plane; let ray_dir = self.player.dir + ray_hit_pos; // Which box we're in let mut curr_grid = Vector2::new( self.player.pos.x as i32, self.player.pos.y as i32, ); // Length of ray from any x/y side to next x/y side let delta_dist = Vector2::new((1.0 / ray_dir.x).abs(), (1.0 / ray_dir.y).abs()); let step_x: i32; let step_y: i32; let mut side_dist_x: f64; let mut side_dist_y: f64; if ray_dir.x < 0.0 { step_x = -1; side_dist_x = (self.player.pos.x - curr_grid.x as f64) * delta_dist.x; } else { step_x = 1; side_dist_x = (curr_grid.x as f64 + 1.0 - self.player.pos.x) * delta_dist.x; } if ray_dir.y < 0.0 { step_y = -1; side_dist_y = (self.player.pos.y - curr_grid.y as f64) * delta_dist.y; } else { step_y = 1; side_dist_y = (curr_grid.y as f64 + 1.0 - self.player.pos.y) * delta_dist.y; } // start DDA let mut side: WallSide; loop { if side_dist_x < side_dist_y { side_dist_x += delta_dist.x; curr_grid.x += step_x; side = WallSide::X; } else { side_dist_y += delta_dist.y; curr_grid.y += step_y; side = WallSide::Y; } if self.world_map.get_cell(curr_grid.x as u32, curr_grid.y as u32).wall_tex > 0 { break; } } let mut perp_wall_dist = match side { WallSide::X => { (curr_grid.x as f64 - self.player.pos.x + (1.0 - step_x as f64) / 2.0) / ray_dir.x } WallSide::Y => { (curr_grid.y as f64 - self.player.pos.y + (1.0 - step_y as f64) / 2.0) / ray_dir.y } }; // Clamp minimum distance to avoid overflow perp_wall_dist = perp_wall_dist.max(0.001); // Save distance in z-buffer self.z_buffer[i as usize] = perp_wall_dist; // Calculate height of line let line_height = (WALL_HEIGHT_SCALE * SCREEN_HEIGHT as f64 / perp_wall_dist) as i32; // Get lowest/highest pixel to draw (drawing walls in middle of screen) let mut draw_start = -1 * line_height / 2 + SCREEN_HEIGHT / 2; if draw_start < 0 { draw_start = 0; } let mut draw_end = line_height / 2 + SCREEN_HEIGHT / 2; if draw_end >= SCREEN_HEIGHT as i32 { draw_end = SCREEN_HEIGHT as i32 - 1; } // Texture calculations let tex_num = self.world_map.get_cell(curr_grid.x as u32, curr_grid.y as u32).wall_tex - 1; // Exact x/y coord where it hit let wall_x = match side { WallSide::X => self.player.pos.y + perp_wall_dist * ray_dir.y, WallSide::Y => self.player.pos.x + perp_wall_dist * ray_dir.x, }; let wall_x = wall_x - wall_x.floor(); //x coord on the texture let mut tex_x = (wall_x * TEX_WIDTH as f64) as u32; if side == WallSide::X && ray_dir.x > 0 as f64 { tex_x = TEX_WIDTH - tex_x - 1; } if side == WallSide::Y && ray_dir.y < 0 as f64 { tex_x = TEX_WIDTH - tex_x - 1; } let texture = match side { WallSide::X => self.texture_manager.get_tex(tex_num as u32), WallSide::Y => self.texture_manager.get_dark_tex(tex_num as u32), }; let mut tex_strip_start = 0; let mut tex_strip_height = TEX_HEIGHT as i32; let screen_wall_ratio = SCREEN_HEIGHT as f64 / line_height as f64; // Trim texture region to only be the portion visible in the viewcreen, if wall > screen height if screen_wall_ratio < 1.0 { let tex_y_drawn = (screen_wall_ratio * TEX_HEIGHT as f64) as i32; let offset = TEX_HEIGHT as i32 - tex_y_drawn; tex_strip_start += offset / 2; tex_strip_height -= offset; } canvas.copy( texture, Rect::new(tex_x as i32, tex_strip_start, 1, tex_strip_height as u32), Rect::new(i as i32, SCREEN_HEIGHT - draw_end, 1, (draw_end - draw_start) as u32), ).unwrap(); } } // Render all current "Entities" as 2d sprites fn render_sprites(&mut self, canvas: &mut Canvas<sdl2::video::Window>) { // Get all entities' sprites and sort them let mut sprite_buffer = vec![]; for ent in self.entities.iter() { sprite_buffer.push(SpriteSortable { entity: ent, distance: (self.player.pos.x - ent.pos.x).powf(2.0) + (self.player.pos.y - ent.pos.y).powf(2.0), // Take distance without square root (doesn't matter) }); } sprite_buffer.sort_by(|a, b| a.distance.partial_cmp(&b.distance).unwrap()); sprite_buffer.reverse(); // Farthest to nearest // draw all sprites for s in sprite_buffer { let sprite = s.entity; let rel_pos = sprite.pos - self.player.pos; //transform sprite with the inverse camera matrix // [ planeX dirX ] -1 [ dirY -dirX ] // [ ] = 1/(planeX*dirY-dirX*planeY) * [ ] // [ planeY dirY ] [ -planeY planeX ] let inv_det = 1.0 / (self.player.camera_plane.x * self.player.dir.y - self.player.dir.x * self.player.camera_plane.y); let transform_x = inv_det * (self.player.dir.y * rel_pos.x - self.player.dir.x * rel_pos.y); let mut transform_y = inv_det * ((-self.player.camera_plane.y) * rel_pos.x + self.player.camera_plane.x * rel_pos.y); // depth of sprite from camera // Clamp transform_y if ~= 0 to prevent overflows if transform_y.abs() < 0.0001 { if transform_y < 0.0 { transform_y = -0.0001; } else { transform_y = 0.0001; } } let mov_screen = (sprite.sprite.v_move as f64 / transform_y) as i32; // User defined sprite offset let sprite_screen_x = ((SCREEN_WIDTH / 2) as f64 * (1.0 + transform_x / transform_y)) as i32; // height of sprite on screen let sprite_height = (((SCREEN_HEIGHT as f64 / transform_y) * sprite.sprite.v_scale) as i32).abs(); let sprite_width = ((SCREEN_HEIGHT as f64 / transform_y) * sprite.sprite.u_scale) as i32; // clamp draw start into screen with max/min let draw_start = Vector2::new(((-sprite_width) / 2 + sprite_screen_x).max(0), ((-sprite_height) / 2 + SCREEN_HEIGHT / 2 + mov_screen).max(0)); let draw_end = Vector2::new((sprite_width / 2 + sprite_screen_x).min(SCREEN_WIDTH - 1), (sprite_height / 2 + SCREEN_HEIGHT / 2 + mov_screen).min(SCREEN_HEIGHT - 1)); // Draw every vertical stripe of sprite for x in draw_start.x..draw_end.x { let mut angle = 0.0; // Only calculate this if the sprite is actually a rotating one if sprite.sprite.rotating { // Get angle between entity's direction and player direction let diff_ray = sprite.pos - self.player.pos; // angle of Sprite's looking direction vs. origin let dir_angle = sprite.dir.y.atan2(sprite.dir.x); angle = diff_ray.y.atan2(diff_ray.x) - dir_angle; if angle > std::f64::consts::PI { angle -= 2.0 * std::f64::consts::PI; } if angle <= -std::f64::consts::PI { angle += 2.0 * std::f64::consts::PI; } } // Get vertical slice on sprite sheet let sprite_rect = sprite.get_frame_rect(x, sprite_screen_x, sprite_width, angle); //1) it's in front of camera plane //2) it's on the screen (left) //3) it's on the screen (right) //4) ZBuffer, with perpendicular distance if transform_y > 0.0 && x > 0 && x < SCREEN_WIDTH && transform_y < self.z_buffer[x as usize] { canvas.copy( self.sprite_manager.get_texture(&sprite.sprite.tex_id).unwrap(), sprite_rect, Rect::new(x, SCREEN_HEIGHT - (draw_end.y + mov_screen), 1, sprite_height as u32) ).unwrap(); } } } } pub fn tick_animations (&mut self, frame_time: f64) { for e in self.entities.iter_mut() { e.tick_animation(frame_time); } } pub fn move_player( &mut self, event_pump: &sdl2::EventPump, frame_time: f64, ) { let rot_speed = frame_time * ROT_SPEED; let pressed_keys: HashSet<Keycode> = event_pump .keyboard_state() .pressed_scancodes() .filter_map(Keycode::from_scancode) .collect(); if pressed_keys.contains(&Keycode::Up) { let dir_normal = self.player.dir.normalize(); let dir = Vector3::new(dir_normal.x, dir_normal.y, 0.0); let new_velocity = self.player.velocity + ACCELERATION * frame_time * dir; if new_velocity.magnitude() < MOVE_SPEED * frame_time { self.player.velocity = new_velocity; } } if pressed_keys.contains(&Keycode::Down) { let dir_normal = self.player.dir.normalize(); let dir = Vector3::new(dir_normal.x, dir_normal.y, 0.0); let new_velocity = self.player.velocity - ACCELERATION * frame_time * dir; if new_velocity.magnitude() < MOVE_SPEED * frame_time { self.player.velocity = new_velocity; } } if pressed_keys.contains(&Keycode::Left) { self.player.dir = Vector2::new( self.player.dir.x * rot_speed.cos() - self.player.dir.y * rot_speed.sin(), self.player.dir.x * rot_speed.sin() + self.player.dir.y * rot_speed.cos(), ); self.player.camera_plane = Vector2::new( self.player.camera_plane.x * rot_speed.cos() - self.player.camera_plane.y * rot_speed.sin(), self.player.camera_plane.x * rot_speed.sin() + self.player.camera_plane.y * rot_speed.cos(), ); } if pressed_keys.contains(&Keycode::Right) { self.player.dir = Vector2::new( self.player.dir.x * (-rot_speed).cos() - self.player.dir.y * (-rot_speed).sin(), self.player.dir.x * (-rot_speed).sin() + self.player.dir.y * (-rot_speed).cos(), ); self.player.camera_plane = Vector2::new( self.player.camera_plane.x * (-rot_speed).cos() - self.player.camera_plane.y * (-rot_speed).sin(), self.player.camera_plane.x * (-rot_speed).sin() + self.player.camera_plane.y * (-rot_speed).cos(), ); } // TODO: remove, just demo'ing animations if pressed_keys.contains(&Keycode::K) { for e in self.entities.iter_mut() { e.kill(self.animation_manager); } } if pressed_keys.contains(&Keycode::R) { for e in self.entities.iter_mut() { e.revive(); } } // Apply drag self.player.velocity -= self.player.velocity * DRAG * frame_time; // Do sprite collision detection for e in self.entities.iter() { if e.collidable { let diff = e.pos - self.player.pos; if diff.magnitude() < e.collision_radius { self.player.velocity = -1.0 * self.player.velocity; } } } // Do wall collision detection if self.player.velocity.magnitude() > 0.0 { // Draw a line from current -> direction * hitbox radius let collision_point = self.player.pos + self.player.velocity.normalize() * PLAYER_RADIUS; // Do wall collision detection // Move player based on current velocity if self.world_map.get_cell(collision_point.x as u32, collision_point.y as u32).wall_tex == 0 { // noop } else { // Compare current/new cells, update velocity according to which way we hit the wall let new_x = collision_point.x as u32; let curr_x = self.player.pos.x as u32; // We hit a wall from the x direction if curr_x != new_x { self.player.velocity = Vector3::new(0.0, self.player.velocity.y, 0.0); } else { // we hit it from the y direction self.player.velocity = Vector3::new(self.player.velocity.x, 0.0, 0.0); } } } let new_pos = self.player.pos + self.player.velocity; self.player.pos = new_pos; } pub fn spawn_entity(&mut self, e: &EntityJSON) { let mut ent = self.entity_manager.create_entity(&e.name).unwrap(); let animation = match e.animation.as_str() { "" => None, _ => self.animation_manager.get_animation(&e.animation), }; ent.animation = animation; ent.pos = Vector3::new(e.x, e.y, 0.0); ent.dir = Vector2::new(e.dir_x, e.dir_y); self.entities.push(ent); } pub fn init_entities(&mut self, ents: &Vec<EntityJSON>) { for e in ents { self.spawn_entity(&e); } } }
use super::{FunctionData, Value, Location, Map, Type, TypeInfo, Instruction, Cast}; struct TypeContext { creators: Map<Value, Location>, type_info: TypeInfo, } impl TypeContext { fn get_type(&self, value: Value) -> Type { self.type_info.get(&value).copied().unwrap() } } impl FunctionData { fn infer_value_type(&self, value: Value, cx: &mut TypeContext) { time!(infer_value_type); let creator = cx.creators.get(&value).map(|location| { self.instruction(*location) }).expect("Value is used without being created."); let ty = match creator { Instruction::ArithmeticUnary { value, .. } => { cx.get_type(*value) } Instruction::ArithmeticBinary { a, b, .. } => { let a = cx.get_type(*a); let b = cx.get_type(*b); assert_eq!(a, b, "Binary arithmetic instruction must have operands \ of the same type."); a } Instruction::IntCompare { a, b, .. } => { let a = cx.get_type(*a); let b = cx.get_type(*b); assert_eq!(a, b, "Int compare instruction must have operands \ of the same type."); Type::U1 } Instruction::Load { ptr, .. } => { cx.get_type(*ptr) .strip_ptr() .expect("Cannot load non-pointer value.") } Instruction::Call { func, .. } => { self.function_prototype(*func) .return_type .expect("Void function return value is used.") } Instruction::Select { on_true, on_false, .. } => { let on_true = cx.get_type(*on_true); let on_false = cx.get_type(*on_false); assert_eq!(on_true, on_false, "Select instruction must have operands \ of the same type."); on_true } Instruction::Phi { incoming, .. } => { let mut result = None; // It's possible that we don't know types of all incoming values. // We always need to know the type of at least one. for &(_, incoming_value) in incoming { if let Some(ty) = cx.type_info.get(&incoming_value) { result = Some(*ty); break; } } result.expect("Failed to get PHI output value.") } Instruction::StackAlloc { ty, .. } => ty.ptr(), Instruction::GetElementPtr { source, .. } => cx.get_type(*source), Instruction::Cast { ty, .. } => *ty, Instruction::Alias { value, .. } => cx.get_type(*value), _ => { panic!("Unexpected value creator: {:?}.", creator); } }; assert!(cx.type_info.insert(value, ty).is_none(), "Value has type infered multiple times."); } fn typecheck(&self, instruction: &Instruction, cx: &mut TypeContext) { time!(typecheck); match instruction { Instruction::ArithmeticUnary { dst, value, .. } => { let dst = cx.get_type(*dst); let value = cx.get_type(*value); assert_eq!(dst, value, "Unary arithmetic instruction requires all \ operands to be of the same type"); assert!(dst.is_arithmetic(), "Unary arithmetic instruction can be \ only done on arithmetic types."); } Instruction::ArithmeticBinary { dst, a, b, .. } => { let dst = cx.get_type(*dst); let a = cx.get_type(*a); let b = cx.get_type(*b); assert!(dst == a && a == b, "Binary arithmetic instruction requires all \ operands to be of the same type"); assert!(dst.is_arithmetic(), "Binary arithmetic instruction can be \ only done on arithmetic types."); } Instruction::IntCompare { dst, a, b, .. } => { let dst = cx.get_type(*dst); let a = cx.get_type(*a); let b = cx.get_type(*b); assert_eq!(dst, Type::U1, "Int compare instruction requires \ destination type to be U1."); assert_eq!(a, b, "Int compare instruction requires all \ input operands to be of the same type"); } Instruction::Load { dst, ptr } => { let dst = cx.get_type(*dst); let ptr = cx.get_type(*ptr); let stripped = ptr.strip_ptr() .expect("Load instruction can only load from pointers."); assert_eq!(dst, stripped, "Load instruction destination must have pointee type."); } Instruction::Store { ptr, value } => { let ptr = cx.get_type(*ptr); let value = cx.get_type(*value); let stripped = ptr.strip_ptr() .expect("Store instruction can only store to pointers."); assert_eq!(value, stripped, "Store instruction value must have pointee type."); } Instruction::Call { dst, func, args } => { let prototype = self.function_prototype(*func); if let Some(dst) = dst { let return_type = prototype.return_type .expect("Cannot take the return value of void function."); assert_eq!(cx.get_type(*dst), return_type, "Function call return value doesn't match."); } assert_eq!(args.len(), prototype.arguments.len(), "Function call with invalid \ argument count."); for (index, arg) in args.iter().enumerate() { assert_eq!(cx.get_type(*arg), prototype.arguments[index], "Function call with invalid arguments."); } } Instruction::Branch { .. } => { } Instruction::BranchCond { cond, .. } => { let cond = cx.get_type(*cond); assert_eq!(cond, Type::U1, "Conditional branch input must be U1."); } Instruction::StackAlloc { dst, ty, size } => { let dst = cx.get_type(*dst); assert!(*size > 0, "Stack alloc cannot allocate 0 sized array."); assert_eq!(dst.strip_ptr().expect("Stack alloc destination must be pointer."), *ty, "Stack alloc destination must be pointer to input type."); } Instruction::Return { value } => { let value = value.map(|value| cx.get_type(value)); assert_eq!(value, self.prototype.return_type, "Return instruction operand type \ must be the same function as function return type."); } Instruction::GetElementPtr { dst, source, index } => { let dst = cx.get_type(*dst); let source = cx.get_type(*source); let index = cx.get_type(*index); assert!(index.is_arithmetic(), "GEP index must be arithmetic."); assert_eq!(dst, source, "GEP destination and source must be the same type."); assert!(dst.is_pointer(), "GEP input type is not valid pointer."); } Instruction::Cast { dst, cast, value, ty } => { let dst = cx.get_type(*dst); let value = cx.get_type(*value); assert_eq!(dst, *ty, "{} destination must be the same type as cast type.", cast); assert!(value != Type::U1 && *ty != Type::U1, "Cannot cast U1s."); match cast { Cast::ZeroExtend | Cast::SignExtend | Cast::Truncate => { assert!(value.is_arithmetic() && ty.is_arithmetic(), "Both types in {} must be arithmetic.", cast); if *cast == Cast::Truncate { assert!(value.size() > ty.size(), "{} must cast from bigger \ integer to smaller one.", cast); } else { assert!(value.size() < ty.size(), "{} must cast from smaller \ integer to bigger one.", cast); } } Cast::Bitcast => { assert_eq!(value.size(), ty.size(), "{} must cast between values \ with the same size.", cast); } } } Instruction::Select { dst, cond, on_true, on_false } => { let dst = cx.get_type(*dst); let cond = cx.get_type(*cond); let on_true = cx.get_type(*on_true); let on_false = cx.get_type(*on_false); assert_eq!(cond, Type::U1, "Select condition input must be U1."); assert!(on_true == on_false && dst == on_true, "Select values and destination \ must have the same type."); } Instruction::Phi { dst, incoming } => { let dst = cx.get_type(*dst); for (_label, value) in incoming { assert_eq!(cx.get_type(*value), dst, "PHI values must have the same types."); } } Instruction::Nop => { } Instruction::Alias { dst, value } => { assert_eq!(cx.get_type(*dst), cx.get_type(*value), "Alias can only alias values \ of the same type."); } } } pub(super) fn build_type_info(&mut self) { time!(build_type_info); let mut cx = TypeContext { type_info: Map::default(), creators: self.value_creators(), }; for (index, value) in self.argument_values.iter().enumerate() { assert!(cx.type_info.insert(*value, self.prototype.arguments[index]).is_none(), "Function arguments defined multiple times."); } for (ty, value) in &self.undefined { assert!(cx.type_info.insert(*value, *ty).is_none(), "Undefined values defined multiple times."); } for (value, (ty, _)) in &self.constants { assert!(cx.type_info.insert(*value, *ty).is_none(), "Constant values defined multiple times."); } for value in self.value_processing_order() { if !self.is_value_special(value) { self.infer_value_type(value, &mut cx); } } for label in self.reachable_labels() { for instruction in &self.blocks[&label] { self.typecheck(instruction, &mut cx); } } self.type_info = Some(cx.type_info); } }
//! Functions and data-structures to load descriptor tables. use core::mem::size_of; use current::irq::IdtEntry; use shared::segmentation::SegmentDescriptor; /// A struct describing a pointer to a descriptor table (GDT / IDT). /// This is in a format suitable for giving to 'lgdt' or 'lidt'. #[derive(Debug)] #[repr(C, packed)] pub struct DescriptorTablePointer<Entry> { /// Size of the DT. pub limit: u16, /// Pointer to the memory region containing the DT. pub base: *const Entry, } impl<T> DescriptorTablePointer<T> { pub fn new(slice: &[T]) -> Self { // GDT, LDT, and IDT all expect the limit to be set to "one less". // See Intel 3a, Section 3.5.1 "Segment Descriptor Tables" and // Section 6.10 "Interrupt Descriptor Table (IDT)". let len = slice.len() * size_of::<T>() - 1; assert!(len < 0x10000); DescriptorTablePointer { base: slice.as_ptr(), limit: len as u16, } } } /// Load GDT table. pub unsafe fn lgdt(gdt: &DescriptorTablePointer<SegmentDescriptor>) { asm!("lgdt ($0)" :: "r" (gdt) : "memory"); } /// Load LDT table. pub unsafe fn lldt(ldt: &DescriptorTablePointer<SegmentDescriptor>) { asm!("lldt ($0)" :: "r" (ldt) : "memory"); } /// Load IDT table. pub unsafe fn lidt(idt: &DescriptorTablePointer<IdtEntry>) { asm!("lidt ($0)" :: "r" (idt) : "memory"); }
use serde::{Deserialize, Serialize}; pub const MAXMIND_CITY_URI: &str = "https://geoip.maxmind.com/geoip/v2.1/city"; /// An API key that can be used to access MaxMind services. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MaxMindAPIKey { username: String, password: String, } impl MaxMindAPIKey { /// Makes a new key from a username and password. pub fn new(username: &str, password: &str) -> Self { Self { username: username.to_owned(), password: password.to_owned(), } } /// Gets the username of the API key. pub fn username(&self) -> &str { &self.username } /// Gets the password of the API key. pub fn password(&self) -> &str { &self.password } }
use bytes::{Buf, Bytes}; use crate::error::Error; use crate::io::BufExt; pub trait MssqlBufExt: Buf { fn get_utf16_str(&mut self, n: usize) -> Result<String, Error>; fn get_b_varchar(&mut self) -> Result<String, Error>; fn get_us_varchar(&mut self) -> Result<String, Error>; fn get_b_varbyte(&mut self) -> Bytes; } impl MssqlBufExt for Bytes { fn get_utf16_str(&mut self, mut n: usize) -> Result<String, Error> { let mut raw = Vec::with_capacity(n * 2); while n > 0 { let ch = self.get_u16_le(); raw.push(ch); n -= 1; } String::from_utf16(&raw).map_err(Error::protocol) } fn get_b_varchar(&mut self) -> Result<String, Error> { let size = self.get_u8(); self.get_utf16_str(size as usize) } fn get_us_varchar(&mut self) -> Result<String, Error> { let size = self.get_u16_le(); self.get_utf16_str(size as usize) } fn get_b_varbyte(&mut self) -> Bytes { let size = self.get_u8(); self.get_bytes(size as usize) } }
#[cfg(test)] extern crate ftp; use ftp::FtpStream; use std::io::Cursor; #[test] fn test_ftp() { let mut ftp_stream = FtpStream::connect("127.0.0.1:21").unwrap(); println!("Welcome message: {:?}", ftp_stream.get_welcome_msg()); let _ = ftp_stream.login("Doe", "mumble").unwrap(); ftp_stream.mkdir("test_dir").unwrap(); ftp_stream.cwd("test_dir").unwrap(); assert!(ftp_stream.pwd().unwrap().ends_with("/test_dir")); // store a file let file_data = "test data\n"; let mut reader = Cursor::new(file_data.as_bytes()); assert!(ftp_stream.put("test_file.txt", &mut reader).is_ok()); // retrieve file assert!(ftp_stream .simple_retr("test_file.txt") .map(|bytes| assert_eq!(bytes.into_inner(), file_data.as_bytes())) .is_ok()); // remove file assert!(ftp_stream.rm("test_file.txt").is_ok()); // cleanup: go up, remove folder, and quit assert!(ftp_stream .cdup() .and_then(|_| ftp_stream.rmdir("test_dir")) .and_then(|_| ftp_stream.quit()) .is_ok()); }
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use funfsm::constraints::{self, Constraints}; use haret::vr::{VrCtx, VrTypes, VrMsg, VrEnvelope, FsmOutput}; pub fn constraints() -> Constraints<VrTypes> { let mut c = Constraints::new(); invariants(&mut c); preconditions(&mut c); transitions(&mut c); c } fn invariants(c: &mut Constraints<VrTypes>) { invariant!(c, |ctx: &VrCtx| ctx.commit_num <= ctx.op); invariant!(c, |ctx: &VrCtx| ctx.old_config != ctx.new_config); } fn preconditions(c: &mut Constraints<VrTypes>) { precondition!(c, "primary", |ctx: &VrCtx| ctx.last_normal_view == ctx.view); precondition!(c, "primary", |ctx: &VrCtx| ctx.primary.as_ref() == Some(&ctx.pid)); precondition!(c, "primary", |ctx: &VrCtx| ctx.recovery_state.is_none()); precondition!(c, "primary", |ctx: &VrCtx| ctx.view_change_state.is_none()); } fn transitions(c: &mut Constraints<VrTypes>) { transition!(c, "primary" => "primary", primary_to_primary); } /// All assertions pertaining to a transition from "primary" state to "primary" state fn primary_to_primary(init_ctx: &VrCtx, final_ctx: &VrCtx, envelope: &VrEnvelope, output: &Vec<FsmOutput>) -> Result<(), String> { let s = "Transition from primary to primary"; if let Some(view) = envelope.msg.get_view() { check!(s, view <= final_ctx.view); } if let Some(epoch) = envelope.msg.get_epoch() { check!(s, epoch <= final_ctx.epoch); } check!(s, final_ctx.last_normal_view == final_ctx.view); check!(s, final_ctx.recovery_state.is_none()); check!(s, final_ctx.view_change_state.is_none()); check!(s, final_ctx.last_normal_view == final_ctx.view); check!(s, final_ctx.primary.as_ref() == Some(&final_ctx.pid)); check!(s, init_ctx.epoch == final_ctx.epoch); if let VrMsg::DoViewChange {view, ..} = envelope.msg { if output.len() == 0 { check!(s, view <= final_ctx.view); } else { check!(s, view == final_ctx.view); } } Ok(()) }
use crate::extractors::amp_spectrum; pub fn compute(signal: &Vec<f64>) -> f64 { let amp_spec: Vec<f64> = amp_spectrum::compute(signal); let fraction = amp_spec .iter() .fold((0.0, 0.0), |acc, &x| (acc.0 + x.ln(), acc.1 + x)); (fraction.0 / amp_spec.len() as f64).exp() * amp_spec.len() as f64 / fraction.1 } #[cfg(test)] mod tests { use super::compute; use crate::utils::test; use std::f64; const FLOAT_PRECISION: f64 = 0.001_000_000; fn test_against(dataset: &test::data::TestDataSet) -> () { let sf = compute(&dataset.signal); assert_relative_eq!( sf, dataset.features.spectralFlatness, epsilon = f64::EPSILON, max_relative = FLOAT_PRECISION ); } #[test] fn test_spectral_flatness() { let datasets = test::data::get_all(); for dataset in datasets.iter() { test_against(dataset); } } }
#![allow(collapsible_if)] use super::*; use castle; use color::Color; use moves::*; use piece::*; use kind::*; impl Position { pub fn is_pseudo_legal(&self, mv: Move) -> bool { // Source square must not be vacant. let from = mv.from.mask(); let piece = self.board.get_piece(from); if piece == VOID { return false; } // Check turn. if piece.color() == Color::White { self.is_pseudo_legal_for(WhiteMove(mv)) } else { self.is_pseudo_legal_for(BlackMove(mv)) } } pub fn is_pseudo_legal_for<M: SidedMove>(&self, mv: M) -> bool { // Source square must not be vacant. let from = mv.from().mask(); let piece = self.board.get_piece(from); if piece == VOID { return false; } // Check turn. if !self.board.occupation_of(self.active).contains(from) { return false; } // Only pawns can promote and only on the back-rank. if mv.promote() != UNKNOWN { if self.active == Color::White { if piece != WHITE_PAWN { return false; } if mv.to().rank() != ::rank::_7 { return false; } } else { if piece != BLACK_PAWN { return false; } if mv.to().rank() != ::rank::_2 { return false; } } } if mv.castle() != castle::NONE { if self.available.contains(mv.castle() & self.active.castle()) { return true; } } // Destination square can not be occupied. let to = mv.to().mask(); // Do squares occupied by active side contain `to`? if self.board.occupation_of(self.active).contains(to) { return false; } // Handle pawn pushes if self.board.pawns_of(self.active).contains(to) { return self.is_pseudo_legal_pawn_move(from, to); } // determine which non-pawn piece this is and check it true } } #[cfg(test)] mod tests { use super::*; use square::*; #[test] fn valid_pawn_move() { yes(Move::new(A2, A4), "8/8/8/8/8/8/P7/8 w - - 0 1"); } #[test] fn source_square_must_not_be_vacant() { no(Move::new(E2, E4), "8/8/8/8/8/8/8/8 w - - 0 1"); } #[test] fn check_turn() { no(Move::new(A2, A4), "8/8/8/8/8/8/P7/8 b - - 0 1"); } fn yes(m: Move, fen: &str) { assert_eq!(test(fen, m), true) } fn no(m: Move, fen: &str) { assert_eq!(test(fen, m), false) } fn test(fen: &str, m: Move) -> bool { Position::parse(fen).is_pseudo_legal(m) } }
/* Heru Handika 19 September 2020 Vector operation modules */ // use std::f64; pub mod vector { pub fn vector_ones(vec_size: usize) -> Vec<i32> { let mut vec_ones: Vec<i32> = Vec::with_capacity(vec_size); for _ in 0..vec_size { vec_ones.push(1); } vec_ones } pub fn add_two_vectors(x: &Vec<i32>, y: &Vec<i32>) -> Vec<i32>{ let mut result = Vec::new(); for (&i, &j) in x.iter().zip(y.iter()) { result.push(i + j); } result } pub fn substract_two_vectors(x: &Vec<i32>, y: &Vec<i32>) -> Vec<i32> { let mut result = Vec::new(); for (&i, &j) in x.iter().zip(y.iter()) { result.push(i - j); } result } pub fn multiply_two_vectors(x: &Vec<i32>, y: &Vec<i32>) -> Vec<i32>{ let mut result = Vec::new(); for (&i, &j) in x.iter().zip(y.iter()) { result.push(i * j); } result } pub fn sum_vectors(x: &Vec<i32>) -> i32 { let mut sum = 0; for &i in x.iter() { sum += i; } sum } pub fn cumsum(x: &[i32]) -> Vec<i32> { let mut res = Vec::new(); let mut sum = 0; for &i in x { sum += i; res.push(sum); } res } pub fn mean_vectors(vec: &Vec<i32>) -> f64 { let n = vec.len(); let mean = sum_vectors(vec) as f64 / n as f64; mean } fn calculate_dot_product(x: &Vec<i32>, y: &Vec<i32>) -> f64 { let mut sum: f64 = 0.0; for (&i, &j) in x.iter().zip(y.iter()) { sum += i as f64 * j as f64; } sum } pub fn calculate_sum_of_square(vec: &Vec<i32>) -> f64 { calculate_dot_product(vec, vec) } fn compute_magnitude(vec: &Vec<i32>) -> f64 { calculate_sum_of_square(&vec).sqrt() } pub fn compute_vector_distance(x: &Vec<i32>, y: &Vec<i32>) -> f64 { let vec: Vec<i32> = substract_two_vectors(&x, &y); let dist = compute_magnitude(&vec); dist } }
use std::ops::Deref; fn main() { let b = Box::new("sample".to_string()); let r1 = b.capacity(); let r2 = b.deref().capacity(); assert_eq!(r1, r2); println!("{}", r1); }
#![feature(used)] pub mod foo { #[no_mangle] #[used] pub static STATIC: [u32; 10] = [1; 10]; pub fn hello() {} } pub fn bar() { foo::hello(); // STATIC not present if commented out }
use std::marker::PhantomData; use super::Key; use super::Session; use super::SessionStore; /// The sessioning middleware. /// /// `Sessions` middleware is given a key-generating function and a /// data store to use for sessioning. /// /// The key is used to select a session from the store. /// No session is actually created during selection. It is up to downstream /// middleware to create/swap/edit sessions stored to a key. /// /// `Sessions` allows guest sessioning (sessions without explicit authorization). /// To prevent guest sessioning, the key generator can produce /// an `Option` value so that all unauthorized users have an empty session. /// /// Session keys can be stored in the `Request` or `Alloy`. /// Usually, keys are stored in signed cookies, but anything /// retrievable from `Request` or `Alloy` will work. pub struct Sessions<K: Key, S: SessionStore<K>> { key_generator: fn(&K) -> K, session_store: S } impl<K: typemap::Key, S: SessionStore<K> + Clone> Clone for Sessions<K, S> { fn clone(&self) -> Sessions<K, S> { Sessions { key_generator: self.key_generator, session_store: self.session_store.clone() } } } /* impl<K: typemap::Key, S: SessionStore<K>> Sessions<K, S> { /// Instantiate new sessioning middleware with the given /// key-generating function and session store. /// /// `key_generator` should generate keys based on the `Request` and `Alloy`. /// These keys should be unique, as identical keys will map to the same session. /// /// The `Alloy` can be used to access /// stores such as cookies to allow persistent sessions for users. /// /// `session_store` must implement the `SessionStore` trait. /// A default `Session` is provided to fulfill this. pub fn new(key_generator: fn(&Request) -> K, store: S) -> Sessions<K, S> { Sessions { key_generator: key_generator, session_store: store } } } */ /// Key for inserting a Session<K, V> in the request extensions. pub struct RequestSession<K> { phantom: PhantomData<K> } //impl<K: 'static, V: 'static> Assoc<session::Session<K, V>> for RequestSession {} impl<K: Key> Key for RequestSession<K> { type Value = Session<K>; }
use challenges::{chal28::*, chal29::*}; fn main() { println!("🔓 Challenge 29"); let mac = SecretPrefixMac::new(); let key_size = deduce_key_size(&mac).unwrap(); let original_msg = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon".as_bytes(); let padding = get_md_padding(&random_bytes(key_size + original_msg.len() as u32)); let extension = b";admin=true"; let mut h = mac.transparent_sign(&[original_msg, &padding].concat()); h.input(&extension[..]); let forged_tag = h.result().to_vec(); assert!(mac.verify(&[original_msg, &padding, extension].concat(), &forged_tag)); println!("Successfully forged a tag via extension attack"); } fn deduce_key_size(mac: &SecretPrefixMac) -> Option<u32> { let ref_tag = mac.sign(&[]); for key_size in 0..256 { let padding = get_md_padding(&random_bytes(key_size)); if mac.raw_sign(&padding) == ref_tag { return Some(key_size); } } None }
use Action::*; use std::ops::Add; fn main() { let actions = include_str!("input").lines().map(str::parse).map(|x| x.unwrap()); let mut pos = Position { x: 0, daim: 0, real_depth: 0 }; for act in actions { pos = pos + act; }; println!("Part one: {}", pos.x*pos.daim); println!("Part two: {}", pos.x*pos.real_depth); } enum Action { Forward(u32), Down(u32), Up(u32) } impl std::str::FromStr for Action { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut iter = s.split(" "); let action = iter.next().unwrap(); let value = iter.next().unwrap().parse().unwrap(); match action { "forward" => Ok(Forward(value)), "down" => Ok(Down(value)), "up" => Ok(Up(value)), _ => Err("Unexpected string") } } } struct Position { x: u32, daim: u32, real_depth: u32, } impl Add<Action> for Position { type Output = Self; fn add(self, rhs: Action) -> Position { match rhs { Forward(v) => Position { x: self.x + v, real_depth: self.real_depth + v*self.daim, daim: self.daim }, Down(v) => Position { daim: self.daim + v, ..self }, Up(v) => Position { daim: self.daim - v, ..self } } } }
use crate::{EitherOsStr, IntoOsString, ToOsStr}; use core::{fmt, mem::transmute, ptr::NonNull, slice, str}; #[cfg(feature = "std")] use std::{ffi, os::unix::ffi::OsStrExt}; #[cfg(not(feature = "std"))] extern "C" { /// Yeah, I had to copy this from std #[cfg(not(target_os = "dragonfly"))] #[cfg_attr( any( target_os = "linux", target_os = "emscripten", target_os = "fuchsia", target_os = "l4re" ), link_name = "__errno_location" )] #[cfg_attr( any( target_os = "netbsd", target_os = "openbsd", target_os = "android", target_os = "redox", target_env = "newlib" ), link_name = "__errno" )] #[cfg_attr(target_os = "solaris", link_name = "___errno")] #[cfg_attr( any(target_os = "macos", target_os = "ios", target_os = "freebsd"), link_name = "__error" )] #[cfg_attr(target_os = "haiku", link_name = "_errnop")] fn errno_location() -> *mut libc::c_int; } #[cfg(not(feature = "std"))] fn errno() -> libc::c_int { unsafe { *errno_location() } } #[cfg(feature = "std")] fn errno() -> libc::c_int { Error::last_os_error().raw_os_error().unwrap_or(0) as libc::c_int } /// A type representing file descriptor on Unix. pub type FileDesc = libc::c_int; /// A type representing Process ID on Unix. pub type Pid = libc::pid_t; #[cfg(feature = "std")] /// An IO error. pub type Error = std::io::Error; #[cfg(not(feature = "std"))] #[derive(Debug)] /// An IO error. Without std, you can only get a message or an OS error code. pub struct Error { code: i32, } #[cfg(not(feature = "std"))] impl Error { /// Creates an error from a raw OS error code. pub fn from_raw_os_error(code: i32) -> Self { Self { code } } /// Creates an error from the last OS error code. pub fn last_os_error() -> Error { Self::from_raw_os_error(errno() as i32) } /// Raw OS error code. Returns option for compatibility with std. pub fn raw_os_error(&self) -> Option<i32> { Some(self.code) } } #[cfg(not(feature = "std"))] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let msg_ptr = unsafe { libc::strerror(self.code as libc::c_int) }; let len = unsafe { libc::strlen(msg_ptr) }; let slice = unsafe { slice::from_raw_parts(msg_ptr, len) }; write!(fmt, "{}", unsafe { OsStr::from_slice(slice) })?; Ok(()) } } /// Owned allocation of an OS-native string. pub struct OsString { alloc: NonNull<libc::c_char>, /// Length without the nul-byte. len: usize, } unsafe impl Send for OsString {} impl Drop for OsString { fn drop(&mut self) { let ptr = self.alloc.as_ptr() as *mut libc::c_void; unsafe { libc::free(ptr) } } } impl AsRef<OsStr> for OsString { fn as_ref(&self) -> &OsStr { unsafe { OsStr::from_slice(slice::from_raw_parts( self.alloc.as_ptr(), self.len, )) } } } /// Borrowed allocation of an OS-native string. #[repr(transparent)] pub struct OsStr { bytes: [libc::c_char], } impl OsStr { /// Unsafe cause sequence needs to end with 0. unsafe fn from_slice(slice: &[libc::c_char]) -> &Self { transmute(slice) } } impl fmt::Debug for OsStr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut first = false; write!(fmt, "[")?; for &signed in &self.bytes { let byte = signed as u8; if first { first = false; } else { write!(fmt, ", ")?; } if byte.is_ascii() { write!(fmt, "{:?}", char::from(byte))?; } else { write!(fmt, "'\\x{:x}'", byte)?; } } write!(fmt, "]")?; Ok(()) } } impl fmt::Display for OsStr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let ptr = self.bytes.as_ptr(); let len = self.bytes.len(); let slice = unsafe { slice::from_raw_parts(ptr as _, len) }; let mut sub = slice; while sub.len() > 0 { match str::from_utf8(sub) { Ok(string) => { write!(fmt, "{}", string)?; sub = &[]; }, Err(err) => { let string = str::from_utf8(&sub[.. err.valid_up_to()]) .expect("Inconsistent utf8 error"); write!(fmt, "{}�", string,)?; sub = &sub[err.valid_up_to() + 1 ..]; }, } } Ok(()) } } impl<'str> IntoOsString for &'str OsStr { fn into_os_string(self) -> Result<OsString, Error> { let len = self.bytes.len(); let alloc = unsafe { libc::malloc(len + 1) }; let alloc = match NonNull::new(alloc as *mut libc::c_char) { Some(alloc) => alloc, None => { return Err(Error::last_os_error()); }, }; unsafe { libc::memcpy( alloc.as_ptr() as *mut libc::c_void, self.bytes.as_ptr() as *const libc::c_void, len + 1, ); } Ok(OsString { alloc, len }) } } impl ToOsStr for str { fn to_os_str(&self) -> Result<EitherOsStr, Error> { make_os_str(self.as_bytes()) } } #[cfg(feature = "std")] impl ToOsStr for ffi::OsStr { fn to_os_str(&self) -> Result<EitherOsStr, Error> { make_os_str(self.as_bytes()) } } /// Path must not contain a nul-byte in the middle, but a nul-byte in the end /// (and only in the end) is allowed, which in this case no extra allocation /// will be made. Otherwise, an extra allocation is made. fn make_os_str(slice: &[u8]) -> Result<EitherOsStr, Error> { if let Some((&last, init)) = slice.split_last() { if init.contains(&0) { panic!("Path to file cannot contain nul-byte in the middle"); } if last == 0 { let str = unsafe { OsStr::from_slice(transmute(slice)) }; return Ok(EitherOsStr::Borrowed(str)); } } let alloc = unsafe { libc::malloc(slice.len() + 1) }; let alloc = match NonNull::new(alloc as *mut libc::c_char) { Some(alloc) => alloc, None => { return Err(Error::last_os_error()); }, }; unsafe { libc::memcpy( alloc.as_ptr() as *mut libc::c_void, slice.as_ptr() as *const libc::c_void, slice.len(), ); *alloc.as_ptr().add(slice.len()) = 0; } Ok(EitherOsStr::Owned(OsString { alloc, len: slice.len() })) } /// Returns the ID of the current process. pub fn pid() -> Pid { unsafe { libc::getpid() } } /// Opens a file with only purpose of locking it. Creates it if it does not /// exist. Path must not contain a nul-byte in the middle, but a nul-byte in the /// end (and only in the end) is allowed, which in this case no extra allocation /// will be made. Otherwise, an extra allocation is made. pub fn open(path: &OsStr) -> Result<FileDesc, Error> { let fd = unsafe { libc::open( path.bytes.as_ptr(), libc::O_RDWR | libc::O_CLOEXEC | libc::O_CREAT, (libc::S_IRUSR | libc::S_IWUSR | libc::S_IRGRP | libc::S_IROTH) as libc::c_int, ) }; if fd >= 0 { Ok(fd) } else { Err(Error::last_os_error()) } } /// Writes data into the given open file. pub fn write(fd: FileDesc, mut bytes: &[u8]) -> Result<(), Error> { while bytes.len() > 0 { let written = unsafe { libc::write(fd, bytes.as_ptr() as *const libc::c_void, bytes.len()) }; if written < 0 && errno() != libc::EAGAIN { return Err(Error::last_os_error()); } bytes = &bytes[written as usize ..]; } Ok(()) } pub fn fsync(fd: FileDesc) -> Result<(), Error> { let result = unsafe { libc::fsync(fd) }; if result >= 0 { Ok(()) } else { Err(Error::last_os_error()) } } /// Truncates the file referenced by the given file descriptor and seeks it to /// the start. pub fn truncate(fd: FileDesc) -> Result<(), Error> { let res = unsafe { libc::lseek(fd, 0, libc::SEEK_SET) }; if res < 0 { return Err(Error::last_os_error()); } let res = unsafe { libc::ftruncate(fd, 0) }; if res < 0 { Err(Error::last_os_error()) } else { Ok(()) } } /// Tries to lock a file and blocks until it is possible to lock. pub fn lock(fd: FileDesc) -> Result<(), Error> { let res = unsafe { libc::flock(fd, libc::LOCK_EX) }; if res >= 0 { Ok(()) } else { Err(Error::last_os_error()) } } /// Tries to lock a file but returns as soon as possible if already locked. pub fn try_lock(fd: FileDesc) -> Result<bool, Error> { let res = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) }; if res >= 0 { Ok(true) } else { let err = errno(); if err == libc::EWOULDBLOCK || err == libc::EINTR { Ok(false) } else { Err(Error::from_raw_os_error(err as i32)) } } } /// Unlocks the file. pub fn unlock(fd: FileDesc) -> Result<(), Error> { let res = unsafe { libc::flock(fd, libc::LOCK_UN) }; if res >= 0 { Ok(()) } else { Err(Error::last_os_error()) } } /// Closes the file. pub fn close(fd: FileDesc) { unsafe { libc::close(fd) }; }
//! Bitswap protocol implementation #[macro_use] extern crate tracing; mod behaviour; mod block; mod error; mod ledger; mod prefix; mod protocol; pub use self::behaviour::{Bitswap, BitswapEvent, Stats}; pub use self::block::Block; pub use self::error::BitswapError; pub use self::ledger::Priority; mod bitswap_pb { include!(concat!(env!("OUT_DIR"), "/bitswap_pb.rs")); }
use num::integer::lcm; #[derive(Clone)] struct Moon { pos: [i64; 3], vel: [i64; 3], } impl Moon { fn new(x: i64, y: i64, z: i64) -> Moon { Moon { pos: [x, y, z], vel: [0, 0, 0] } } fn adjust_vel(&mut self, om: &Moon) { for i in 0..3 { if self.pos[i] != om.pos[i] { if self.pos[i] > om.pos[i] { self.vel[i] -= 1; } else { self.vel[i] += 1; } } } } fn adjust_pos(&mut self) { for i in 0..3 { self.pos[i] += self.vel[i]; } } } pub fn run_puzzle() { let mut moons = Vec::new(); moons.push(Moon::new(-3, 15, -11)); moons.push(Moon::new(3, 13, -19)); moons.push(Moon::new(-13, 18, -2)); moons.push(Moon::new(6, 0, -1)); let mut periods = [0; 3]; let initial_state = moons.clone(); for round in 0..1000000 { for coor in 0..3 { if periods[coor] == 0 { let mut found = true; for i in 0..4 { if moons[i].pos[coor] != initial_state[i].pos[coor] || moons[i].vel[coor] != initial_state[i].vel[coor] { found = false; break; } } if found { periods[coor] = round; } } } if periods[0] != 0 && periods[1] != 0 && periods[2] != 0 { break; } let old_moons = moons.clone(); for m in &mut moons { for om in &old_moons { m.adjust_vel(om); } } moons.iter_mut().for_each(|m| m.adjust_pos()); } let result = lcm::<i64>(lcm::<i64>(periods[0], periods[1]), periods[2]); println!("First repetition: {}", result); }
extern crate serde; mod test_utils; use flexi_logger::LoggerHandle; use hdbconnect_async::{time::HanaDate, Connection, HdbResult, ToHana}; use log::{debug, info, trace}; use time::{format_description::FormatItem, macros::format_description, Date, Month}; #[tokio::test] // cargo test --test test_024_daydate pub async fn test_024_daydate() -> HdbResult<()> { let mut loghandle = test_utils::init_logger(); let start = std::time::Instant::now(); let mut connection = test_utils::get_authenticated_connection().await?; test_daydate(&mut loghandle, &mut connection).await?; test_utils::closing_info(connection, start).await } // Test the conversion of time values // - during serialization (input to prepared_statements) // - during deserialization (result) #[allow(clippy::cognitive_complexity)] async fn test_daydate(_loghandle: &mut LoggerHandle, connection: &mut Connection) -> HdbResult<()> { info!("verify that Date values match the expected string representation"); debug!("prepare the test data"); let date_values: Vec<Date> = vec![ Date::from_calendar_date(1, Month::January, 1).unwrap(), Date::from_calendar_date(1, Month::January, 2).unwrap(), Date::from_calendar_date(2012, Month::February, 2).unwrap(), Date::from_calendar_date(2013, Month::March, 3).unwrap(), Date::from_calendar_date(2014, Month::April, 4).unwrap(), ]; let string_values = vec![ "0001-01-01", "0001-01-02", "2012-02-02", "2013-03-03", "2014-04-04", ]; const FMT: &[FormatItem] = format_description!("[year]-[month]-[day]"); for i in 0..5 { assert_eq!(date_values[i].format(&FMT).unwrap(), string_values[i]); } // Insert the data such that the conversion "String -> SecondTime" is done on the // server side (we assume that this conversion is error-free). let insert_stmt = |n, d| format!("insert into TEST_DAYDATE (number,mydate) values({n}, '{d}')",); connection .multiple_statements_ignore_err(vec!["drop table TEST_DAYDATE"]) .await; connection .multiple_statements(vec![ "create table TEST_DAYDATE (number INT primary key, mydate DAYDATE)", &insert_stmt(13, string_values[0]), &insert_stmt(14, string_values[1]), &insert_stmt(15, string_values[2]), &insert_stmt(16, string_values[3]), &insert_stmt(17, string_values[4]), ]) .await?; { info!("test the conversion Date -> DB"); trace!("calling prepare()"); let mut prep_stmt = connection .prepare("select sum(number) from TEST_DAYDATE where mydate = ? or mydate = ?") .await?; // Enforce that Date values are converted in the client (with serde) to the DB type: trace!("calling add_batch()"); prep_stmt.add_batch(&(date_values[2].to_hana(), date_values[3].to_hana()))?; trace!("calling execute_batch()"); let response = prep_stmt.execute_batch().await?; let typed_result: i32 = response.into_resultset()?.try_into().await?; assert_eq!(typed_result, 31); } { info!("test the conversion DB -> Date"); let s = "select mydate from TEST_DAYDATE order by number asc"; let rs = connection.query(s).await?; trace!("rs = {:?}", rs); let times: Vec<HanaDate> = rs.try_into().await?; trace!("times = {:?}", times); for (time, ntv) in times.iter().zip(date_values.iter()) { debug!("{}, {}", **time, ntv); assert_eq!(**time, *ntv); } } { info!("prove that '' is the same as '0001:01:01'"); let rows_affected = connection.dml(&insert_stmt(77, "")).await?; trace!("rows_affected = {}", rows_affected); assert_eq!(rows_affected, 1); let dates: Vec<HanaDate> = connection .query("select mydate from TEST_DAYDATE where number = 77 or number = 13") .await? .try_into() .await?; trace!("query sent"); assert_eq!(dates.len(), 2); for date in dates { assert_eq!(*date, date_values[0]); } } { info!("test null values"); let q = "insert into TEST_DAYDATE (number) values(2350)"; let rows_affected = connection.dml(q).await?; trace!("rows_affected = {}", rows_affected); assert_eq!(rows_affected, 1); let date: Option<Date> = connection .query("select mydate from TEST_DAYDATE where number = 2350") .await? .try_into() .await?; trace!("query sent"); assert_eq!(date, None); } Ok(()) }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(maps:values/1)] pub fn result(process: &Process, map: Term) -> exception::Result<Term> { let boxed_map = term_try_into_map_or_badmap!(process, map)?; let values = boxed_map.values(); let list = process.list_from_slice(&values); Ok(list) }
#[cfg(test)] #[path = "./player_tests.rs"] pub mod player_tests; use game::{State, MAX_TRAVERSABLE}; use map::{adj_rooms_to, is_adj}; use map::{RoomNum, NUM_OF_ROOMS}; use message; use std::cell::Cell; use util::{print, read_line, read_sanitized_line}; pub const ARROW_CAPACITY: u8 = 5; #[derive(Debug, Clone, PartialEq)] pub enum Action { Shoot(Vec<RoomNum>), Move(RoomNum), Quit } pub struct Player { pub room: Cell<RoomNum>, pub arrow_count: Cell<u8>, director: Box<dyn Director> } impl Player { pub fn new(room: RoomNum) -> Self { Player { director: box PlayerDirector, room: Cell::new(room), arrow_count: Cell::new(ARROW_CAPACITY) } } pub fn get_action(&self, state: &State) -> Action { let action = self.director.next(state); if is_shoot(&action) { let c = self.arrow_count.get(); self.arrow_count.set(c - 1); } action } } fn is_shoot(a: &Action) -> bool { match *a { Action::Shoot(..) => true, _ => false } } pub trait Director { fn next(&self, state: &State) -> Action; } pub struct PlayerDirector; impl Director for PlayerDirector { fn next(&self, state: &State) -> Action { let room_num = state.player; loop { println!("You are in room {}", room_num); let (a, b, c) = adj_rooms_to(room_num); println!("Tunnel leads to {} {} {}", a, b, c); print(message::Prompt::ACTION); match read_sanitized_line().as_ref() { "M" => return Action::Move(get_adj_room_to(room_num)), "Q" => return Action::Quit, "S" => return Action::Shoot(get_rooms_to_shoot(room_num)), _ => continue } } } } pub fn get_adj_room_to(room: RoomNum) -> RoomNum { print("Where to? "); loop { let input = read_sanitized_line(); match input.parse::<RoomNum>() { Ok(next) if is_adj(room, next) => return next, _ => print("Not Possible - Where to? ") } } } fn get_rooms_to_shoot(player: RoomNum) -> Vec<RoomNum> { loop { print("Enter up to 5 space separated rooms to shoot: "); if let Some(rooms) = try_parse_rooms_from_user(player) { if is_too_crooked(&rooms) { println!("{}", message::Message::TOO_CROOKED); } else { return rooms; } } } } fn try_parse_rooms_from_user(player: RoomNum) -> Option<Vec<RoomNum>> { let mut result = vec![player]; let line = read_line(); let rooms = line .split_whitespace() .take(MAX_TRAVERSABLE) .map(|r| r.parse::<RoomNum>()); for r in rooms { match r { Ok(room_num) => { if room_num > 0 && room_num <= NUM_OF_ROOMS { result.push(room_num); } else { println!("The room number {} is out of bounds.", room_num); return None; } } Err(_) => { println!("The given list of rooms contains one or more invalid numbers."); return None; } } } Some(result) } /// A path is too crooked if it contains an A-B-A path where A is adjacent to B. fn is_too_crooked(path: &[RoomNum]) -> bool { path.windows(3) .any(|x| x.len() == 3 && is_adj(x[0], x[1]) && x[0] == x[2]) }
//! This example renders a cube to an SVG file using both a perspective camera //! and an orthographic camera. use cam_geom::*; use nalgebra::{ allocator::Allocator, storage::Storage, DefaultAllocator, Dim, Matrix, SMatrix, Unit, Vector3, U1, U2, U3, }; /// Create a perspective camera. fn get_perspective_cam() -> Camera<f64, IntrinsicParametersPerspective<f64>> { // Set intrinsic parameters let intrinsics = PerspectiveParams { fx: 100.0, fy: 100.0, skew: 0.0, cx: 640.0, cy: 480.0, }; // Set extrinsic parameters. let camcenter = Vector3::new(10.0, 3.0, 5.0); let lookat = Vector3::new(0.0, 0.0, 0.0); let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)); let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up); // Create camera with both intrinsic and extrinsic parameters. Camera::new(intrinsics.into(), pose) } /// Create an orthographic camera. fn get_ortho_cam() -> Camera<f64, IntrinsicParametersOrthographic<f64>> { let intrinsics = OrthographicParams { sx: 100.0, sy: 102.0, cx: 321.0, cy: 239.9, }; // Set extrinsic parameters. let camcenter = Vector3::new(10.0, 3.0, 5.0); let lookat = Vector3::new(0.0, 0.0, 0.0); let up = Unit::new_normalize(Vector3::new(0.0, 0.0, 1.0)); let pose = ExtrinsicParameters::from_view(&camcenter, &lookat, &up); // Create camera with both intrinsic and extrinsic parameters. Camera::new(intrinsics.into(), pose) } /// A simple SVG file writer struct SvgWriter { segs: Vec<((f64, f64), (f64, f64))>, xmin: f64, xmax: f64, ymin: f64, ymax: f64, } impl SvgWriter { fn new() -> Self { Self { xmin: std::f64::INFINITY, xmax: -std::f64::INFINITY, ymin: std::f64::INFINITY, ymax: -std::f64::INFINITY, segs: Vec::new(), } } fn add_edge<S>(&mut self, pt0: &Matrix<f64, U1, U2, S>, pt1: &Matrix<f64, U1, U2, S>) where S: Storage<f64, U1, U2>, { self.xmin = self.xmin.min(pt0[0]); self.xmin = self.xmin.min(pt1[0]); self.ymin = self.ymin.min(pt0[1]); self.ymin = self.ymin.min(pt1[1]); self.xmax = self.xmax.max(pt0[0]); self.xmax = self.xmax.max(pt1[0]); self.ymax = self.ymax.max(pt0[1]); self.ymax = self.ymax.max(pt1[1]); self.segs.push(((pt0[0], pt0[1]), (pt1[0], pt1[1]))); } fn save(&self, fname: &str) -> Result<(), std::io::Error> { use std::io::prelude::*; let header = "<svg version=\"1.1\" \ baseProfile=\"full\" \ width=\"300\" height=\"200\" \ xmlns=\"http://www.w3.org/2000/svg\">\n"; let footer = "</svg>\n"; let width = 300.0; let height = 200.0; let border = 5.0; let mut xscale = (width - 2.0 * border) / (self.xmax - self.xmin); let mut yscale = (height - 2.0 * border) / (self.ymax - self.ymin); // Keep aspect ratio equal for x and y dimensions. if xscale > yscale { xscale = yscale; } else { yscale = xscale; } let xoffset = -self.xmin * xscale + border; let yoffset = -self.ymin * yscale + border; let mut file = std::fs::File::create(fname)?; file.write_all(header.as_bytes())?; let radius = border; let stroke_width = 2.0; for seg in &self.segs { let x1 = (seg.0).0 * xscale + xoffset; let x2 = (seg.1).0 * xscale + xoffset; let y1 = (seg.0).1 * yscale + yoffset; let y2 = (seg.1).1 * yscale + yoffset; let buf = format!("<line x1=\"{}\" x2=\"{}\" y1=\"{}\" y2=\"{}\" stroke=\"orange\" stroke-width=\"{}\"/>", x1, x2, y1, y2, stroke_width); file.write_all(buf.as_bytes())?; let buf = format!( "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"green\" />\n", x1, y1, radius ); file.write_all(buf.as_bytes())?; let buf = format!( "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"green\" />\n", x2, y2, radius ); file.write_all(buf.as_bytes())?; } file.write_all(footer.as_bytes())?; Ok(()) } } // Save a wireframe rendering of the vertices and edges to an SVG file. fn render_wireframe<NPTS, I, S>( verts: &Points<WorldFrame, f64, NPTS, S>, edges: &[(usize, usize)], cam: &Camera<f64, I>, fname: &str, ) -> Result<(), std::io::Error> where NPTS: Dim, I: IntrinsicParameters<f64>, S: Storage<f64, NPTS, U3>, DefaultAllocator: Allocator<f64, NPTS, U3>, DefaultAllocator: Allocator<f64, NPTS, U2>, { // Project the original 3D coordinates to 2D pixel coordinates. let pixel_coords = cam.world_to_pixel(verts); let mut wtr = SvgWriter::new(); for edge in edges { let (i0, i1) = edge; let pt0 = pixel_coords.data.row(*i0); let pt1 = pixel_coords.data.row(*i1); wtr.add_edge(&pt0, &pt1); } wtr.save(fname)?; Ok(()) } fn main() -> Result<(), std::io::Error> { // Create cube vertices in the world coordinate frame. let world_coords = Points::<WorldFrame, _, _, _>::new(SMatrix::<f64, 8, 3>::from_row_slice(&[ -1.0, -1.0, -1.0, // v1 1.0, -1.0, -1.0, // v2 1.0, 1.0, -1.0, // v3 -1.0, 1.0, -1.0, // v4 -1.0, -1.0, 1.0, // v5 1.0, -1.0, 1.0, // v6 1.0, 1.0, 1.0, // v7 -1.0, 1.0, 1.0, // v8 ])); let edges = [ (0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7), ]; let cam = get_perspective_cam(); render_wireframe(&world_coords, &edges, &cam, "cube-perspective.svg")?; let cam = get_ortho_cam(); render_wireframe(&world_coords, &edges, &cam, "cube-ortho.svg")?; Ok(()) }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type ConditionForceEffect = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ConditionForceEffectKind(pub i32); impl ConditionForceEffectKind { pub const Spring: Self = Self(0i32); pub const Damper: Self = Self(1i32); pub const Inertia: Self = Self(2i32); pub const Friction: Self = Self(3i32); } impl ::core::marker::Copy for ConditionForceEffectKind {} impl ::core::clone::Clone for ConditionForceEffectKind { fn clone(&self) -> Self { *self } } pub type ConstantForceEffect = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ForceFeedbackEffectAxes(pub u32); impl ForceFeedbackEffectAxes { pub const None: Self = Self(0u32); pub const X: Self = Self(1u32); pub const Y: Self = Self(2u32); pub const Z: Self = Self(4u32); } impl ::core::marker::Copy for ForceFeedbackEffectAxes {} impl ::core::clone::Clone for ForceFeedbackEffectAxes { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ForceFeedbackEffectState(pub i32); impl ForceFeedbackEffectState { pub const Stopped: Self = Self(0i32); pub const Running: Self = Self(1i32); pub const Paused: Self = Self(2i32); pub const Faulted: Self = Self(3i32); } impl ::core::marker::Copy for ForceFeedbackEffectState {} impl ::core::clone::Clone for ForceFeedbackEffectState { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ForceFeedbackLoadEffectResult(pub i32); impl ForceFeedbackLoadEffectResult { pub const Succeeded: Self = Self(0i32); pub const EffectStorageFull: Self = Self(1i32); pub const EffectNotSupported: Self = Self(2i32); } impl ::core::marker::Copy for ForceFeedbackLoadEffectResult {} impl ::core::clone::Clone for ForceFeedbackLoadEffectResult { fn clone(&self) -> Self { *self } } pub type ForceFeedbackMotor = *mut ::core::ffi::c_void; pub type IForceFeedbackEffect = *mut ::core::ffi::c_void; pub type PeriodicForceEffect = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct PeriodicForceEffectKind(pub i32); impl PeriodicForceEffectKind { pub const SquareWave: Self = Self(0i32); pub const SineWave: Self = Self(1i32); pub const TriangleWave: Self = Self(2i32); pub const SawtoothWaveUp: Self = Self(3i32); pub const SawtoothWaveDown: Self = Self(4i32); } impl ::core::marker::Copy for PeriodicForceEffectKind {} impl ::core::clone::Clone for PeriodicForceEffectKind { fn clone(&self) -> Self { *self } } pub type RampForceEffect = *mut ::core::ffi::c_void;
use std::cmp::{Ord, Ordering, PartialOrd}; use std::hash::{Hash, Hasher}; use chrono::prelude::*; use failure::Fail; use super::prelude::*; use util::format_error_with_causes; #[derive(Clone, Debug)] pub struct ErrorMessage { pub id: MessageID, pub channel_id: ChannelID, pub text: String, } impl Hash for ErrorMessage { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state) } } impl PartialEq for ErrorMessage { fn eq(&self, rhs: &ErrorMessage) -> bool { self.id.eq(&rhs.id) } } impl Eq for ErrorMessage {} impl PartialOrd for ErrorMessage { fn partial_cmp(&self, rhs: &ErrorMessage) -> Option<Ordering> { self.id.partial_cmp(&rhs.id) } } impl Ord for ErrorMessage { fn cmp(&self, rhs: &ErrorMessage) -> Ordering { self.id.cmp(&rhs.id) } } impl ErrorMessage { pub fn from_error<E: Fail>(channel_id: &ChannelID, error: E) -> ErrorMessage { ErrorMessage { id: Local::now().into(), channel_id: channel_id.clone(), text: format_error_with_causes(error), } } } impl HistoryEntry for ErrorMessage { fn id(&self) -> &MessageID { &self.id } fn channel_id(&self) -> &ChannelID { &self.channel_id } fn render_as_canvas(&self, _state: &AppState, width: u16) -> Canvas { use tui::style::*; let red = Style::default().fg(Color::Red); let mut canvas = Canvas::new(width); canvas.add_string_truncated("Error\n", red); canvas.add_string_wrapped(&self.text, red); canvas } fn into_message(self) -> Message { Message::Error(self) } } #[cfg(test)] mod tests { use super::*; #[test] fn it_renders_as_canvas() { let state = AppState::fixture(); let message = ErrorMessage { id: "1110000.000000".into(), channel_id: "C1".into(), text: "Thing happened".into(), }; let big_canvas = message.render_as_canvas(&state, 50); assert_eq!( &big_canvas.render_to_string(Some("|")), "Error | Thing happened |" ); } }
use lazy_static::lazy_static; use regex::Regex; lazy_static! { static ref NATIONAL_CODE_REGEX: Regex = Regex::new(r"^\d{10}$").unwrap(); } pub fn verify_iranian_national_code<T: AsRef<str>>(code: T) -> bool { let code = code.as_ref(); if !NATIONAL_CODE_REGEX.is_match(code) { return false; } if let Ok(num) = code[3..].parse::<u32>() { if num == 0 { return false; } } let last_index = code[9..].parse::<u32>().unwrap(); let mut sum: u32 = 0; for i in 0..9 { sum += code[i..i + 1].parse::<u32>().unwrap() * (10 - i) as u32; } sum %= 11; (sum < 2 && last_index == sum) || (sum >= 2 && last_index == 11 - sum) } #[cfg(test)] mod test { use super::*; #[test] fn verify_iranian_national_code_test() { let result = verify_iranian_national_code("3020588391"); assert!(result); } #[test] fn regex_test() { assert!(NATIONAL_CODE_REGEX.is_match("1234567890")); assert_eq!(NATIONAL_CODE_REGEX.is_match("123456789"), false); assert_eq!(NATIONAL_CODE_REGEX.is_match("123456789a"), false); assert_eq!(NATIONAL_CODE_REGEX.is_match("12345678911"), false); } }
/*! A very simple application that show how to use a flexbox layout. Requires the following features: `cargo run --example flexbox_d --features "flexbox"` */ extern crate native_windows_gui as nwg; extern crate native_windows_derive as nwd; use nwd::NwgUi; use nwg::NativeUi; // Stretch style use nwg::stretch::{geometry::{Size, Rect}, style::{Dimension as D, FlexDirection, AlignSelf}}; const FIFTY_PC: D = D::Percent(0.5); const PT_10: D = D::Points(10.0); const PT_5: D = D::Points(5.0); const PADDING: Rect<D> = Rect{ start: PT_10, end: PT_10, top: PT_10, bottom: PT_10 }; const MARGIN: Rect<D> = Rect{ start: PT_5, end: PT_5, top: PT_5, bottom: PT_5 }; #[derive(Default, NwgUi)] pub struct FlexBoxApp { #[nwg_control(size: (500, 300), position: (300, 300), title: "Flexbox example")] #[nwg_events( OnWindowClose: [nwg::stop_thread_dispatch()] )] window: nwg::Window, #[nwg_layout(parent: window, flex_direction: FlexDirection::Row, padding: PADDING)] layout: nwg::FlexboxLayout, #[nwg_control(text: "Btn 1")] #[nwg_layout_item(layout: layout, margin: MARGIN, max_size: Size { width: D::Points(200.0), height: D::Undefined }, size: Size { width: FIFTY_PC, height: D::Auto } )] button1: nwg::Button, #[nwg_control(text: "Btn 2")] #[nwg_layout_item(layout: layout, margin: MARGIN, align_self: AlignSelf::FlexEnd, size: Size { width: D::Percent(0.25), height: FIFTY_PC } )] button2: nwg::Button, #[nwg_control(text: "Btn 3")] #[nwg_layout_item(layout: layout, margin: MARGIN, flex_grow: 2.0, size: Size { width: D::Auto, height: D::Auto } )] button3: nwg::Button } fn main() { nwg::init().expect("Failed to init Native Windows GUI"); nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font"); let _ui = FlexBoxApp::build_ui(Default::default()).expect("Failed to build UI"); nwg::dispatch_thread_events(); }
use std::any::Any; use crate::mutators::tuples::{RefTypes, TupleMutator, TupleStructure}; use crate::Mutator; pub enum NeverMutator {} impl<T: Clone + 'static> Mutator<T> for NeverMutator { #[doc(hidden)] type Cache = (); #[doc(hidden)] type MutationStep = (); #[doc(hidden)] type ArbitraryStep = (); #[doc(hidden)] type UnmutateToken = (); #[doc(hidden)] #[no_coverage] fn initialize(&self) {} #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { unreachable!() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, _value: &T) -> bool { unreachable!() } #[doc(hidden)] #[no_coverage] fn validate_value(&self, _value: &T) -> Option<Self::Cache> { unreachable!() } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, _value: &T, _cache: &Self::Cache) -> Self::MutationStep { unreachable!() } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn complexity(&self, _value: &T, _cache: &Self::Cache) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, _step: &mut Self::ArbitraryStep, _max_cplx: f64) -> Option<(T, f64)> { unreachable!() } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, _max_cplx: f64) -> (T, f64) { unreachable!() } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, _value: &mut T, _cache: &mut Self::Cache, _step: &mut Self::MutationStep, _subvalue_provider: &dyn crate::SubValueProvider, _max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { unreachable!() } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, _value: &mut T, _cache: &mut Self::Cache, _max_cplx: f64) -> (Self::UnmutateToken, f64) { unreachable!() } #[doc(hidden)] #[no_coverage] fn unmutate(&self, _value: &mut T, _cache: &mut Self::Cache, _t: Self::UnmutateToken) { unreachable!() } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>(&self, _value: &'a T, _cache: &'a Self::Cache, _visit: &mut dyn FnMut(&'a dyn Any, f64)) { unreachable!() } } impl<T: Clone + 'static, TupleKind: RefTypes> TupleMutator<T, TupleKind> for NeverMutator where T: TupleStructure<TupleKind>, { #[doc(hidden)] type Cache = (); #[doc(hidden)] type MutationStep = (); #[doc(hidden)] type ArbitraryStep = (); #[doc(hidden)] type UnmutateToken = (); #[doc(hidden)] #[no_coverage] fn initialize(&self) {} #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { unreachable!() } #[doc(hidden)] #[no_coverage] fn complexity<'a>(&self, _value: TupleKind::Ref<'a>, _cache: &'a Self::Cache) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, _value: TupleKind::Ref<'_>) -> bool { unreachable!() } #[doc(hidden)] #[no_coverage] fn validate_value(&self, _value: TupleKind::Ref<'_>) -> Option<Self::Cache> { unreachable!() } #[doc(hidden)] #[no_coverage] fn default_mutation_step<'a>(&self, _value: TupleKind::Ref<'a>, _cache: &'a Self::Cache) -> Self::MutationStep { unreachable!() } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { unreachable!() } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, _step: &mut Self::ArbitraryStep, _max_cplx: f64) -> Option<(T, f64)> { unreachable!() } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, _max_cplx: f64) -> (T, f64) { unreachable!() } #[doc(hidden)] #[no_coverage] fn ordered_mutate<'a>( &self, _value: TupleKind::Mut<'a>, _cache: &'a mut Self::Cache, _step: &'a mut Self::MutationStep, _subvalue_provider: &dyn crate::SubValueProvider, _max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { unreachable!() } #[doc(hidden)] #[no_coverage] fn random_mutate<'a>( &self, _value: TupleKind::Mut<'a>, _cache: &'a mut Self::Cache, _max_cplx: f64, ) -> (Self::UnmutateToken, f64) { unreachable!() } #[doc(hidden)] #[no_coverage] fn unmutate<'a>(&self, _value: TupleKind::Mut<'a>, _cache: &'a mut Self::Cache, _t: Self::UnmutateToken) { unreachable!() } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>( &self, _value: TupleKind::Ref<'a>, _cache: &'a Self::Cache, _visit: &mut dyn FnMut(&'a dyn Any, f64), ) { unreachable!() } }
mod utils; fn main() { let data = utils::load_input("./data/day_1.txt").unwrap(); let mut data: Vec<u32> = data .lines() .map(|l| l.trim().parse::<u32>().unwrap()) .collect(); let mut answer_not_found = true; let mut answer_1 = 0; let mut answer_2 = 0; while answer_not_found { let d1 = data.pop().expect("No more data"); for d2 in &data { if d1 + d2 == 2020 { answer_1 = d1 * d2; answer_not_found = false; } for d3 in &data { if d1 + d2 + d3 == 2020 { answer_2 = d1 * d2 * d3; } } } } println!("Answer 1/2: {}", answer_1); println!("Answer 2/2: {}", answer_2); }
#[doc = "Reader of register MPCBB2_VCTR46"] pub type R = crate::R<u32, super::MPCBB2_VCTR46>; #[doc = "Writer for register MPCBB2_VCTR46"] pub type W = crate::W<u32, super::MPCBB2_VCTR46>; #[doc = "Register MPCBB2_VCTR46 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB2_VCTR46 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `B1472`"] pub type B1472_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1472`"] pub struct B1472_W<'a> { w: &'a mut W, } impl<'a> B1472_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) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `B1473`"] pub type B1473_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1473`"] pub struct B1473_W<'a> { w: &'a mut W, } impl<'a> B1473_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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B1474`"] pub type B1474_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1474`"] pub struct B1474_W<'a> { w: &'a mut W, } impl<'a> B1474_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 `B1475`"] pub type B1475_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1475`"] pub struct B1475_W<'a> { w: &'a mut W, } impl<'a> B1475_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 `B1476`"] pub type B1476_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1476`"] pub struct B1476_W<'a> { w: &'a mut W, } impl<'a> B1476_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 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `B1477`"] pub type B1477_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1477`"] pub struct B1477_W<'a> { w: &'a mut W, } impl<'a> B1477_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 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `B1478`"] pub type B1478_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1478`"] pub struct B1478_W<'a> { w: &'a mut W, } impl<'a> B1478_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 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `B1479`"] pub type B1479_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1479`"] pub struct B1479_W<'a> { w: &'a mut W, } impl<'a> B1479_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B1480`"] pub type B1480_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1480`"] pub struct B1480_W<'a> { w: &'a mut W, } impl<'a> B1480_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B1481`"] pub type B1481_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1481`"] pub struct B1481_W<'a> { w: &'a mut W, } impl<'a> B1481_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B1482`"] pub type B1482_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1482`"] pub struct B1482_W<'a> { w: &'a mut W, } impl<'a> B1482_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B1483`"] pub type B1483_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1483`"] pub struct B1483_W<'a> { w: &'a mut W, } impl<'a> B1483_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B1484`"] pub type B1484_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1484`"] pub struct B1484_W<'a> { w: &'a mut W, } impl<'a> B1484_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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `B1485`"] pub type B1485_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1485`"] pub struct B1485_W<'a> { w: &'a mut W, } impl<'a> B1485_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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `B1486`"] pub type B1486_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1486`"] pub struct B1486_W<'a> { w: &'a mut W, } impl<'a> B1486_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B1487`"] pub type B1487_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1487`"] pub struct B1487_W<'a> { w: &'a mut W, } impl<'a> B1487_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B1488`"] pub type B1488_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1488`"] pub struct B1488_W<'a> { w: &'a mut W, } impl<'a> B1488_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `B1489`"] pub type B1489_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1489`"] pub struct B1489_W<'a> { w: &'a mut W, } impl<'a> B1489_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `B1490`"] pub type B1490_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1490`"] pub struct B1490_W<'a> { w: &'a mut W, } impl<'a> B1490_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `B1491`"] pub type B1491_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1491`"] pub struct B1491_W<'a> { w: &'a mut W, } impl<'a> B1491_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `B1492`"] pub type B1492_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1492`"] pub struct B1492_W<'a> { w: &'a mut W, } impl<'a> B1492_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B1493`"] pub type B1493_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1493`"] pub struct B1493_W<'a> { w: &'a mut W, } impl<'a> B1493_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B1494`"] pub type B1494_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1494`"] pub struct B1494_W<'a> { w: &'a mut W, } impl<'a> B1494_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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `B1495`"] pub type B1495_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1495`"] pub struct B1495_W<'a> { w: &'a mut W, } impl<'a> B1495_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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `B1496`"] pub type B1496_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1496`"] pub struct B1496_W<'a> { w: &'a mut W, } impl<'a> B1496_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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `B1497`"] pub type B1497_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1497`"] pub struct B1497_W<'a> { w: &'a mut W, } impl<'a> B1497_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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B1498`"] pub type B1498_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1498`"] pub struct B1498_W<'a> { w: &'a mut W, } impl<'a> B1498_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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B1499`"] pub type B1499_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1499`"] pub struct B1499_W<'a> { w: &'a mut W, } impl<'a> B1499_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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B1500`"] pub type B1500_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1500`"] pub struct B1500_W<'a> { w: &'a mut W, } impl<'a> B1500_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B1501`"] pub type B1501_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1501`"] pub struct B1501_W<'a> { w: &'a mut W, } impl<'a> B1501_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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B1502`"] pub type B1502_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1502`"] pub struct B1502_W<'a> { w: &'a mut W, } impl<'a> B1502_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B1503`"] pub type B1503_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1503`"] pub struct B1503_W<'a> { w: &'a mut W, } impl<'a> B1503_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B1472"] #[inline(always)] pub fn b1472(&self) -> B1472_R { B1472_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B1473"] #[inline(always)] pub fn b1473(&self) -> B1473_R { B1473_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B1474"] #[inline(always)] pub fn b1474(&self) -> B1474_R { B1474_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B1475"] #[inline(always)] pub fn b1475(&self) -> B1475_R { B1475_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B1476"] #[inline(always)] pub fn b1476(&self) -> B1476_R { B1476_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B1477"] #[inline(always)] pub fn b1477(&self) -> B1477_R { B1477_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B1478"] #[inline(always)] pub fn b1478(&self) -> B1478_R { B1478_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B1479"] #[inline(always)] pub fn b1479(&self) -> B1479_R { B1479_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B1480"] #[inline(always)] pub fn b1480(&self) -> B1480_R { B1480_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B1481"] #[inline(always)] pub fn b1481(&self) -> B1481_R { B1481_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B1482"] #[inline(always)] pub fn b1482(&self) -> B1482_R { B1482_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B1483"] #[inline(always)] pub fn b1483(&self) -> B1483_R { B1483_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B1484"] #[inline(always)] pub fn b1484(&self) -> B1484_R { B1484_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B1485"] #[inline(always)] pub fn b1485(&self) -> B1485_R { B1485_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B1486"] #[inline(always)] pub fn b1486(&self) -> B1486_R { B1486_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B1487"] #[inline(always)] pub fn b1487(&self) -> B1487_R { B1487_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B1488"] #[inline(always)] pub fn b1488(&self) -> B1488_R { B1488_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B1489"] #[inline(always)] pub fn b1489(&self) -> B1489_R { B1489_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B1490"] #[inline(always)] pub fn b1490(&self) -> B1490_R { B1490_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B1491"] #[inline(always)] pub fn b1491(&self) -> B1491_R { B1491_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B1492"] #[inline(always)] pub fn b1492(&self) -> B1492_R { B1492_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B1493"] #[inline(always)] pub fn b1493(&self) -> B1493_R { B1493_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B1494"] #[inline(always)] pub fn b1494(&self) -> B1494_R { B1494_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B1495"] #[inline(always)] pub fn b1495(&self) -> B1495_R { B1495_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B1496"] #[inline(always)] pub fn b1496(&self) -> B1496_R { B1496_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B1497"] #[inline(always)] pub fn b1497(&self) -> B1497_R { B1497_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B1498"] #[inline(always)] pub fn b1498(&self) -> B1498_R { B1498_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B1499"] #[inline(always)] pub fn b1499(&self) -> B1499_R { B1499_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B1500"] #[inline(always)] pub fn b1500(&self) -> B1500_R { B1500_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B1501"] #[inline(always)] pub fn b1501(&self) -> B1501_R { B1501_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B1502"] #[inline(always)] pub fn b1502(&self) -> B1502_R { B1502_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B1503"] #[inline(always)] pub fn b1503(&self) -> B1503_R { B1503_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B1472"] #[inline(always)] pub fn b1472(&mut self) -> B1472_W { B1472_W { w: self } } #[doc = "Bit 1 - B1473"] #[inline(always)] pub fn b1473(&mut self) -> B1473_W { B1473_W { w: self } } #[doc = "Bit 2 - B1474"] #[inline(always)] pub fn b1474(&mut self) -> B1474_W { B1474_W { w: self } } #[doc = "Bit 3 - B1475"] #[inline(always)] pub fn b1475(&mut self) -> B1475_W { B1475_W { w: self } } #[doc = "Bit 4 - B1476"] #[inline(always)] pub fn b1476(&mut self) -> B1476_W { B1476_W { w: self } } #[doc = "Bit 5 - B1477"] #[inline(always)] pub fn b1477(&mut self) -> B1477_W { B1477_W { w: self } } #[doc = "Bit 6 - B1478"] #[inline(always)] pub fn b1478(&mut self) -> B1478_W { B1478_W { w: self } } #[doc = "Bit 7 - B1479"] #[inline(always)] pub fn b1479(&mut self) -> B1479_W { B1479_W { w: self } } #[doc = "Bit 8 - B1480"] #[inline(always)] pub fn b1480(&mut self) -> B1480_W { B1480_W { w: self } } #[doc = "Bit 9 - B1481"] #[inline(always)] pub fn b1481(&mut self) -> B1481_W { B1481_W { w: self } } #[doc = "Bit 10 - B1482"] #[inline(always)] pub fn b1482(&mut self) -> B1482_W { B1482_W { w: self } } #[doc = "Bit 11 - B1483"] #[inline(always)] pub fn b1483(&mut self) -> B1483_W { B1483_W { w: self } } #[doc = "Bit 12 - B1484"] #[inline(always)] pub fn b1484(&mut self) -> B1484_W { B1484_W { w: self } } #[doc = "Bit 13 - B1485"] #[inline(always)] pub fn b1485(&mut self) -> B1485_W { B1485_W { w: self } } #[doc = "Bit 14 - B1486"] #[inline(always)] pub fn b1486(&mut self) -> B1486_W { B1486_W { w: self } } #[doc = "Bit 15 - B1487"] #[inline(always)] pub fn b1487(&mut self) -> B1487_W { B1487_W { w: self } } #[doc = "Bit 16 - B1488"] #[inline(always)] pub fn b1488(&mut self) -> B1488_W { B1488_W { w: self } } #[doc = "Bit 17 - B1489"] #[inline(always)] pub fn b1489(&mut self) -> B1489_W { B1489_W { w: self } } #[doc = "Bit 18 - B1490"] #[inline(always)] pub fn b1490(&mut self) -> B1490_W { B1490_W { w: self } } #[doc = "Bit 19 - B1491"] #[inline(always)] pub fn b1491(&mut self) -> B1491_W { B1491_W { w: self } } #[doc = "Bit 20 - B1492"] #[inline(always)] pub fn b1492(&mut self) -> B1492_W { B1492_W { w: self } } #[doc = "Bit 21 - B1493"] #[inline(always)] pub fn b1493(&mut self) -> B1493_W { B1493_W { w: self } } #[doc = "Bit 22 - B1494"] #[inline(always)] pub fn b1494(&mut self) -> B1494_W { B1494_W { w: self } } #[doc = "Bit 23 - B1495"] #[inline(always)] pub fn b1495(&mut self) -> B1495_W { B1495_W { w: self } } #[doc = "Bit 24 - B1496"] #[inline(always)] pub fn b1496(&mut self) -> B1496_W { B1496_W { w: self } } #[doc = "Bit 25 - B1497"] #[inline(always)] pub fn b1497(&mut self) -> B1497_W { B1497_W { w: self } } #[doc = "Bit 26 - B1498"] #[inline(always)] pub fn b1498(&mut self) -> B1498_W { B1498_W { w: self } } #[doc = "Bit 27 - B1499"] #[inline(always)] pub fn b1499(&mut self) -> B1499_W { B1499_W { w: self } } #[doc = "Bit 28 - B1500"] #[inline(always)] pub fn b1500(&mut self) -> B1500_W { B1500_W { w: self } } #[doc = "Bit 29 - B1501"] #[inline(always)] pub fn b1501(&mut self) -> B1501_W { B1501_W { w: self } } #[doc = "Bit 30 - B1502"] #[inline(always)] pub fn b1502(&mut self) -> B1502_W { B1502_W { w: self } } #[doc = "Bit 31 - B1503"] #[inline(always)] pub fn b1503(&mut self) -> B1503_W { B1503_W { w: self } } }
//! Lock file management //! //! When dealing with server software, it is often necessary to make sure that only one instance //! is running at a time. Lock files are a common way to do that. This module provides a //! convenient abstraction over low-level commands for lock file management. All magic is done //! inside of [`Lock`], an exclusive lock file handle. //! //! [`Lock`]: struct.Lock.html use errors::*; use std::fs::{OpenOptions, remove_file}; use std::io::prelude::*; use std::path::PathBuf; /// A `Lock` is the exclusive handle representing an existing lock file. /// /// When creating a `Lock`, a lock file is auto-created and stored at the given path. The current /// process id (PID) is written into the lock file. When a `Lock` is dropped (== goes /// out-of-scope), the lock file is removed. /// /// A `Lock` does never exist without its lock file. Neither does a lock file exist without its /// handle, except for one occasion: When the process receives a SIGINT, the destructor will not /// run and the lock file remains in the file system while the process is stopped. It is possible /// to mitigate this behavior with a SIGINT handler that catches the signal, removes the lock file /// and then stops the process. Such a handler can be set up using [`handle_sigint`]. /// /// A `Lock` is exclusive: It is impossible to clone or create a `Lock` that refers to the same /// lock file. The reason is that dropping a `Lock` referencing a lock file that has already been /// removed, would cause a runtime error. If you need more than one handle consider using a smart /// pointer. /// /// [`handle_sigint`]: #method.handle_sigint /// /// # Example /// ```no_run /// # use dynonym::lock::Lock; /// let path = "dynonym.lock".into(); /// let lock = Lock::create(path).unwrap() /// .handle_sigint().unwrap(); // optional /// /// // some code /// /// lock.release(); // optional /// ``` pub struct Lock { path: PathBuf, } impl Lock { /// Creates a new `Lock`. This includes /// /// 1. creating a new lock file at the given path and /// 2. saving the current process id (PID) into the file. pub fn create(path: PathBuf) -> Result<Self> { // Create a lock file let mut file = OpenOptions::new() .write(true) .create_new(true) .open(&path) .chain_err(|| ErrorKind::LockFileCreate(path.clone()))?; // Write the process id into the lock file let pid = format!( "{}\n", unsafe { ::libc::getpid() } ); file.write_all(pid.as_bytes()) .chain_err(|| ErrorKind::LockFileWrite(path.clone()))?; // Create struct let lock = Lock { path }; Ok(lock) } /// Creates a SIGINT handler for the given `Lock` that makes sure the lock file is removed even /// if the process is interrupted. pub fn handle_sigint(self) -> Result<Self> { // Create a clone // // WARNING: Do not derive Clone for Lock in order to simplify this operation since it is // not a good idea to have a twin in the wild. The relation between a Lock and its lock // file should be 1-to-1 because a lock -- when going out of scope -- removes the lock // file. Having a clone will result in a runtime error as soon as the second lock goes out // of scope and tries to remove the -- no longer existing -- lock file. let twin = Lock { path: self.path.clone() }; // Setup SIGINT handler // TODO Replace ctrlc by tokio-signal?! ::ctrlc::set_handler(move || { if let Err(err) = twin.release_ref() { handle(&err); } ::std::process::exit(0); }) .chain_err(|| ErrorKind::LockFileSetupSigintHandler)?; // Return self Ok(self) } /// Releases the given `Lock` and removes the corresponding lock file. /// /// It most cases it is not necessary to explicitly call this function since the lock file is /// auto-removed as soon as the `Lock` is dropped. pub fn release(self) { } fn release_ref(&self) -> Result<()> { // Remove the lock file remove_file(&self.path) .chain_err(|| ErrorKind::LockFileRemove(self.path.clone()))?; Ok(()) } } impl Drop for Lock { fn drop(&mut self) { if let Err(err) = self.release_ref() { handle(&err); } } }
/// Jika kita mencantumkan semua bilangan asli di bawah 10 yang merupakan kelipatan 3 atau 5, /// kita mendapatkan 3, 5, 6 dan 9. Jumlah kelipatan ini adalah 23. /// Temukan jumlah semua kelipatan 3 atau 5 di bawah 1000. /// bil yg merupakan kelipatan 3 adalah yg habis dibagi 3 fn main() { let mut res = 0; for i in 1..1000 { if i % 3 == 0 || i % 5 == 0 { res += i; } else { continue; } } println!("{:?}", res); }
use std::collections::HashMap; use crate::common::{Board, Coordinate, Player}; use crate::strategy::Strategy; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(s: &str); } pub struct MinMaxStrategy { player: Player, depth: i32, // for memoization board_scores: HashMap<Board, i32>, } struct Node { board: Board, edges: Vec<(Option<Coordinate>, Node)>, } impl MinMaxStrategy { pub fn new(player: Player, depth: i32) -> MinMaxStrategy { MinMaxStrategy { player, depth, board_scores: HashMap::new(), } } fn eval_board(&mut self, board: Board) -> i32 { if let Some(score) = self.board_scores.get(&board) { return *score; } let mut score = 0; // high score for having more stones in the later stage if board.count(self.player) + board.count(self.player.other()) >= 55 { score += (board.count(self.player) - board.count(self.player.other())) * 5; } for x in 0..8 { for y in 0..8 { if board.is_valid_move(Coordinate { x, y }, self.player) { // high score for having many options score = score + 1; } if board.is_valid_move(Coordinate { x, y }, self.player.other()) { // low score for giving many options score = score - 1; } if (x == 0 || x == 7) && (y == 0 || y == 7) { if board.cell(Coordinate { x, y }) == Some(self.player) { // good score for getting corners score = score + 10; } else if board.is_valid_move(Coordinate { x, y }, self.player.other()) { // low score for losing corners score = score - 10; } } } } self.board_scores.insert(board, score); score } fn construct_tree(&self, board: Board, depth: i32, player: Player) -> Node { let mut root = Node { board, edges: Vec::new(), }; if depth > 0 { if !board.has_valid_move(player) { root .edges .push((None, self.construct_tree(board, depth - 1, player.other()))) } for x in 0..8 { for y in 0..8 { if let Some(board_updated) = board.simulate(Coordinate { x, y }, player) { root.edges.push(( Some(Coordinate { x, y }), self.construct_tree(board_updated, depth - 1, player.other()), )); } } } } root } fn eval_tree(&mut self, node: &Node, opponent: bool) -> (i32, Option<Coordinate>) { if node.edges.len() == 0 { return (self.eval_board(node.board), None); } let mut score; let mut c = None; if opponent { // find the minimum score = std::i32::MAX; for edge in node.edges.iter() { let s = self.eval_tree(&edge.1, !opponent).0; if s < score { score = s; c = edge.0; } } } else { // find the maximum score = std::i32::MIN; for edge in node.edges.iter() { let s = self.eval_tree(&edge.1, !opponent).0; if s > score { score = s; c = edge.0; } } } (score, c) } fn tree_size(&self, tree: &Node) -> i32 { let mut cnt = 0; for edge in tree.edges.iter() { cnt += self.tree_size(&edge.1); } cnt + 1 } } impl Strategy for MinMaxStrategy { fn make_move(&mut self, board: Board) -> Option<Coordinate> { let tree = self.construct_tree(board, self.depth, self.player); log(&format!("tree size: {}", self.tree_size(&tree))); return self.eval_tree(&tree, false).1; } fn to_string(&self) -> String { format!("MinMax strategy (depth: {})", self.depth) } }
extern crate rand; extern crate zktx; extern crate tokio_core; extern crate web3; extern crate protobuf; extern crate rustc_hex; use rand::{Rng, thread_rng}; use zktx::base::*; use zktx::c2p::*; use zktx::p2c::*; use zktx::contract::*; use web3::api::Cita; use web3::transports::Http; use web3::types::{H256, H160, FilterBuilder, BlockNumber}; use web3::cita_types::Account as Cita_Account; use web3::futures::Future; use tokio_core::reactor::Core; use protobuf::core::Message; use std::str::FromStr; use rustc_hex::ToHex; use std::thread::sleep; use std::time::Duration; struct Account{ pub balance: String,//in homomorphic encrpytion, = vP1+rP2 pub address: String,//address v: [u64;2],//private information: balance r: [u64;4],//private information: random number sk: String,//private information: secret_key } struct PrivateSendMessage{ v:[u64;2], r:[u64;2] } struct PrivateReceiveMessage{ v:[u64;2], r:[u64;2] } impl Account{ pub fn new(v:[u64;2],r:[u64;2])->Self{ let rng = &mut thread_rng(); let sk = zktx::sk2str((0..ADSK).map(|_| rng.gen()).collect::<Vec<bool>>()); let address = address(sk.clone()); let balance = v_p1_add_r_p2(v,r); Account{ balance, address, v, r:[r[0],r[1],0,0], sk } } pub fn get_address(&self)->String{ self.address.clone() } pub fn get_balance(&self)->String{ self.balance.clone() } fn add_balance(&mut self,value:String){ self.balance = ecc_add(self.balance.clone(),value); } fn sub_balance(&mut self,value:String){ self.balance = ecc_sub(self.balance.clone(),value); } pub fn send(&self,v:[u64;2],rcm:[u64;2],address:String, block_number: u64)->(SenderProof,PrivateSendMessage){ let rng = &mut thread_rng(); let enc_random = [rng.gen(),rng.gen(),rng.gen(),rng.gen()]; let (proof,hb,coin,delt_ba,enc) = p2c_info(self.r,rcm,self.v,v,address.clone(),self.sk.clone(),enc_random).unwrap(); assert_eq!(hb,self.get_balance()); let enc1 = encrypt([rcm[0],rcm[1],v[0],v[1]],enc_random,address.clone()); assert_eq!(enc,enc1); ( SenderProof{ proof, coin, delt_ba, enc, block_number }, PrivateSendMessage{ v,r:rcm } ) } pub fn send_refresh(&mut self, private_message: &PrivateSendMessage){ let pr = private_message.r; self.r = u644sub(self.r,[pr[0],pr[1],0,0]); let pv = private_message.v; let sv = self.v; let temp = u644sub([sv[0],sv[1],0,0],[pv[0],pv[1],0,0]); self.v = [temp[0],temp[1]]; } pub fn receive(&self, enc: String, authentication_path: Vec<String>, index: Vec<bool>)->(ReceiverProof,PrivateReceiveMessage){ let (va,rcm) = decrypt(enc,self.sk.clone()); let rng = &mut thread_rng(); let rcm_new = [rng.gen(),rng.gen()]; let (proof,nullifier,root,delt_ba) = c2p_info(rcm, rcm_new, va, self.sk.clone(), authentication_path, index).unwrap(); ( ReceiverProof{ proof, nullifier, root, delt_ba }, PrivateReceiveMessage{ v:va, r:rcm_new } ) } pub fn receive_refresh(&mut self,private_message:&PrivateReceiveMessage){ let pr = private_message.r; self.r = u644add(self.r,[pr[0],pr[1],0,0]); let pv = private_message.v; let sv = self.v; let temp = u644add([sv[0],sv[1],0,0],[pv[0],pv[1],0,0]); self.v = [temp[0],temp[1]]; } pub fn check_coin(&self,coin:String,enc:String)->bool{ check(coin,enc,self.sk.clone()) } pub fn state_out(&self,name:&str){ println!("{}: v = {:?}, r = {:?}",name,self.v,self.r); } } /*fn verify_send(message:&mut SendMessage,sender:&mut Account){ assert!(p2c_verify(sender.get_balance(),message.coin,message.delt_ba,message.rp,message.enc,message.proof).unwrap()); message.on_chain(); sender.sub_balance(message.delt_ba); }*/ /*fn verify_receive(message:&mut ReceiveMessage,receiver:&mut Account){ assert!(c2p_verify(message.nullifier,message.root,message.delt_ba,message.proof).unwrap()); message.on_chain(); receiver.add_balance(message.delt_ba); }*/ fn get_block_number(cita: &Cita<Http>, event_loop: &mut Core) -> u64 { let height = cita.block_number().map(|height| { println!("height: {:?}", height); height }); event_loop.run(height).unwrap().low_u64() } fn set_balance(cita: &Cita<Http>, event_loop: &mut Core, account: &[Cita_Account], addr: String, balance: String) { let number = get_block_number(cita, event_loop); let hasher = "05e3cb61"; let mut data = hasher.to_string(); data.push_str(&addr.as_bytes().to_hex()); data.push_str(&balance.as_bytes().to_hex()); println!("data={}", data); let tx = cita.generate_tx( &account[0].secret, data, "0x0000000000000000000000000000000012345678".to_string(), number, 100000, "abcd".to_string(), ).write_to_bytes() .unwrap() .to_hex(); println!("hex = {:?}", tx); let tx = cita.send_transaction(tx).map(|tx_response| { println!("tx_response: {:?}", tx_response); tx_response }); event_loop.run(tx).unwrap(); } fn send_verify(cita: &Cita<Http>, event_loop: &mut Core, account: &[Cita_Account], addr: String, proof: SenderProof) { let number = get_block_number(cita, event_loop); let hasher = "c73b5a8f"; let mut data = hasher.to_string(); data.push_str(&addr.as_bytes().to_hex()); data.push_str(&proof.proof.as_bytes().to_hex()); data.push_str(&proof.coin.as_bytes().to_hex()); data.push_str(&proof.delt_ba.as_bytes().to_hex()); data.push_str(&proof.enc.as_bytes().to_hex()); println!("data={}", data); let tx = cita.generate_tx( &account[0].secret, data, "0x0000000000000000000000000000000012345678".to_string(), number, 11000000, "send_verify".to_string(), ).write_to_bytes() .unwrap() .to_hex(); println!("hex = {:?}", tx); let tx = cita.send_transaction(tx).map(|tx_response| { println!("tx_response: {:?}", tx_response); tx_response }); event_loop.run(tx).unwrap(); } fn receive_verify(cita: &Cita<Http>, event_loop: &mut Core, account: &[Cita_Account], addr: String, proof: ReceiverProof) { let number = get_block_number(cita, event_loop); let hasher = "882b30d2"; let mut data = hasher.to_string(); data.push_str(&addr.as_bytes().to_hex()); data.push_str(&proof.proof.as_bytes().to_hex()); data.push_str(&proof.nullifier.as_bytes().to_hex()); data.push_str(&proof.root.as_bytes().to_hex()); data.push_str(&proof.delt_ba.as_bytes().to_hex()); println!("data={}", data); let tx = cita.generate_tx( &account[0].secret, data, "0x0000000000000000000000000000000012345678".to_string(), number, 11000000, "receive_verify".to_string(), ).write_to_bytes() .unwrap() .to_hex(); println!("hex = {:?}", tx); let tx = cita.send_transaction(tx).map(|tx_response| { println!("tx_response: {:?}", tx_response); tx_response }); event_loop.run(tx).unwrap(); } fn round_test(){ // init web3 let mut event_loop = Core::new().unwrap(); let web3 = web3::Web3::new( web3::transports::Http::with_event_loop( "http://localhost:1337", &event_loop.handle(), 64, ).unwrap(), ); //study create sendtransaction param let cita = web3.cita(); let account = cita.accounts("config.json".as_ref()).map_err(|err|{ println!("{:?}",err) }).unwrap(); println!("acount = {:?}", account); // install filter let current_block_number = get_block_number(&cita, &mut event_loop); let eth_filter = web3.eth_filter(); let filter = FilterBuilder::default().address(vec![H160::from_str("0x0000000000000000000000000000000012345678").unwrap()]) .topics(Some(vec![H256::from_str("0xc73b5a8f31a1a078a14123cc93687f4a59389c76caf88d5d2154d3f3ce25ff49").unwrap()]), None, None, None) .from_block(BlockNumber::Number(current_block_number)) .build(); let filter = event_loop.run(eth_filter.create_logs_filter(filter)).unwrap(); println!("install filter {:?}", filter); let rng = &mut thread_rng(); let mut alice = Account::new([1001,0],[rng.gen(),rng.gen()]); let mut bob = Account::new([1000,0],[rng.gen(),rng.gen()]); //privacy_contract.set_banlance(alice.get_address(), alice.get_balance()); let addr = alice.get_address(); let balance = alice.get_balance(); set_balance(&cita, &mut event_loop, &account, addr, balance); println!("alice set_balance, waiting ..."); sleep(Duration::new(10, 0)); //privacy_contract.set_banlance(bob.get_address(), bob.get_balance()); let addr = bob.get_address(); let balance = bob.get_balance(); set_balance(&cita, &mut event_loop, &account, addr, balance); println!("bob set_balance, waiting ..."); sleep(Duration::new(10, 0)); // get current block number by jsonrpc let current_block_number = get_block_number(&cita, &mut event_loop); let (alice_send_message,alice_private_send_message) = alice.send([10,0],[rng.gen(),rng.gen()],bob.get_address(), current_block_number); //verify_send(&mut alice_send_message,&mut alice); // let (ok, path) = privacy_contract.send_verify(alice.get_address(), alice_send_message.clone()); // if !ok { // panic!("alice send_verify failed"); // } send_verify(&cita, &mut event_loop, &account, alice.get_address(), alice_send_message.clone()); println!("alice send_verify, wait for log ..."); //get path from log let mut logs; loop { let ret = event_loop.run(filter.logs()); if ret.is_err() { println!("get log error {:?}", ret); continue; } logs = ret.unwrap(); if logs.len() > 0 { println!("got logs! data len {}", logs[0].data.0.len()); break; } println!("wait for log ..."); sleep(Duration::new(3, 0)); } let log_data = &logs[0].data.0; let coin = String::from_utf8(log_data.get(0..64).unwrap().to_vec()).unwrap(); println!("coin in log {}", coin); let enc = String::from_utf8(log_data.get(64..64+192).unwrap().to_vec()).unwrap(); println!("enc in log {}", enc); let mut authentication_path = Vec::new(); for i in 0..TREEDEPTH { let hash = String::from_utf8(log_data.get(64+192+i*64..64+192+i*64+64).unwrap().to_vec()).unwrap(); println!("authentication_path {} {}", i, hash); authentication_path.push(hash); } let mut index = Vec::new(); for i in 0..TREEDEPTH { if log_data[64+192+TREEDEPTH*64+i] == 1 { index.push(true); } else { index.push(false); } } println!("index in log {:?}", index); // use log confirm sender proof verified alice.send_refresh(&alice_private_send_message); alice.sub_balance(alice_send_message.delt_ba.clone()); alice.state_out("alice"); // bob get alice_send_message by private channel // or listen all message from privacy contract (Maybe filter by sender) // check is the coin is to bob? if bob.check_coin(coin.clone(), enc.clone()) { println!("There is a coin to me"); let (bob_receive_message,bob_private_receive_message) = bob.receive(enc, authentication_path, index); //verify_receive(&mut bob_receive_message,&mut bob); // if !privacy_contract.receive_verify(bob.get_address(), bob_receive_message.clone()) { // panic!("bob receive_verify failed"); // } receive_verify(&cita, &mut event_loop, &account, bob.get_address(), bob_receive_message.clone()); bob.receive_refresh(&bob_private_receive_message); bob.add_balance(bob_receive_message.delt_ba); bob.state_out("bob"); } else { println!("This coin is not mine"); } let current_block_number = get_block_number(&cita, &mut event_loop); let (bob_send_message,bob_private_send_message) = bob.send([200,0],[rng.gen(),rng.gen()],alice.get_address(), current_block_number); //verify_send(&mut bob_send_message,&mut bob); // let (ok, path) = privacy_contract.send_verify(bob.get_address(), bob_send_message.clone()); // if !ok { // panic!("bob send_verify failed"); // } send_verify(&cita, &mut event_loop, &account, bob.get_address(), bob_send_message.clone()); println!("bob send_verify, wait for log ..."); //get path from log let mut logs; loop { let ret = event_loop.run(filter.logs()); if ret.is_err() { println!("get log error {:?}", ret); continue; } logs = ret.unwrap(); if logs.len() > 0 { println!("got logs! data len {}", logs[0].data.0.len()); break; } println!("wait for log ..."); sleep(Duration::new(3, 0)); } let log_data = &logs[0].data.0; let coin = String::from_utf8(log_data.get(0..64).unwrap().to_vec()).unwrap(); println!("coin in log {}", coin); let enc = String::from_utf8(log_data.get(64..64+192).unwrap().to_vec()).unwrap(); println!("enc in log {}", enc); let mut authentication_path = Vec::new(); for i in 0..TREEDEPTH { let hash = String::from_utf8(log_data.get(64+192+i*64..64+192+i*64+64).unwrap().to_vec()).unwrap(); println!("authentication_path {} {}", i, hash); authentication_path.push(hash); } let mut index = Vec::new(); for i in 0..TREEDEPTH { if log_data[64+192+TREEDEPTH*64+i] == 1 { index.push(true); } else { index.push(false); } } println!("index in log {:?}", index); bob.send_refresh(&bob_private_send_message); bob.sub_balance(bob_send_message.delt_ba.clone()); bob.state_out("bob"); if alice.check_coin(coin.clone(), enc.clone()) { println!("There is a coin to me"); let (alice_receive_message,alice_private_receive_message) = alice.receive(enc, authentication_path, index); //verify_receive(&mut alice_receive_message,&mut alice); // if !privacy_contract.receive_verify(alice.get_address(), alice_receive_message.clone()) { // panic!("alice receive_verify failed"); // } receive_verify(&cita, &mut event_loop, &account, alice.get_address(), alice_receive_message.clone()); alice.receive_refresh(&alice_private_receive_message); alice.state_out("alice"); } else { println!("This coin is not mine"); } } fn main(){ zktx::set_param_path("PARAMS"); println!("Round Test:"); round_test(); println!("Test End."); }
//! Ffi-safe equivalents of `std::io::{ErrorKind, Error, SeekFrom}`. #![allow(clippy::missing_const_for_fn)] use std::{ error::Error as ErrorTrait, fmt::{self, Debug, Display}, io::{Error as ioError, ErrorKind, SeekFrom}, }; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ std_types::{RBoxError, RNone, ROption, RSome}, traits::{IntoReprC, IntoReprRust}, }; /////////////////////////////////////////////////////////////////////////// /// Ffi safe equivalent to `std::io::ErrorKind`. /// /// Using a struct with associated constants is the /// ffi-safe way of doing `#[non_exhaustive]` field-less enums. #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] #[derive(StableAbi)] pub struct RIoErrorKind { value: u8, } macro_rules! impl_error_kind { ( $( $variant: ident, discriminant = $value: expr , message = $as_str_msg: expr ; )* ) => ( /// Every (visible) variant of RIoErrorKind, equivalent to that of `std::io::ErrorKind`. #[allow(non_upper_case_globals)] impl RIoErrorKind { $( /// pub const $variant: Self = RIoErrorKind { value: $value }; )* /// pub const Other: Self = RIoErrorKind { value: 0 }; } impl Debug for RIoErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match *self { $( RIoErrorKind::$variant=> stringify!($variant), )* _ => "Other", }; Display::fmt(s, f) } } impl_from_rust_repr! { impl From<ErrorKind> for RIoErrorKind { fn(this){ match this { $( ErrorKind::$variant=> RIoErrorKind::$variant, )* _ => RIoErrorKind::Other, } } } } impl_into_rust_repr! { impl Into<ErrorKind> for RIoErrorKind { fn(this){ match this { $( RIoErrorKind::$variant=> ErrorKind::$variant, )* _ => ErrorKind::Other, } } } } impl RIoErrorKind { pub(crate) fn error_message(&self) -> &'static str { match *self { $( RIoErrorKind::$variant => $as_str_msg, )* _=> "other os error", } } } ) } impl_error_kind! { NotFound, discriminant = 1 , message = "entity not found" ; PermissionDenied, discriminant = 2 , message = "permission denied" ; ConnectionRefused, discriminant = 3 , message = "connection refused" ; ConnectionReset, discriminant = 4 , message = "connection reset" ; ConnectionAborted, discriminant = 5 , message = "connection aborted" ; NotConnected, discriminant = 6 , message = "not connected" ; AddrInUse, discriminant = 7 , message = "address in use" ; AddrNotAvailable, discriminant = 8 , message = "address not available" ; BrokenPipe, discriminant = 9 , message = "broken pipe" ; AlreadyExists, discriminant = 10 , message = "entity already exists" ; WouldBlock, discriminant = 11 , message = "operation would block" ; InvalidInput, discriminant = 12 , message = "invalid input parameter" ; InvalidData, discriminant = 13 , message = "invalid data" ; TimedOut, discriminant = 14 , message = "timed out" ; WriteZero, discriminant = 15 , message = "write zero" ; Interrupted, discriminant = 16 , message = "operation interrupted" ; UnexpectedEof, discriminant = 17 , message = "unexpected end of file" ; } /////////////////////////////////////////////////////////////////////////// /// Ffi-safe equivalent of [`std::io::SeekFrom`]. /// /// [`std::io::SeekFrom`]: https://doc.rust-lang.org/std/io/enum.SeekFrom.html #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(u8)] #[derive(StableAbi)] pub enum RSeekFrom { /// Start(u64), /// End(i64), /// Current(i64), } impl_from_rust_repr! { impl From<SeekFrom> for RSeekFrom { fn(this){ match this { SeekFrom::Start(x) => RSeekFrom::Start(x), SeekFrom::End(x) => RSeekFrom::End(x), SeekFrom::Current(x) => RSeekFrom::Current(x), } } } } impl_into_rust_repr! { impl Into<SeekFrom> for RSeekFrom { fn(this){ match this { RSeekFrom::Start(x) => SeekFrom::Start(x), RSeekFrom::End(x) => SeekFrom::End(x), RSeekFrom::Current(x) => SeekFrom::Current(x), } } } } /////////////////////////////////////////////////////////////////////////// /// Ffi safe equivalent to `std::io::Error`. /// /// # Example /// /// Defining an extern function to write a slice into a writer twice. /// /// ``` /// use abi_stable::{ /// erased_types::interfaces::IoWriteInterface, /// rtry, sabi_extern_fn, /// std_types::{RIoError, ROk, RResult}, /// traits::IntoReprC, /// DynTrait, RMut, /// }; /// /// use std::io::Write; /// /// #[sabi_extern_fn] /// pub fn write_slice_twice( /// mut write: DynTrait<RMut<'_, ()>, IoWriteInterface>, /// slice: &[u8], /// ) -> RResult<(), RIoError> { /// rtry!(write.write_all(slice).into_c()); /// rtry!(write.write_all(slice).into_c()); /// ROk(()) /// } /// /// ``` /// #[repr(C)] #[derive(StableAbi)] pub struct RIoError { kind: RIoErrorKind, error: ROption<RBoxError>, } impl_from_rust_repr! { impl From<ioError> for RIoError { fn(this){ RIoError{ kind: this.kind().into(), error: this.into_inner().map(RBoxError::from_box).into_c() } } } } impl_into_rust_repr! { impl Into<ioError> for RIoError { fn(this){ let kind = this.kind().into_::<ErrorKind>(); match this.into_inner() { Some(e) => ioError::new(kind, RBoxError::into_box(e)), None => ioError::from(kind), } } } } impl From<RIoErrorKind> for RIoError { fn from(kind: RIoErrorKind) -> Self { Self { kind, error: RNone } } } impl From<ErrorKind> for RIoError { fn from(kind: ErrorKind) -> Self { Self { kind: kind.into(), error: RNone, } } } impl RIoError { /// Constructs an `RIoError` from an error and a `std::io::ErrorKind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// let err = RIoError::new(ErrorKind::Other, "".parse::<u64>().unwrap_err()); /// ``` pub fn new<E>(kind: ErrorKind, error: E) -> Self where E: ErrorTrait + Send + Sync + 'static, { RIoError { kind: kind.into_c(), error: RSome(RBoxError::new(error)), } } /// Constructs an `RIoError` from a type convertible into a /// `Box<dyn std::error::Error + Send + Sync + 'static>`, and a `std::io::ErrorKind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// let str_err = "Timeout receiving the response from server."; /// /// let err = RIoError::new_(ErrorKind::TimedOut, str_err); /// ``` #[inline] pub fn new_<E>(kind: ErrorKind, error: E) -> Self where E: Into<Box<dyn ErrorTrait + Send + Sync + 'static>>, { Self::with_box(kind, error.into()) } /// Constructs an `RIoError` from a `std::io::ErrorKind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// ``` pub fn from_kind(kind: ErrorKind) -> Self { Self { kind: kind.into_c(), error: RNone, } } /// Constructs an `RIoError` from a /// `Box<dyn std::error::Error + Send + Sync + 'static>` and a `std::io::ErrorKind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// let str_err = "Could not create file \"memes.txt\" because it already exists."; /// /// let err = RIoError::with_box(ErrorKind::AlreadyExists, str_err.into()); /// ``` pub fn with_box(kind: ErrorKind, error: Box<dyn ErrorTrait + Send + Sync + 'static>) -> Self { RIoError { kind: kind.into_c(), error: RSome(RBoxError::from_box(error)), } } /// Constructs an `RIoError` from an `RBoxError` and a `std::io::ErrorKind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// type DynErr = Box<dyn std::error::Error + Send + Sync>; /// /// let str_err: DynErr = "IP address `256.256.256.256` is already in use.".into(); /// /// let err = RIoError::with_rboxerror(ErrorKind::AddrInUse, str_err.into()); /// ``` pub fn with_rboxerror(kind: ErrorKind, error: RBoxError) -> Self { RIoError { kind: kind.into_c(), error: RSome(error), } } /// Retrieves the kind of io error. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// /// assert_eq!(err.kind(), RIoErrorKind::AlreadyExists); /// ``` pub fn kind(&self) -> RIoErrorKind { self.kind } /// Gets the internal error, /// returning `None` if this was constructed with `RIoError::from_kind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RBoxError, RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// /// { /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// assert_eq!(err.get_ref().map(|_| ()), None); /// } /// { /// let msg = "Cannot access directory at \"/home/Steve/memes/\"."; /// let err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// /// assert!(err.get_ref().is_some()); /// } /// /// ``` pub fn get_ref(&self) -> Option<&RBoxError> { self.error.as_ref().into_rust() } /// Gets the internal error, /// returning `None` if this was constructed with `RIoError::from_kind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RBoxError, RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// /// { /// let mut err = RIoError::from_kind(ErrorKind::AlreadyExists); /// assert_eq!(err.get_mut().map(|_| ()), None); /// } /// { /// let mut msg = "Cannot access directory at \"/home/Patrick/373.15K takes/\"."; /// let mut err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// assert!(err.get_mut().is_some()); /// } /// /// ``` pub fn get_mut(&mut self) -> Option<&mut RBoxError> { self.error.as_mut().into_rust() } /// Converts this into the internal error, /// returning `None` if this was constructed with `RIoError::from_kind`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// /// { /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// assert_eq!(err.into_inner().map(|_| ()), None); /// } /// { /// let mut msg = "Cannot access directory at \"/home/wo_boat/blog/\"."; /// let err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// assert!(err.into_inner().is_some()); /// } /// /// ``` pub fn into_inner(self) -> Option<RBoxError> { self.error.into_rust() } } impl Debug for RIoError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.error.as_ref() { RSome(c) => Debug::fmt(&c, f), RNone => f.debug_tuple("Kind").field(&self.kind).finish(), } } } impl Display for RIoError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.error.as_ref() { RSome(c) => Display::fmt(&c, f), RNone => Display::fmt(self.kind.error_message(), f), } } } impl ErrorTrait for RIoError {} /////////////////////////////////////////////////////////////////////////////////// #[cfg(all(test, not(feature = "only_new_tests")))] mod error_kind_tests { use super::*; #[test] fn conversions() { for (from, to) in [ (ErrorKind::NotConnected, RIoErrorKind::NotConnected), (ErrorKind::AddrInUse, RIoErrorKind::AddrInUse), (ErrorKind::Other, RIoErrorKind::Other), ] { assert_eq!(RIoErrorKind::from(from), to); assert_eq!(to.into_::<ErrorKind>(), from); } } } #[cfg(all(test, not(feature = "only_new_tests")))] mod io_error_tests { use super::*; use crate::test_utils::{check_formatting_equivalence, deref_address, Stringy}; #[test] fn from_error_kind() { for kind in [ ErrorKind::NotConnected, ErrorKind::AddrInUse, ErrorKind::Other, ] { let err = kind.piped(RIoError::from_kind); assert_eq!(err.kind(), kind.into_c()); } } #[test] fn from_value() { let err = Stringy::new("What\nis\ra\tline"); let e0 = RIoError::new(ErrorKind::Other, err.clone()); check_formatting_equivalence(&err, &e0); } #[test] fn from_boxerror() { let err = Stringy::new("What\nis\ra\tline"); let box_ = err.clone().piped(Box::new); let addr = deref_address(&box_); let ioerr = RIoError::with_box(ErrorKind::Other, box_); check_formatting_equivalence(&err, &ioerr); assert_eq!( addr, ioerr .into_inner() .unwrap() .into_box() .piped_ref(deref_address) ); } #[test] fn from_rboxerror() { let err = Stringy::new("What\nis\ra\tline"); let rbox = err.clone().piped(RBoxError::new); let addr = rbox.heap_address(); let mut ioerr = RIoError::with_rboxerror(ErrorKind::Other, rbox); check_formatting_equivalence(&err, &ioerr); assert_eq!(addr, ioerr.get_ref().unwrap().heap_address()); assert_eq!(addr, ioerr.get_mut().unwrap().heap_address()); assert_eq!(addr, ioerr.into_inner().unwrap().heap_address()); } }
//! `Mapper` implementation for the hadoop-rs project. extern crate hadoop_rs; use hadoop_rs::mappers::PageRankMapper; fn main() { // execute the mapping phase efflux::run_mapper(PageRankMapper); }
use std::alloc::Layout; use std::mem; use std::ptr::{self, NonNull}; use std::sync::Arc; use crate::borrow::CloneToProcess; use crate::erts::fragment::HeapFragment; use crate::erts::process::alloc::TermAlloc; use crate::erts::process::trace::Trace; use crate::erts::term::prelude::*; use super::AllocResult; /// The raw representation of an Erlang panic. /// /// Initially, this type is allocated on the global heap and not /// attached to any given process. It can propagate through /// the exception handling system within a process freely. Once caught and /// it is being converted to an Erlang term, or if it is being reified by /// a process somewhere via a trace constructor, the following occurs: /// /// - The exception reason is cloned to the process heap first /// - The trace term is constructed from the raw trace /// - This structure is then bitwise copied to the process heap, but with the fragment set to None /// and the trace set to a null pointer /// - The trace field of the copy is then overwritten with the box which points to the trace term. /// /// When the original exception is cleaned up, this structure is dropped, /// which deallocates the memory it used on the global heap, and also /// drops the underlying heap fragment (if there was one). If this was /// the last outstanding reference to the Trace, then that will also be /// deallocated. /// /// Since the layout of this type perfectly matches that of a tuple /// of the same arity, this makes it a lot more efficient to pass around, /// as we only need to effectively make a single memcpy and one store to convert it /// to a tuple on the process heap; this also avoids copying parts of the /// exception to the process heap that can be allocated globally and shared /// as the exception propagates; only explicitly modifying the trace term would /// incur a copy to the process heap. This is especially important as we don't /// know if we'll be able to allocate much, if any, space on the process heap /// and our exceptions should not be reliant on doing so except when running /// the process code. #[allow(improper_ctypes)] #[derive(Debug)] #[repr(C)] pub struct ErlangException { _header: Header<Tuple>, kind: Term, reason: Term, trace: *mut Trace, fragment: Option<NonNull<HeapFragment>>, } impl ErlangException { pub fn new(kind: Term, reason: Term, trace: Arc<Trace>) -> Box<ErlangException> { let header = Header::<Tuple>::from_arity(3); let trace = Trace::into_raw(trace); match reason.size_in_words() { 0 => Box::new(Self { _header: header, kind, reason, trace, fragment: None, }), n => { if let Ok(mut nn) = HeapFragment::new_from_word_size(n) { let fragment = unsafe { nn.as_mut() }; let reason = reason.clone_to_heap(fragment).unwrap(); Box::new(Self { _header: header, kind, reason, trace, fragment: Some(nn), }) } else { // Fallback to 'unavailable' as reason Box::new(Self { _header: header, kind, reason: Atom::str_to_term("unavailable"), trace, fragment: None, }) } } } } /// When a throw propagates to the top of a process stack, it /// gets converted to an exit with `{nocatch, Reason}` as the /// exit reason. To facilitate that, we allocate the needed /// space in advance if we already required a fragment, otherwise /// we create one on demand if possible. If we can't allocate one, /// then we have to panic pub fn set_nocatch(&mut self) { use std::intrinsics::unlikely; if unlikely(self.fragment.is_none()) { let layout = Tuple::layout_for_len(2); let nn = HeapFragment::new(layout).expect("out of memory"); self.fragment = Some(nn); } let frag = self .fragment .map(|nn| unsafe { &mut *nn.as_ptr() }) .unwrap(); let mut nocatch_reason = frag.mut_tuple(2).unwrap(); let nocatch = Atom::str_to_term("nocatch"); nocatch_reason.set_element(0, nocatch).unwrap(); nocatch_reason.set_element(1, self.reason).unwrap(); // Update kind and reason self.kind = Atom::EXIT.as_term(); self.reason = nocatch_reason.into(); } #[inline] pub fn kind(&self) -> Term { self.kind } #[inline] pub fn reason(&self) -> Term { self.reason } #[inline] pub fn fragment(&self) -> Option<NonNull<HeapFragment>> { self.fragment } #[inline] pub fn trace(&self) -> Arc<Trace> { // HACK(pauls): Manufacture a new reference to the underlying // trace. Since we created the exception using Trace::into_raw, // we must drop this structure with a corresponding from_raw; if // we don't do this little trick here, we would end up dropping // the trace prematurely while the exception struct is still live let trace = unsafe { Trace::from_raw(self.trace) }; let result = trace.clone(); let _ = Trace::into_raw(trace); result } } impl Drop for ErlangException { fn drop(&mut self) { if let Some(fragment) = self.fragment { unsafe { fragment.as_ptr().drop_in_place(); } } // Drop our trace reference let _ = unsafe { Trace::from_raw(self.trace) }; } } impl CloneToProcess for ErlangException { fn clone_to_heap<A>(&self, heap: &mut A) -> AllocResult<Term> where A: ?Sized + TermAlloc, { let reason = self.reason.clone_to_heap(heap)?; let trace = self.trace().as_term()?; let tuple = unsafe { let ptr = heap .alloc_layout(Layout::new::<Self>())? .cast::<Self>() .as_ptr(); ptr.write(Self { _header: self._header, kind: self.kind, reason, trace: ptr::null_mut(), fragment: None, }); let mut tuple = Tuple::from_raw_term(ptr as *mut Term); tuple.set_element(2, trace).unwrap(); tuple }; Ok(tuple.into()) } fn layout(&self) -> Layout { // Account for possibility that this could be promoted to a nocatch // error, in which case we need a 2-element tuple to fill let (layout, _) = Tuple::layout_for_len(3) .extend(Tuple::layout_for_len(2)) .unwrap(); let tuple_size = layout.size(); let reason_size = self.reason.size_in_words() * mem::size_of::<Term>(); let size = tuple_size + reason_size; let align = layout.align(); Layout::from_size_align(size, align).unwrap() } /// Returns the size in words needed to allocate this value #[inline] fn size_in_words(&self) -> usize { crate::erts::to_word_size(self.layout().size()) } }
use std::process::Command; use std::env; use std::fs; fn main() { let mut args = env::args(); args.next().expect("program name"); match args.next() { Some(ref s) if s == "pgo" => { match args.next() { Some(ref s) if s == "instr" => { match args.next() { Some(ref s) if s == "build" => instrumented("build", true, args), Some(ref s) if s == "rustc" => instrumented("rustc", true, args), Some(ref s) if s == "run" => instrumented("run", true, args), Some(ref s) if s == "test" => instrumented("test", true, args), Some(ref s) if s == "bench" => instrumented("bench", false, args), Some(ref s) => invalid_arg(s), _ => show_usage(), } } Some(ref s) if s == "opt" => { match args.next() { Some(ref s) if s == "build" => optimized("build", true, args), Some(ref s) if s == "rustc" => optimized("rustc", true, args), Some(ref s) if s == "run" => optimized("run", true, args), Some(ref s) if s == "test" => optimized("test", true, args), Some(ref s) if s == "bench" => optimized("bench", false, args), Some(ref s) => invalid_arg(s), _ => show_usage(), } } Some(ref s) if s == "merge" => { merge_profiles(); } Some(ref s) if s == "clean" => clean(), Some(ref s) => invalid_arg(s), _ => show_usage(), } } Some(ref s) => invalid_arg(s), _ => show_usage(), } } fn show_usage() { println!("cargo-pgo v{} {}", option_env!("CARGO_PKG_VERSION").unwrap_or("?"), if cfg!(feature = "standalone") { "(standalone)" } else { "" }); println!("Usage: cargo pgo <command>...\ \nCommands:\ \n instr build|rustc ... - build an instrumented binary\ \n instr run|test|bench ... - run the instrumented binary while recording profiling data\ \n merge - merge raw profiling data\ \n opt build|rustc ... - merge raw profiling data, then build an optimized binary\ \n opt run|test|bench ... - run the optimized binary\ \n clean - remove recorded profiling data"); } fn invalid_arg(arg: &str) { println!("Unexpected argument: {}\n", arg); show_usage(); } fn get_clang_target_arch() -> &'static str { if cfg!(target_arch = "x86_64") { "x86_64" } else if cfg!(target_arch = "x86") { "i386" } else if cfg!(target_arch = "aarch64") { "aarch64" } else if cfg!(target_arch = "arm") { "armhf" } else if cfg!(target_arch = "mips") { "mips" } else { unimplemented!() } } fn instrumented(subcommand: &str, release_flag: bool, args: env::Args) { let mut args: Vec<String> = args.collect(); if release_flag { args.insert(0, "--release".to_string()); } let old_rustflags = env::var("RUSTFLAGS").unwrap_or(String::new()); let profiler_rt_lib = if cfg!(feature = "standalone") { "profiler-rt".to_string() } else { format!("clang_rt.profile-{0}", get_clang_target_arch()) }; let rustflags = format!("{0} --cfg=profiling \ -Cllvm-args=-profile-generate \ -Cllvm-args=-profile-generate-file=target/release/pgo/%p.profraw \ -Lnative={1} -Clink-args=-l{2}", old_rustflags, env::current_exe().unwrap().parent().unwrap().to_str().unwrap(), profiler_rt_lib); let mut child = Command::new("cargo") .arg(subcommand) .args(&args) .env("RUSTFLAGS", rustflags) .spawn().unwrap_or_else(|e| panic!("{}", e)); child.wait().unwrap_or_else(|e| panic!("{}", e)); } fn optimized(subcommand: &str, release_flag: bool, args: env::Args) { let mut args = args.collect::<Vec<_>>(); if release_flag { args.insert(0, "--release".to_string()); } if !merge_profiles() { println!("Warning: no profiling data was found - this build will not be PGO-optimized."); } let old_rustflags = env::var("RUSTFLAGS").unwrap_or(String::new()); let rustflags = format!("{} -Cllvm-args=-profile-use=target/release/pgo/merged.profdata", old_rustflags); let mut child = Command::new("cargo") .arg(subcommand) .args(&args) .env("RUSTFLAGS", rustflags) .spawn().unwrap_or_else(|e| panic!("{}", e)); child.wait().unwrap_or_else(|e| panic!("{}", e)); } // Get all target/release/pgo/*.profraw files fn gather_raw_profiles() -> Vec<std::path::PathBuf> { let dir = match fs::read_dir("target/release/pgo") { Ok(dir) => dir, Err(_) => return vec![], }; let mut raw_profiles = Vec::new(); let mut found_empty = false; for entry in dir { if let Ok(entry) = entry { if let Some(ext) = entry.path().extension() { if ext == "profraw" { if let Ok(metadata) = entry.metadata() { if metadata.len() > 0 { raw_profiles.push(entry.path()); } else { found_empty = true; } } } } } } if found_empty { println!("Warhing: empty profiling data files were found - some training runs may have crashed."); } raw_profiles } #[cfg(not(feature="standalone"))] // Use external tool fn merge_profiles() -> bool { let raw_profiles = gather_raw_profiles(); if raw_profiles.len() == 0 { return false; } let mut child = Command::new("llvm-profdata") .arg("merge") .args(&raw_profiles) .arg("--output").arg("target/release/pgo/merged.profdata") .spawn().unwrap_or_else(|e| panic!("{}", e)); let exit_status = child.wait().unwrap_or_else(|e| panic!("{}", e)); return exit_status.code() == Some(0); } #[cfg(feature="standalone")] // Use the built-in profile merger fn merge_profiles() -> bool { extern crate profdata; let raw_profiles = gather_raw_profiles(); if raw_profiles.len() == 0 { return false; } let inputs: Vec<&str> = raw_profiles.iter().map(|p| p.to_str().unwrap()).collect(); if !profdata::merge_instr_profiles(&inputs, "target/release/pgo/merged.profdata") { return false; } return true; } fn clean() { let _ = fs::remove_dir_all("target/release/pgo"); }
use csv; use std::error; use std::fmt; #[derive(Debug)] struct MultiFrameError {} impl fmt::Display for MultiFrameError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "error that signifies multiple frames were present in file parsing") } } impl error::Error for MultiFrameError { fn description(&self) -> &str { return "must supply only one frame in file"; } fn cause(&self) -> Option<&error::Error> { return None; } } #[derive(RustcDecodable, Copy, Clone)] pub struct Frame { pub screen_width: u32, pub screen_height: u32, pub x_min: f64, pub x_max: f64, pub y_min: f64, pub y_max: f64, pub iterations: u32, } pub fn parse_frame(filename: &str) -> Result<Frame, Box<error::Error>> { let mut reader = try!(csv::Reader::from_file(filename)); let mut frames: Vec<Frame> = Vec::new(); for record in reader.decode() { let shape_source: Frame = try!(record); frames.push(shape_source); } return match frames.len() { 1 => Ok(frames[0]), _ => Err(Box::new(MultiFrameError {})), }; }
use time::Duration; use nickel_session::{Store}; use nickel_cookies::{SecretKey, KeyProvider}; pub struct ServerData; pub static SECRET_KEY: &'static SecretKey = &SecretKey([0; 32]); impl KeyProvider for ServerData { fn key(&self) -> SecretKey { SECRET_KEY.clone() } } impl Store for ServerData { type Session = Option<String>; fn timeout() -> Duration { Duration::seconds(100) } }
pub mod array_strings_are_equal; pub mod balanced_string_split; pub mod binary_search; pub mod buddy_strings; pub mod check_inclusion; pub mod check_perfect_number; pub mod common_chars; pub mod count_consistent_strings; pub mod count_good_triplets; pub mod count_points; pub mod count_primes; pub mod decompress_rl_elist; pub mod deepest_leaves_sum; pub mod dest_city; pub mod duplicate_zeroes; pub mod fib; pub mod find_center; pub mod find_numbers_with_even_digits; pub mod find_special_integer; pub mod find_words; pub mod fizz_buzz; pub mod flood_fill; pub mod int_to_roman; pub mod is_palindrome; pub mod is_power_of_four; pub mod is_same_tree; pub mod is_symmetric; pub mod kids_with_greatest_numbers_of_candy; pub mod length_of_longest_substring; pub mod max_area_of_island; pub mod max_depth; pub mod max_ice_cream; pub mod max_sub_array; pub mod maximum69_number; pub mod maximum_wealth; pub mod merge_alternately; pub mod merge_trees; pub mod merge_two_lists; pub mod min_operations; pub mod min_time_to_visit_all_points; pub mod move_zeroes; pub mod my_sqrt; pub mod nearest_valid_point; pub mod num_teams; pub mod odd_cells; pub mod oranges_rotting; pub mod parking_system; pub mod remove_duplicates; pub mod repeated_n_times; pub mod rotate; pub mod self_dividing_number; pub mod self_price; pub mod shuffle; pub mod shuffle_string; pub mod single_number; pub mod smaller_than_the_current_number; pub mod sorted_squares; pub mod sub_rectangle_queries; pub mod subtract_product_and_sum; pub mod sum_even_grandparent; pub mod sum_odd_length_subarrays; pub mod sum_of_unique; pub mod two_sum; pub mod unique_occurrences; pub mod update_matrix; pub mod word_pattern;
#![allow(clippy::cast_possible_truncation)] #![allow(clippy::cast_precision_loss)] #![allow(clippy::cast_lossless)] #![allow(clippy::too_many_lines)] #![allow(clippy::module_name_repetitions)] #![allow(clippy::similar_names)] //! Utility to retreive and format weather data from openweathermap.org //! //! ```bash //! Please specify one of zipcode(country_code), city_name, or lat and lon. //! //! USAGE: //! weather-util-rust [OPTIONS] //! //! FLAGS: //! -h, --help Prints help information //! -V, --version Prints version information //! //! OPTIONS: //! -k, --api-key <api-key> Api key (optional but either this or API_KEY environemnt variable must exist) //! --city-name <city-name> City Name (optional) //! -c, --country-code <country-code> Country Code (optional), if not specified `us` will be assumed //! --lat <lat> Latitude (must also specify Longitude) //! --lon <lon> Longitude (must also specify Latitude) //! -z, --zipcode <zipcode> Zipcode (optional) pub mod angle; /// Configuration data pub mod config; /// Direction in degrees pub mod direction; /// Distance in meters pub mod distance; /// Relative Humidity in percent pub mod humidity; /// Latitude pub mod latitude; /// Longitude pub mod longitude; /// Precipitation (rain/snow) in mm pub mod precipitation; /// Pressure module: conversions between hPa, kPa, Pa pub mod pressure; /// Speed as meters per second pub mod speed; /// Temperature module: conversions between Kelvin, Ceclius and Fahrenheit pub mod temperature; /// Serialize/Deserialize Unix Timetstamp to/from `DateTime` pub mod timestamp; /// Timezone offset as seconds before / after UTC pub mod timezone; /// Reqwest Client pub mod weather_api; /// Representation of Weather Data from openweathermap.org pub mod weather_data; /// Representation of Weather Forecast from openweathermap.org pub mod weather_forecast; /// CLI App Options and implementation pub mod weather_opts; /// `WeatherUtil` Error pub mod error; pub use error::Error; use time::{macros::datetime, OffsetDateTime}; #[must_use] pub fn default_datetime() -> OffsetDateTime { datetime!(1970-01-01 00:00:00).assume_utc() } #[cfg(feature = "stackstring")] use stack_string::{SmallString, StackString}; #[cfg(feature = "stackstring")] pub type StringType = StackString; #[cfg(feature = "stackstring")] pub type ApiStringType = SmallString<32>; #[cfg(feature = "stackstring")] pub fn apistringtype_from_display(buf: impl std::fmt::Display) -> ApiStringType { SmallString::from_display(buf) } #[cfg(not(feature = "stackstring"))] pub type StringType = String; #[cfg(not(feature = "stackstring"))] pub type ApiStringType = String; #[cfg(not(feature = "stackstring"))] pub fn apistringtype_from_display(buf: impl std::fmt::Display) -> ApiStringType { format!("{buf}") } #[cfg(feature = "stackstring")] #[macro_export] macro_rules! format_string { ($($arg:tt)*) => { { use std::fmt::Write; let mut buf = stack_string::StackString::new(); std::write!(buf, "{}", std::format_args!($($arg)*)).unwrap(); buf } }; } #[cfg(not(feature = "stackstring"))] #[macro_export] macro_rules! format_string { ($($arg:tt)*) => { { use std::fmt::Write; let mut buf = String::new(); std::write!(buf, "{}", std::format_args!($($arg)*)).unwrap(); buf } }; }
use std; use std::{ptr, slice}; use std::old_io::{timer}; use std::num::{Int}; use std::raw::{Slice}; use std::mem::{transmute}; use std::time::{Duration}; use std::path::{PathBuf}; use std::ffi::{OsStr}; use std::os::unix::{OsStrExt, OsStringExt}; use comm::{self, spsc}; use core::ll::*; use core::{Address, ClientId, Event, ConnectionStatus, UserStatus, ChatChange, ControlType, Faerr, TransferType, AvatarFormat, MAX_NAME_LENGTH, AVATAR_MAX_DATA_LENGTH, Hash, GroupchatType}; use core::Event::*; use core::ConnectionStatus::*; use core::TransferType::*; use av::{AvControl, AvEvents}; use super::{ControlProducer, CoreEvents}; use libc::{c_void, c_uint}; type OneSpaceProducer<T> = spsc::one_space::Producer<'static, T>; pub enum Control { GetAddress(OneSpaceProducer<Address>), AddFriend(Box<Address>, String, OneSpaceProducer<Result<i32, Faerr>>), AddFriendNorequest(Box<ClientId>, OneSpaceProducer<Result<i32, ()>>), GetFriendNumber(Box<ClientId>, OneSpaceProducer<Result<i32, ()>>), GetClientId(i32, OneSpaceProducer<Result<Box<ClientId>, ()>>), DelFriend(i32, OneSpaceProducer<Result<(),()>>), GetFriendConnectionStatus(i32, OneSpaceProducer<Result<ConnectionStatus, ()>>), FriendExists(i32, OneSpaceProducer<bool>), SendMessage(i32, String, OneSpaceProducer<Result<u32, ()>>), SendAction(i32, String, OneSpaceProducer<Result<u32, ()>>), SetName(String, OneSpaceProducer<Result<(),()>>), GetSelfName(OneSpaceProducer<Result<String, ()>>), GetName(i32, OneSpaceProducer<Result<String, ()>>), SetStatusMessage(String, OneSpaceProducer<Result<(), ()>>), SetUserStatus(UserStatus, OneSpaceProducer<Result<(), ()>>), GetStatusMessage(i32, OneSpaceProducer<Result<String, ()>>), GetSelfStatusMessage(OneSpaceProducer<Result<String, ()>>), GetUserStatus(i32, OneSpaceProducer<Result<UserStatus, ()>>), GetSelfUserStatus(OneSpaceProducer<Result<UserStatus, ()>>), GetLastOnline(i32, OneSpaceProducer<Result<u64, ()>>), SetUserIsTyping(i32, bool, OneSpaceProducer<Result<(), ()>>), GetIsTyping(i32, OneSpaceProducer<bool>), CountFriendlist(OneSpaceProducer<u32>), GetNumOnlineFriends(OneSpaceProducer<u32>), GetFriendlist(OneSpaceProducer<Vec<i32>>), GetNospam(OneSpaceProducer<[u8; 4]>), SetNospam([u8; 4]), AddGroupchat(OneSpaceProducer<Result<i32, ()>>), DelGroupchat(i32, OneSpaceProducer<Result<(), ()>>), GroupPeername(i32, i32, OneSpaceProducer<Result<String, ()>>), InviteFriend(i32, i32, OneSpaceProducer<Result<(), ()>>), JoinGroupchat(i32, Vec<u8>, OneSpaceProducer<Result<i32, ()>>), GroupMessageSend(i32, String, OneSpaceProducer<Result<(), ()>>), GroupActionSend(i32, String, OneSpaceProducer<Result<(), ()>>), GroupNumberPeers(i32, OneSpaceProducer<Result<i32, ()>>), GroupGetNames(i32, OneSpaceProducer<Result<Vec<Option<String>>, ()>>), CountChatlist(OneSpaceProducer<u32>), GetChatlist(OneSpaceProducer<Vec<i32>>), SetAvatar(AvatarFormat, Vec<u8>, OneSpaceProducer<Result<(), ()>>), UnsetAvatar, GetSelfAvatar(OneSpaceProducer<Result<(AvatarFormat, Vec<u8>, Hash), ()>>), RequestAvatarInfo(i32, OneSpaceProducer<Result<(), ()>>), RequestAvatarData(i32, OneSpaceProducer<Result<(), ()>>), SendAvatarInfo(i32, OneSpaceProducer<Result<(), ()>>), NewFileSender(i32, u64, PathBuf, OneSpaceProducer<Result<i32, ()>>), FileSendControl(i32, TransferType, u8, u8, Vec<u8>, OneSpaceProducer<Result<(), ()>>), FileSendData(i32, u8, Vec<u8>, OneSpaceProducer<Result<(), ()>>), FileDataSize(i32, OneSpaceProducer<Result<i32, ()>>), FileDataRemaining(i32, u8, TransferType, OneSpaceProducer<Result<u64, ()>>), BootstrapFromAddress(String, u16, Box<ClientId>, OneSpaceProducer<Result<(), ()>>), Isconnected(OneSpaceProducer<bool>), Save(OneSpaceProducer<Vec<u8>>), Load(Vec<u8>, OneSpaceProducer<Result<(), ()>>), Raw(OneSpaceProducer<*mut Tox>), Av(i32, OneSpaceProducer<Option<(AvControl, AvEvents)>>), } unsafe impl Send for Control { } pub struct Backend { raw: *mut Tox, internal: Box<Internal>, control: spsc::one_space::Consumer<'static, Control>, av: Option<spsc::one_space::Consumer<'static, ()>>, } unsafe impl Send for Backend { } impl Drop for Backend { fn drop(&mut self) { unsafe { tox_kill(self.raw); } } } impl Backend { fn get_address(&mut self) -> Address { let mut adr: Address = unsafe { std::mem::uninitialized() }; unsafe { tox_get_address(&*self.raw, &mut adr as *mut _ as *mut _); } adr } fn add_friend(&mut self, address: Box<Address>, msg: String) -> Result<i32, Faerr> { let res = unsafe { tox_add_friend(self.raw, &*address as *const _ as *const _, msg.as_bytes().as_ptr(), msg.len() as u16) }; match res { TOX_FAERR_TOOLONG => Err(Faerr::Toolong), TOX_FAERR_NOMESSAGE => Err(Faerr::Nomessage), TOX_FAERR_OWNKEY => Err(Faerr::Ownkey), TOX_FAERR_ALREADYSENT => Err(Faerr::Alreadysent), TOX_FAERR_UNKNOWN => Err(Faerr::Unknown), TOX_FAERR_BADCHECKSUM => Err(Faerr::Badchecksum), TOX_FAERR_SETNEWNOSPAM => Err(Faerr::Setnewnospam), TOX_FAERR_NOMEM => Err(Faerr::Nomem), n if n >= 0 => Ok(n), _ => Err(Faerr::Unknown), } } fn add_friend_norequest(&mut self, client_id: Box<ClientId>) -> Result<i32, ()> { match unsafe { tox_add_friend_norequest(self.raw, client_id.raw.as_ptr()) } { -1 => Err(()), n => Ok(n), } } fn get_friend_number(&mut self, client_id: Box<ClientId>) -> Result<i32, ()> { let res = unsafe { tox_get_friend_number(&*self.raw, client_id.raw.as_ptr()) }; match res { -1 => Err(()), n => Ok(n), } } fn get_client_id(&mut self, friendnumber: i32) -> Result<Box<ClientId>, ()> { let mut client: ClientId = unsafe { std::mem::uninitialized() }; let res = unsafe { tox_get_client_id(&*self.raw, friendnumber, client.raw.as_mut_ptr()) }; match res { -1 => Err(()), _ => Ok(Box::new(client)), } } fn del_friend(&mut self, friendnumber: i32) -> Result<(),()> { match unsafe { tox_del_friend(self.raw, friendnumber) } { -1 => Err(()), _ => Ok(()), } } fn get_friend_connection_status( &mut self, friendnumber: i32) -> Result<ConnectionStatus, ()> { match unsafe { tox_get_friend_connection_status(&*self.raw, friendnumber) } { 1 => Ok(Online), 0 => Ok(Offline), _ => Err(()), } } fn friend_exists(&mut self, friendnumber: i32) -> bool { match unsafe { tox_friend_exists(&*self.raw, friendnumber) } { 1 => true, _ => false, } } fn send_message(&mut self, friendnumber: i32, mut msg: String) -> Result<u32, ()> { let res = unsafe { tox_send_message(self.raw, friendnumber, msg.as_mut_vec().as_ptr(), msg.len() as u32) }; match res { 0 => Err(()), n => Ok(n), } } fn send_action(&mut self, friendnumber: i32, mut action: String) -> Result<u32, ()> { let res = unsafe { tox_send_action(self.raw, friendnumber, action.as_mut_vec().as_ptr(), action.len() as u32) }; match res { 0 => Err(()), n => Ok(n), } } fn set_name(&mut self, mut name: String) -> Result<(),()> { let res = unsafe { tox_set_name(self.raw, name.as_mut_vec().as_ptr(), name.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn get_self_name(&mut self) -> Result<String, ()> { let mut name = Vec::with_capacity(MAX_NAME_LENGTH); let res = unsafe { let len = tox_get_self_name(&*self.raw, name.as_mut_ptr()); name.set_len(len as usize); len }; match res { 0 => Err(()), _ => match String::from_utf8(name) { Ok(name) => Ok(name), _ => Err(()), }, } } fn get_name(&mut self, friendnumber: i32) -> Result<String, ()> { let mut name = Vec::with_capacity(MAX_NAME_LENGTH); let res = unsafe { let len = tox_get_name(&*self.raw, friendnumber, name.as_mut_ptr()); // len might be -1 but it doesn't matter if we don't return name. name.set_len(len as usize); len }; match res { -1 => Err(()), _ => match String::from_utf8(name) { Ok(name) => Ok(name), _ => Err(()), }, } } fn set_status_message(&mut self, mut status: String) -> Result<(),()> { let res = unsafe { tox_set_status_message(self.raw, status.as_mut_vec().as_ptr(), status.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn set_user_status(&mut self, userstatus: UserStatus) -> Result<(), ()> { match unsafe { tox_set_user_status(self.raw, userstatus as u8) } { 0 => Ok(()), _ => Err(()), } } fn get_status_message(&mut self, friendnumber: i32) -> Result<String, ()> { let size = unsafe { tox_get_status_message_size(&*self.raw, friendnumber) }; let size = match size { -1 => return Err(()), _ => size, }; let mut status = Vec::with_capacity(size as usize); let size = unsafe { let len = tox_get_status_message(&*self.raw, friendnumber, status.as_mut_ptr(), size as u32); status.set_len(len as usize); len }; match size { -1 => return Err(()), _ => match String::from_utf8(status) { Ok(status) => Ok(status), _ => return Err(()), }, } } fn get_self_status_message(&mut self) -> Result<String, ()> { let size = unsafe { tox_get_self_status_message_size(&*self.raw) }; let size = match size { -1 => return Err(()), _ => size as u32, }; let mut status = Vec::with_capacity(size as usize); let size = unsafe { let len = tox_get_self_status_message(&*self.raw, status.as_mut_ptr(), size); status.set_len(len as usize); len }; match size { -1 => return Err(()), _ => match String::from_utf8(status) { Ok(status) => Ok(status), _ => return Err(()), }, } } fn get_user_status(&mut self, friendnumber: i32) -> Result<UserStatus, ()> { match unsafe { tox_get_user_status(&*self.raw, friendnumber) as u32 } { TOX_USERSTATUS_AWAY => Ok(UserStatus::Away), TOX_USERSTATUS_NONE => Ok(UserStatus::None), TOX_USERSTATUS_BUSY => Ok(UserStatus::Busy), _ => Err(()) } } fn get_self_user_status(&mut self) -> Result<UserStatus, ()> { match unsafe { tox_get_self_user_status(&*self.raw) as u32 } { TOX_USERSTATUS_AWAY => Ok(UserStatus::Away), TOX_USERSTATUS_NONE => Ok(UserStatus::None), TOX_USERSTATUS_BUSY => Ok(UserStatus::Busy), _ => Err(()) } } fn get_last_online(&mut self, friendnumber: i32) -> Result<u64, ()> { match unsafe { tox_get_last_online(&*self.raw, friendnumber) } { -1 => Err(()), n => Ok(n), } } fn set_user_is_typing(&mut self, friendnumber: i32, is_typing: bool) -> Result<(), ()> { let raw = unsafe { tox_set_user_is_typing(self.raw, friendnumber, is_typing as u8) }; match raw { 0 => Ok(()), _ => Err(()), } } fn get_is_typing(&mut self, friendnumber: i32) -> bool { match unsafe { tox_get_is_typing(&*self.raw, friendnumber) } { 0 => false, _ => true, } } fn count_friendlist(&mut self) -> u32 { unsafe { tox_count_friendlist(&*self.raw) } } fn get_num_online_friends(&mut self) -> u32 { unsafe { tox_get_num_online_friends(&*self.raw) } } fn get_friendlist(&mut self) -> Vec<i32> { let size = self.count_friendlist(); let mut vec = Vec::with_capacity(size as usize); unsafe { let len = tox_get_friendlist(&*self.raw, vec.as_mut_ptr(), size); vec.set_len(len as usize); } vec } fn get_nospam(&mut self) -> [u8; 4] { unsafe { std::mem::transmute(tox_get_nospam(&*self.raw).to_be()) } } fn set_nospam(&mut self, nospam: [u8; 4]) { unsafe { tox_set_nospam(self.raw, Int::from_be(std::mem::transmute(nospam))); } } fn add_groupchat(&mut self) -> Result<i32, ()> { match unsafe { tox_add_groupchat(self.raw) } { -1 => Err(()), n => Ok(n), } } fn del_groupchat(&mut self, groupnumber: i32) -> Result<(),()> { match unsafe { tox_del_groupchat(self.raw, groupnumber) } { 0 => Ok(()), _ => Err(()), } } fn group_peername(&mut self, groupnumber: i32, peernumber: i32) -> Result<String, ()> { let mut vec = Vec::with_capacity(MAX_NAME_LENGTH); let len = unsafe { let len = tox_group_peername(&*self.raw, groupnumber, peernumber, vec.as_mut_ptr()); vec.set_len(len as usize); len }; match len { -1 => Err(()), _ => match String::from_utf8(vec) { Ok(name) => Ok(name), _ => Err(()), } } } fn invite_friend(&mut self, friendnumber: i32, groupnumber: i32) -> Result<(), ()> { match unsafe { tox_invite_friend(self.raw, friendnumber, groupnumber) } { 0 => Ok(()), _ => Err(()), } } fn join_groupchat(&mut self, friendnumber: i32, data: Vec<u8>) -> Result<i32, ()> { let res = unsafe { tox_join_groupchat(self.raw, friendnumber, data.as_ptr(), data.len() as u16) }; match res { -1 => Err(()), n => Ok(n), } } fn group_message_send(&mut self, groupnumber: i32, mut msg: String) -> Result<(), ()> { let res = unsafe { tox_group_message_send(self.raw, groupnumber, msg.as_mut_vec().as_ptr(), msg.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn group_action_send(&mut self, groupnumber: i32, mut act: String) -> Result<(), ()> { let res = unsafe { tox_group_action_send(self.raw, groupnumber, act.as_mut_vec().as_ptr(), act.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn group_number_peers(&mut self, groupnumber: i32) -> Result<i32, ()> { match unsafe { tox_group_number_peers(&*self.raw, groupnumber) } { -1 => Err(()), n => Ok(n), } } fn group_get_names(&mut self, groupnumber: i32) -> Result<Vec<Option<String>>, ()> { let num = match self.group_number_peers(groupnumber) { Ok(n) => n as usize, _ => return Err(()), }; let mut names = Vec::with_capacity(num); let mut lengths = Vec::with_capacity(num); let len = unsafe { let len = tox_group_get_names(&*self.raw, groupnumber, names.as_mut_ptr(), lengths.as_mut_ptr(), num as u16); names.set_len(len as usize); lengths.set_len(len as usize); len }; if len == -1 { return Err(()); } let mut real_names = Vec::with_capacity(len as usize); for (name, &length) in names.iter().zip(lengths.iter()) { match std::str::from_utf8(&name[..length as usize]) { Ok(s) => real_names.push(Some(s.to_string())), _ => real_names.push(None), } } Ok(real_names) } fn count_chatlist(&mut self) -> u32 { unsafe { tox_count_chatlist(&*self.raw) } } fn get_chatlist(&mut self) -> Vec<i32> { let num = unsafe { tox_count_chatlist(&*self.raw) }; let mut vec = Vec::with_capacity(num as usize); unsafe { let num = tox_get_chatlist(&*self.raw, vec.as_mut_ptr(), num); vec.set_len(num as usize); } vec } fn set_avatar(&mut self, format: AvatarFormat, data: Vec<u8>) -> Result<(), ()> { let res = unsafe { tox_set_avatar(self.raw, format as u8, data.as_ptr(), data.len() as u32) }; match res { 0 => Ok(()), _ => Err(()), } } fn unset_avatar(&mut self) { unsafe { tox_unset_avatar(self.raw); } } fn get_self_avatar(&mut self) -> Result<(AvatarFormat, Vec<u8>, Hash), ()> { let mut data = Vec::with_capacity(AVATAR_MAX_DATA_LENGTH); let mut hash: Hash = unsafe { std::mem::uninitialized() }; let mut format = 0; let mut length = 0; let res = unsafe { tox_get_self_avatar(self.raw, &mut format, data.as_mut_ptr(), &mut length, AVATAR_MAX_DATA_LENGTH as u32, hash.hash.as_mut_ptr()) }; if res == -1 { return Err(()); } unsafe { data.set_len(length as usize); } data.shrink_to_fit(); let format = match format as c_uint { TOX_AVATAR_FORMAT_NONE => AvatarFormat::None, TOX_AVATAR_FORMAT_PNG => AvatarFormat::PNG, _ => return Err(()), }; Ok((format, data, hash)) } fn request_avatar_info(&self, friendnumber: i32) -> Result<(), ()> { let res = unsafe { tox_request_avatar_info(self.raw, friendnumber) }; match res { 0 => Ok(()), _ => Err(()), } } fn request_avatar_data(&self, friendnumber: i32) -> Result<(), ()> { let res = unsafe { tox_request_avatar_data(self.raw, friendnumber) }; match res { 0 => Ok(()), _ => Err(()), } } fn send_avatar_info(&mut self, friendnumber: i32) -> Result<(), ()> { let res = unsafe { tox_send_avatar_info(self.raw, friendnumber) }; match res { 0 => Ok(()), _ => Err(()), } } fn new_file_sender(&mut self, friendnumber: i32, filesize: u64, filename: PathBuf) -> Result<i32, ()> { let filename = filename.into_os_string().into_vec(); let res = unsafe { tox_new_file_sender(self.raw, friendnumber, filesize, filename.as_ptr(), filename.len() as u16) }; match res { -1 => Err(()), n => Ok(n) } } fn file_send_control(&mut self, friendnumber: i32, send_receive: TransferType, filenumber: u8, message_id: u8, data: Vec<u8>) -> Result<(), ()> { let res = unsafe { tox_file_send_control(self.raw, friendnumber, 1 - send_receive as u8, filenumber, message_id, data.as_ptr(), data.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn file_send_data(&mut self, friendnumber: i32, filenumber: u8, data: Vec<u8>) -> Result<(), ()> { let res = unsafe { tox_file_send_data(self.raw, friendnumber, filenumber, data.as_ptr(), data.len() as u16) }; match res { 0 => Ok(()), _ => Err(()), } } fn file_data_size(&mut self, friendnumber: i32) -> Result<i32, ()> { match unsafe { tox_file_data_size(&*self.raw, friendnumber) } { -1 => Err(()), n => Ok(n), } } fn file_data_remaining(&mut self, friendnumber: i32, filenumber: u8, send_receive: TransferType) -> Result<u64, ()> { let res = unsafe { tox_file_data_remaining(&*self.raw, friendnumber, filenumber, send_receive as u8) }; match res { 0 => Err(()), n => Ok(n), } } fn bootstrap_from_address(&mut self, mut address: String, port: u16, public_key: Box<ClientId>) -> Result<(), ()> { let res = unsafe { address.as_mut_vec().push(0); tox_bootstrap_from_address(self.raw, address.as_bytes().as_ptr() as *const _, port, public_key.raw.as_ptr()) }; match res { 1 => Ok(()), _ => Err(()), } } fn is_connected(&mut self) -> bool { match unsafe { tox_isconnected(&*self.raw) } { 0 => false, _ => true, } } fn av(&mut self, max_calls: i32) -> Option<(AvControl, AvEvents)> { if self.av.is_some() { return None; } let (send_end, recv_end) = spsc::one_space::new(); let av = AvControl::new(self.raw, max_calls, send_end); if av.is_some() { self.av = Some(recv_end); } av } pub fn new(opts: &mut Tox_Options) -> Option<(ControlProducer, CoreEvents)> { let tox = unsafe { tox_new(opts) }; if tox.is_null() { return None; } let (event_send, event_recv) = spsc::bounded::new(64); let mut internal = Box::new(Internal { stop: false, events: event_send }); unsafe { let ip = &mut *internal as *mut _ as *mut c_void; tox_callback_friend_request( tox, Some(on_friend_request), ip); tox_callback_friend_message( tox, Some(on_friend_message), ip); tox_callback_friend_action( tox, Some(on_friend_action), ip); tox_callback_name_change( tox, Some(on_name_change), ip); tox_callback_status_message( tox, Some(on_status_message), ip); tox_callback_user_status( tox, Some(on_user_status), ip); tox_callback_typing_change( tox, Some(on_typing_change), ip); tox_callback_read_receipt( tox, Some(on_read_receipt), ip); tox_callback_connection_status( tox, Some(on_connection_status), ip); tox_callback_group_invite( tox, Some(on_group_invite), ip); tox_callback_group_message( tox, Some(on_group_message), ip); tox_callback_group_action( tox, Some(on_group_action), ip); tox_callback_group_namelist_change( tox, Some(on_group_namelist_change), ip); tox_callback_file_send_request( tox, Some(on_file_send_request), ip); tox_callback_file_control( tox, Some(on_file_control), ip); tox_callback_file_data( tox, Some(on_file_data), ip); tox_callback_avatar_info( tox, Some(on_avatar_info), ip); tox_callback_avatar_data( tox, Some(on_avatar_data), ip); } let (control_send, control_recv) = spsc::one_space::new(); let backend = Backend { raw: tox, internal: internal, control: control_recv, av: None, }; std::thread::spawn(move || backend.run()); Some((control_send, event_recv)) } fn run(mut self) { 'outer: loop { unsafe { tox_do(self.raw); } if self.internal.stop { break 'outer; } 'inner: loop { match self.control.recv_async() { Ok(ctrl) => self.control(ctrl), Err(comm::Error::Disconnected) => break 'outer, _ => break 'inner, } } if self.av.as_ref().map(|x| x.recv_async()) == Some(Err(comm::Error::Disconnected)) { self.av.take(); } let interval = unsafe { tox_do_interval(self.raw) as i64 }; timer::sleep(Duration::milliseconds(interval)); } // If we have an AV session then we have to continue if let Some(ref av) = self.av { loop { if av.recv_async() == Err(comm::Error::Disconnected) { break; } let interval = unsafe { tox_do_interval(self.raw) as i64 }; timer::sleep(Duration::milliseconds(interval)); unsafe { tox_do(self.raw); } } } } fn control(&mut self, ctrl: Control) { match ctrl { Control::GetAddress(ret) => ret.send(self.get_address()).unwrap(), Control::AddFriend(addr, msg, ret) => ret.send(self.add_friend(addr, msg)).unwrap(), Control::AddFriendNorequest(id, ret) => ret.send(self.add_friend_norequest(id)).unwrap(), Control::GetFriendNumber(id, ret) => ret.send(self.get_friend_number(id)).unwrap(), Control::GetClientId(friend, ret) => ret.send(self.get_client_id(friend)).unwrap(), Control::DelFriend(friend, ret) => ret.send(self.del_friend(friend)).unwrap(), Control::GetFriendConnectionStatus(friend, ret) => ret.send(self.get_friend_connection_status(friend)).unwrap(), Control::FriendExists(friend, ret) => ret.send(self.friend_exists(friend)).unwrap(), Control::SendMessage(friend, msg, ret) => ret.send(self.send_message(friend, msg)).unwrap(), Control::SendAction(friend, act, ret) => ret.send(self.send_action(friend, act)).unwrap(), Control::SetName(name, ret) => ret.send(self.set_name(name)).unwrap(), Control::GetSelfName(ret) => ret.send(self.get_self_name()).unwrap(), Control::GetName(friend, ret) => ret.send(self.get_name(friend)).unwrap(), Control::SetStatusMessage(msg, ret) => ret.send(self.set_status_message(msg)).unwrap(), Control::SetUserStatus(status, ret) => ret.send(self.set_user_status(status)).unwrap(), Control::GetStatusMessage(friend, ret) => ret.send(self.get_status_message(friend)).unwrap(), Control::GetSelfStatusMessage(ret) => ret.send(self.get_self_status_message()).unwrap(), Control::GetUserStatus(friend, ret) => ret.send(self.get_user_status(friend)).unwrap(), Control::GetSelfUserStatus(ret) => ret.send(self.get_self_user_status()).unwrap(), Control::GetLastOnline(friend, ret) => ret.send(self.get_last_online(friend)).unwrap(), Control::SetUserIsTyping(friend, is, ret) => ret.send(self.set_user_is_typing(friend, is)).unwrap(), Control::GetIsTyping(friend, ret) => ret.send(self.get_is_typing(friend)).unwrap(), Control::CountFriendlist(ret) => ret.send(self.count_friendlist()).unwrap(), Control::GetNumOnlineFriends(ret) => ret.send(self.get_num_online_friends()).unwrap(), Control::GetFriendlist(ret) => ret.send(self.get_friendlist()).unwrap(), Control::GetNospam(ret) => ret.send(self.get_nospam()).unwrap(), Control::SetNospam(ns) => self.set_nospam(ns), Control::AddGroupchat(ret) => ret.send(self.add_groupchat()).unwrap(), Control::DelGroupchat(group, ret) => ret.send(self.del_groupchat(group)).unwrap(), Control::GroupPeername(group, peer, ret) => ret.send(self.group_peername(group, peer)).unwrap(), Control::InviteFriend(friend, group, ret) => ret.send(self.invite_friend(friend, group)).unwrap(), Control::JoinGroupchat(friend, group, ret) => ret.send(self.join_groupchat(friend, group)).unwrap(), Control::GroupMessageSend(group, msg, ret) => ret.send(self.group_message_send(group, msg)).unwrap(), Control::GroupActionSend(group, action, ret) => ret.send(self.group_action_send(group, action)).unwrap(), Control::GroupNumberPeers(group, ret) => ret.send(self.group_number_peers(group)).unwrap(), Control::GroupGetNames(group, ret) => ret.send(self.group_get_names(group)).unwrap(), Control::CountChatlist(ret) => ret.send(self.count_chatlist()).unwrap(), Control::GetChatlist(ret) => ret.send(self.get_chatlist()).unwrap(), Control::SetAvatar(format, data, ret) => ret.send(self.set_avatar(format, data)).unwrap(), Control::UnsetAvatar => self.unset_avatar(), Control::GetSelfAvatar(ret) => ret.send(self.get_self_avatar()).unwrap(), Control::RequestAvatarInfo(friend, ret) => ret.send(self.request_avatar_info(friend)).unwrap(), Control::RequestAvatarData(friend, ret) => ret.send(self.request_avatar_data(friend)).unwrap(), Control::SendAvatarInfo(friend, ret) => ret.send(self.send_avatar_info(friend)).unwrap(), Control::NewFileSender(friend, size, file, ret) => ret.send(self.new_file_sender(friend, size, file)).unwrap(), Control::FileSendControl(friend, ty, num, msg, data, ret) => ret.send(self.file_send_control(friend, ty, num, msg, data)).unwrap(), Control::FileSendData(friend, num, data, ret) => ret.send(self.file_send_data(friend, num, data)).unwrap(), Control::FileDataSize(friend, ret) => ret.send(self.file_data_size(friend)).unwrap(), Control::FileDataRemaining(friend, num, ty, ret) => ret.send(self.file_data_remaining(friend, num, ty)).unwrap(), Control::BootstrapFromAddress(addr, port, id, ret) => ret.send(self.bootstrap_from_address(addr, port, id)).unwrap(), Control::Isconnected(ret) => ret.send(self.is_connected()).unwrap(), Control::Save(ret) => ret.send(self.save()).unwrap(), Control::Load(data, ret) => ret.send(self.load(data)).unwrap(), Control::Raw(ret) => ret.send(self.raw).unwrap(), Control::Av(max_calls, ret) => ret.send(self.av(max_calls)).map_err(|e|e.1).unwrap(), } } fn save(&mut self) -> Vec<u8> { let size = unsafe { tox_size(&*self.raw) as usize }; let mut vec = Vec::with_capacity(size); unsafe { tox_save(&*self.raw, vec.as_mut_ptr()); vec.set_len(size); } vec } fn load(&mut self, data: Vec<u8>) -> Result<(), ()> { match unsafe { tox_load(self.raw, data.as_ptr(), data.len() as u32) } { 0 => Ok(()), _ => Err(()), } } } struct Internal { stop: bool, events: spsc::bounded::Producer<'static, Event>, } macro_rules! get_int { ($i:ident) => { unsafe { let internal = transmute::<_, &mut Internal>($i); if internal.stop { return } internal } } } macro_rules! send_or_stop { ($internal:ident, $event:expr) => { match $internal.events.send_sync($event) { Ok(()) => { }, _ => $internal.stop = true, } } } macro_rules! parse_string { ($p:ident, $l:ident) => { { let slice = to_slice($p as *const u8, $l as usize); match std::str::from_utf8(slice) { Ok(s) => s.to_string(), _ => return, } } } } fn to_slice<'a, T>(p: *const T, l: usize) -> &'a [T] { unsafe { transmute(Slice { data: p, len: l }) } } extern fn on_friend_request(_: *mut Tox, public_key: *const u8, data: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let msg = parse_string!(data, length); let id = ClientId { raw: unsafe { ptr::read(public_key as *const _) } }; send_or_stop!(internal, FriendRequest(Box::new(id), msg)); } extern fn on_friend_message(_: *mut Tox, friendnumber: i32, msg: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let msg = parse_string!(msg, length); send_or_stop!(internal, FriendMessage(friendnumber, msg)); } extern fn on_friend_action(_: *mut Tox, friendnumber: i32, act: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let act = parse_string!(act, length); send_or_stop!(internal, FriendAction(friendnumber, act)); } extern fn on_name_change(_: *mut Tox, friendnumber: i32, new: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let new = parse_string!(new, length); send_or_stop!(internal, NameChange(friendnumber, new)); } extern fn on_status_message(_: *mut Tox, friendnumber: i32, new: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let new = parse_string!(new, length); send_or_stop!(internal, StatusMessage(friendnumber, new)); } extern fn on_user_status(_: *mut Tox, friendnumber: i32, status: u8, internal: *mut c_void) { let internal = get_int!(internal); let status = match status as u32 { TOX_USERSTATUS_NONE => UserStatus::None, TOX_USERSTATUS_AWAY => UserStatus::Away, TOX_USERSTATUS_BUSY => UserStatus::Busy, _ => return, }; send_or_stop!(internal, UserStatusVar(friendnumber, status)); } extern fn on_typing_change(_: *mut Tox, friendnumber: i32, is_typing: u8, internal: *mut c_void) { let internal = get_int!(internal); send_or_stop!(internal, TypingChange(friendnumber, is_typing != 0)); } extern fn on_read_receipt(_: *mut Tox, friendnumber: i32, receipt: u32, internal: *mut c_void) { let internal = get_int!(internal); send_or_stop!(internal, ReadReceipt(friendnumber, receipt)); } extern fn on_connection_status(_: *mut Tox, friendnumber: i32, status: u8, internal: *mut c_void) { let internal = get_int!(internal); let status = match status { 1 => Online, _ => Offline, }; send_or_stop!(internal, ConnectionStatusVar(friendnumber, status)); } extern fn on_group_invite(_: *mut Tox, friendnumber: i32, ty: u8, data: *const u8, length: u16, internal: *mut c_void) { let internal = get_int!(internal); let data = unsafe { slice::from_raw_parts(data, length as usize).to_vec() }; let ty = match ty as c_uint { TOX_GROUPCHAT_TYPE_TEXT => GroupchatType::Text, TOX_GROUPCHAT_TYPE_AV => GroupchatType::Av, _ => return, }; send_or_stop!(internal, GroupInvite(friendnumber, ty, data)); } extern fn on_group_message(_: *mut Tox, groupnumber: i32, frindgroupnumber: i32, message: *const u8, len: u16, internal: *mut c_void) { let internal = get_int!(internal); let msg = parse_string!(message, len); send_or_stop!(internal, GroupMessage(groupnumber, frindgroupnumber, msg)); } extern fn on_group_action(_: *mut Tox, groupnumber: i32, frindgroupnumber: i32, action: *const u8, len: u16, internal: *mut c_void) { let internal = get_int!(internal); let action = parse_string!(action, len); send_or_stop!(internal, GroupMessage(groupnumber, frindgroupnumber, action)); } extern fn on_group_namelist_change(_: *mut Tox, groupnumber: i32, peernumber: i32, change: u8, internal: *mut c_void) { let internal = get_int!(internal); let change = match change as u32 { TOX_CHAT_CHANGE_PEER_ADD => ChatChange::PeerAdd, TOX_CHAT_CHANGE_PEER_DEL => ChatChange::PeerDel, TOX_CHAT_CHANGE_PEER_NAME => ChatChange::PeerName, _ => return, }; send_or_stop!(internal, GroupNamelistChange(groupnumber, peernumber, change)); } extern fn on_file_send_request(_: *mut Tox, friendnumber: i32, filenumber: u8, filesize: u64, filename: *const u8, len: u16, internal: *mut c_void) { let internal = get_int!(internal); let slice = to_slice(filename as *const u8, len as usize); let path = match PathBuf::new(<OsStr as OsStrExt>::from_bytes(slice)).file_name() { Some(f) => f.as_bytes().to_vec(), None => b"\xbf\xef".to_vec(), }; send_or_stop!(internal, FileSendRequest(friendnumber, filenumber, filesize, path)); } extern fn on_file_control(_: *mut Tox, friendnumber: i32, receive_send: u8, filenumber: u8, control_type: u8, data: *const u8, len: u16, internal: *mut c_void) { let internal = get_int!(internal); let ty = match control_type as u32 { TOX_FILECONTROL_ACCEPT => ControlType::Accept, TOX_FILECONTROL_PAUSE => ControlType::Pause, TOX_FILECONTROL_KILL => ControlType::Kill, TOX_FILECONTROL_FINISHED => ControlType::Finished, TOX_FILECONTROL_RESUME_BROKEN => ControlType::ResumeBroken, _ => return, }; let tt = match receive_send { 1 => Sending, 0 => Receiving, _ => return, }; let data = to_slice(data, len as usize).to_vec(); send_or_stop!(internal, FileControl(friendnumber, tt, filenumber, ty, data)); } extern fn on_file_data(_: *mut Tox, friendnumber: i32, filenumber: u8, data: *const u8, len: u16, internal: *mut c_void) { let internal = get_int!(internal); let data = to_slice(data, len as usize).to_vec(); send_or_stop!(internal, FileData(friendnumber, filenumber, data)); } extern fn on_avatar_info(_: *mut Tox, friendnumber: i32, format: u8, hash: *mut u8, internal: *mut c_void) { let internal = get_int!(internal); let format = match format as c_uint { TOX_AVATAR_FORMAT_NONE => AvatarFormat::None, TOX_AVATAR_FORMAT_PNG => AvatarFormat::PNG, _ => return, }; let hash = unsafe { ptr::read(hash as *const u8 as *const _) }; send_or_stop!(internal, AvatarInfo(friendnumber, format, hash)); } extern fn on_avatar_data(_: *mut Tox, friendnumber: i32, format: u8, hash: *mut u8, data: *mut u8, datalen: u32, internal: *mut c_void) { let internal = get_int!(internal); let format = match format as c_uint { TOX_AVATAR_FORMAT_NONE => AvatarFormat::None, TOX_AVATAR_FORMAT_PNG => AvatarFormat::PNG, _ => return, }; let hash = unsafe { ptr::read(hash as *const u8 as *const _) }; let data = unsafe { slice::from_raw_parts_mut(data, datalen as usize).to_vec() }; send_or_stop!(internal, AvatarData(friendnumber, format, hash, data)); }
use crate::rr_tools_lib::rrxml::parcel::Parcel; use std::path::PathBuf; pub type Checks = Vec<Parcel>; pub type SuccesfullRrXmls = Vec<PathBuf>; pub type Merged = Option<Result<PathBuf, PathBuf>>; #[derive(Clone)] pub enum Message { UpdateLabel(String), CheckCompleted(Checks), ToDxfCompleted(SuccesfullRrXmls, Merged), }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DMA mode register"] pub dmamr: DMAMR, #[doc = "0x04 - System bus mode register"] pub dmasbmr: DMASBMR, #[doc = "0x08 - Interrupt status register"] pub dmaisr: DMAISR, #[doc = "0x0c - Debug status register"] pub dmadsr: DMADSR, _reserved4: [u8; 240usize], #[doc = "0x100 - Channel control register"] pub dmaccr: DMACCR, #[doc = "0x104 - Channel transmit control register"] pub dmactx_cr: DMACTXCR, #[doc = "0x108 - Channel receive control register"] pub dmacrx_cr: DMACRXCR, _reserved7: [u8; 8usize], #[doc = "0x114 - Channel Tx descriptor list address register"] pub dmactx_dlar: DMACTXDLAR, _reserved8: [u8; 4usize], #[doc = "0x11c - Channel Rx descriptor list address register"] pub dmacrx_dlar: DMACRXDLAR, #[doc = "0x120 - Channel Tx descriptor tail pointer register"] pub dmactx_dtpr: DMACTXDTPR, _reserved10: [u8; 4usize], #[doc = "0x128 - Channel Rx descriptor tail pointer register"] pub dmacrx_dtpr: DMACRXDTPR, #[doc = "0x12c - Channel Tx descriptor ring length register"] pub dmactx_rlr: DMACTXRLR, #[doc = "0x130 - Channel Rx descriptor ring length register"] pub dmacrx_rlr: DMACRXRLR, #[doc = "0x134 - Channel interrupt enable register"] pub dmacier: DMACIER, #[doc = "0x138 - Channel Rx interrupt watchdog timer register"] pub dmacrx_iwtr: DMACRXIWTR, _reserved15: [u8; 8usize], #[doc = "0x144 - Channel current application transmit descriptor register"] pub dmaccatx_dr: DMACCATXDR, _reserved16: [u8; 4usize], #[doc = "0x14c - Channel current application receive descriptor register"] pub dmaccarx_dr: DMACCARXDR, _reserved17: [u8; 4usize], #[doc = "0x154 - Channel current application transmit buffer register"] pub dmaccatx_br: DMACCATXBR, _reserved18: [u8; 4usize], #[doc = "0x15c - Channel current application receive buffer register"] pub dmaccarx_br: DMACCARXBR, #[doc = "0x160 - Channel status register"] pub dmacsr: DMACSR, _reserved20: [u8; 8usize], #[doc = "0x16c - Channel missed frame count register"] pub dmacmfcr: DMACMFCR, } #[doc = "DMA mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmamr](dmamr) module"] pub type DMAMR = crate::Reg<u32, _DMAMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMAMR; #[doc = "`read()` method returns [dmamr::R](dmamr::R) reader structure"] impl crate::Readable for DMAMR {} #[doc = "`write(|w| ..)` method takes [dmamr::W](dmamr::W) writer structure"] impl crate::Writable for DMAMR {} #[doc = "DMA mode register"] pub mod dmamr; #[doc = "System bus mode register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmasbmr](dmasbmr) module"] pub type DMASBMR = crate::Reg<u32, _DMASBMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMASBMR; #[doc = "`read()` method returns [dmasbmr::R](dmasbmr::R) reader structure"] impl crate::Readable for DMASBMR {} #[doc = "`write(|w| ..)` method takes [dmasbmr::W](dmasbmr::W) writer structure"] impl crate::Writable for DMASBMR {} #[doc = "System bus mode register"] pub mod dmasbmr; #[doc = "Interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaisr](dmaisr) module"] pub type DMAISR = crate::Reg<u32, _DMAISR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMAISR; #[doc = "`read()` method returns [dmaisr::R](dmaisr::R) reader structure"] impl crate::Readable for DMAISR {} #[doc = "`write(|w| ..)` method takes [dmaisr::W](dmaisr::W) writer structure"] impl crate::Writable for DMAISR {} #[doc = "Interrupt status register"] pub mod dmaisr; #[doc = "Debug status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmadsr](dmadsr) module"] pub type DMADSR = crate::Reg<u32, _DMADSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMADSR; #[doc = "`read()` method returns [dmadsr::R](dmadsr::R) reader structure"] impl crate::Readable for DMADSR {} #[doc = "`write(|w| ..)` method takes [dmadsr::W](dmadsr::W) writer structure"] impl crate::Writable for DMADSR {} #[doc = "Debug status register"] pub mod dmadsr; #[doc = "Channel control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaccr](dmaccr) module"] pub type DMACCR = crate::Reg<u32, _DMACCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACCR; #[doc = "`read()` method returns [dmaccr::R](dmaccr::R) reader structure"] impl crate::Readable for DMACCR {} #[doc = "`write(|w| ..)` method takes [dmaccr::W](dmaccr::W) writer structure"] impl crate::Writable for DMACCR {} #[doc = "Channel control register"] pub mod dmaccr; #[doc = "Channel transmit control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmactx_cr](dmactx_cr) module"] pub type DMACTXCR = crate::Reg<u32, _DMACTXCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACTXCR; #[doc = "`read()` method returns [dmactx_cr::R](dmactx_cr::R) reader structure"] impl crate::Readable for DMACTXCR {} #[doc = "`write(|w| ..)` method takes [dmactx_cr::W](dmactx_cr::W) writer structure"] impl crate::Writable for DMACTXCR {} #[doc = "Channel transmit control register"] pub mod dmactx_cr; #[doc = "Channel receive control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacrx_cr](dmacrx_cr) module"] pub type DMACRXCR = crate::Reg<u32, _DMACRXCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACRXCR; #[doc = "`read()` method returns [dmacrx_cr::R](dmacrx_cr::R) reader structure"] impl crate::Readable for DMACRXCR {} #[doc = "`write(|w| ..)` method takes [dmacrx_cr::W](dmacrx_cr::W) writer structure"] impl crate::Writable for DMACRXCR {} #[doc = "Channel receive control register"] pub mod dmacrx_cr; #[doc = "Channel Tx descriptor list address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmactx_dlar](dmactx_dlar) module"] pub type DMACTXDLAR = crate::Reg<u32, _DMACTXDLAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACTXDLAR; #[doc = "`read()` method returns [dmactx_dlar::R](dmactx_dlar::R) reader structure"] impl crate::Readable for DMACTXDLAR {} #[doc = "`write(|w| ..)` method takes [dmactx_dlar::W](dmactx_dlar::W) writer structure"] impl crate::Writable for DMACTXDLAR {} #[doc = "Channel Tx descriptor list address register"] pub mod dmactx_dlar; #[doc = "Channel Rx descriptor list address register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacrx_dlar](dmacrx_dlar) module"] pub type DMACRXDLAR = crate::Reg<u32, _DMACRXDLAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACRXDLAR; #[doc = "`read()` method returns [dmacrx_dlar::R](dmacrx_dlar::R) reader structure"] impl crate::Readable for DMACRXDLAR {} #[doc = "`write(|w| ..)` method takes [dmacrx_dlar::W](dmacrx_dlar::W) writer structure"] impl crate::Writable for DMACRXDLAR {} #[doc = "Channel Rx descriptor list address register"] pub mod dmacrx_dlar; #[doc = "Channel Tx descriptor tail pointer register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmactx_dtpr](dmactx_dtpr) module"] pub type DMACTXDTPR = crate::Reg<u32, _DMACTXDTPR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACTXDTPR; #[doc = "`read()` method returns [dmactx_dtpr::R](dmactx_dtpr::R) reader structure"] impl crate::Readable for DMACTXDTPR {} #[doc = "`write(|w| ..)` method takes [dmactx_dtpr::W](dmactx_dtpr::W) writer structure"] impl crate::Writable for DMACTXDTPR {} #[doc = "Channel Tx descriptor tail pointer register"] pub mod dmactx_dtpr; #[doc = "Channel Rx descriptor tail pointer register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacrx_dtpr](dmacrx_dtpr) module"] pub type DMACRXDTPR = crate::Reg<u32, _DMACRXDTPR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACRXDTPR; #[doc = "`read()` method returns [dmacrx_dtpr::R](dmacrx_dtpr::R) reader structure"] impl crate::Readable for DMACRXDTPR {} #[doc = "`write(|w| ..)` method takes [dmacrx_dtpr::W](dmacrx_dtpr::W) writer structure"] impl crate::Writable for DMACRXDTPR {} #[doc = "Channel Rx descriptor tail pointer register"] pub mod dmacrx_dtpr; #[doc = "Channel Tx descriptor ring length register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmactx_rlr](dmactx_rlr) module"] pub type DMACTXRLR = crate::Reg<u32, _DMACTXRLR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACTXRLR; #[doc = "`read()` method returns [dmactx_rlr::R](dmactx_rlr::R) reader structure"] impl crate::Readable for DMACTXRLR {} #[doc = "`write(|w| ..)` method takes [dmactx_rlr::W](dmactx_rlr::W) writer structure"] impl crate::Writable for DMACTXRLR {} #[doc = "Channel Tx descriptor ring length register"] pub mod dmactx_rlr; #[doc = "Channel Rx descriptor ring length register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacrx_rlr](dmacrx_rlr) module"] pub type DMACRXRLR = crate::Reg<u32, _DMACRXRLR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACRXRLR; #[doc = "`read()` method returns [dmacrx_rlr::R](dmacrx_rlr::R) reader structure"] impl crate::Readable for DMACRXRLR {} #[doc = "`write(|w| ..)` method takes [dmacrx_rlr::W](dmacrx_rlr::W) writer structure"] impl crate::Writable for DMACRXRLR {} #[doc = "Channel Rx descriptor ring length register"] pub mod dmacrx_rlr; #[doc = "Channel interrupt enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacier](dmacier) module"] pub type DMACIER = crate::Reg<u32, _DMACIER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACIER; #[doc = "`read()` method returns [dmacier::R](dmacier::R) reader structure"] impl crate::Readable for DMACIER {} #[doc = "`write(|w| ..)` method takes [dmacier::W](dmacier::W) writer structure"] impl crate::Writable for DMACIER {} #[doc = "Channel interrupt enable register"] pub mod dmacier; #[doc = "Channel Rx interrupt watchdog timer register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacrx_iwtr](dmacrx_iwtr) module"] pub type DMACRXIWTR = crate::Reg<u32, _DMACRXIWTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACRXIWTR; #[doc = "`read()` method returns [dmacrx_iwtr::R](dmacrx_iwtr::R) reader structure"] impl crate::Readable for DMACRXIWTR {} #[doc = "`write(|w| ..)` method takes [dmacrx_iwtr::W](dmacrx_iwtr::W) writer structure"] impl crate::Writable for DMACRXIWTR {} #[doc = "Channel Rx interrupt watchdog timer register"] pub mod dmacrx_iwtr; #[doc = "Channel current application transmit descriptor register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaccatx_dr](dmaccatx_dr) module"] pub type DMACCATXDR = crate::Reg<u32, _DMACCATXDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACCATXDR; #[doc = "`read()` method returns [dmaccatx_dr::R](dmaccatx_dr::R) reader structure"] impl crate::Readable for DMACCATXDR {} #[doc = "`write(|w| ..)` method takes [dmaccatx_dr::W](dmaccatx_dr::W) writer structure"] impl crate::Writable for DMACCATXDR {} #[doc = "Channel current application transmit descriptor register"] pub mod dmaccatx_dr; #[doc = "Channel current application receive descriptor register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaccarx_dr](dmaccarx_dr) module"] pub type DMACCARXDR = crate::Reg<u32, _DMACCARXDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACCARXDR; #[doc = "`read()` method returns [dmaccarx_dr::R](dmaccarx_dr::R) reader structure"] impl crate::Readable for DMACCARXDR {} #[doc = "`write(|w| ..)` method takes [dmaccarx_dr::W](dmaccarx_dr::W) writer structure"] impl crate::Writable for DMACCARXDR {} #[doc = "Channel current application receive descriptor register"] pub mod dmaccarx_dr; #[doc = "Channel current application transmit buffer register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaccatx_br](dmaccatx_br) module"] pub type DMACCATXBR = crate::Reg<u32, _DMACCATXBR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACCATXBR; #[doc = "`read()` method returns [dmaccatx_br::R](dmaccatx_br::R) reader structure"] impl crate::Readable for DMACCATXBR {} #[doc = "`write(|w| ..)` method takes [dmaccatx_br::W](dmaccatx_br::W) writer structure"] impl crate::Writable for DMACCATXBR {} #[doc = "Channel current application transmit buffer register"] pub mod dmaccatx_br; #[doc = "Channel current application receive buffer register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmaccarx_br](dmaccarx_br) module"] pub type DMACCARXBR = crate::Reg<u32, _DMACCARXBR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACCARXBR; #[doc = "`read()` method returns [dmaccarx_br::R](dmaccarx_br::R) reader structure"] impl crate::Readable for DMACCARXBR {} #[doc = "`write(|w| ..)` method takes [dmaccarx_br::W](dmaccarx_br::W) writer structure"] impl crate::Writable for DMACCARXBR {} #[doc = "Channel current application receive buffer register"] pub mod dmaccarx_br; #[doc = "Channel status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacsr](dmacsr) module"] pub type DMACSR = crate::Reg<u32, _DMACSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACSR; #[doc = "`read()` method returns [dmacsr::R](dmacsr::R) reader structure"] impl crate::Readable for DMACSR {} #[doc = "`write(|w| ..)` method takes [dmacsr::W](dmacsr::W) writer structure"] impl crate::Writable for DMACSR {} #[doc = "Channel status register"] pub mod dmacsr; #[doc = "Channel missed frame count register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dmacmfcr](dmacmfcr) module"] pub type DMACMFCR = crate::Reg<u32, _DMACMFCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DMACMFCR; #[doc = "`read()` method returns [dmacmfcr::R](dmacmfcr::R) reader structure"] impl crate::Readable for DMACMFCR {} #[doc = "`write(|w| ..)` method takes [dmacmfcr::W](dmacmfcr::W) writer structure"] impl crate::Writable for DMACMFCR {} #[doc = "Channel missed frame count register"] pub mod dmacmfcr;
use game_core::GameStage; use game_lib::{ bevy::{ecs as bevy_ecs, prelude::*}, tracing::{self, instrument}, }; use std::time::Duration; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Timed(Duration); impl Timed { pub fn new(lifetime: Duration) -> Self { Timed(lifetime) } pub fn remaining(&self) -> Duration { self.0 } pub fn update(&mut self, elapsed: Duration) { self.0 = self.0.saturating_sub(elapsed); } pub fn extend(&mut self, extension: Duration) { self.0 = self.0.saturating_add(extension); } } #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, SystemLabel)] pub struct TimedPlugin; impl TimedPlugin { #[instrument(skip(commands, time, query))] fn update_lifetimes( mut commands: Commands, time: Res<Time>, mut query: Query<(Entity, &mut Timed)>, ) { for (entity, mut timed) in query.iter_mut() { timed.update(time.delta()); if timed.remaining() <= Duration::ZERO { commands.entity(entity).despawn_recursive(); } } } } impl Plugin for TimedPlugin { fn build(&self, app: &mut AppBuilder) { app.add_system_set_to_stage( GameStage::GamePreUpdate, SystemSet::new() .label(TimedPlugin) .with_system(Self::update_lifetimes.system()), ); } }
//! CM3's Private Peripheral Bus pub mod scb; pub mod systmr; pub mod nvic; pub mod mpu;
//! Test suite for the Web and headless browsers. #![cfg(target_arch = "wasm32")] // Necessary for the assert_eq! which now fails clippy #![allow(clippy::eq_op)] extern crate wasm_bindgen_test; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn pass() { assert_eq!(1 + 1, 2); }
/// tests for this pallet use super::*; use itertools::Itertools; use log; use more_asserts::*; use quickcheck::{QuickCheck, TestResult}; use rand::{thread_rng, Rng}; use std::sync::atomic::{AtomicU64, Ordering}; use frame_support::{assert_ok, impl_outer_origin, parameter_types, weights::Weight}; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, Fixed64, Perbill, }; use sp_std::iter; use system; impl_outer_origin! { pub enum Origin for Test {} } const TEST_BASE_UNIT: u64 = 1000; static LAST_PRICE: AtomicU64 = AtomicU64::new(TEST_BASE_UNIT); pub struct RandomPrice; impl FetchPrice<Coins> for RandomPrice { fn fetch_price() -> Coins { let prev = LAST_PRICE.load(Ordering::SeqCst); let random = thread_rng().gen_range(500, 1500); let ratio: Ratio<u64> = Ratio::new(random, 1000); let next = ratio .checked_mul(&prev.into()) .map(|r| r.to_integer()) .unwrap_or(prev); LAST_PRICE.store(next + 1, Ordering::SeqCst); prev } } // For testing the pallet, we construct most of a mock runtime. This means // first constructing a configuration type (`Test`) which `impl`s each of the // configuration traits of modules we want to use. #[derive(Clone, Eq, PartialEq)] pub struct Test; parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75); // expire bonds quickly in tests pub const ExpirationPeriod: u64 = 100; // allow few bids pub const MaximumBids: u64 = 10; // adjust supply every second block pub const AdjustmentFrequency: u64 = 2; pub const BaseUnit: u64 = TEST_BASE_UNIT; pub const InitialSupply: u64 = 100 * BaseUnit::get(); pub const MinimumSupply: u64 = BaseUnit::get(); pub const MinimumBondPrice: Perbill = Perbill::from_percent(10); } type AccountId = u64; type BlockNumber = u64; impl system::Trait for Test { type Origin = Origin; type Call = (); type Index = u64; type BlockNumber = BlockNumber; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; type MaximumBlockWeight = MaximumBlockWeight; type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); type ModuleToIndex = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); } impl Trait for Test { type Event = (); type CoinPrice = RandomPrice; type ExpirationPeriod = ExpirationPeriod; type MaximumBids = MaximumBids; type AdjustmentFrequency = AdjustmentFrequency; type BaseUnit = BaseUnit; type InitialSupply = InitialSupply; type MinimumSupply = MinimumSupply; type MinimumBondPrice = MinimumBondPrice; } type System = system::Module<Test>; type Stablecoin = Module<Test>; // This function basically just builds a genesis storage key/value store according to // our desired mockup. fn new_test_ext() -> sp_io::TestExternalities { let mut storage = system::GenesisConfig::default().build_storage::<Test>().unwrap(); let shareholders: Vec<(AccountId, u64)> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10] .into_iter() .zip(iter::repeat(1)) .collect(); // make sure to run our storage build function to check config let _ = GenesisConfig::<Test> { shareholders }.assimilate_storage(&mut storage); storage.into() } fn new_test_ext_with(shareholders: Vec<AccountId>) -> sp_io::TestExternalities { let mut storage = system::GenesisConfig::default().build_storage::<Test>().unwrap(); let shareholders: Vec<(AccountId, u64)> = shareholders.into_iter().zip(iter::repeat(1)).collect(); // make sure to run our storage build function to check config let _ = GenesisConfig::<Test> { shareholders }.assimilate_storage(&mut storage); storage.into() } // ------------------------------------------------------------ // utils type BondT = Bond<AccountId, BlockNumber>; // Implementation that we will instantiate. type Transient = BoundedDeque<BondT, <Stablecoin as Store>::BondsRange, <Stablecoin as Store>::Bonds, BondIndex>; fn add_bond(bond: BondT) { let mut bonds = Transient::new(); bonds.push_back(bond); bonds.commit(); } // ------------------------------------------------------------ // init tests #[test] fn init_test() { new_test_ext().execute_with(|| { let shares = Stablecoin::shares(); assert_eq!( shares, vec![ (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1) ] ); let share_supply: u64 = shares.iter().map(|(_a, s)| s).sum(); assert_eq!(share_supply, 10); }); } // ------------------------------------------------------------ // balances #[test] fn transfer_test() { new_test_ext().execute_with(|| { let first_acc = 1; let second_acc = 2; let amount = TEST_BASE_UNIT; let from_balance_before = Stablecoin::get_balance(first_acc); let to_balance_before = Stablecoin::get_balance(second_acc); assert_ok!(Stablecoin::transfer_from_to(&first_acc, &second_acc, amount)); assert_eq!(Stablecoin::get_balance(first_acc), from_balance_before - amount); assert_eq!(Stablecoin::get_balance(second_acc), to_balance_before + amount); }); } // ------------------------------------------------------------ // currency trait #[test] fn slash_test() { new_test_ext().execute_with(|| { let acc = 1; let amount = TEST_BASE_UNIT; let balance_before = Stablecoin::get_balance(acc); assert_eq!(Stablecoin::slash(&acc, amount), 0); assert_eq!(Stablecoin::get_balance(acc), balance_before - amount); }); } // ------------------------------------------------------------ // bids #[test] fn bids_are_sorted_highest_to_lowest() { new_test_ext().execute_with(|| { let bid_amount = 5 * BaseUnit::get(); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(25), bid_amount)); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(33), bid_amount)); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(50), bid_amount)); let bids = Stablecoin::bond_bids(); let prices: Vec<_> = bids.into_iter().map(|Bid { price, .. }| price).collect(); // largest bid is stored last so we can pop assert_eq!( prices, vec![ Perbill::from_percent(25), Perbill::from_percent(33), Perbill::from_percent(50), ] ); }); } #[test] fn amount_of_bids_is_limited() { new_test_ext().execute_with(|| { let bid_amount = 5 * BaseUnit::get(); for _i in 0..(2 * MaximumBids::get()) { Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(25), bid_amount)); } assert_eq!(Stablecoin::bond_bids().len() as u64, MaximumBids::get()); }); } #[test] fn truncated_bids_are_refunded() { new_test_ext_with(vec![1]).execute_with(|| { let price = Perbill::from_percent(25); let quantity = BaseUnit::get(); for _i in 0..(MaximumBids::get() + 1) { assert_ok!(Stablecoin::bid_for_bond(Origin::signed(1), price, quantity)); } assert_eq!(Stablecoin::bond_bids().len() as u64, MaximumBids::get()); let expected = InitialSupply::get() - price * quantity * (MaximumBids::get() as u64); assert_eq!(Stablecoin::get_balance(1), expected); }); } #[test] fn cancel_all_bids_test() { new_test_ext().execute_with(|| { let bid_amount = 5 * BaseUnit::get(); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(25), bid_amount)); Stablecoin::add_bid(Bid::new(2, Perbill::from_percent(33), bid_amount)); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(50), bid_amount)); Stablecoin::add_bid(Bid::new(3, Perbill::from_percent(50), bid_amount)); assert_eq!(Stablecoin::bond_bids().len(), 4); assert_ok!(Stablecoin::cancel_all_bids(Origin::signed(1))); let bids = Stablecoin::bond_bids(); assert_eq!(bids.len(), 2); for bid in bids { assert!(bid.account != 1); } }); } #[test] fn cancel_selected_bids_test() { new_test_ext().execute_with(|| { let bid_amount = 5 * BaseUnit::get(); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(25), bid_amount)); Stablecoin::add_bid(Bid::new(2, Perbill::from_percent(33), bid_amount)); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(45), bid_amount)); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(50), bid_amount)); Stablecoin::add_bid(Bid::new(3, Perbill::from_percent(55), bid_amount)); assert_eq!(Stablecoin::bond_bids().len(), 5); assert_ok!(Stablecoin::cancel_bids_at_or_below( Origin::signed(1), Perbill::from_percent(45) )); let bids = Stablecoin::bond_bids(); assert_eq!(bids.len(), 3); let bids: Vec<(_, _)> = bids .into_iter() .map(|Bid { account, price, .. }| (account, price)) .collect(); // highest bid is last so we can pop assert_eq!( bids, vec![ (2, Perbill::from_percent(33)), (1, Perbill::from_percent(50)), (3, Perbill::from_percent(55)), ] ); }); } // ------------------------------------------------------------ // bonds #[test] fn adding_bonds() { new_test_ext().execute_with(|| { let payout = Fixed64::from_rational(20, 100).saturated_multiply_accumulate(BaseUnit::get()); add_bond(Stablecoin::new_bond(3, payout)); let (start, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 1); let bond = &Stablecoin::get_bond(start); assert_eq!(bond.expiration, System::block_number() + ExpirationPeriod::get()); }) } #[test] fn expire_bonds() { new_test_ext_with(vec![1]).execute_with(|| { let acc = 3; let prev_acc_balance = Stablecoin::get_balance(acc); let payout = Fixed64::from_rational(20, 100).saturated_multiply_accumulate(BaseUnit::get()); add_bond(Stablecoin::new_bond(acc, payout)); let (start, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 1); let bond = &Stablecoin::get_bond(start); assert_eq!(bond.expiration, System::block_number() + ExpirationPeriod::get()); let prev_supply = Stablecoin::coin_supply(); // set blocknumber past expiration time System::set_block_number(System::block_number() + ExpirationPeriod::get()); assert_ok!(Stablecoin::expand_supply(prev_supply, 42)); let acc_balance = Stablecoin::get_balance(acc); assert_eq!( prev_acc_balance, acc_balance, "account balance should not change as the bond expired" ); assert_eq!( prev_supply + 42, Stablecoin::coin_supply(), "coin supply should have increased" ); }); } #[test] fn expire_bonds_and_expand_supply() { new_test_ext_with(vec![1]).execute_with(|| { let first_acc = 3; let prev_first_acc_balance = Stablecoin::get_balance(first_acc); // 1.2 * BaseUnit let payout = Fixed64::from_rational(20, 100).saturated_multiply_accumulate(BaseUnit::get()); add_bond(Stablecoin::new_bond(first_acc, payout)); let (start, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 1); let bond = &Stablecoin::get_bond(start); assert_eq!(bond.expiration, System::block_number() + ExpirationPeriod::get()); let prev_supply = Stablecoin::coin_supply(); let second_acc = first_acc + 1; let prev_second_acc_balance = Stablecoin::get_balance(second_acc); // set blocknumber to the block number right before the first bond's expiration block System::set_block_number(System::block_number() + ExpirationPeriod::get() - 1); // Add a new bond add_bond(Stablecoin::new_bond(second_acc, payout)); add_bond(Stablecoin::new_bond(second_acc, payout)); add_bond(Stablecoin::new_bond(second_acc, payout)); // Note: this one is from first_acc add_bond(Stablecoin::new_bond(first_acc, payout)); // check bonds length let (_, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 5); // Increase block number by one so that we reach the first bond's expiration block number. System::set_block_number(System::block_number() + 1); // expand the supply, only hitting the last bond that was added to the queue, but not fully filling it let new_coins = payout; assert_ok!(Stablecoin::expand_supply(Stablecoin::coin_supply(), new_coins)); // make sure there are only three bonds left (the first one expired, the second one got consumed) let (_, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 3); // make sure the first account's balance hasn't changed assert_eq!(prev_first_acc_balance, Stablecoin::get_balance(first_acc)); // make sure the second account's balance has increased by `new_coins` let intermediate_second_acc_balance = prev_second_acc_balance + new_coins; assert_eq!( prev_second_acc_balance + new_coins, Stablecoin::get_balance(second_acc) ); // make sure total supply increased by `new_coins` assert_eq!(prev_supply + new_coins, Stablecoin::coin_supply()); let intermediate_supply = Stablecoin::coin_supply(); // Set the block number to be *exactly equal* to the expiration date of all bonds that are left in the queue System::set_block_number(System::block_number() + ExpirationPeriod::get() - 1); // try to expand_supply, expected to do nothing because all bonds have expired let new_coins = 42; assert_ok!(Stablecoin::expand_supply(intermediate_supply, new_coins)); // make sure there are no bonds left (they have all expired) let (_, length) = Stablecoin::bonds_range(); // computing the length this way is fine because there was no overflow assert_eq!(length, 0); // make sure first and second's balances haven't changed assert_eq!(prev_first_acc_balance, Stablecoin::get_balance(first_acc)); assert_eq!( intermediate_second_acc_balance, Stablecoin::get_balance(second_acc) ); // Make sure coin supply has increased by `new_coins` assert_eq!( intermediate_supply + new_coins, Stablecoin::coin_supply(), "coin supply should not change as the bond expired" ); }); } // ------------------------------------------------------------ // handout tests #[test] fn simple_handout_test() { new_test_ext().execute_with(|| { let balance_per_acc = InitialSupply::get() / 10; assert_eq!(Stablecoin::get_balance(1), balance_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc); let amount = 30 * BaseUnit::get(); assert_ok!(Stablecoin::hand_out_coins( &Stablecoin::shares(), amount, Stablecoin::coin_supply() )); let amount_per_acc = 3 * BaseUnit::get(); assert_eq!(Stablecoin::get_balance(1), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(2), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(3), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(7), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc + amount_per_acc); }); } #[test] fn handout_less_than_shares_test() { new_test_ext().execute_with(|| { let balance_per_acc = InitialSupply::get() / 10; assert_eq!(Stablecoin::get_balance(1), balance_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc); let amount = 8; assert_ok!(Stablecoin::hand_out_coins( &Stablecoin::shares(), amount, Stablecoin::coin_supply() )); let amount_per_acc = 1; assert_eq!(Stablecoin::get_balance(1), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(2), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(3), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(7), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(8), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(9), balance_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc); }); } #[test] fn handout_more_than_shares_test() { new_test_ext().execute_with(|| { let balance_per_acc = InitialSupply::get() / 10; assert_eq!(Stablecoin::get_balance(1), balance_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc); let amount = 13; assert_ok!(Stablecoin::hand_out_coins( &Stablecoin::shares(), amount, Stablecoin::coin_supply() )); let amount_per_acc = 1; assert_eq!(Stablecoin::get_balance(1), balance_per_acc + amount_per_acc + 1); assert_eq!(Stablecoin::get_balance(2), balance_per_acc + amount_per_acc + 1); assert_eq!(Stablecoin::get_balance(3), balance_per_acc + amount_per_acc + 1); assert_eq!(Stablecoin::get_balance(4), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(8), balance_per_acc + amount_per_acc); assert_eq!(Stablecoin::get_balance(10), balance_per_acc + amount_per_acc); }); } #[test] fn handout_quickcheck() { fn property(shareholders: Vec<AccountId>, amount: Coins) -> TestResult { let len = shareholders.len(); if amount == 0 { return TestResult::discard(); } // Expects between 1 and 999 shareholders. if len < 1 || len > 999 { return TestResult::discard(); } // 0 is not a valid AccountId if shareholders.iter().any(|s| *s == 0) { return TestResult::discard(); } // make sure shareholders are distinct if shareholders.iter().unique().count() != len { return TestResult::discard(); } let first = shareholders[0]; new_test_ext_with(shareholders).execute_with(|| { let amount = amount; // this assert might actually produce a false positive // as there might be errors returned that are the correct // behavior for the given parameters assert_ok!(Stablecoin::hand_out_coins( &Stablecoin::shares(), amount, Stablecoin::coin_supply() )); let len = len as u64; let payout = amount; let balance = Stablecoin::get_balance(first); assert_ge!(balance, InitialSupply::get() / len + payout / len); assert_le!(balance, InitialSupply::get() / len + 1 + payout / len + 1); TestResult::passed() }) } QuickCheck::new() .min_tests_passed(5) .tests(50) .max_tests(500) .quickcheck(property as fn(Vec<u64>, u64) -> TestResult) } // ------------------------------------------------------------ // expand and contract tests #[test] fn expand_supply_test() { new_test_ext().execute_with(|| { // payout of 120% of BaseUnit let payout = Fixed64::from_rational(20, 100).saturated_multiply_accumulate(BaseUnit::get()); add_bond(Stablecoin::new_bond(2, payout)); add_bond(Stablecoin::new_bond(3, payout)); add_bond(Stablecoin::new_bond(4, payout)); add_bond(Stablecoin::new_bond(5, 7 * payout)); let prev_supply = Stablecoin::coin_supply(); let amount = 13 * BaseUnit::get(); assert_ok!(Stablecoin::expand_supply(prev_supply, amount)); let amount_per_acc = InitialSupply::get() / 10 + BaseUnit::get() / 10; assert_eq!(Stablecoin::get_balance(1), amount_per_acc); assert_eq!(Stablecoin::get_balance(2), amount_per_acc + payout); assert_eq!(Stablecoin::get_balance(3), amount_per_acc + payout); assert_eq!(Stablecoin::get_balance(4), amount_per_acc + payout); assert_eq!(Stablecoin::get_balance(5), amount_per_acc + 7 * payout); assert_eq!(Stablecoin::get_balance(8), amount_per_acc); assert_eq!(Stablecoin::get_balance(10), amount_per_acc); assert_eq!( Stablecoin::coin_supply(), prev_supply + amount, "supply should be increased by amount" ); }); } #[test] fn contract_supply_test() { new_test_ext().execute_with(|| { let bond_amount = Ratio::new(125, 100) .checked_mul(&BaseUnit::get().into()) .map(|r| r.to_integer()) .expect("bond_amount should not have overflowed"); Stablecoin::add_bid(Bid::new(1, Perbill::from_percent(80), bond_amount)); Stablecoin::add_bid(Bid::new(2, Perbill::from_percent(75), 2 * BaseUnit::get())); let prev_supply = Stablecoin::coin_supply(); let amount = 2 * BaseUnit::get(); assert_ok!(Stablecoin::contract_supply(prev_supply, amount)); let bids = Stablecoin::bond_bids(); assert_eq!(bids.len(), 1, "exactly one bid should have been removed"); let remainging_bid_quantity = Fixed64::from_rational(667, 1_000) .saturated_multiply_accumulate(BaseUnit::get()) - BaseUnit::get(); assert_eq!( bids[0], Bid::new(2, Perbill::from_percent(75), remainging_bid_quantity) ); let (start, _) = Stablecoin::bonds_range(); assert_eq!(Stablecoin::get_bond(start).payout, bond_amount); assert_eq!( Stablecoin::get_bond(start + 1).payout, Fixed64::from_rational(333, 1_000).saturated_multiply_accumulate(BaseUnit::get()) ); assert_eq!( Stablecoin::coin_supply(), prev_supply - amount, "supply should be decreased by amount" ); }) } #[test] fn expand_or_contract_quickcheck() { fn property(bonds: Vec<(u64, u64)>, prices: Vec<Coins>) -> TestResult { new_test_ext().execute_with(|| { if prices.iter().any(|p| p == &0) { return TestResult::discard(); } for (account, payout) in bonds { if account > 0 && payout > 0 { add_bond(Stablecoin::new_bond(account, payout)); } } for price in prices { // this assert might actually produce a false positive // as there might be errors returned that are the correct // behavior for the given parameters assert!(matches!( Stablecoin::expand_or_contract_on_price(price), Ok(()) | Err(DispatchError::Module { index: 0, error: 0, message: Some("CoinSupplyOverflow") }) )); } TestResult::passed() }) } QuickCheck::new() .min_tests_passed(5) .tests(50) .max_tests(500) .quickcheck(property as fn(Vec<(u64, u64)>, Vec<u64>) -> TestResult) } #[test] fn expand_or_contract_smoketest() { new_test_ext().execute_with(|| { let mut rng = rand::thread_rng(); let bonds: Vec<(u64, u64)> = (0..100) .map(|_| (rng.gen_range(1, 200), rng.gen_range(1, 10 * BaseUnit::get()))) .collect(); for (account, payout) in bonds { add_bond(Stablecoin::new_bond(account, payout)); } for _ in 0..150 { let price = RandomPrice::fetch_price(); Stablecoin::on_block_with_price(0, price).unwrap_or_else(|e| { log::error!("could not adjust supply: {:?}", e); }); } }) } #[test] fn supply_change_calculation() { let price = TEST_BASE_UNIT + 100; let supply = u64::max_value(); let contract_by = Stablecoin::calculate_supply_change(price, TEST_BASE_UNIT, supply); // the error should be low enough assert_ge!(contract_by, u64::max_value() / 10 - 1); assert_le!(contract_by, u64::max_value() / 10 + 1); }
use chrono::Utc; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Serialize)] pub struct Budget { pub id: i32, pub name: String, pub open: chrono::DateTime<Utc>, pub close: chrono::DateTime<Utc>, } impl Budget { pub fn new( id: i32, name: &String, open: chrono::DateTime<Utc>, close: chrono::DateTime<Utc>, ) -> Budget { Budget { id: id, name: String::from(name), open: open, close: close, } } } #[derive(Debug, Deserialize)] pub struct NewBudget { pub name: String, pub open: String, pub close: String, } #[derive(Debug, Serialize, Deserialize)] pub struct BudgetEntry { pub id: i32, pub account: i32, pub budget: i32, pub balance: i32, } #[derive(Debug, Deserialize)] pub struct NewBudgetEntry { pub account: i32, pub balance: i32, }
//! Syntax highlighting for buffer contents via [tree-sitter]. //! //! # Notes about `Range` //! //! This module uses tree-sitter's convenient `Range` type for representing regions of the buffer, //! but it differs slightly from the other geometric types used by the editor: //! //! - Ranges are endpoint-exclusive only on the X-axis. So, we have to add 1 to //! the Y-coordinate to get non-empty areas for single-line ranges. //! - Ranges work like a highlighter. Multi-line ranges implicitly include all text between the //! points. Therefore nanges cannot be converted directly to rectangular buffer `Span`s. //! //! [tree-sitter]: https://tree-sitter.github.io/tree-sitter/ use std::cell::RefCell; use std::cmp; use std::collections::HashMap; use std::convert::TryFrom; use lazy_static::lazy_static; use log::*; use maplit::hashmap; use tree_sitter::{InputEdit, Parser, Point, Query, QueryCursor, Range, Tree}; use crate::buffer::units::BytePosition; use crate::syntax::Syntax; use crate::ui::{Bounds, Color, Coordinates, Screen}; use super::{edit::Edit, Buffer, Span}; lazy_static! { static ref DEFAULT_THEME: HashMap<&'static str, Color> = hashmap! { "attribute" => Color::new(0xff, 0x00, 0x00), "comment" => Color::new(0x4e, 0x4e, 0x4e), "constant" => Color::new(0x00, 0x87, 0x87), "escape" => Color::new(0xff, 0xd7, 0x00), "function" => Color::new(0xff, 0x87, 0x00), "function.macro" => Color::new(0xff, 0x00, 0x00), "keyword" => Color::new(0xff, 0xff, 0x00), "label" => Color::new(0xff, 0xff, 0x00), "number" => Color::new(0x00, 0x87, 0x87), "operator" => Color::new(0xff, 0xff, 0x00), "string" => Color::new(0x5f, 0x87, 0xd7), "type" => Color::new(0x00, 0xff, 0x00), }; } pub struct Theme { /// Map of capture index to associated color, if any. colors: Vec<Option<Color>>, } impl Theme { pub fn new(capture_names: &[String]) -> Self { let theme = &DEFAULT_THEME; Self { colors: capture_names .iter() .map(|name| { if let Some(color) = theme.get(name.as_str()) { return Some(*color); } for (pos, _) in name.rmatch_indices('.') { let fallback_name = &name[..pos]; if let Some(color) = theme.get(&fallback_name) { info!("no color for {}, falling back to {}", name, &fallback_name); return Some(*color); } } info!("no color for {}", name); None }) .collect(), } } pub fn color_for(&self, capture_index: usize) -> Option<Color> { self.colors[capture_index] } } pub struct Highlighter { parser: RefCell<Parser>, query: Query, old_tree: Option<Tree>, theme: Theme, } impl Highlighter { pub fn new(language: Syntax) -> Self { let (language, query) = tree_sitter_highlight_config(language); let mut parser = Parser::new(); parser .set_language(language) .expect("incompatible tree-sitter version"); let theme = Theme::new(query.capture_names()); Highlighter { query, parser: RefCell::new(parser), old_tree: None, theme, } } /// Notifies the highlighter that the underlying text has been edited. pub fn edit( &mut self, edit: &Edit, start_position: BytePosition, old_end_position: BytePosition, new_end_position: BytePosition, ) { if let Some(tree) = &mut self.old_tree { tree.edit(&InputEdit { start_byte: edit.range.start.0, old_end_byte: edit.range.end.0, new_end_byte: edit.range.start.0 + edit.new_text.len(), start_position: Point { row: start_position.y, column: start_position.x, }, old_end_position: Point { row: old_end_position.y, column: old_end_position.x, }, new_end_position: Point { row: new_end_position.y, column: new_end_position.x, }, }); } } /// Apply syntax highlighting from buffer to the screen. pub fn highlight(&self, screen: &mut Screen, buffer: &Buffer) { debug!("starting highlighting"); let tree = self.parser.borrow_mut().parse_with( &mut |_, point| { buffer .storage .slice_at(BytePosition::new(point.column, point.row)) }, self.old_tree.as_ref(), ); let tree = match tree { Some(tree) => tree, None => return, }; let mut cursor = QueryCursor::new(); let viewport = buffer .viewport .expect("attempted to highlight hidden buffer"); let (start, end) = span_to_points(viewport); cursor.set_point_range(start, end); let captures_query = cursor.captures(&self.query, tree.root_node(), |node| { let Range { start_point, end_point, .. } = node.range(); let start = BytePosition::new(start_point.column, start_point.row); let end = BytePosition::new(end_point.column, end_point.row); &buffer.storage[start..end] }); for (m, _) in captures_query { for capture in m.captures { let range = capture.node.range(); let index = capture.index as usize; let color = self.theme.color_for(index); if log_enabled!(log::Level::Debug) { // The capture range may span across lines, so we can't use the storage's // `Index` implementation. let text = &buffer.storage.to_string()[range.start_byte..range.end_byte]; debug!( "capture={} color={:?} text={:?}", self.query.capture_names()[index], color, text, ); } if let Some(color) = color { highlight_range(screen, viewport, range, color); } } } debug!("finished highlighting"); } } /// Highlights a tree-sitter range on the screen. fn highlight_range(screen: &mut Screen, viewport: Span, range: Range, color: Color) { debug!("highlighting range {:?}", range); // Split the range into rectangular areas per-line. for y in range.start_point.row..=cmp::min(range.end_point.row, viewport.max_y() - 1) { let mut start_x = if y == range.start_point.row { cmp::max(range.start_point.column, viewport.min_x()) } else { 0 }; start_x = start_x.saturating_sub(viewport.min_x()); let mut end_x = if y == range.end_point.row { cmp::min(range.end_point.column, viewport.max_x()) } else { viewport.max_x() }; end_x = end_x.saturating_sub(viewport.min_x()); // If we're told to start highlighting at the edge of the viewport, bail out. // TODO: Is this a bug in tree-sitter? if start_x == end_x { return; } let start_x = u16::try_from(start_x).expect("attempted to draw outside screen bounds"); let end_x = u16::try_from(end_x).expect("attempted to draw outside screen bounds"); let y = u16::try_from(y.saturating_sub(viewport.min_y())) .expect("viewport outside screen bounds"); let highlight_bounds = Bounds::new( Coordinates::new(start_x as u16, y), Coordinates::new(end_x as u16, y + 1), ); screen.apply_color(highlight_bounds, color); } } fn tree_sitter_highlight_config(language: Syntax) -> (tree_sitter::Language, Query) { use Syntax::*; match language { JavaScript => tree_sitter_languages::javascript(), Rust => tree_sitter_languages::rust(), } } fn span_to_points(span: Span) -> (Point, Point) { ( Point::new(span.min_y(), span.min_x()), Point::new(span.max_y() - 1, span.max_x()), ) } #[cfg(test)] mod tests { use euclid::{rect, size2}; use indoc::indoc; use tree_sitter::Point; use crate::buffer::{Buffer, Span}; use crate::ui::{Bounds, Color, Context, Drawable, Screen, Size}; use super::{span_to_points, Syntax, Theme}; #[test] fn points_from_span() { let span = Span::from_size(size2(2, 1)); let (min, max) = span_to_points(span); assert_eq!(min, Point::new(0, 0)); assert_eq!(max, Point::new(0, 2)); } // TODO: it might be better to just unit test highlight_range directly... #[test] fn highlight_large_buffer() { let mut buffer = Buffer::from(indoc! {r#" fn main() { println!("Hello, world!") } "#}); buffer.set_syntax(Some(Syntax::Rust)); let mut screen = Screen::new(Size::new(5, 2)); let mut ctx = Context { bounds: Bounds::from_size(screen.size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_left_viewport_edge() { let mut buffer = Buffer::from(indoc! {" extern crate foo; "}); buffer.set_syntax(Some(Syntax::Rust)); let mut screen = Screen::new(size2(4, 2)); buffer.viewport = Some(rect(6, 0, 4, 2)); let mut ctx = Context { bounds: Bounds::from_size(size2(4, 2)), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_right_viewport_edge() { let mut buffer = Buffer::from(r"parse('\n');"); buffer.set_syntax(Some(Syntax::JavaScript)); let size = Size::new(6, 2); let mut screen = Screen::new(size); buffer.viewport = Some(Span::from_size(size.cast().cast_unit())); let mut ctx = Context { bounds: Bounds::from_size(size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_at_edge_of_screen() { let mut buffer = Buffer::from("impl Debug for Foo {}"); buffer.set_syntax(Some(Syntax::Rust)); let size = Size::new(5, 1); let mut screen = Screen::new(size); buffer.viewport = Some(Span::from_size(size.cast().cast_unit())); let mut ctx = Context { bounds: Bounds::from_size(size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_through_edge_of_screen() { let mut buffer = Buffer::from("'long string literal'"); buffer.set_syntax(Some(Syntax::JavaScript)); let size = Size::new(5, 1); let mut screen = Screen::new(size); buffer.viewport = Some(Span::from_size(size.cast().cast_unit())); let mut ctx = Context { bounds: Bounds::from_size(size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_multiline_comment() { let mut buffer = Buffer::from(indoc! {r#" /* * I am a multi-line comment. * I should be fully highlighted! */ "#}); let size = Size::new(30, 5); buffer.set_syntax(Some(Syntax::JavaScript)); buffer.viewport = Some(Span::from_size(size.cast().cast_unit())); let mut screen = Screen::new(size); let mut ctx = Context { bounds: Bounds::from_size(size), screen: &mut screen, }; buffer.draw(&mut ctx); assert_eq!(ctx.screen[(0, 0)].c, Some('/')); assert!(ctx.screen[(0, 0)].color.is_some()); assert!(ctx.screen[(0, 1)].color.is_some()); assert!(ctx.screen[(1, 10)].color.is_some()); // Shift the viewport to be within the highlight range. buffer .viewport .as_mut() .map(|viewport| viewport.origin.y += 1); buffer.draw(&mut ctx); assert_eq!(ctx.screen[(0, 3)].c, Some('I')); } #[test] fn highlight_shifted_viewport() { let mut buffer = Buffer::from(indoc! {" /* hello, world! goodbye, world! */ "}); buffer.set_syntax(Some(Syntax::JavaScript)); buffer.viewport = Some(rect(1, 0, 5, 2)); let mut screen = Screen::new(size2(5, 2)); let mut ctx = Context { bounds: Bounds::from_size(screen.size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn highlight_through_viewport_bottom() { let mut buffer = Buffer::from(indoc! {" /* * Long * multi-line * comment */ "}); buffer.set_syntax(Some(Syntax::JavaScript)); buffer.viewport = Some(rect(0, 0, 5, 1)); let mut screen = Screen::new(size2(5, 1)); let mut ctx = Context { bounds: Bounds::from_size(screen.size), screen: &mut screen, }; buffer.draw(&mut ctx); } #[test] fn theme_capture_name_fallback() { let theme = Theme::new(&[ String::from("function"), String::from("function.method"), String::from("function.builtin.static"), ]); assert_eq!(theme.color_for(1), Some(Color::new(0xff, 0x87, 0x00))); assert_eq!(theme.color_for(2), Some(Color::new(0xff, 0x87, 0x00))); } }
use conrod; #[derive(Debug, Clone, Copy)] pub struct Color { r: f32, g: f32, b: f32, a: f32, } pub const LIGHT_BLUE: Color = Color { r: 0.203, g: 0.59375, b: 0.85547, a: 1.0, }; pub const DARK_BLUE: Color = Color { r: 0.1601, g: 0.5, b: 0.72265, a: 1.0, }; pub const LIGHT_GREEN: Color = Color { r: 0.17968, g: 0.7968, b: 0.4414, a: 1.0, }; // const DARK_GREEN: Color = {}; // const BLUE_GRAY: Color = {}; // const MIDNIGHT: Color = {}; // const TURQUOISE: Color = {}; // const GREENSEA: Color = {}; // const LIGHT_PURPLE: Color = {}; // const DARK_PURPLE: Color = {}; pub const LIGHT_RED: Color = Color { r: 0.905, g: 0.298, b: 0.235, a: 1.0, }; // const DARK_RED: Color = {}; // const LIGHT_ORANGE: Color = {}; // const DARK_ORANGE: Color = {}; pub const LIGHT_YELLOW: Color = Color { r: 0.943, g: 0.768, b: 0.059, a: 1.0, }; // const DARK_YELLOW: Color = {}; pub const WHITE: Color = Color { r: 0.925, g: 0.941, b: 0.943, a: 1.0, }; // const SILVER: Color = {}; // const LIGHT_GRAY: Color = {}; // const DARK_GRAY: Color = {}; pub const BROWN: Color = Color { r: 0.2421, g: 0.1406, b: 0.1406, a: 1.0, }; impl Color { pub fn to_conrod_color(self) -> conrod::Color { conrod::Color::Rgba(self.r, self.g, self.b, self.a) } pub fn into(self) -> [f32; 3] { [self.r, self.g, self.b] } pub fn into_with_a(self) -> [f32; 4] { [self.r, self.g, self.b, self.a] } }
#![allow(unused_variables, dead_code)] use azul_css::{ StyleTextAlignmentHorz, StyleTextAlignmentVert, ScrollbarInfo, }; pub use webrender::api::{ GlyphInstance, LayoutSize, LayoutRect, LayoutPoint, }; pub use harfbuzz_sys::{hb_glyph_info_t as GlyphInfo, hb_glyph_position_t as GlyphPosition}; pub type WordIndex = usize; pub type GlyphIndex = usize; pub type LineLength = f32; pub type IndexOfLineBreak = usize; pub type RemainingSpaceToRight = f32; pub type LineBreaks = Vec<(GlyphIndex, RemainingSpaceToRight)>; const DEFAULT_LINE_HEIGHT: f32 = 1.0; const DEFAULT_WORD_SPACING: f32 = 1.0; const DEFAULT_LETTER_SPACING: f32 = 0.0; const DEFAULT_TAB_WIDTH: f32 = 4.0; /// Text broken up into `Tab`, `Word()`, `Return` characters #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Words { pub items: Vec<Word>, // NOTE: Can't be a string, because it wouldn't be possible to take substrings // (since in UTF-8, multiple characters can be encoded in one byte). internal_str: String, internal_chars: Vec<char>, } impl Words { pub fn get_substr(&self, word: &Word) -> String { self.internal_chars[word.start..word.end].iter().collect() } pub fn get_str(&self) -> &str { &self.internal_str } pub fn get_char(&self, idx: usize) -> Option<char> { self.internal_chars.get(idx).cloned() } } /// Section of a certain type #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Word { pub start: usize, pub end: usize, pub word_type: WordType, } /// Either a white-space delimited word, tab or return character #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum WordType { /// Encountered a word (delimited by spaces) Word, // `\t` or `x09` Tab, /// `\r`, `\n` or `\r\n`, escaped: `\x0D`, `\x0A` or `\x0D\x0A` Return, /// Space character Space, } /// A paragraph of words that are shaped and scaled (* but not yet layouted / positioned*!) /// according to their final size in pixels. #[derive(Debug, Clone)] pub struct ScaledWords { /// Font size (in pixels) that was used to scale these words pub font_size_px: f32, /// Words scaled to their appropriate font size, but not yet positioned on the screen pub items: Vec<ScaledWord>, /// Longest word in the `self.scaled_words`, necessary for /// calculating overflow rectangles. pub longest_word_width: f32, /// Horizontal advance of the space glyph pub space_advance_px: f32, /// Glyph index of the space character pub space_codepoint: u32, } /// Word that is scaled (to a font / font instance), but not yet positioned #[derive(Debug, Clone)] pub struct ScaledWord { /// Glyphs, positions are relative to the first character of the word pub glyph_infos: Vec<GlyphInfo>, /// Horizontal advances of each glyph, necessary for /// hit-testing characters later on (for text selection). pub glyph_positions: Vec<GlyphPosition>, /// The sum of the width of all the characters in this word pub word_width: f32, } /// Stores the positions of the vertically laid out texts #[derive(Debug, Clone, PartialEq)] pub struct WordPositions { /// Font size that was used to layout this text (value in pixels) pub font_size_px: f32, /// Options like word spacing, character spacing, etc. that were /// used to layout these glyphs pub text_layout_options: TextLayoutOptions, /// Stores the positions of words. pub word_positions: Vec<LayoutPoint>, /// Index of the word at which the line breaks + length of line /// (useful for text selection + horizontal centering) pub line_breaks: Vec<(WordIndex, LineLength)>, /// Horizontal width of the last line (in pixels), necessary for inline layout later on, /// so that the next text run can contine where the last text run left off. /// /// Usually, the "trailing" of the current text block is the "leading" of the /// next text block, to make it seem like two text runs push into each other. pub trailing: f32, /// How many words are in the text? pub number_of_words: usize, /// How many lines (NOTE: virtual lines, meaning line breaks in the layouted text) are there? pub number_of_lines: usize, /// Horizontal and vertical boundaries of the layouted words. /// /// Note that the vertical extent can be larger than the last words' position, /// because of trailing negative glyph advances. pub content_size: LayoutSize, } /// Width and height of the scrollbars at the side of the text field. /// /// This information is necessary in order to reserve space at /// the side of the text field so that the text doesn't overlap the scrollbar. /// In some cases (when the scrollbar is set to "auto"), the scrollbar space /// is only taken up when the text overflows the rectangle itself. #[derive(Debug, Default, Clone, PartialEq, PartialOrd)] pub struct ScrollbarStyle { /// Vertical scrollbar style, if any pub horizontal: Option<ScrollbarInfo>, /// Horizontal scrollbar style, if any pub vertical: Option<ScrollbarInfo>, } /// Layout options that can impact the flow of word positions #[derive(Debug, Clone, PartialEq, Default)] pub struct TextLayoutOptions { /// Multiplier for the line height, default to 1.0 pub line_height: Option<f32>, /// Additional spacing between glyphs (in pixels) pub letter_spacing: Option<f32>, /// Additional spacing between words (in pixels) pub word_spacing: Option<f32>, /// How many spaces should a tab character emulate /// (multiplying value, i.e. `4.0` = one tab = 4 spaces)? pub tab_width: Option<f32>, /// Maximum width of the text (in pixels) - if the text is set to `overflow:visible`, set this to None. pub max_horizontal_width: Option<f32>, /// How many pixels of leading does the first line have? Note that this added onto to the holes, /// so for effects like `:first-letter`, use a hole instead of a leading. pub leading: Option<f32>, /// This is more important for inline text layout where items can punch "holes" /// into the text flow, for example an image that floats to the right. /// /// TODO: Currently unused! pub holes: Vec<LayoutRect>, } /// Given the scale of words + the word positions, lays out the words in a #[derive(Debug, Clone, PartialEq)] pub struct LeftAlignedGlyphs<'a> { /// Width that was used to layout these glyphs (or None if the text has overflow:visible) pub max_horizontal_width: Option<f32>, /// Actual glyph instances, copied pub glyphs: Vec<&'a GlyphInstance>, /// Rectangles of the different lines, necessary for text selection /// and hovering over text, etc. pub line_rects: &'a Vec<LayoutRect>, /// Horizontal and vertical extent of the text pub text_bbox: LayoutSize, } /// Returns the layouted glyph instances #[derive(Debug, Clone, PartialEq)] pub struct LayoutedGlyphs { pub glyphs: Vec<GlyphInstance>, } /// Whether the text overflows the parent rectangle, and if yes, by how many pixels, /// necessary for determining if / how to show a scrollbar + aligning / centering text. #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] pub enum TextOverflow { /// Text is overflowing, by how much (in pixels)? IsOverflowing(f32), /// Text is in bounds, how much space is available until the edge of the rectangle (in pixels)? InBounds(f32), } /// Iterator over glyphs that returns information about the cluster that this glyph belongs to. /// Returned by the `ScaledWord::cluster_iter()` function. /// /// For each glyph, returns information about what cluster this glyph belongs to. Useful for /// doing operations per-cluster instead of per-glyph. /// *Note*: The iterator returns once-per-glyph, not once-per-cluster, however /// you can merge the clusters into groups by using the `ClusterInfo.cluster_idx`. #[derive(Debug, Clone)] pub struct ClusterIterator<'a> { /// What codepoint does the current glyph have - set to `None` if the first character isn't yet processed. cur_codepoint: Option<u32>, /// What cluster *index* are we currently at - default: 0 cluster_count: usize, word: &'a ScaledWord, /// Store what glyph we are currently processing in this word cur_glyph_idx: usize, } /// Info about what cluster a certain glyph belongs to. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ClusterInfo { /// Cluster index in this word pub cluster_idx: usize, /// Codepoint of this cluster pub codepoint: u32, /// What the glyph index of this cluster is pub glyph_idx: usize, } impl<'a> Iterator for ClusterIterator<'a> { type Item = ClusterInfo; /// Returns an iterator over the clusters in this word. /// /// Note: This will return one `ClusterInfo` per glyph, so you can't just /// use `.cluster_iter().count()` to count the glyphs: Instead, use `.cluster_iter().last().cluster_idx`. fn next(&mut self) -> Option<ClusterInfo> { let next_glyph = self.word.glyph_infos.get(self.cur_glyph_idx)?; let glyph_idx = self.cur_glyph_idx; if self.cur_codepoint != Some(next_glyph.cluster) { self.cur_codepoint = Some(next_glyph.cluster); self.cluster_count += 1; } self.cur_glyph_idx += 1; Some(ClusterInfo { cluster_idx: self.cluster_count, codepoint: self.cur_codepoint.unwrap_or(0), glyph_idx, }) } } impl ScaledWord { /// Creates an iterator over clusters instead of glyphs pub fn cluster_iter<'a>(&'a self) -> ClusterIterator<'a> { ClusterIterator { cur_codepoint: None, cluster_count: 0, word: &self, cur_glyph_idx: 0, } } pub fn number_of_clusters(&self) -> usize { self.cluster_iter().last().map(|l| l.cluster_idx).unwrap_or(0) } } /// Splits the text by whitespace into logical units (word, tab, return, whitespace). pub fn split_text_into_words(text: &str) -> Words { use unicode_normalization::UnicodeNormalization; // Necessary because we need to handle both \n and \r\n characters // If we just look at the characters one-by-one, this wouldn't be possible. let normalized_string = text.nfc().collect::<String>(); let normalized_chars = normalized_string.chars().collect::<Vec<char>>(); let mut words = Vec::new(); // Instead of storing the actual word, the word is only stored as an index instead, // which reduces allocations and is important for later on introducing RTL text // (where the position of the character data does not correspond to the actual glyph order). let mut current_word_start = 0; let mut last_char_idx = 0; let mut last_char_was_whitespace = false; let char_len = normalized_chars.len(); for (ch_idx, ch) in normalized_chars.iter().enumerate() { let ch = *ch; let current_char_is_whitespace = ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; let should_push_delimiter = match ch { ' ' => { Some(Word { start: last_char_idx + 1, end: ch_idx + 1, word_type: WordType::Space }) }, '\t' => { Some(Word { start: last_char_idx + 1, end: ch_idx + 1, word_type: WordType::Tab }) }, '\n' => { Some(if normalized_chars[last_char_idx] == '\r' { // "\r\n" return Word { start: last_char_idx, end: ch_idx + 1, word_type: WordType::Return, } } else { // "\n" return Word { start: last_char_idx + 1, end: ch_idx + 1, word_type: WordType::Return, } }) }, _ => None, }; // Character is a whitespace or the character is the last character in the text (end of text) let should_push_word = if current_char_is_whitespace && !last_char_was_whitespace { Some(Word { start: current_word_start, end: ch_idx, word_type: WordType::Word }) } else { None }; if current_char_is_whitespace { current_word_start = ch_idx + 1; } let mut push_words = |arr: [Option<Word>;2]| { words.extend(arr.into_iter().filter_map(|e| *e)); }; push_words([should_push_word, should_push_delimiter]); last_char_was_whitespace = current_char_is_whitespace; last_char_idx = ch_idx; } // Push the last word if current_word_start != last_char_idx + 1 { words.push(Word { start: current_word_start, end: normalized_chars.len(), word_type: WordType::Word }); } // If the last item is a `Return`, remove it if let Some(Word { word_type: WordType::Return, .. }) = words.last() { words.pop(); } Words { items: words, internal_str: normalized_string, internal_chars: normalized_chars, } } /// Takes a text broken into semantic items and a font instance and /// scales the font accordingly. pub fn words_to_scaled_words( words: &Words, font_bytes: &[u8], font_index: u32, font_size_px: f32, ) -> ScaledWords { use text_shaping::{self, HbBuffer, HbFont, HbScaledFont}; let hb_font = HbFont::from_bytes(font_bytes, font_index); let hb_scaled_font = HbScaledFont::from_font(&hb_font, font_size_px); // Get the dimensions of the space glyph let hb_space_buffer = HbBuffer::from_str(" "); let hb_shaped_space = text_shaping::shape_word_hb(&hb_space_buffer, &hb_scaled_font); let space_advance_px = hb_shaped_space.glyph_positions[0].x_advance as f32 / 128.0; // TODO: Half width for spaces? let space_codepoint = hb_shaped_space.glyph_infos[0].codepoint; let hb_buffer_entire_paragraph = HbBuffer::from_str(&words.internal_str); let hb_shaped_entire_paragraph = text_shaping::shape_word_hb(&hb_buffer_entire_paragraph, &hb_scaled_font); let mut shaped_word_positions = Vec::new(); let mut shaped_word_infos = Vec::new(); let mut current_word_positions = Vec::new(); let mut current_word_infos = Vec::new(); for i in 0..hb_shaped_entire_paragraph.glyph_positions.len() { let glyph_info = hb_shaped_entire_paragraph.glyph_infos[i]; let glyph_position = hb_shaped_entire_paragraph.glyph_positions[i]; let is_space = glyph_info.codepoint == space_codepoint; if is_space { shaped_word_positions.push(current_word_positions.clone()); shaped_word_infos.push(current_word_infos.clone()); current_word_positions.clear(); current_word_infos.clear(); } else { current_word_positions.push(glyph_position); current_word_infos.push(glyph_info); } } if !current_word_positions.is_empty() { shaped_word_positions.push(current_word_positions); shaped_word_infos.push(current_word_infos); } let mut longest_word_width = 0.0_f32; let scaled_words = words.items.iter() .filter(|w| w.word_type == WordType::Word) .enumerate() .filter_map(|(word_idx, word)| { let hb_glyph_positions = shaped_word_positions.get(word_idx)?; let hb_glyph_infos = shaped_word_infos.get(word_idx)?; let hb_word_width = text_shaping::get_word_visual_width_hb(&hb_glyph_positions); let hb_glyph_positions = text_shaping::get_glyph_positions_hb(&hb_glyph_positions); let hb_glyph_infos = text_shaping::get_glyph_infos_hb(&hb_glyph_infos); longest_word_width = longest_word_width.max(hb_word_width.abs()); Some(ScaledWord { glyph_infos: hb_glyph_infos, glyph_positions: hb_glyph_positions, word_width: hb_word_width, }) }).collect(); ScaledWords { items: scaled_words, longest_word_width: longest_word_width, space_advance_px, space_codepoint, font_size_px, } } /// Positions the words on the screen (does not layout any glyph positions!), necessary for estimating /// the intrinsic width + height of the text content. pub fn position_words( words: &Words, scaled_words: &ScaledWords, text_layout_options: &TextLayoutOptions, font_size_px: f32, ) -> WordPositions { use self::WordType::*; use std::f32; let space_advance = scaled_words.space_advance_px; let word_spacing_px = space_advance * text_layout_options.word_spacing.unwrap_or(DEFAULT_WORD_SPACING); let line_height_px = space_advance * text_layout_options.line_height.unwrap_or(DEFAULT_LINE_HEIGHT); let tab_width_px = space_advance * text_layout_options.tab_width.unwrap_or(DEFAULT_TAB_WIDTH); let letter_spacing_px = text_layout_options.letter_spacing.unwrap_or(DEFAULT_LETTER_SPACING); let mut line_breaks = Vec::new(); let mut word_positions = Vec::new(); let mut line_number = 0; let mut line_caret_x = 0.0; let mut current_word_idx = 0; macro_rules! advance_caret {($line_caret_x:expr) => ({ let caret_intersection = caret_intersects_with_holes( $line_caret_x, line_number, font_size_px, line_height_px, &text_layout_options.holes, text_layout_options.max_horizontal_width, ); if let LineCaretIntersection::PushCaretOntoNextLine(_, _) = caret_intersection { line_breaks.push((current_word_idx, line_caret_x)); } // Correct and advance the line caret position advance_caret( &mut $line_caret_x, &mut line_number, caret_intersection, ); })} advance_caret!(line_caret_x); if let Some(leading) = text_layout_options.leading { line_caret_x += leading; advance_caret!(line_caret_x); } // NOTE: word_idx increases only on words, not on other symbols! let mut word_idx = 0; macro_rules! handle_word {() => ({ let scaled_word = match scaled_words.items.get(word_idx) { Some(s) => s, None => continue, }; let reserved_letter_spacing_px = match text_layout_options.letter_spacing { None => 0.0, Some(spacing_multiplier) => spacing_multiplier * scaled_word.number_of_clusters().saturating_sub(1) as f32, }; // Calculate where the caret would be for the next word let word_advance_x = scaled_word.word_width + reserved_letter_spacing_px; let mut new_caret_x = line_caret_x + word_advance_x; // NOTE: Slightly modified "advance_caret!(new_caret_x);" - due to line breaking behaviour let caret_intersection = caret_intersects_with_holes( new_caret_x, line_number, font_size_px, line_height_px, &text_layout_options.holes, text_layout_options.max_horizontal_width, ); let mut is_line_break = false; if let LineCaretIntersection::PushCaretOntoNextLine(_, _) = caret_intersection { line_breaks.push((current_word_idx, line_caret_x)); is_line_break = true; } if !is_line_break { let line_caret_y = get_line_y_position(line_number, font_size_px, line_height_px); word_positions.push(LayoutPoint::new(line_caret_x, line_caret_y)); } // Correct and advance the line caret position advance_caret( &mut new_caret_x, &mut line_number, caret_intersection, ); line_caret_x = new_caret_x; // If there was a line break, the position needs to be determined after the line break happened if is_line_break { let line_caret_y = get_line_y_position(line_number, font_size_px, line_height_px); word_positions.push(LayoutPoint::new(line_caret_x, line_caret_y)); // important! - if the word is pushed onto the next line, the caret has to be // advanced by that words width! line_caret_x += word_advance_x; } // NOTE: Word index is increased before pushing, since word indices are 1-indexed // (so that paragraphs can be selected via "(0..word_index)"). word_idx += 1; current_word_idx = word_idx; })} // The last word is a bit special: Any text must have at least one line break! for word in words.items.iter().take(words.items.len().saturating_sub(1)) { match word.word_type { Word => { handle_word!(); }, Return => { line_breaks.push((current_word_idx, line_caret_x)); line_number += 1; let mut new_caret_x = 0.0; advance_caret!(new_caret_x); line_caret_x = new_caret_x; }, Space => { let mut new_caret_x = line_caret_x + word_spacing_px; advance_caret!(new_caret_x); line_caret_x = new_caret_x; }, Tab => { let mut new_caret_x = line_caret_x + word_spacing_px + tab_width_px; advance_caret!(new_caret_x); line_caret_x = new_caret_x; }, } } // Handle the last word, but ignore any last Return, Space or Tab characters for word in &words.items[words.items.len().saturating_sub(1)..] { if word.word_type == Word { handle_word!(); } line_breaks.push((current_word_idx, line_caret_x)); } let trailing = line_caret_x; let number_of_lines = line_number + 1; let number_of_words = current_word_idx + 1; let longest_line_width = line_breaks.iter().map(|(_word_idx, line_length)| *line_length).fold(0.0_f32, f32::max); let content_size_y = get_line_y_position(line_number, font_size_px, line_height_px); let content_size_x = text_layout_options.max_horizontal_width.unwrap_or(longest_line_width); let content_size = LayoutSize::new(content_size_x, content_size_y); WordPositions { font_size_px, text_layout_options: text_layout_options.clone(), trailing, number_of_words, number_of_lines, content_size, word_positions, line_breaks, } } pub fn get_layouted_glyphs_unpositioned( word_positions: &WordPositions, scaled_words: &ScaledWords, ) -> LayoutedGlyphs { use text_shaping; let mut glyphs = Vec::with_capacity(scaled_words.items.len()); let letter_spacing_px = word_positions.text_layout_options.letter_spacing.unwrap_or(0.0); for (scaled_word, word_position) in scaled_words.items.iter() .zip(word_positions.word_positions.iter()) { glyphs.extend( text_shaping::get_glyph_instances_hb(&scaled_word.glyph_infos, &scaled_word.glyph_positions) .into_iter() .zip(scaled_word.cluster_iter()) .map(|(mut glyph, cluster_info)| { glyph.point.x += word_position.x; glyph.point.y += word_position.y; glyph.point.x += letter_spacing_px * cluster_info.cluster_idx as f32; glyph }) ) } LayoutedGlyphs { glyphs } } pub fn get_layouted_glyphs_with_horizonal_alignment( word_positions: &WordPositions, scaled_words: &ScaledWords, alignment_horz: StyleTextAlignmentHorz, ) -> (LayoutedGlyphs, LineBreaks) { let mut glyphs = get_layouted_glyphs_unpositioned(word_positions, scaled_words); // Align glyphs horizontal let line_breaks = get_char_indices(&word_positions, &scaled_words); align_text_horz(&mut glyphs.glyphs, alignment_horz, &line_breaks); (glyphs, line_breaks) } /// Returns the final glyphs and positions them relative to the `rect_offset`, /// ready for webrender to display pub fn get_layouted_glyphs( word_positions: &WordPositions, scaled_words: &ScaledWords, alignment_horz: StyleTextAlignmentHorz, alignment_vert: StyleTextAlignmentVert, rect_offset: LayoutPoint, bounding_size_height_px: f32, ) -> LayoutedGlyphs { let (mut glyphs, line_breaks) = get_layouted_glyphs_with_horizonal_alignment(word_positions, scaled_words, alignment_horz); // Align glyphs vertically let vertical_overflow = get_vertical_overflow(&word_positions, bounding_size_height_px); align_text_vert(&mut glyphs.glyphs, alignment_vert, &line_breaks, vertical_overflow); add_origin(&mut glyphs.glyphs, rect_offset.x, rect_offset.y); glyphs } /// Given a width, returns the vertical height and width of the text pub fn get_positioned_word_bounding_box(word_positions: &WordPositions) -> LayoutSize { word_positions.content_size } pub fn get_vertical_overflow(word_positions: &WordPositions, bounding_size_height_px: f32) -> TextOverflow { let content_size = word_positions.content_size; if bounding_size_height_px > content_size.height { TextOverflow::InBounds(bounding_size_height_px - content_size.height) } else { TextOverflow::IsOverflowing(content_size.height - bounding_size_height_px) } } pub fn word_item_is_return(item: &Word) -> bool { item.word_type == WordType::Return } pub fn text_overflow_is_overflowing(overflow: &TextOverflow) -> bool { use self::TextOverflow::*; match overflow { IsOverflowing(_) => true, InBounds(_) => false, } } pub fn get_char_indices(word_positions: &WordPositions, scaled_words: &ScaledWords) -> LineBreaks { let width = word_positions.content_size.width; if scaled_words.items.is_empty() { return Vec::new(); } let mut current_glyph_count = 0; let mut last_word_idx = 0; word_positions.line_breaks.iter().map(|(current_word_idx, line_length)| { let remaining_space_px = width - line_length; let words = &scaled_words.items[last_word_idx..*current_word_idx]; let glyphs_in_this_line: usize = words.iter().map(|w| w.glyph_infos.len()).sum::<usize>(); current_glyph_count += glyphs_in_this_line; last_word_idx = *current_word_idx; (current_glyph_count, remaining_space_px) }).collect() } /// For a given line number (**NOTE: 0-indexed!**), calculates the Y /// position of the bottom left corner pub fn get_line_y_position(line_number: usize, font_size_px: f32, line_height_px: f32) -> f32 { ((font_size_px + line_height_px) * line_number as f32) + font_size_px } #[derive(Debug, Copy, Clone, PartialOrd, PartialEq)] enum LineCaretIntersection { /// OK: Caret does not interset any elements NoIntersection, /// In order to not intersect with any holes, the caret needs to /// be advanced to the position x, but can stay on the same line. AdvanceCaretTo(f32), /// Caret needs to advance X number of lines and be positioned /// with a leading of x PushCaretOntoNextLine(usize, f32), } /// Check if the caret intersects with any holes and if yes, if the cursor should move to a new line. /// /// # Inputs /// /// - `line_caret_x`: The current horizontal caret position /// - `line_number`: The current line number /// - `holes`: Whether the text should respect any rectangular regions /// where the text can't flow (preparation for inline / float layout). /// - `max_width`: Does the text have a restriction on how wide it can be (in pixels) fn caret_intersects_with_holes( line_caret_x: f32, line_number: usize, font_size_px: f32, line_height_px: f32, holes: &[LayoutRect], max_width: Option<f32>, ) -> LineCaretIntersection { let mut new_line_caret_x = None; let mut line_advance = 0; // If the caret is outside of the max_width, move it to the start of a new line if let Some(max_width) = max_width { if line_caret_x > max_width { new_line_caret_x = Some(0.0); line_advance += 1; } } for hole in holes { let mut should_move_caret = false; let mut current_line_advance = 0; let mut new_line_number = line_number + current_line_advance; let mut current_caret = LayoutPoint::new( new_line_caret_x.unwrap_or(line_caret_x), get_line_y_position(new_line_number, font_size_px, line_height_px) ); // NOTE: holes need to be sorted by Y origin (from smallest to largest Y), // and be sorted from left to right while hole.contains(&current_caret) { should_move_caret = true; if let Some(max_width) = max_width { if hole.origin.x + hole.size.width >= max_width { // Need to break the line here current_line_advance += 1; new_line_number = line_number + current_line_advance; current_caret = LayoutPoint::new( new_line_caret_x.unwrap_or(line_caret_x), get_line_y_position(new_line_number, font_size_px, line_height_px) ); } else { new_line_number = line_number + current_line_advance; current_caret = LayoutPoint::new( hole.origin.x + hole.size.width, get_line_y_position(new_line_number, font_size_px, line_height_px) ); } } else { // No max width, so no need to break the line, move the caret to the right side of the hole new_line_number = line_number + current_line_advance; current_caret = LayoutPoint::new( hole.origin.x + hole.size.width, get_line_y_position(new_line_number, font_size_px, line_height_px) ); } } if should_move_caret { new_line_caret_x = Some(current_caret.x); line_advance += current_line_advance; } } if let Some(new_line_caret_x) = new_line_caret_x { if line_advance == 0 { LineCaretIntersection::AdvanceCaretTo(new_line_caret_x) } else { LineCaretIntersection::PushCaretOntoNextLine(line_advance, new_line_caret_x) } } else { LineCaretIntersection::NoIntersection } } fn advance_caret(caret: &mut f32, line_number: &mut usize, intersection: LineCaretIntersection) { use self::LineCaretIntersection::*; match intersection { NoIntersection => { }, AdvanceCaretTo(x) => { *caret = x; }, PushCaretOntoNextLine(num_lines, x) => { *line_number += num_lines; *caret = x; }, } } pub fn align_text_horz( glyphs: &mut [GlyphInstance], alignment: StyleTextAlignmentHorz, line_breaks: &[(usize, f32)] ) { use azul_css::StyleTextAlignmentHorz::*; // Text alignment is theoretically very simple: // // If we have a bunch of text, such as this (the `glyphs`): // ^^^^^^^^^^^^ // ^^^^^^^^ // ^^^^^^^^^^^^^^^^ // ^^^^^^^^^^ // and we have information about how much space each line has to the right: // (the "---" is the space) // ^^^^^^^^^^^^---- // ^^^^^^^^-------- // ^^^^^^^^^^^^^^^^ // ^^^^^^^^^^------ // Then we can center-align the text, by just taking the "-----", dividing // it by 2 and moving all characters to the right: // --^^^^^^^^^^^^-- // ----^^^^^^^^---- // ^^^^^^^^^^^^^^^^ // ---^^^^^^^^^^--- // Same for right-aligned text, but without the "divide by 2 step" if line_breaks.is_empty() || glyphs.is_empty() { return; // ??? maybe a 0-height rectangle? } // // assert that the last info in the line_breaks vec has the same glyph index // // i.e. the last line has to end with the last glyph // assert!(glyphs.len() - 1 == line_breaks[line_breaks.len() - 1].0); let multiply_factor = match alignment { Left => return, Center => 0.5, // move the line by the half width Right => 1.0, // move the line by the full width }; // If we have the characters "ABC\n\nDEF", this will result in: // // [ Glyph(A), Glyph(B), Glyph(C), Glyph(D), Glyph(E), Glyph(F)] // // [LineBreak(2), LineBreak(2), LineBreak(5)] // // If we'd just shift every character after the line break, we'd get into // the problem of shifting the 3rd character twice, because of the \n\n. // // To avoid the double-line-break problem, we can use ranges: // // - from 0..=2, shift the characters at i by X amount // - from 3..3 (e.g. 0 characters) shift the characters at i by X amount // - from 3..=5 shift the characters by X amount // // Because the middle range selects 0 characters, the shift is effectively // ignored, which is what we want - because there are no characters to shift. let mut start_range_char = 0; for (line_break_char, line_break_amount) in line_breaks { // NOTE: Inclusive range - beware: off-by-one-errors! for glyph in &mut glyphs[start_range_char..*line_break_char] { let old_glyph_x = glyph.point.x; glyph.point.x += line_break_amount * multiply_factor; } start_range_char = *line_break_char; // NOTE: beware off-by-one error - note the +1! } } pub fn align_text_vert( glyphs: &mut [GlyphInstance], alignment: StyleTextAlignmentVert, line_breaks: &[(usize, f32)], vertical_overflow: TextOverflow, ){ use self::TextOverflow::*; use self::StyleTextAlignmentVert::*; if line_breaks.is_empty() || glyphs.is_empty() { return; } // // Die if we have a line break at a position bigger than the position of the last glyph, // // because something went horribly wrong! // // // // The next unwrap is always safe as line_breaks will have a minimum of one entry! // assert!(glyphs.len() - 1 == line_breaks.last().unwrap().0); let multiply_factor = match alignment { Top => return, Center => 0.5, Bottom => 1.0, }; let space_to_add = match vertical_overflow { IsOverflowing(_) => return, InBounds(remaining_space_px) => { // Total text height (including last leading!) // All metrics in pixels (remaining_space_px * multiply_factor) }, }; glyphs.iter_mut().for_each(|g| g.point.y += space_to_add); } /// Adds the X and Y offset to each glyph in the positioned glyph pub fn add_origin(positioned_glyphs: &mut [GlyphInstance], x: f32, y: f32) { for c in positioned_glyphs { c.point.x += x; c.point.y += y; } } #[test] fn test_split_words() { fn print_words(w: &Words) { println!("-- string: {:?}", w.get_str()); for item in &w.items { println!("{:?} - ({}..{}) = {:?}", w.get_substr(item), item.start, item.end, item.word_type); } } fn string_to_vec(s: String) -> Vec<char> { s.chars().collect() } fn assert_words(expected: &Words, got_words: &Words) { for (idx, expected_word) in expected.items.iter().enumerate() { let got = got_words.items.get(idx); if got != Some(expected_word) { println!("expected: "); print_words(expected); println!("got: "); print_words(got_words); panic!("Expected word idx {} - expected: {:#?}, got: {:#?}", idx, Some(expected_word), got); } } } let ascii_str = String::from("abc\tdef \nghi\r\njkl"); let words_ascii = split_text_into_words(&ascii_str); let words_ascii_expected = Words { internal_str: ascii_str.clone(), internal_chars: string_to_vec(ascii_str), items: vec![ Word { start: 0, end: 3, word_type: WordType::Word }, // "abc" - (0..3) = Word Word { start: 3, end: 4, word_type: WordType::Tab }, // "\t" - (3..4) = Tab Word { start: 4, end: 7, word_type: WordType::Word }, // "def" - (4..7) = Word Word { start: 7, end: 8, word_type: WordType::Space }, // " " - (7..8) = Space Word { start: 8, end: 9, word_type: WordType::Space }, // " " - (8..9) = Space Word { start: 9, end: 10, word_type: WordType::Return }, // "\n" - (9..10) = Return Word { start: 10, end: 13, word_type: WordType::Word }, // "ghi" - (10..13) = Word Word { start: 13, end: 15, word_type: WordType::Return }, // "\r\n" - (13..15) = Return Word { start: 15, end: 18, word_type: WordType::Word }, // "jkl" - (15..18) = Word ], }; assert_words(&words_ascii_expected, &words_ascii); let unicode_str = String::from("㌊㌋㌌㌍㌎㌏㌐㌑ ㌒㌓㌔㌕㌖㌗"); let words_unicode = split_text_into_words(&unicode_str); let words_unicode_expected = Words { internal_str: unicode_str.clone(), internal_chars: string_to_vec(unicode_str), items: vec![ Word { start: 0, end: 8, word_type: WordType::Word }, // "㌊㌋㌌㌍㌎㌏㌐㌑" Word { start: 8, end: 9, word_type: WordType::Space }, // " " Word { start: 9, end: 15, word_type: WordType::Word }, // "㌒㌓㌔㌕㌖㌗" ], }; assert_words(&words_unicode_expected, &words_unicode); let single_str = String::from("A"); let words_single_str = split_text_into_words(&single_str); let words_single_str_expected = Words { internal_str: single_str.clone(), internal_chars: string_to_vec(single_str), items: vec![ Word { start: 0, end: 1, word_type: WordType::Word }, // "A" ], }; assert_words(&words_single_str_expected, &words_single_str); } #[test] fn test_get_line_y_position() { assert_eq!(get_line_y_position(0, 20.0, 0.0), 20.0); assert_eq!(get_line_y_position(1, 20.0, 0.0), 40.0); assert_eq!(get_line_y_position(2, 20.0, 0.0), 60.0); // lines: // 0 - height 20, padding 5 = 20.0 (padding is for the next line) // 1 - height 20, padding 5 = 45.0 ( = 20 + 20 + 5) // 2 - height 20, padding 5 = 70.0 ( = 20 + 20 + 5 + 20 + 5) assert_eq!(get_line_y_position(0, 20.0, 5.0), 20.0); assert_eq!(get_line_y_position(1, 20.0, 5.0), 45.0); assert_eq!(get_line_y_position(2, 20.0, 5.0), 70.0); } // Scenario 1: // // +---------+ // |+ ------>|+ // | | // +---------+ // rectangle: 100x200 // max-width: none, line-height 1.0, font-size: 20 // cursor is at: 0x, 20y // expect cursor to advance to 100x, 20y // #[test] fn test_caret_intersects_with_holes_1() { let line_caret_x = 0.0; let line_number = 0; let font_size_px = 20.0; let line_height_px = 0.0; let max_width = None; let holes = vec![LayoutRect::new(LayoutPoint::new(0.0, 0.0), LayoutSize::new(200.0, 100.0))]; let result = caret_intersects_with_holes( line_caret_x, line_number, font_size_px, line_height_px, &holes, max_width, ); assert_eq!(result, LineCaretIntersection::AdvanceCaretTo(200.0)); } // Scenario 2: // // +---------+ // |+ -----> | // |-------> | // |---------| // |+ | // | | // +---------+ // rectangle: 100x200 // max-width: 200px, line-height 1.0, font-size: 20 // cursor is at: 0x, 20y // expect cursor to advance to 0x, 100y (+= 4 lines) // #[test] fn test_caret_intersects_with_holes_2() { let line_caret_x = 0.0; let line_number = 0; let font_size_px = 20.0; let line_height_px = 0.0; let max_width = Some(200.0); let holes = vec![LayoutRect::new(LayoutPoint::new(0.0, 0.0), LayoutSize::new(200.0, 100.0))]; let result = caret_intersects_with_holes( line_caret_x, line_number, font_size_px, line_height_px, &holes, max_width, ); assert_eq!(result, LineCaretIntersection::PushCaretOntoNextLine(4, 0.0)); } // Scenario 3: // // +----------------+ // | | | +-----> // |------->+ | // |------+ | // | | // | | // +----------------+ // rectangle: 100x200 // max-width: 400px, line-height 1.0, font-size: 20 // cursor is at: 450x, 20y // expect cursor to advance to 200x, 40y (+= 1 lines, leading of 200px) // #[test] fn test_caret_intersects_with_holes_3() { let line_caret_x = 450.0; let line_number = 0; let font_size_px = 20.0; let line_height_px = 0.0; let max_width = Some(400.0); let holes = vec![LayoutRect::new(LayoutPoint::new(0.0, 0.0), LayoutSize::new(200.0, 100.0))]; let result = caret_intersects_with_holes( line_caret_x, line_number, font_size_px, line_height_px, &holes, max_width, ); assert_eq!(result, LineCaretIntersection::PushCaretOntoNextLine(1, 200.0)); } // Scenario 4: // // +----------------+ // | + +------+ | // | | | | // | | | | // | +------+ | // | | // +----------------+ // rectangle: 100x200 @ 80.0x, 20.0y // max-width: 400px, line-height 1.0, font-size: 20 // cursor is at: 40x, 20y // expect cursor to not advance at all // #[test] fn test_caret_intersects_with_holes_4() { let line_caret_x = 40.0; let line_number = 0; let font_size_px = 20.0; let line_height_px = 0.0; let max_width = Some(400.0); let holes = vec![LayoutRect::new(LayoutPoint::new(80.0, 20.0), LayoutSize::new(200.0, 100.0))]; let result = caret_intersects_with_holes( line_caret_x, line_number, font_size_px, line_height_px, &holes, max_width, ); assert_eq!(result, LineCaretIntersection::NoIntersection); }
// Copyright 2013-2017, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> #![allow(unused_imports)] #[macro_use] extern crate bitflags; #[macro_use] extern crate lazy_static; #[macro_use] extern crate glib; extern crate glib_sys; extern crate gobject_sys; extern crate gtk; extern crate javascriptcore_sys; extern crate libc; pub use javascriptcore_sys::*; macro_rules! assert_initialized_main_thread { () => { if !::gtk::is_initialized_main_thread() { if ::gtk::is_initialized() { //panic!("GTK may only be used from the main thread."); } else { panic!("GTK has not been initialized. Call `gtk::init` first."); } } }; } macro_rules! skip_assert_initialized { () => {}; } mod auto; mod class; mod class_vtable; mod context; mod function; mod global_context_ref; mod value; mod value_ref; pub use crate::auto::*; pub use crate::class::*; pub use crate::class_vtable::*; pub use crate::context::*; pub use crate::global_context_ref::*; pub use crate::value::*; pub use crate::value_ref::*;
use std::ops::Deref; use std::str; use ::bytes::{Bytes, BytesMut, IntoBuf, Buf, BufMut, BigEndian}; use ::enum_primitive::FromPrimitive; use super::types::*; use super::Header; use ::errors::{Result, ErrorKind, ResultExt}; pub struct ConnectFlags(ConnFlags); impl From<ConnFlags> for ConnectFlags { fn from(flags: ConnFlags) -> ConnectFlags { ConnectFlags(flags) } } impl Deref for ConnectFlags { type Target = ConnFlags; fn deref(&self) -> &ConnFlags { &self.0 } } impl Header for ConnectFlags { fn header_name() -> &'static str { "connect_flags" } fn parse_header(raw: &Bytes) -> Result<ConnectFlags> { ConnFlags::from_bits(raw.into_buf().get_u8()).map(|f| ConnectFlags(f)) .ok_or(ErrorKind::PacketDecodingError.into()) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u8(self.bits()); Ok(()) } } pub struct ConnectAckFlags(ConnAckFlags); impl From<ConnAckFlags> for ConnectAckFlags { fn from(flags: ConnAckFlags) -> ConnectAckFlags { ConnectAckFlags(flags) } } impl Deref for ConnectAckFlags { type Target = ConnAckFlags; fn deref(&self) -> &ConnAckFlags { &self.0 } } impl Header for ConnectAckFlags { fn header_name() -> &'static str { "connect_ack_flags" } fn parse_header(raw: &Bytes) -> Result<ConnectAckFlags> { ConnAckFlags::from_bits(raw.into_buf().get_u8()).map(|f| ConnectAckFlags(f)) .ok_or(ErrorKind::PacketDecodingError.into()) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u8(self.bits()); Ok(()) } } pub struct ConnectReturnCode(ConnRetCode); impl From<ConnRetCode> for ConnectReturnCode { fn from(code: ConnRetCode) -> ConnectReturnCode { ConnectReturnCode(code) } } impl Deref for ConnectReturnCode { type Target = ConnRetCode; fn deref(&self) -> &ConnRetCode { &self.0 } } impl Header for ConnectReturnCode { fn header_name() -> &'static str { "connect_return_code" } fn parse_header(raw: &Bytes) -> Result<ConnectReturnCode> { ConnRetCode::from_u8(raw.into_buf().get_u8()).map(|c| ConnectReturnCode(c)) .ok_or(ErrorKind::PacketDecodingError.into()) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u8(self.as_u8()); Ok(()) } } #[derive(Clone, Eq, PartialEq, Hash)] pub struct PacketId(u16); impl Deref for PacketId { type Target = u16; fn deref(&self) -> &u16 { &self.0 } } impl From<u16> for PacketId { fn from(value: u16) -> Self { PacketId(value) } } impl Header for PacketId { fn header_name() -> &'static str { "packet_id" } fn parse_header(raw: &Bytes) -> Result<PacketId> { if raw.len() < 2 { bail!(ErrorKind::PacketDecodingError) } else { Ok(PacketId(raw.into_buf().get_u16::<BigEndian>())) } } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u16::<BigEndian>(self.0); Ok(()) } } pub struct KeepAlive(u16); impl From<u16> for KeepAlive { fn from(ka: u16) -> KeepAlive { KeepAlive(ka) } } impl Deref for KeepAlive { type Target = u16; fn deref(&self) -> &u16 { &self.0 } } impl Header for KeepAlive { fn header_name() -> &'static str { "keep_alive" } fn parse_header(raw: &Bytes) -> Result<KeepAlive> { if raw.len() < 2 { bail!(ErrorKind::PacketDecodingError) } else { Ok(KeepAlive(raw.into_buf().get_u16::<BigEndian>())) } } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u16::<BigEndian>(self.0); Ok(()) } } pub struct ProtocolLevel(ProtoLvl); impl From<ProtoLvl> for ProtocolLevel { fn from(level: ProtoLvl) -> ProtocolLevel { ProtocolLevel(level) } } impl Deref for ProtocolLevel { type Target = ProtoLvl; fn deref(&self) -> &ProtoLvl { &self.0 } } impl Header for ProtocolLevel { fn header_name() -> &'static str { "protocol_level" } fn parse_header(raw: &Bytes) -> Result<ProtocolLevel> { ProtoLvl::from_u8(raw.into_buf().get_u8()).map(|c| ProtocolLevel(c)) .ok_or(ErrorKind::PacketDecodingError.into()) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { out.put_u8(self.as_u8()); Ok(()) } } pub struct ProtocolName(MqttString); impl From<MqttString> for ProtocolName { fn from(value: MqttString) -> Self { ProtocolName(value) } } impl Deref for ProtocolName { type Target = MqttString; fn deref(&self) -> &MqttString { &self.0 } } impl Header for ProtocolName { fn header_name() -> &'static str { "protocol_name" } fn parse_header(raw: &Bytes) -> Result<ProtocolName> { str::from_utf8(raw) .chain_err(|| ErrorKind::StringConversionError) .and_then(|s| MqttString::from_str(s)) .map(|s| ProtocolName(s)) .chain_err(|| ErrorKind::PacketDecodingError) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { self.encode(out); Ok(()) } } pub struct TopicName(MqttString); impl From<MqttString> for TopicName { fn from(value: MqttString) -> Self { TopicName(value) } } impl Deref for TopicName { type Target = MqttString; fn deref(&self) -> &MqttString { &self.0 } } impl Header for TopicName { fn header_name() -> &'static str { "topic_name" } fn parse_header(raw: &Bytes) -> Result<TopicName> { str::from_utf8(raw) .chain_err(|| ErrorKind::StringConversionError) .and_then(|t| MqttString::from_str(t)) .map(|s| TopicName(s)) .chain_err(|| ErrorKind::PacketDecodingError) } fn fmt_header(&self, out: &mut BytesMut) -> Result<()> { self.encode(out); Ok(()) } }