text
stringlengths
8
4.13M
use proconio::{fastout, input}; #[fastout] fn main() { input! { k: i64, }; let kk = if k % 7 == 0 { k * 9 / 7 } else { k * 9 }; let mut ans = -1; let mut temp = 1; for i in 1..=9000_000 { temp = temp * 10 % kk; if temp == 1 { ans = i; break; } } println!("{}", ans); }
use serde::{Deserialize, Serialize}; use planetr::wasm::Context; use planetr::wasm::PlanetrError; #[derive(Deserialize, Serialize)] pub struct InputPayload { // Define input payload JSON structure HERE name: String, } #[derive(Deserialize, Serialize)] pub struct OuputPayload { // Define output payload JSON structure HERE hello: String, } pub fn handle_req(args: InputPayload, ctx: Context) -> Result<OuputPayload, PlanetrError> { // ----------------------------- // Sample code. Edit Below. // ----------------------------- //error condition if args.name == "" { return Err(PlanetrError::new("missing name field in request")); } //HTTP request feature... /* let resp = match ctx.http_get("https://planetr.io"){ Ok(resp) => resp, Err(err) => return Err(err) }; */ //Log ctx.log(format!("Name={}", args.name)); //convert to upper case and respond Hello... Ok(OuputPayload{ hello: format!("Hello {}", args.name).to_string(), }) }
// https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/boxing_errors.html type Er = Box<dyn std::error::Error>; #[derive(Debug)] struct CustomError; impl std::fmt::Display for CustomError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "custom error is here") } } impl std::error::Error for CustomError { } fn mayfail(i: i32) -> Result<(), Er> { if i > 10 { return Err(CustomError.into()); } if i > 0 { return Ok(()); } return Err("oops".into()); } fn main() { println!("-1: {:?}", mayfail(-1)); println!("1: {:?}", mayfail(1)); }
use libc::{c_char, c_uint, c_ulong, c_void, size_t, ssize_t, time_t}; use H5Ipublic::hid_t; use H5public::{H5_ih_info_t, H5_index_t, H5_iter_order_t, haddr_t, herr_t, hsize_t, htri_t}; #[derive(Clone, Copy, Debug)] #[repr(C)] pub enum H5O_type_t { H5O_TYPE_UNKNOWN = -1, H5O_TYPE_GROUP, H5O_TYPE_DATASET, H5O_TYPE_NAMED_DATATYPE, H5O_TYPE_NTYPES, } pub use self::H5O_type_t::*; #[derive(Debug)] #[repr(C)] pub struct H5O_hdr_info_space_t { pub total: hsize_t, pub meta: hsize_t, pub mesg: hsize_t, pub free: hsize_t, } #[derive(Debug)] #[repr(C)] pub struct H5O_hdr_info_mesg_t { pub present: u64, pub shared: u64, } #[derive(Debug)] #[repr(C)] pub struct H5O_hdr_info_t { pub version: c_uint, pub nmesgs: c_uint, pub nchunks: c_uint, pub flags: c_uint, pub space: H5O_hdr_info_space_t, pub mesg: H5O_hdr_info_mesg_t, } #[derive(Debug)] #[repr(C)] pub struct H5O_info_meta_size_t { pub obj: H5_ih_info_t, pub attr: H5_ih_info_t, } #[derive(Debug)] #[repr(C)] pub struct H5O_info_t { pub fileno: c_ulong, pub addr: haddr_t, pub info_type: H5O_type_t, pub rc: c_uint, pub atime: time_t, pub mtime: time_t, pub ctime: time_t, pub btime: time_t, pub num_attrs: hsize_t, pub hdr: H5O_hdr_info_t, pub meta_size: H5O_info_meta_size_t, } pub type H5O_msg_crt_idx_t = u32; pub type H5O_iterate_t = extern "C" fn(hid_t, *const c_char, *const H5O_info_t, *mut c_void) -> herr_t; #[derive(Clone, Copy, Debug)] #[repr(C)] pub enum H5O_mcdt_search_ret_t { H5O_MCDT_SEARCH_ERROR = -1, H5O_MCDT_SEARCH_CONT, H5O_MCDT_SEARCH_STOP, } pub use self::H5O_mcdt_search_ret_t::*; pub type H5O_mcdt_search_cb_t = extern "C" fn(*mut c_void) -> H5O_mcdt_search_ret_t; extern "C" { pub fn H5Oopen(loc_id: hid_t, name: *const c_char, lapl_id: hid_t) -> hid_t; pub fn H5Oopen_by_idx(loc_id: hid_t, group_name: *const c_char, index_type: H5_index_t, order: H5_iter_order_t, n: hsize_t, lapl_id: hid_t) -> hid_t; pub fn H5Oopen_by_addr(loc_id: hid_t, addr: haddr_t) -> hid_t; pub fn H5Olink(object_id: hid_t, new_loc_id: hid_t, new_link_name: *const c_char, lcpl: hid_t, lapl: hid_t) -> herr_t; pub fn H5Oclose(object_id: hid_t) -> herr_t; pub fn H5Ocopy(src_loc_id: hid_t, src_name: *const c_char, dst_loc_id: hid_t, dst_name: *const c_char, ocpypl_id: hid_t, lcpl_id: hid_t) -> herr_t; pub fn H5Ovisit(object_id: hid_t, index_type: H5_index_t, order: H5_iter_order_t, op: H5O_iterate_t, op_data: *const c_void) -> herr_t; pub fn H5Ovisit_by_name(loc_id: hid_t, object_name: *const c_char, index_type: H5_index_t, order: H5_iter_order_t, op: H5O_iterate_t, op_data: *const c_void, lapl_id: hid_t) -> herr_t; pub fn H5Oget_comment(object_id: hid_t, comment: *mut c_char, bufsize: size_t) -> ssize_t; pub fn H5Oget_comment_by_name(loc_id: hid_t, name: *const c_char, comment: *mut c_char, bufsize: size_t, lapl_id: hid_t) -> ssize_t; pub fn H5Oexists_by_name(loc_id: hid_t, name: *const c_char, lapl_id: hid_t) -> htri_t; pub fn H5Oget_info(object_id: hid_t, object_info: *mut H5O_info_t) -> herr_t; pub fn H5Oget_info_by_name(loc_id: hid_t, object_name: *const c_char, object_info: *mut H5O_info_t, lapl_id: hid_t) -> herr_t; pub fn H5Oget_info_by_idx(loc_id: hid_t, group_name: *const c_char, index_field: H5_index_t, order: H5_iter_order_t, n: hsize_t, object_info: *mut H5O_info_t, lapl_id: hid_t) -> herr_t; pub fn H5Oincr_refcount(object_id: hid_t) -> herr_t; pub fn H5Odecr_refcount(object_id: hid_t) -> herr_t; }
#![no_std] #![no_main] use core::panic::PanicInfo; use cortex_m_rt::{entry, exception}; use stm32f7::stm32f7x6::{CorePeripherals, Peripherals}; use stm32f746g_disc::{ gpio::{GpioPort, OutputPin}, init, system_clock::{self, Hz}, }; #[entry] fn main() -> ! { let core_peripherals = CorePeripherals::take().unwrap(); let mut systick = core_peripherals.SYST; let peripherals = Peripherals::take().unwrap(); let mut rcc = peripherals.RCC; let mut pwr = peripherals.PWR; let mut flash = peripherals.FLASH; init::init_system_clock_216mhz(&mut rcc, &mut pwr, &mut flash); init::enable_gpio_ports(&mut rcc); let gpio_a = GpioPort::new(peripherals.GPIOA); let gpio_b = GpioPort::new(peripherals.GPIOB); let gpio_c = GpioPort::new(peripherals.GPIOC); let gpio_d = GpioPort::new(peripherals.GPIOD); let gpio_e = GpioPort::new(peripherals.GPIOE); let gpio_f = GpioPort::new(peripherals.GPIOF); let gpio_g = GpioPort::new(peripherals.GPIOG); let gpio_h = GpioPort::new(peripherals.GPIOH); let gpio_i = GpioPort::new(peripherals.GPIOI); let gpio_j = GpioPort::new(peripherals.GPIOJ); let gpio_k = GpioPort::new(peripherals.GPIOK); let mut pins = init::pins( gpio_a, gpio_b, gpio_c, gpio_d, gpio_e, gpio_f, gpio_g, gpio_h, gpio_i, gpio_j, gpio_k, ); // configure the systick timer 20Hz (20 ticks per second) init::init_systick(Hz(20), &mut systick, &rcc); systick.enable_interrupt(); // turn led on pins.led.set(true); let mut last_led_toggle = system_clock::ticks(); loop { let ticks = system_clock::ticks(); // every 0.5 seconds (we have 20 ticks per second) if ticks - last_led_toggle >= 10 { pins.led.toggle(); last_led_toggle = ticks; } } } #[exception] fn SysTick() { system_clock::tick(); } #[panic_handler] fn panic(info: &PanicInfo) -> ! { use core::fmt::Write; use cortex_m::asm; use cortex_m_semihosting::hio; if let Ok(mut hstdout) = hio::hstdout() { let _ = writeln!(hstdout, "{}", info); } // OK to fire a breakpoint here because we know the microcontroller is connected to a debugger asm::bkpt(); loop {} }
pub mod cr1 { pub mod arpe { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40001400u32 as *const u32) >> 7) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001400u32 as *const u32); reg &= 0xFFFFFF7Fu32; reg |= (val & 0x1) << 7; core::ptr::write_volatile(0x40001400u32 as *mut u32, reg); } } } pub mod opm { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40001400u32 as *const u32) >> 3) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001400u32 as *const u32); reg &= 0xFFFFFFF7u32; reg |= (val & 0x1) << 3; core::ptr::write_volatile(0x40001400u32 as *mut u32, reg); } } } pub mod urs { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40001400u32 as *const u32) >> 2) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001400u32 as *const u32); reg &= 0xFFFFFFFBu32; reg |= (val & 0x1) << 2; core::ptr::write_volatile(0x40001400u32 as *mut u32, reg); } } } pub mod udis { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40001400u32 as *const u32) >> 1) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001400u32 as *const u32); reg &= 0xFFFFFFFDu32; reg |= (val & 0x1) << 1; core::ptr::write_volatile(0x40001400u32 as *mut u32, reg); } } } pub mod cen { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40001400u32 as *const u32) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001400u32 as *const u32); reg &= 0xFFFFFFFEu32; reg |= val & 0x1; core::ptr::write_volatile(0x40001400u32 as *mut u32, reg); } } } } pub mod cr2 { pub mod mms { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x40001404u32 as *const u32) >> 4) & 0x7 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001404u32 as *const u32); reg &= 0xFFFFFF8Fu32; reg |= (val & 0x7) << 4; core::ptr::write_volatile(0x40001404u32 as *mut u32, reg); } } } } pub mod dier { pub mod ude { pub fn get() -> u32 { unsafe { (core::ptr::read_volatile(0x4000140Cu32 as *const u32) >> 8) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x4000140Cu32 as *const u32); reg &= 0xFFFFFEFFu32; reg |= (val & 0x1) << 8; core::ptr::write_volatile(0x4000140Cu32 as *mut u32, reg); } } } pub mod uie { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x4000140Cu32 as *const u32) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x4000140Cu32 as *const u32); reg &= 0xFFFFFFFEu32; reg |= val & 0x1; core::ptr::write_volatile(0x4000140Cu32 as *mut u32, reg); } } } } pub mod sr { pub mod uif { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40001410u32 as *const u32) & 0x1 } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001410u32 as *const u32); reg &= 0xFFFFFFFEu32; reg |= val & 0x1; core::ptr::write_volatile(0x40001410u32 as *mut u32, reg); } } } } pub mod egr { pub mod ug { pub fn set(val: u32) { unsafe { let reg = val & 0x1; core::ptr::write_volatile(0x40001414u32 as *mut u32, reg); } } } } pub mod cnt { pub mod cnt { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40001424u32 as *const u32) & 0xFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001424u32 as *const u32); reg &= 0xFFFF0000u32; reg |= val & 0xFFFF; core::ptr::write_volatile(0x40001424u32 as *mut u32, reg); } } } } pub mod psc { pub mod psc { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x40001428u32 as *const u32) & 0xFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x40001428u32 as *const u32); reg &= 0xFFFF0000u32; reg |= val & 0xFFFF; core::ptr::write_volatile(0x40001428u32 as *mut u32, reg); } } } } pub mod arr { pub mod arr { pub fn get() -> u32 { unsafe { core::ptr::read_volatile(0x4000142Cu32 as *const u32) & 0xFFFF } } pub fn set(val: u32) { unsafe { let mut reg = core::ptr::read_volatile(0x4000142Cu32 as *const u32); reg &= 0xFFFF0000u32; reg |= val & 0xFFFF; core::ptr::write_volatile(0x4000142Cu32 as *mut u32, reg); } } } }
use pairing::{Engine, Field, PrimeField, CurveAffine, CurveProjective}; use crate::srs::SRS; use crate::utils::*; /// An additional elements in our shared information pub struct SrsPerm<E: Engine> { n: usize, p_1: E::G1Affine, p_2: Vec<E::G1Affine>, p_3: E::G1Affine, p_4: Vec<E::G1Affine>, } impl<E: Engine> SrsPerm<E> { pub fn gen_from_coeffs( non_permuted_coeffs: &Vec<Vec<E::Fr>>, perms: &Vec<Vec<usize>>, srs: &SRS<E>, ) -> Self { assert!(!non_permuted_coeffs.is_empty()); assert!(non_permuted_coeffs.len() == perms.len()); let n = non_permuted_coeffs[0].len(); // A commitment to the powers of x which is the srs's randomness let p_1 = multiexp( srs.g_pos_x_alpha[..n].iter(), vec![E::Fr::one(); n].iter() ).into_affine(); let p_3 = { let vals: Vec<E::Fr> = (1..=n).map(|e| { let mut repr = <<E as Engine>::Fr as PrimeField>::Repr::default(); repr.as_mut()[0] = e as u64; let re = E::Fr::from_repr(repr).unwrap(); re }).collect(); multiexp( srs.g_pos_x_alpha[0..n].iter(), vals.iter() ).into_affine() }; let mut p_2 = vec![]; let mut p_4 = vec![]; for (coeff, perm) in non_permuted_coeffs.iter().zip(perms.iter()) { assert_eq!(coeff.len(), perm.len()); let p2_el = multiexp( srs.g_pos_x_alpha[..n].iter(), coeff.iter() ).into_affine(); p_2.push(p2_el); let vals: Vec<E::Fr> = perm.iter().map(|e| { let mut repr = <<E as Engine>::Fr as PrimeField>::Repr::default(); repr.as_mut()[0] = *e as u64; let re = E::Fr::from_repr(repr).unwrap(); re }).collect(); let p4_el = multiexp( srs.g_pos_x_alpha[..n].iter(), vals.iter() ).into_affine(); p_4.push(p4_el); } SrsPerm { n, p_1, p_2, p_3, p_4, } } } pub struct ProofSCC<E: Engine> { j: usize, s_opening: E::G1Affine, s_zy: E::G1Affine, } pub struct PermutationArgument<E: Engine> { n: usize, non_permuted_coeffs: Vec<Vec<E::Fr>>, permutated_coeffs: Vec<Vec<E::Fr>>, permutated_y_coeffs: Vec<Vec<E::Fr>>, perms: Vec<Vec<usize>>, } impl<E: Engine> PermutationArgument<E> { pub fn new(coeffs: Vec<Vec<E::Fr>>, perms: Vec<Vec<usize>>) -> Self { assert!(!coeffs.is_empty()); assert_eq!(coeffs.len(), perms.len()); unimplemented!(); } pub fn commit(&mut self, y: E::Fr, srs: &SRS<E>) -> Vec<(E::G1Affine, E::G1Affine)> { // let acc = vec![]; // let mut permutated_coeffs = vec![]; // let mut permutated_y_coeffs = vec![]; // for (coeffs, perm) for self.non_permuted_coeffs.iter().zip(self.perms.iter()) { // eval_bivar_poly(coeffs: &mut [E::Fr], first_power: E::Fr, base: E::Fr) // } unimplemented!(); } pub fn gen_perm_arg( &self, beta: E::Fr, gamma: E::Fr, srs: &SRS<E>, y: E::Fr, z: E::Fr, srs_perm: &SrsPerm<E>, ) -> ProofSCC<E> { unimplemented!(); } } fn permute<E: Engine>(coeffs: &[E::Fr], perm: &[usize]) -> Vec<E::Fr> { assert_eq!(coeffs.len(), perm.len()); let mut res = vec![E::Fr::zero(); coeffs.len()]; for (i, j) in perm.iter().enumerate() { res[*j - 1] = coeffs[i]; } res }
// FIPS-180-2 compliant SHA-256 implementation // // The SHA-256 Secure Hash Standard was published by NIST in 2002. // <http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf> use cfg_if::cfg_if; use core::convert::TryFrom; cfg_if! { if #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), not(feature = "force-soft")))] { mod x86; cfg_if! { if #[cfg(target_feature = "sha")] { // Optimize with SHA-NI #[inline] fn transform(state: &mut [u32; 8], block: &[u8]) { x86::transform(state, block) } } else { mod generic; // If compile without `+sha` then we will check for `sha` feature in runtime. // FIXME: It will have performance lost. We should find a better way. #[inline] fn transform(state: &mut [u32; 8], block: &[u8]) { if std::is_x86_feature_detected!("sha") { x86::transform(state, block) } else { generic::transform(state, block) } } } } } else if #[cfg(all(target_arch = "aarch64", not(feature = "force-soft")))] { mod aarch64; cfg_if! { if #[cfg(target_feature = "sha2")] { fn transform(state: &mut [u32; 8], block: &[u8]) { aarch64::transform(state, block) } } else { mod generic; fn transform(state: &mut [u32; 8], block: &[u8]) { if std::is_aarch64_feature_detected!("sha2") { aarch64::transform(state, block) } else { generic::transform(state, block) } } } } } else { mod generic; #[inline] fn transform(state: &mut [u32; 8], block: &[u8]) { generic::transform(state, block) } } } // Round constants const K32: [u32; 64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; const INITIAL_STATE: [u32; 8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, ]; /// SHA2-224 pub fn sha224<T: AsRef<[u8]>>(data: T) -> [u8; Sha224::DIGEST_LEN] { Sha224::oneshot(data) } /// SHA2-256 pub fn sha256<T: AsRef<[u8]>>(data: T) -> [u8; Sha256::DIGEST_LEN] { Sha256::oneshot(data) } /// A 224-bit One-way Hash Function: SHA-224 /// /// <https://tools.ietf.org/html/rfc3874> #[derive(Clone)] pub struct Sha224 { inner: Sha256, } impl Sha224 { pub const BLOCK_LEN: usize = 64; pub const DIGEST_LEN: usize = 28; pub fn new() -> Self { const SHA_224_INITIAL_STATE: [u32; 8] = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, ]; Self { inner: Sha256 { buffer: [0u8; 64], state: SHA_224_INITIAL_STATE, len: 0, offset: 0, }, } } pub fn update(&mut self, data: &[u8]) { self.inner.update(data); } pub fn finalize(self) -> [u8; Self::DIGEST_LEN] { let mut digest = [0u8; Self::DIGEST_LEN]; digest.copy_from_slice(&self.inner.finalize()[..Self::DIGEST_LEN]); digest } pub fn oneshot<T: AsRef<[u8]>>(data: T) -> [u8; Self::DIGEST_LEN] { let mut m = Self::new(); m.update(data.as_ref()); m.finalize() } } /// SHA2-256 #[derive(Clone)] pub struct Sha256 { buffer: [u8; Self::BLOCK_LEN], state: [u32; 8], len: u64, // in bytes. offset: usize, } impl Sha256 { pub const BLOCK_LEN: usize = 64; pub const DIGEST_LEN: usize = 32; const BLOCK_LEN_BITS: u64 = Self::BLOCK_LEN as u64 * 8; const MLEN_SIZE: usize = core::mem::size_of::<u64>(); const MLEN_SIZE_BITS: u64 = Self::MLEN_SIZE as u64 * 8; const MAX_PAD_LEN: usize = Self::BLOCK_LEN + Self::MLEN_SIZE as usize; pub fn new() -> Self { Self { buffer: [0u8; 64], state: INITIAL_STATE, len: 0, offset: 0, } } pub fn update(&mut self, data: &[u8]) { let mut i = 0usize; while i < data.len() { if self.offset < Self::BLOCK_LEN { self.buffer[self.offset] = data[i]; self.offset += 1; i += 1; } if self.offset == Self::BLOCK_LEN { transform(&mut self.state, &self.buffer); self.offset = 0; self.len += Self::BLOCK_LEN as u64; } } } pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] { // 5. PREPROCESSING // 5.1 Padding the Message // 5.1.1 SHA-1 and SHA-256 // 5.1.2 SHA-384 and SHA-512 // https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf // // 423 bits 64 bits or 128 bits // ------- ----------- // 01100001 01100010 01100011 1 00...00 00...011000 // -------- -------- -------- ----------- // "a" "b" "c" L = 24 bits ๏ผˆๅคง็ซฏๅบ๏ผ‰ // let mlen = self.len + self.offset as u64; // in bytes let mlen_bits = mlen * 8; // in bits // pad len, in bits let plen_bits = Self::BLOCK_LEN_BITS - (mlen_bits + Self::MLEN_SIZE_BITS + 1) % Self::BLOCK_LEN_BITS + 1; // pad len, in bytes let plen = plen_bits / 8; debug_assert_eq!(plen_bits % 8, 0); debug_assert!(plen > 1); debug_assert_eq!( (mlen + plen + Self::MLEN_SIZE as u64) % Self::BLOCK_LEN as u64, 0 ); // NOTE: MAX_PAD_LEN ๆ˜ฏไธ€ไธชๅพˆๅฐ็š„ๆ•ฐๅญ—๏ผŒๆ‰€ไปฅ่ฟ™้‡Œๅฏไปฅๅฎ‰ๅ…จ็š„ unwrap. let plen = usize::try_from(plen).unwrap(); let mut padding: [u8; Self::MAX_PAD_LEN] = [0u8; Self::MAX_PAD_LEN]; padding[0] = 0x80; let mlen_octets: [u8; Self::MLEN_SIZE] = mlen_bits.to_be_bytes(); padding[plen..plen + Self::MLEN_SIZE].copy_from_slice(&mlen_octets); let data = &padding[..plen + Self::MLEN_SIZE]; self.update(data); // NOTE: ๆ•ฐๆฎๅกซๅ……ๅฎŒๆฏ•ๅŽ๏ผŒๆญคๆ—ถๅทฒ็ปๅค„็†็š„ๆถˆๆฏๅบ”่ฏฅๆ˜ฏ BLOCK_LEN ็š„ๅ€ๆ•ฐ๏ผŒๅ› ๆญค๏ผŒoffset ๆญคๆ—ถๅทฒ่ขซๆธ…้›ถใ€‚ debug_assert_eq!(self.offset, 0); let mut output = [0u8; Self::DIGEST_LEN]; output[0..4].copy_from_slice(&self.state[0].to_be_bytes()); output[4..8].copy_from_slice(&self.state[1].to_be_bytes()); output[8..12].copy_from_slice(&self.state[2].to_be_bytes()); output[12..16].copy_from_slice(&self.state[3].to_be_bytes()); output[16..20].copy_from_slice(&self.state[4].to_be_bytes()); output[20..24].copy_from_slice(&self.state[5].to_be_bytes()); output[24..28].copy_from_slice(&self.state[6].to_be_bytes()); output[28..32].copy_from_slice(&self.state[7].to_be_bytes()); output } pub fn oneshot<T: AsRef<[u8]>>(data: T) -> [u8; Self::DIGEST_LEN] { let mut m = Self::new(); m.update(data.as_ref()); m.finalize() } } #[test] fn test_sha224() { // 3. Test Vectors // https://tools.ietf.org/html/rfc3874#section-3 // 3.1. Test Vector #1 let state = [ 0x23097d22u32, 0x3405d822, 0x8642a477, 0xbda255b3, 0x2aadbce4, 0xbda0b3f7, 0xe36c9da7, ]; let mut digest = [0u8; Sha224::DIGEST_LEN]; digest[0..4].copy_from_slice(&state[0].to_be_bytes()); digest[4..8].copy_from_slice(&state[1].to_be_bytes()); digest[8..12].copy_from_slice(&state[2].to_be_bytes()); digest[12..16].copy_from_slice(&state[3].to_be_bytes()); digest[16..20].copy_from_slice(&state[4].to_be_bytes()); digest[20..24].copy_from_slice(&state[5].to_be_bytes()); digest[24..28].copy_from_slice(&state[6].to_be_bytes()); assert_eq!(sha224(b"abc"), digest); // 3.2. Test Vector #2 let state = [ 0x75388b16u32, 0x512776cc, 0x5dba5da1, 0xfd890150, 0xb0c6455c, 0xb4f58b19, 0x52522525, ]; let mut digest = [0u8; Sha224::DIGEST_LEN]; digest[0..4].copy_from_slice(&state[0].to_be_bytes()); digest[4..8].copy_from_slice(&state[1].to_be_bytes()); digest[8..12].copy_from_slice(&state[2].to_be_bytes()); digest[12..16].copy_from_slice(&state[3].to_be_bytes()); digest[16..20].copy_from_slice(&state[4].to_be_bytes()); digest[20..24].copy_from_slice(&state[5].to_be_bytes()); digest[24..28].copy_from_slice(&state[6].to_be_bytes()); assert_eq!( sha224(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), digest ); // 3.3. Test Vector #3 let state = [ 0x20794655u32, 0x980c91d8, 0xbbb4c1ea, 0x97618a4b, 0xf03f4258, 0x1948b2ee, 0x4ee7ad67, ]; let mut digest = [0u8; Sha224::DIGEST_LEN]; digest[0..4].copy_from_slice(&state[0].to_be_bytes()); digest[4..8].copy_from_slice(&state[1].to_be_bytes()); digest[8..12].copy_from_slice(&state[2].to_be_bytes()); digest[12..16].copy_from_slice(&state[3].to_be_bytes()); digest[16..20].copy_from_slice(&state[4].to_be_bytes()); digest[20..24].copy_from_slice(&state[5].to_be_bytes()); digest[24..28].copy_from_slice(&state[6].to_be_bytes()); let msg = vec![b'a'; 1000_000]; assert_eq!(sha224(&msg), digest); } #[test] fn test_sha256_one_block_message() { let msg = b"abc"; let digest = [ 186, 120, 22, 191, 143, 1, 207, 234, 65, 65, 64, 222, 93, 174, 34, 35, 176, 3, 97, 163, 150, 23, 122, 156, 180, 16, 255, 97, 242, 0, 21, 173, ]; assert_eq!(Sha256::oneshot(&msg), digest); } #[test] fn test_sha256_multi_block_message() { let msg = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; let digest = [ 36, 141, 106, 97, 210, 6, 56, 184, 229, 192, 38, 147, 12, 62, 96, 57, 163, 60, 228, 89, 100, 255, 33, 103, 246, 236, 237, 212, 25, 219, 6, 193, ]; assert_eq!(Sha256::oneshot(&msg[..]), digest); } #[test] fn test_sha256_long_message() { let msg = vec![b'a'; 1000_000]; let digest = [ 205, 199, 110, 92, 153, 20, 251, 146, 129, 161, 199, 226, 132, 215, 62, 103, 241, 128, 154, 72, 164, 151, 32, 14, 4, 109, 57, 204, 199, 17, 44, 208, ]; assert_eq!(Sha256::oneshot(&msg), digest); } #[test] fn test_transform_block() { let mut state = INITIAL_STATE; let data = [0u8; 64]; transform(&mut state, &data); assert_eq!( state, [ 3663108286, 398046313, 1647531929, 2006957770, 2363872401, 3235013187, 3137272298, 406301144 ] ); }
use num::{One, Zero}; use alga::general::{SubsetOf, SupersetOf, ClosedDiv}; use core::{Scalar, Matrix, ColumnVector, OwnedColumnVector}; use core::dimension::{DimName, DimNameSum, DimNameAdd, U1}; use core::storage::OwnedStorage; use core::allocator::{Allocator, OwnedAllocator}; use geometry::{PointBase, OwnedPoint}; /* * This file provides the following conversions: * ============================================= * * PointBase -> PointBase * PointBase -> ColumnVector (homogeneous) */ impl<N1, N2, D, SA, SB> SubsetOf<PointBase<N2, D, SB>> for PointBase<N1, D, SA> where D: DimName, N1: Scalar, N2: Scalar + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, D, U1>, SB::Alloc: OwnedAllocator<N2, D, U1, SB>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> { #[inline] fn to_superset(&self) -> PointBase<N2, D, SB> { PointBase::from_coordinates(self.coords.to_superset()) } #[inline] fn is_in_subset(m: &PointBase<N2, D, SB>) -> bool { // FIXME: is there a way to reuse the `.is_in_subset` from the matrix implementation of // SubsetOf? m.iter().all(|e| e.is_in_subset()) } #[inline] unsafe fn from_superset_unchecked(m: &PointBase<N2, D, SB>) -> Self { PointBase::from_coordinates(Matrix::from_superset_unchecked(&m.coords)) } } impl<N1, N2, D, SA, SB> SubsetOf<ColumnVector<N2, DimNameSum<D, U1>, SB>> for PointBase<N1, D, SA> where D: DimNameAdd<U1>, N1: Scalar, N2: Scalar + Zero + One + ClosedDiv + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, DimNameSum<D, U1>, U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> + Allocator<N1, DimNameSum<D, U1>, U1>, SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, U1, SB> + Allocator<N2, D, U1> { #[inline] fn to_superset(&self) -> ColumnVector<N2, DimNameSum<D, U1>, SB> { let p: OwnedPoint<N2, D, SB::Alloc> = self.to_superset(); p.to_homogeneous() } #[inline] fn is_in_subset(v: &ColumnVector<N2, DimNameSum<D, U1>, SB>) -> bool { ::is_convertible::<_, OwnedColumnVector<N1, DimNameSum<D, U1>, SA::Alloc>>(v) && !v[D::dim()].is_zero() } #[inline] unsafe fn from_superset_unchecked(v: &ColumnVector<N2, DimNameSum<D, U1>, SB>) -> Self { let coords = v.fixed_slice::<D, U1>(0, 0) / v[D::dim()]; Self::from_coordinates(::convert_unchecked(coords)) } }
mod debug; mod rectangle; pub mod render_gl; pub mod resources; mod triangle; use debug::{failure_to_string, FPSCounter}; use failure; use nalgebra as na; use rectangle::Rectangle; use render_gl::ColorBuffer; use render_gl::Viewport; use resources::{Reloadable, ResourceWatcher, Resources}; use std::path::Path; use triangle::Triangle; const WINDOW_TITLE: &str = "OpenGL "; struct State { _sdl: sdl2::Sdl, gl: gl::Gl, _gl_context: sdl2::video::GLContext, triangle: Triangle, rectangle: Rectangle, window: sdl2::video::Window, event_pump: sdl2::EventPump, viewport: Viewport, color_buffer: ColorBuffer, fps_counter: FPSCounter, watcher: ResourceWatcher, resources: Resources, } fn setup() -> Result<State, failure::Error> { let sdl = sdl2::init().map_err(failure::err_msg)?; let timer = sdl.timer().map_err(failure::err_msg)?; let fps_counter = FPSCounter::new(timer); let video = sdl.video().map_err(failure::err_msg)?; let gl_attr = video.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(3, 3); let window = video .window(WINDOW_TITLE, 800, 600) .opengl() .resizable() .build() .map_err(failure::err_msg)?; let event_pump = sdl.event_pump().map_err(failure::err_msg)?; let gl_context = window.gl_create_context().map_err(failure::err_msg)?; let gl = gl::Gl::load_with(|s| video.gl_get_proc_address(s) as *const std::os::raw::c_void); let resources = Resources::from_relative_exe_path(Path::new("assets"))?; let triangle = Triangle::new(&resources, &gl)?; let rectangle = Rectangle::new(&resources, &gl)?; let viewport = Viewport::for_window(800, 600); viewport.set_used(&gl); let color_buffer = ColorBuffer::from_color(na::Vector3::new(0.3, 0.3, 0.5)); color_buffer.set_used(&gl); let mut watcher = ResourceWatcher::new(); watcher.add_reloadable(&triangle); watcher.add_reloadable(&rectangle); Ok(State { _sdl: sdl, _gl_context: gl_context, gl, triangle, rectangle, window, event_pump, viewport, color_buffer, fps_counter, watcher, resources, }) } fn run(state: State) -> Result<(), failure::Error> { match state { State { gl, mut triangle, mut rectangle, window, mut event_pump, mut viewport, color_buffer, mut fps_counter, resources, watcher, .. } => 'main: loop { match watcher.rx.try_recv() { Ok(evt) => { println!("{:#?}", evt); triangle.reload(&gl, &resources)?; rectangle.reload(&gl, &resources)?; } Err(_) => {} } fps_counter.count(); color_buffer.clear(&gl); // triangle.render(&gl); rectangle.render(&gl); window.gl_swap_window(); for event in event_pump.poll_iter() { use sdl2::event::Event::{Quit, Window}; use sdl2::event::WindowEvent::Resized; match event { Quit { .. } => break 'main, Window { win_event, .. } => match win_event { Resized(w, h) => { viewport.update_size(w, h); viewport.set_used(&gl); } _ => {} }, _ => {} } } }, }; Ok(()) } fn main() { if let Err(e) = setup().and_then(run) { println!("Error occurred: {}", failure_to_string(e)); std::process::exit(1); } }
{ "id": "0296d855-e9da-49b3-a0bb-cd16a1d39758", "$type": "NestingPartResource", "NestingPart": { "$type": "NestingPart", "Part": { "$type": "NestingPart", "Part": { "$type": "NestingPart", "Part": { "$type": "NestingPart", "Part": { "$type": "NestingPart", "Part": { "$type": "NestingPart", "TestString": "4" }, "TestString": "3" }, "TestString": "2" }, "TestString": "4" }, "TestString": "3" }, "TestString": "2444" } }
/// An enum to represent all characters in the Wancho block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Wancho { /// \u{1e2c0}: '๐ž‹€' LetterAa, /// \u{1e2c1}: '๐ž‹' LetterA, /// \u{1e2c2}: '๐ž‹‚' LetterBa, /// \u{1e2c3}: '๐ž‹ƒ' LetterCa, /// \u{1e2c4}: '๐ž‹„' LetterDa, /// \u{1e2c5}: '๐ž‹…' LetterGa, /// \u{1e2c6}: '๐ž‹†' LetterYa, /// \u{1e2c7}: '๐ž‹‡' LetterPha, /// \u{1e2c8}: '๐ž‹ˆ' LetterLa, /// \u{1e2c9}: '๐ž‹‰' LetterNa, /// \u{1e2ca}: '๐ž‹Š' LetterPa, /// \u{1e2cb}: '๐ž‹‹' LetterTa, /// \u{1e2cc}: '๐ž‹Œ' LetterTha, /// \u{1e2cd}: '๐ž‹' LetterFa, /// \u{1e2ce}: '๐ž‹Ž' LetterSa, /// \u{1e2cf}: '๐ž‹' LetterSha, /// \u{1e2d0}: '๐ž‹' LetterJa, /// \u{1e2d1}: '๐ž‹‘' LetterZa, /// \u{1e2d2}: '๐ž‹’' LetterWa, /// \u{1e2d3}: '๐ž‹“' LetterVa, /// \u{1e2d4}: '๐ž‹”' LetterKa, /// \u{1e2d5}: '๐ž‹•' LetterO, /// \u{1e2d6}: '๐ž‹–' LetterAu, /// \u{1e2d7}: '๐ž‹—' LetterRa, /// \u{1e2d8}: '๐ž‹˜' LetterMa, /// \u{1e2d9}: '๐ž‹™' LetterKha, /// \u{1e2da}: '๐ž‹š' LetterHa, /// \u{1e2db}: '๐ž‹›' LetterE, /// \u{1e2dc}: '๐ž‹œ' LetterI, /// \u{1e2dd}: '๐ž‹' LetterNga, /// \u{1e2de}: '๐ž‹ž' LetterU, /// \u{1e2df}: '๐ž‹Ÿ' LetterLlha, /// \u{1e2e0}: '๐ž‹ ' LetterTsa, /// \u{1e2e1}: '๐ž‹ก' LetterTra, /// \u{1e2e2}: '๐ž‹ข' LetterOng, /// \u{1e2e3}: '๐ž‹ฃ' LetterAang, /// \u{1e2e4}: '๐ž‹ค' LetterAng, /// \u{1e2e5}: '๐ž‹ฅ' LetterIng, /// \u{1e2e6}: '๐ž‹ฆ' LetterOn, /// \u{1e2e7}: '๐ž‹ง' LetterEn, /// \u{1e2e8}: '๐ž‹จ' LetterAan, /// \u{1e2e9}: '๐ž‹ฉ' LetterNya, /// \u{1e2ea}: '๐ž‹ช' LetterUen, /// \u{1e2eb}: '๐ž‹ซ' LetterYih, /// \u{1e2ec}: '๐ž‹ฌ' ToneTup, /// \u{1e2ed}: '๐ž‹ญ' ToneTupni, /// \u{1e2ee}: '๐ž‹ฎ' ToneKoi, /// \u{1e2ef}: '๐ž‹ฏ' ToneKoini, /// \u{1e2f0}: '๐ž‹ฐ' DigitZero, /// \u{1e2f1}: '๐ž‹ฑ' DigitOne, /// \u{1e2f2}: '๐ž‹ฒ' DigitTwo, /// \u{1e2f3}: '๐ž‹ณ' DigitThree, /// \u{1e2f4}: '๐ž‹ด' DigitFour, /// \u{1e2f5}: '๐ž‹ต' DigitFive, /// \u{1e2f6}: '๐ž‹ถ' DigitSix, /// \u{1e2f7}: '๐ž‹ท' DigitSeven, /// \u{1e2f8}: '๐ž‹ธ' DigitEight, /// \u{1e2f9}: '๐ž‹น' DigitNine, } impl Into<char> for Wancho { fn into(self) -> char { match self { Wancho::LetterAa => '๐ž‹€', Wancho::LetterA => '๐ž‹', Wancho::LetterBa => '๐ž‹‚', Wancho::LetterCa => '๐ž‹ƒ', Wancho::LetterDa => '๐ž‹„', Wancho::LetterGa => '๐ž‹…', Wancho::LetterYa => '๐ž‹†', Wancho::LetterPha => '๐ž‹‡', Wancho::LetterLa => '๐ž‹ˆ', Wancho::LetterNa => '๐ž‹‰', Wancho::LetterPa => '๐ž‹Š', Wancho::LetterTa => '๐ž‹‹', Wancho::LetterTha => '๐ž‹Œ', Wancho::LetterFa => '๐ž‹', Wancho::LetterSa => '๐ž‹Ž', Wancho::LetterSha => '๐ž‹', Wancho::LetterJa => '๐ž‹', Wancho::LetterZa => '๐ž‹‘', Wancho::LetterWa => '๐ž‹’', Wancho::LetterVa => '๐ž‹“', Wancho::LetterKa => '๐ž‹”', Wancho::LetterO => '๐ž‹•', Wancho::LetterAu => '๐ž‹–', Wancho::LetterRa => '๐ž‹—', Wancho::LetterMa => '๐ž‹˜', Wancho::LetterKha => '๐ž‹™', Wancho::LetterHa => '๐ž‹š', Wancho::LetterE => '๐ž‹›', Wancho::LetterI => '๐ž‹œ', Wancho::LetterNga => '๐ž‹', Wancho::LetterU => '๐ž‹ž', Wancho::LetterLlha => '๐ž‹Ÿ', Wancho::LetterTsa => '๐ž‹ ', Wancho::LetterTra => '๐ž‹ก', Wancho::LetterOng => '๐ž‹ข', Wancho::LetterAang => '๐ž‹ฃ', Wancho::LetterAng => '๐ž‹ค', Wancho::LetterIng => '๐ž‹ฅ', Wancho::LetterOn => '๐ž‹ฆ', Wancho::LetterEn => '๐ž‹ง', Wancho::LetterAan => '๐ž‹จ', Wancho::LetterNya => '๐ž‹ฉ', Wancho::LetterUen => '๐ž‹ช', Wancho::LetterYih => '๐ž‹ซ', Wancho::ToneTup => '๐ž‹ฌ', Wancho::ToneTupni => '๐ž‹ญ', Wancho::ToneKoi => '๐ž‹ฎ', Wancho::ToneKoini => '๐ž‹ฏ', Wancho::DigitZero => '๐ž‹ฐ', Wancho::DigitOne => '๐ž‹ฑ', Wancho::DigitTwo => '๐ž‹ฒ', Wancho::DigitThree => '๐ž‹ณ', Wancho::DigitFour => '๐ž‹ด', Wancho::DigitFive => '๐ž‹ต', Wancho::DigitSix => '๐ž‹ถ', Wancho::DigitSeven => '๐ž‹ท', Wancho::DigitEight => '๐ž‹ธ', Wancho::DigitNine => '๐ž‹น', } } } impl std::convert::TryFrom<char> for Wancho { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { '๐ž‹€' => Ok(Wancho::LetterAa), '๐ž‹' => Ok(Wancho::LetterA), '๐ž‹‚' => Ok(Wancho::LetterBa), '๐ž‹ƒ' => Ok(Wancho::LetterCa), '๐ž‹„' => Ok(Wancho::LetterDa), '๐ž‹…' => Ok(Wancho::LetterGa), '๐ž‹†' => Ok(Wancho::LetterYa), '๐ž‹‡' => Ok(Wancho::LetterPha), '๐ž‹ˆ' => Ok(Wancho::LetterLa), '๐ž‹‰' => Ok(Wancho::LetterNa), '๐ž‹Š' => Ok(Wancho::LetterPa), '๐ž‹‹' => Ok(Wancho::LetterTa), '๐ž‹Œ' => Ok(Wancho::LetterTha), '๐ž‹' => Ok(Wancho::LetterFa), '๐ž‹Ž' => Ok(Wancho::LetterSa), '๐ž‹' => Ok(Wancho::LetterSha), '๐ž‹' => Ok(Wancho::LetterJa), '๐ž‹‘' => Ok(Wancho::LetterZa), '๐ž‹’' => Ok(Wancho::LetterWa), '๐ž‹“' => Ok(Wancho::LetterVa), '๐ž‹”' => Ok(Wancho::LetterKa), '๐ž‹•' => Ok(Wancho::LetterO), '๐ž‹–' => Ok(Wancho::LetterAu), '๐ž‹—' => Ok(Wancho::LetterRa), '๐ž‹˜' => Ok(Wancho::LetterMa), '๐ž‹™' => Ok(Wancho::LetterKha), '๐ž‹š' => Ok(Wancho::LetterHa), '๐ž‹›' => Ok(Wancho::LetterE), '๐ž‹œ' => Ok(Wancho::LetterI), '๐ž‹' => Ok(Wancho::LetterNga), '๐ž‹ž' => Ok(Wancho::LetterU), '๐ž‹Ÿ' => Ok(Wancho::LetterLlha), '๐ž‹ ' => Ok(Wancho::LetterTsa), '๐ž‹ก' => Ok(Wancho::LetterTra), '๐ž‹ข' => Ok(Wancho::LetterOng), '๐ž‹ฃ' => Ok(Wancho::LetterAang), '๐ž‹ค' => Ok(Wancho::LetterAng), '๐ž‹ฅ' => Ok(Wancho::LetterIng), '๐ž‹ฆ' => Ok(Wancho::LetterOn), '๐ž‹ง' => Ok(Wancho::LetterEn), '๐ž‹จ' => Ok(Wancho::LetterAan), '๐ž‹ฉ' => Ok(Wancho::LetterNya), '๐ž‹ช' => Ok(Wancho::LetterUen), '๐ž‹ซ' => Ok(Wancho::LetterYih), '๐ž‹ฌ' => Ok(Wancho::ToneTup), '๐ž‹ญ' => Ok(Wancho::ToneTupni), '๐ž‹ฎ' => Ok(Wancho::ToneKoi), '๐ž‹ฏ' => Ok(Wancho::ToneKoini), '๐ž‹ฐ' => Ok(Wancho::DigitZero), '๐ž‹ฑ' => Ok(Wancho::DigitOne), '๐ž‹ฒ' => Ok(Wancho::DigitTwo), '๐ž‹ณ' => Ok(Wancho::DigitThree), '๐ž‹ด' => Ok(Wancho::DigitFour), '๐ž‹ต' => Ok(Wancho::DigitFive), '๐ž‹ถ' => Ok(Wancho::DigitSix), '๐ž‹ท' => Ok(Wancho::DigitSeven), '๐ž‹ธ' => Ok(Wancho::DigitEight), '๐ž‹น' => Ok(Wancho::DigitNine), _ => Err(()), } } } impl Into<u32> for Wancho { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for Wancho { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for Wancho { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl Wancho { /// The character with the lowest index in this unicode block pub fn new() -> Self { Wancho::LetterAa } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("Wancho{:#?}", self); string_morph::to_sentence_case(&s) } }
#[doc = "Register `MEMRMP` reader"] pub type R = crate::R<MEMRMP_SPEC>; #[doc = "Register `MEMRMP` writer"] pub type W = crate::W<MEMRMP_SPEC>; #[doc = "Field `MEM_MODE` reader - Memory mapping selection"] pub type MEM_MODE_R = crate::FieldReader<MEM_MODE_A>; #[doc = "Memory mapping selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum MEM_MODE_A { #[doc = "0: Main Flash memory mapped at 0x0000_0000"] MainFlash = 0, #[doc = "1: System Flash memory mapped at 0x0000_0000"] SystemFlash = 1, #[doc = "3: Embedded SRAM mapped at 0x0000_0000"] Sram = 3, } impl From<MEM_MODE_A> for u8 { #[inline(always)] fn from(variant: MEM_MODE_A) -> Self { variant as _ } } impl crate::FieldSpec for MEM_MODE_A { type Ux = u8; } impl MEM_MODE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<MEM_MODE_A> { match self.bits { 0 => Some(MEM_MODE_A::MainFlash), 1 => Some(MEM_MODE_A::SystemFlash), 3 => Some(MEM_MODE_A::Sram), _ => None, } } #[doc = "Main Flash memory mapped at 0x0000_0000"] #[inline(always)] pub fn is_main_flash(&self) -> bool { *self == MEM_MODE_A::MainFlash } #[doc = "System Flash memory mapped at 0x0000_0000"] #[inline(always)] pub fn is_system_flash(&self) -> bool { *self == MEM_MODE_A::SystemFlash } #[doc = "Embedded SRAM mapped at 0x0000_0000"] #[inline(always)] pub fn is_sram(&self) -> bool { *self == MEM_MODE_A::Sram } } #[doc = "Field `MEM_MODE` writer - Memory mapping selection"] pub type MEM_MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O, MEM_MODE_A>; impl<'a, REG, const O: u8> MEM_MODE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "Main Flash memory mapped at 0x0000_0000"] #[inline(always)] pub fn main_flash(self) -> &'a mut crate::W<REG> { self.variant(MEM_MODE_A::MainFlash) } #[doc = "System Flash memory mapped at 0x0000_0000"] #[inline(always)] pub fn system_flash(self) -> &'a mut crate::W<REG> { self.variant(MEM_MODE_A::SystemFlash) } #[doc = "Embedded SRAM mapped at 0x0000_0000"] #[inline(always)] pub fn sram(self) -> &'a mut crate::W<REG> { self.variant(MEM_MODE_A::Sram) } } impl R { #[doc = "Bits 0:2 - Memory mapping selection"] #[inline(always)] pub fn mem_mode(&self) -> MEM_MODE_R { MEM_MODE_R::new((self.bits & 7) as u8) } } impl W { #[doc = "Bits 0:2 - Memory mapping selection"] #[inline(always)] #[must_use] pub fn mem_mode(&mut self) -> MEM_MODE_W<MEMRMP_SPEC, 0> { MEM_MODE_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "memory remap register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`memrmp::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`memrmp::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct MEMRMP_SPEC; impl crate::RegisterSpec for MEMRMP_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`memrmp::R`](R) reader structure"] impl crate::Readable for MEMRMP_SPEC {} #[doc = "`write(|w| ..)` method takes [`memrmp::W`](W) writer structure"] impl crate::Writable for MEMRMP_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets MEMRMP to value 0"] impl crate::Resettable for MEMRMP_SPEC { const RESET_VALUE: Self::Ux = 0; }
/// Toy example of an actix-web server that has endpoints for hashing and verifying passwords extern crate actix_web; extern crate argonautica; extern crate dotenv; extern crate env_logger; #[macro_use] extern crate failure; extern crate futures; extern crate futures_cpupool; extern crate futures_timer; #[macro_use] extern crate serde; extern crate serde_json; use std::collections::HashMap; use std::env; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use actix_web::http::Method; use actix_web::middleware::Logger; use actix_web::{server, App, AsyncResponder, Error, HttpMessage, HttpRequest, HttpResponse}; use argonautica::input::SecretKey; use argonautica::{Hasher, Verifier}; use futures::Future; use futures_cpupool::CpuPool; use futures_timer::Delay; // This will be used for the register and verify routes. We want these routes to take a // at least a minimum amount of time to load since we don't want to give potential attackers // any insight into what our code does with invalid inputs const MINIMUM_DURATION_IN_MILLIS: u64 = 400; // Helper method to load the secret key from a .env file. Used in `main` below. fn load_secret_key() -> Result<SecretKey<'static>, failure::Error> { let dotenv_path = env::current_dir()?.join("examples").join("example.env"); dotenv::from_path(&dotenv_path).map_err(|e| format_err!("{}", e))?; let base64_encoded_secret_key = env::var("SECRET_KEY")?; Ok(SecretKey::from_base64_encoded( &base64_encoded_secret_key, )?) } // "Global" state that will be passed to every call to a handler. Here we include the "database", // which for example purposes is just a HashMap (but in real life would probably be Postgres // or something of the sort), as well as instances of our Hasher and Verifier, which we "preload" // with our secret key struct State<'a> { database: Arc<Mutex<HashMap<String, String>>>, hasher: Hasher<'a>, verifier: Verifier<'a>, } impl<'a> State<'a> { // Since actix-web uses futures extensively, let's have the Hasher and Verifier // share a common CpuPool. In addition, as mentioned above, we "preload" the Hasher and // Verifier with our secret key; so we only have to do this once (at creation of the // server in 'main') fn new(secret_key: &SecretKey<'a>) -> State<'static> { let cpu_pool = CpuPool::new(4); State { database: Arc::new(Mutex::new(HashMap::new())), hasher: { let mut hasher = Hasher::default(); hasher .configure_cpu_pool(cpu_pool.clone()) .with_secret_key(secret_key.to_owned()); hasher }, verifier: { let mut verifier = Verifier::default(); verifier .configure_cpu_pool(cpu_pool) .with_secret_key(secret_key.to_owned()); verifier }, } } fn database_ptr(&self) -> Arc<Mutex<HashMap<String, String>>> { self.database.clone() } fn hasher(&self) -> Hasher<'static> { self.hasher.to_owned() } fn verifier(&self) -> Verifier<'static> { self.verifier.to_owned() } } // Handler for the "/database" route. This just returns a copy of the "database" (in json) // In real life, you would obviously restrict access to this route to admins only // or something of the sort, but in this example the routes is open to anyone fn database(req: HttpRequest<State<'static>>) -> HttpResponse { let database_ptr = req.state().database_ptr(); let database = { match database_ptr.lock() { Ok(database) => database, Err(_) => return HttpResponse::InternalServerError().finish(), } }; HttpResponse::Ok().json(&*database) } // Struct representing the json object clients will need to provide when making // a POST request to the "/register" route #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct RegisterRequest { email: String, password: String, } // Handler for the "/register" route. First we parse the client-provided json. // Then we hash the password they provided using argonautica. Next we add the email they // provided and the hash to our "database". Finally, if all worked correctly, we // return an empty 201 Created response. Note that we would like to // ensure that calling this route always takes at least a minimum amount of time // (to prevent attackers from gaining insight into our code); so at the end, we also // delay before returning if the function has taken less than the minimum required amount // of time. fn register(req: HttpRequest<State<'static>>) -> Box<Future<Item = HttpResponse, Error = Error>> { let start = Instant::now(); let database_ptr = req.state().database_ptr(); let mut hasher = req.state().hasher(); req.json() .map_err(|e| e.into()) .and_then(move |register_request: RegisterRequest| { hasher .with_password(register_request.password.clone()) .hash_non_blocking() .map_err(|e| e.into()) // Futures are kind finicky; so let's map the result of our // call to hasher_non_blocking (which, if successful, is just a String) // to a tuple that includes both the resulting String and the original // RegisterRequest. This is needed for us to be able to access // the RegisterRequest in the next and_then block .map(|hash| (hash, register_request)) }) .and_then(move |(hash, register_request)| { let mut database = database_ptr.lock().map_err(|e| format_err!("{}", e))?; (*database).insert(register_request.email, hash); Ok::<_, failure::Error>(()) }) .then(move |result1| { let duration = Duration::from_millis(MINIMUM_DURATION_IN_MILLIS) .checked_sub(start.elapsed()) .unwrap_or_else(|| Duration::from_millis(0)); Delay::new(duration).then(move |result2| { if result1.is_err() { return Ok(HttpResponse::BadRequest().finish()); } if result2.is_err() { return Ok(HttpResponse::InternalServerError().finish()); } Ok(HttpResponse::Created().finish()) }) }) .responder() } // Struct representing the json object clients will need to provide when making // a POST request to the "/verify" route #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct VerifyRequest { email: String, password: String, } // Handler for the "/verify" routes. First we parse the client-provided json. // Then we look up the client's hash in the "database" using the email they provided. // Next we verify the password they provided against the hash we pulled from the // "database". Finally, if all worked correctly, we return an empty 200 OK response // to indicate that the password provided did indeed match the hash in our "database". // As with the "/register" method above, we would like to ensure that calling this route // always takes at least a minimum amount of time (to prevent attackers from gaining insight // into our code); so we use the same trick with the `futures_timer` crate to ensure that here. fn verify(req: HttpRequest<State<'static>>) -> Box<Future<Item = HttpResponse, Error = Error>> { let start = Instant::now(); let database_ptr = req.state().database_ptr(); let mut verifier = req.state().verifier(); req.json() .map_err(|e| e.into()) .and_then(move |verify_request: VerifyRequest| { let hash = { let database = database_ptr.lock().map_err(|e| format_err!("{}", e))?; database .get(&verify_request.email) .ok_or(format_err!("not in database"))? .clone() }; Ok::<_, failure::Error>((hash, verify_request)) }) .and_then(move |(hash, verify_request)| { verifier .with_hash(&hash) .with_password(verify_request.password.clone()) .verify_non_blocking() .map_err(|e| e.into()) }) .then(move |result1| { let duration = Duration::from_millis(MINIMUM_DURATION_IN_MILLIS) .checked_sub(start.elapsed()) .unwrap_or_else(|| Duration::from_millis(0)); Delay::new(duration).then(move |result2| { if result2.is_err() { return Ok(HttpResponse::InternalServerError().finish()); } let is_valid = match result1 { Ok(is_valid) => is_valid, Err(_) => return Ok(HttpResponse::Unauthorized().finish()), }; if !is_valid { return Ok(HttpResponse::Unauthorized().finish()); } Ok(HttpResponse::Ok().finish()) }) }) .responder() } // Main function to kick off the server and provide a small logging middleware // that will print to stdout the amount of time that each request took to process fn main() -> Result<(), failure::Error> { env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); let secret_key = load_secret_key()?; server::new(move || { App::with_state(State::new(&secret_key)) .middleware(Logger::new("Milliseconds to process request: %D")) .resource("/database", |r| r.method(Method::GET).f(database)) .resource("/register", |r| r.method(Method::POST).f(register)) .resource("/verify", |r| r.method(Method::POST).f(verify)) }).bind("127.0.0.1:8080")? .run(); Ok(()) }
use na::Vector2; pub fn vec_determinant(v1: &Vector2<f32>, v2: &Vector2<f32>) -> f32 { // |v1, v2| = (v1.x * v2.y) - (v2.x * v1.y) (v1.x * v2.y) - (v2.x * v1.y) }
use utils; pub fn problem_020() -> u32 { let n = 100; let mut fact: Vec<u32> = vec![1]; for i in 1..(n + 1) { fact = utils::scalar_multiply_digit_array(&fact[..], i); } fact.iter().fold(0, |a, &b| a + b) } #[cfg(test)] mod test { use super::*; use test::Bencher; #[test] fn test_problem_020() { let ans: u32 = problem_020(); println!("Answer to Problem 20: {}", ans); assert!(ans == 648) } #[bench] fn bench_problem_020(b: &mut Bencher) { b.iter(|| problem_020()); } }
//! Test vectors from: https://datatracker.ietf.org/doc/html/rfc9058 aead::new_test!(kuznyechik, "kuznyechik", mgm::Mgm<kuznyechik::Kuznyechik>); aead::new_test!(magma, "magma", mgm::Mgm<magma::Magma>);
#![cfg_attr(not(feature = "std"), no_std)] // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); #[cfg(feature = "std")] /// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics. pub fn wasm_binary_unwrap() -> &'static [u8] { WASM_BINARY.expect( "Development wasm binary is not available. Testing is only \ supported with the flag disabled.", ) } #[cfg(not(feature = "std"))] use sp_std::{vec, vec::Vec}; #[cfg(not(feature = "std"))] use sp_core::{ed25519, sr25519}; #[cfg(not(feature = "std"))] use sp_io::{ crypto::{ed25519_verify, sr25519_verify}, hashing::{blake2_128, blake2_256, sha2_256, twox_128, twox_256}, storage, wasm_tracing, }; #[cfg(not(feature = "std"))] use sp_runtime::{ print, traits::{BlakeTwo256, Hash}, }; #[cfg(not(feature = "std"))] use sp_sandbox::Value; extern "C" { #[allow(dead_code)] fn missing_external(); #[allow(dead_code)] fn yet_another_missing_external(); } #[cfg(not(feature = "std"))] /// Mutable static variables should be always observed to have /// the initialized value at the start of a runtime call. static mut MUTABLE_STATIC: u64 = 32; sp_core::wasm_export_functions! { fn test_calling_missing_external() { unsafe { missing_external() } } fn test_calling_yet_another_missing_external() { unsafe { yet_another_missing_external() } } fn test_data_in(input: Vec<u8>) -> Vec<u8> { print("set_storage"); storage::set(b"input", &input); print("storage"); let foo = storage::get(b"foo").unwrap(); print("set_storage"); storage::set(b"baz", &foo); print("finished!"); b"all ok!".to_vec() } fn test_clear_prefix(input: Vec<u8>) -> Vec<u8> { storage::clear_prefix(&input); b"all ok!".to_vec() } fn test_empty_return() {} fn test_exhaust_heap() -> Vec<u8> { Vec::with_capacity(16777216) } fn test_panic() { panic!("test panic") } fn test_conditional_panic(input: Vec<u8>) -> Vec<u8> { if input.len() > 0 { panic!("test panic") } input } fn test_blake2_256(input: Vec<u8>) -> Vec<u8> { blake2_256(&input).to_vec() } fn test_blake2_128(input: Vec<u8>) -> Vec<u8> { blake2_128(&input).to_vec() } fn test_sha2_256(input: Vec<u8>) -> Vec<u8> { sha2_256(&input).to_vec() } fn test_twox_256(input: Vec<u8>) -> Vec<u8> { twox_256(&input).to_vec() } fn test_twox_128(input: Vec<u8>) -> Vec<u8> { twox_128(&input).to_vec() } fn test_ed25519_verify(input: Vec<u8>) -> bool { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; ed25519_verify(&ed25519::Signature(sig), &msg[..], &ed25519::Public(pubkey)) } fn test_sr25519_verify(input: Vec<u8>) -> bool { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; sr25519_verify(&sr25519::Signature(sig), &msg[..], &sr25519::Public(pubkey)) } fn test_ordered_trie_root() -> Vec<u8> { BlakeTwo256::ordered_trie_root( vec![ b"zero"[..].into(), b"one"[..].into(), b"two"[..].into(), ], ).as_ref().to_vec() } fn test_sandbox(code: Vec<u8>) -> bool { execute_sandboxed(&code, &[]).is_ok() } fn test_sandbox_args(code: Vec<u8>) -> bool { execute_sandboxed( &code, &[ Value::I32(0x12345678), Value::I64(0x1234567887654321), ], ).is_ok() } fn test_sandbox_return_val(code: Vec<u8>) -> bool { let ok = match execute_sandboxed( &code, &[ Value::I32(0x1336), ] ) { Ok(sp_sandbox::ReturnValue::Value(Value::I32(0x1337))) => true, _ => false, }; ok } fn test_sandbox_instantiate(code: Vec<u8>) -> u8 { let env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new(); let code = match sp_sandbox::Instance::new(&code, &env_builder, &mut ()) { Ok(_) => 0, Err(sp_sandbox::Error::Module) => 1, Err(sp_sandbox::Error::Execution) => 2, Err(sp_sandbox::Error::OutOfBounds) => 3, }; code } fn test_sandbox_get_global_val(code: Vec<u8>) -> i64 { let env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new(); let instance = if let Ok(i) = sp_sandbox::Instance::new(&code, &env_builder, &mut ()) { i } else { return 20; }; match instance.get_global_val("test_global") { Some(sp_sandbox::Value::I64(val)) => val, None => 30, val => 40, } } fn test_offchain_index_set() { sp_io::offchain_index::set(b"k", b"v"); } fn test_offchain_local_storage() -> bool { let kind = sp_core::offchain::StorageKind::PERSISTENT; assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None); sp_io::offchain::local_storage_set(kind, b"test", b"asd"); assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), Some(b"asd".to_vec())); let res = sp_io::offchain::local_storage_compare_and_set( kind, b"test", Some(b"asd".to_vec()), b"", ); assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), Some(b"".to_vec())); res } fn test_offchain_local_storage_with_none() { let kind = sp_core::offchain::StorageKind::PERSISTENT; assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), None); let res = sp_io::offchain::local_storage_compare_and_set(kind, b"test", None, b"value"); assert_eq!(res, true); assert_eq!(sp_io::offchain::local_storage_get(kind, b"test"), Some(b"value".to_vec())); } fn test_offchain_http() -> bool { use sp_core::offchain::HttpRequestStatus; let run = || -> Option<()> { let id = sp_io::offchain::http_request_start( "POST", "http://localhost:12345", &[], ).ok()?; sp_io::offchain::http_request_add_header(id, "X-Auth", "test").ok()?; sp_io::offchain::http_request_write_body(id, &[1, 2, 3, 4], None).ok()?; sp_io::offchain::http_request_write_body(id, &[], None).ok()?; let status = sp_io::offchain::http_response_wait(&[id], None); assert!(status == vec![HttpRequestStatus::Finished(200)], "Expected Finished(200) status."); let headers = sp_io::offchain::http_response_headers(id); assert_eq!(headers, vec![(b"X-Auth".to_vec(), b"hello".to_vec())]); let mut buffer = vec![0; 64]; let read = sp_io::offchain::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 3); assert_eq!(&buffer[0..read as usize], &[1, 2, 3]); let read = sp_io::offchain::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 0); Some(()) }; run().is_some() } // Just some test to make sure that `sp-allocator` compiles on `no_std`. fn test_sp_allocator_compiles() { sp_allocator::FreeingBumpHeapAllocator::new(0); } fn test_enter_span() -> u64 { wasm_tracing::enter_span(Default::default()) } fn test_exit_span(span_id: u64) { wasm_tracing::exit(span_id) } fn returns_mutable_static() -> u64 { unsafe { MUTABLE_STATIC += 1; MUTABLE_STATIC } } fn allocates_huge_stack_array(trap: bool) -> Vec<u8> { // Allocate a stack frame that is approx. 75% of the stack (assuming it is 1MB). // This will just decrease (stacks in wasm32-u-u grow downwards) the stack // pointer. This won't trap on the current compilers. let mut data = [0u8; 1024 * 768]; // Then make sure we actually write something to it. // // If: // 1. the stack area is placed at the beginning of the linear memory space, and // 2. the stack pointer points to out-of-bounds area, and // 3. a write is performed around the current stack pointer. // // then a trap should happen. // for (i, v) in data.iter_mut().enumerate() { *v = i as u8; // deliberate truncation } if trap { // There is a small chance of this to be pulled up in theory. In practice // the probability of that is rather low. panic!() } data.to_vec() } // Check that the heap at `heap_base + offset` don't contains the test message. // After the check succeeds the test message is written into the heap. // // It is expected that the given pointer is not allocated. fn check_and_set_in_heap(heap_base: u32, offset: u32) { let test_message = b"Hello invalid heap memory"; let ptr = unsafe { (heap_base + offset) as *mut u8 }; let message_slice = unsafe { sp_std::slice::from_raw_parts_mut(ptr, test_message.len()) }; assert_ne!(test_message, message_slice); message_slice.copy_from_slice(test_message); } } #[cfg(not(feature = "std"))] fn execute_sandboxed( code: &[u8], args: &[Value], ) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> { struct State { counter: u32, } fn env_assert( _e: &mut State, args: &[Value], ) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> { if args.len() != 1 { return Err(sp_sandbox::HostError) } let condition = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?; if condition != 0 { Ok(sp_sandbox::ReturnValue::Unit) } else { Err(sp_sandbox::HostError) } } fn env_inc_counter( e: &mut State, args: &[Value], ) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> { if args.len() != 1 { return Err(sp_sandbox::HostError) } let inc_by = args[0].as_i32().ok_or_else(|| sp_sandbox::HostError)?; e.counter += inc_by as u32; Ok(sp_sandbox::ReturnValue::Value(Value::I32(e.counter as i32))) } let mut state = State { counter: 0 }; let env_builder = { let mut env_builder = sp_sandbox::EnvironmentDefinitionBuilder::new(); env_builder.add_host_func("env", "assert", env_assert); env_builder.add_host_func("env", "inc_counter", env_inc_counter); let memory = match sp_sandbox::Memory::new(1, Some(16)) { Ok(m) => m, Err(_) => unreachable!( " Memory::new() can return Err only if parameters are borked; \ We passing params here explicitly and they're correct; \ Memory::new() can't return a Error qed" ), }; env_builder.add_memory("env", "memory", memory); env_builder }; let mut instance = sp_sandbox::Instance::new(code, &env_builder, &mut state)?; let result = instance.invoke("call", args, &mut state); result.map_err(|_| sp_sandbox::HostError) }
use std::fmt; use std::fmt::Display; use std::sync; use failure::{Backtrace, Context, Fail}; use crate::model::*; pub type Result<T> = ::std::result::Result<T, Error>; #[derive(Fail, Debug, Clone, PartialEq, Eq)] pub enum ErrorKind { #[fail(display = "io error")] Io, #[fail(display = "poisoned error: {}", _0)] Poisoned(String), #[fail(display = "disconnected channel error: {}", name)] Disconnected { name: String }, #[fail(display = "message format error: {}", message)] MessageFormat { message: String }, #[fail(display = "authentication error: general")] Authentication, #[fail(display = "authentication error: no acceptable method")] NoAcceptableMethod, #[fail(display = "authentication error: unrecognized username/password")] UnrecognizedUsernamePassword, #[fail(display = "command not supported: {:?}", cmd)] CommandNotSupported { cmd: Command }, #[fail(display = "host unreachable: {}:{}", host, port)] HostUnreachable { host: String, port: u16 }, #[fail(display = "name not resolved: {}:{}", domain, port)] DomainNotResolved { domain: String, port: u16 }, #[fail(display = "packet size limit exceeded: {} > {}", size, limit)] PacketSizeLimitExceeded { size: usize, limit: usize }, #[fail(display = "address already in use: {}", addr)] AddressAlreadInUse { addr: SocketAddr }, #[fail(display = "address not available: {}", addr)] AddressNotAvailable { addr: SocketAddr }, /// rejected by gatekeeper #[fail(display = "connection not allowed: {}: {}", addr, protocol)] ConnectionNotAllowed { addr: Address, protocol: L4Protocol }, /// rejected by external server #[fail(display = "connection refused: {}: {}", addr, protocol)] ConnectionRefused { addr: Address, protocol: L4Protocol }, } impl ErrorKind { pub fn disconnected<S: Into<String>>(name: S) -> Self { ErrorKind::Disconnected { name: name.into() } } pub fn message_fmt(message: fmt::Arguments) -> Self { ErrorKind::MessageFormat { message: message.to_string(), } } pub fn command_not_supported(cmd: Command) -> Self { ErrorKind::CommandNotSupported { cmd } } pub fn connection_not_allowed(addr: Address, protocol: L4Protocol) -> Self { ErrorKind::ConnectionNotAllowed { addr, protocol } } pub fn connection_refused(addr: Address, protocol: L4Protocol) -> Self { ErrorKind::ConnectionRefused { addr, protocol } } } #[derive(Debug)] pub struct Error { inner: Context<ErrorKind>, } impl Fail for Error { fn cause(&self) -> Option<&dyn Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&self.inner, f) } } impl Error { pub fn new(inner: Context<ErrorKind>) -> Error { Error { inner } } pub fn kind(&self) -> &ErrorKind { self.inner.get_context() } pub fn cerr(&self) -> ConnectError { use ConnectError as CErr; use ErrorKind as K; match self.kind() { K::Io => CErr::ServerFailure, K::Poisoned(_) => CErr::ServerFailure, K::Disconnected { .. } => CErr::ServerFailure, K::MessageFormat { .. } => CErr::ServerFailure, K::Authentication => CErr::ConnectionNotAllowed, K::NoAcceptableMethod => CErr::ConnectionNotAllowed, K::UnrecognizedUsernamePassword => CErr::ConnectionNotAllowed, K::CommandNotSupported { .. } => CErr::CommandNotSupported, K::HostUnreachable { .. } => CErr::HostUnreachable, K::DomainNotResolved { .. } => CErr::NetworkUnreachable, K::PacketSizeLimitExceeded { .. } => CErr::ServerFailure, K::AddressAlreadInUse { .. } => CErr::ServerFailure, K::AddressNotAvailable { .. } => CErr::ServerFailure, K::ConnectionNotAllowed { .. } => CErr::ConnectionNotAllowed, K::ConnectionRefused { .. } => CErr::ConnectionRefused, } } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { inner: Context::new(kind), } } } impl From<Context<ErrorKind>> for Error { fn from(inner: Context<ErrorKind>) -> Error { Error { inner } } } impl From<std::io::Error> for Error { fn from(error: std::io::Error) -> Self { Error { inner: error.context(ErrorKind::Io), } } } impl<T: fmt::Debug> From<sync::PoisonError<T>> for Error { fn from(error: sync::PoisonError<T>) -> Self { ErrorKind::Poisoned(format!("{:?}", error)).into() } }
use futures::{Poll, Async}; use futures::stream::Stream; pub trait BorrowStream<'a> { /// The type of item this stream will yield on success. type Item; /// The type of error this stream may generate. type Error; fn poll(&'a mut self) -> Poll<Option<Self::Item>, Self::Error>; }
pub use sys;
/// Application config pub mod config; /// Application export pub mod http;
use std::io::Write; use std::mem; use std::net::{Ipv4Addr, Ipv6Addr}; use byteorder::{ByteOrder, WriteBytesExt}; use nom::*; use errors::{PcapError, Result}; use pcapng::options::{opt, parse_options, Opt, Options}; use pcapng::{Block, BlockType}; use traits::WriteTo; pub const BLOCK_TYPE: u32 = 0x0000_0001; pub const IF_NAME: u16 = 2; pub const IF_DESCRIPTION: u16 = 3; pub const IF_IPV4ADDR: u16 = 4; pub const IF_IPV6ADDR: u16 = 5; pub const IF_MACADDR: u16 = 6; pub const IF_EUIADDR: u16 = 7; pub const IF_SPEED: u16 = 8; pub const IF_TSRESOL: u16 = 9; pub const IF_TZONE: u16 = 10; pub const IF_FILTER: u16 = 11; pub const IF_OS: u16 = 12; pub const IF_FCSLEN: u16 = 13; pub const IF_TSOFFSET: u16 = 14; pub const DEFAULT_TIMESTAMP_RESOLUTION: u64 = 100_0000; /// This option is a UTF-8 string containing the name of the device used to capture data. pub fn if_name<T: AsRef<str> + ?Sized>(value: &T) -> Opt { opt(IF_NAME, value.as_ref()) } /// This option is a UTF-8 string containing the description of the device used to capture data. pub fn if_description<T: AsRef<str> + ?Sized>(value: &T) -> Opt { opt(IF_DESCRIPTION, value.as_ref()) } /// This option s an IPv4 network address and corresponding netmask for the interface. pub fn if_ipv4addr<'a, T: Into<Ipv4Addr>>(addr: T, mask: T) -> Opt<'a> { let mut buf = addr.into().octets().to_vec(); buf.write_all(&mask.into().octets()[..]).unwrap(); Opt::new(IF_IPV4ADDR, buf) } /// This option is an IPv6 network address and corresponding prefix length for the interface. pub fn if_ipv6addr<'a, T: Into<Ipv6Addr>>(addr: T, prefix: u8) -> Opt<'a> { let mut buf = addr.into().octets().to_vec(); buf.push(prefix); Opt::new(IF_IPV6ADDR, buf) } pub type MacAddr = [u8; 6]; /// This option is the Interface Hardware MAC address (48 bits), if available. pub fn if_macaddr<'a>(addr: MacAddr) -> Opt<'a> { Opt::new(IF_MACADDR, addr.to_vec()) } pub type EuiAddr = [u8; 8]; /// This option is the Interface Hardware EUI address (64 bits), if available. pub fn if_euiaddr<'a>(addr: EuiAddr) -> Opt<'a> { Opt::new(IF_EUIADDR, addr.to_vec()) } /// This option is a 64-bit number for the Interface speed (in bits per second). pub fn if_speed<'a, T: ByteOrder>(value: u64) -> Opt<'a> { Opt::u64::<T>(IF_SPEED, value) } /// This option identifies the resolution of timestamps. pub fn if_tsresol<'a>(resolution: u64) -> Opt<'a> { Opt::new( IF_TSRESOL, vec![if resolution.is_power_of_two() { (resolution.trailing_zeros() as u8) | 0x80 } else { (resolution as f64).log10().round() as u8 }], ) } /// This option identifies the time zone for GMT support. pub fn if_tzone<'a, T: ByteOrder>(tzone: u32) -> Opt<'a> { Opt::u32::<T>(IF_TZONE, tzone) } /// This option identifies the filter (e.g. "capture only TCP traffic") used to capture traffic. pub fn if_filter<T: AsRef<str> + ?Sized>(value: &T) -> Opt { opt(IF_FILTER, value.as_ref()) } /// This option is a UTF-8 string containing the name of the operating system of the machine /// in which this interface is installed. pub fn if_os<T: AsRef<str> + ?Sized>(value: &T) -> Opt { opt(IF_OS, value.as_ref()) } /// This option is an 8-bit unsigned integer value that specifies /// the length of the Frame Check Sequence (in bits) for this interface. pub fn if_fcslen<'a>(bits: u8) -> Opt<'a> { Opt::new(IF_FCSLEN, vec![bits]) } /// This option is a 64-bit integer value that specifies an offset (in seconds) /// that must be added to the timestamp of each packet to obtain the absolute timestamp of a packet. pub fn if_tsoffset<'a, T: ByteOrder>(value: u64) -> Opt<'a> { Opt::u64::<T>(IF_TSOFFSET, value) } /// An Interface Description Block (IDB) is the container for information describing an interface /// on which packet data is captured. #[derive(Clone, Debug, PartialEq)] pub struct InterfaceDescription<'a> { /// a value that defines the link layer type of this interface. pub link_type: u16, /// not used pub reserved: u16, /// maximum number of octets captured from each packet. pub snap_len: u32, /// a list of options pub options: Options<'a>, } impl<'a> InterfaceDescription<'a> { pub fn block_type() -> BlockType { BlockType::InterfaceDescription } pub fn size(&self) -> usize { self.options.iter().fold( mem::size_of::<u16>() * 2 + mem::size_of::<u32>(), |size, opt| size + opt.size(), ) } pub fn parse(buf: &'a [u8], endianness: Endianness) -> Result<(&'a [u8], Self)> { parse_interface_description(buf, endianness).map_err(|err| PcapError::from(err).into()) } pub fn name(&self) -> Option<&str> { self.options .iter() .find(|opt| opt.code == IF_NAME) .and_then(|opt| opt.as_str()) } pub fn description(&self) -> Option<&str> { self.options .iter() .find(|opt| opt.code == IF_DESCRIPTION) .and_then(|opt| opt.as_str()) } pub fn ipv4addr(&self) -> Vec<(Ipv4Addr, Ipv4Addr)> { self.options .iter() .filter(|opt| opt.code == IF_IPV4ADDR && opt.value.len() == mem::size_of::<u32>() * 2) .map(|opt| { ( Ipv4Addr::from(*array_ref![opt.value, 0, 4]), Ipv4Addr::from(*array_ref![opt.value, 4, 4]), ) }) .collect() } pub fn ipv6addr(&self) -> Vec<(Ipv6Addr, u8)> { self.options .iter() .filter(|opt| opt.code == IF_IPV6ADDR && opt.value.len() == 17) .map(|opt| (Ipv6Addr::from(*array_ref![opt.value, 0, 16]), opt.value[16])) .collect() } pub fn macaddr(&self) -> Option<&MacAddr> { self.options .iter() .find(|opt| opt.code == IF_MACADDR && opt.value.len() == 6) .map(|opt| array_ref![opt.value, 0, 6]) } pub fn euiaddr(&self) -> Option<&EuiAddr> { self.options .iter() .find(|opt| opt.code == IF_EUIADDR && opt.value.len() == 8) .map(|opt| array_ref![opt.value, 0, 8]) } pub fn speed<T: ByteOrder>(&self) -> Option<u64> { self.options .iter() .find(|opt| opt.code == IF_SPEED && opt.value.len() == mem::size_of::<u64>()) .map(|opt| T::read_u64(&opt.value)) } pub fn tsresol(&self) -> Option<u64> { self.options .iter() .find(|opt| opt.code == IF_TSRESOL && opt.value.len() == 1) .map(|opt| { let n = opt.value[0]; if (n & 0x80) == 0x80 { let tsresol_shift = n & 0x7F; if tsresol_shift < 64 { 1 << tsresol_shift } else { DEFAULT_TIMESTAMP_RESOLUTION } } else { let tsresol_opt = n as i8; if tsresol_opt < 20 { 10u64.pow(tsresol_opt as u32) } else { DEFAULT_TIMESTAMP_RESOLUTION } } }) } pub fn tzone<T: ByteOrder>(&self) -> Option<u32> { self.options .iter() .find(|opt| opt.code == IF_TZONE && opt.value.len() == mem::size_of::<u32>()) .map(|opt| T::read_u32(&opt.value)) } pub fn filter(&self) -> Option<&str> { self.options .iter() .find(|opt| opt.code == IF_FILTER) .and_then(|opt| opt.as_str()) } pub fn os(&self) -> Option<&str> { self.options .iter() .find(|opt| opt.code == IF_OS) .and_then(|opt| opt.as_str()) } pub fn fcslen(&self) -> Option<u8> { self.options .iter() .find(|opt| opt.code == IF_FCSLEN && opt.value.len() == 1) .map(|opt| opt.value[0]) } pub fn tsoffset<T: ByteOrder>(&self) -> Option<u64> { self.options .iter() .find(|opt| opt.code == IF_TSOFFSET && opt.value.len() == mem::size_of::<u64>()) .map(|opt| T::read_u64(&opt.value)) } } /// 0 1 2 3 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 /// +---------------------------------------------------------------+ /// 0 | Block Type = 0x00000001 | /// +---------------------------------------------------------------+ /// 4 | Block Total Length | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// 8 | LinkType | Reserved | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// 12 | SnapLen | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// 16 / / /// / Options (variable) / /// / / /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// | Block Total Length | /// +---------------------------------------------------------------+ named_args!(parse_interface_description(endianness: Endianness)<InterfaceDescription>, do_parse!( link_type: u16!(endianness) >> reserved: u16!(endianness) >> snap_len: u32!(endianness) >> options: apply!(parse_options, endianness) >> ( InterfaceDescription { link_type, reserved, snap_len, options, } ) ) ); impl<'a> WriteTo for InterfaceDescription<'a> { fn write_to<T: ByteOrder, W: Write>(&self, w: &mut W) -> Result<usize> { w.write_u16::<T>(self.link_type)?; w.write_u16::<T>(self.reserved)?; w.write_u32::<T>(self.snap_len)?; self.options.write_to::<T, _>(w)?; Ok(self.size()) } } impl<'a> Block<'a> { pub fn is_interface_description(&self) -> bool { self.ty == BLOCK_TYPE } pub fn as_interface_description( &'a self, endianness: Endianness, ) -> Option<InterfaceDescription<'a>> { if self.is_interface_description() { InterfaceDescription::parse(&self.body, endianness) .map(|(_, interface_description)| interface_description) .map_err(|err| { warn!("fail to parse interface description: {:?}", err); hexdump!(self.body); err }) .ok() } else { None } } } #[cfg(test)] pub mod tests { use byteorder::LittleEndian; use super::*; use pcapng::Block; use LinkType; pub const LE_INTERFACE_DESCRIPTION: &[u8] = b"\x01\x00\x00\x00\ \x5C\x00\x00\x00\ \x01\x00\ \x00\x00\ \x00\x00\x08\x00\ \x02\x00\x03\x00en0\x00\ \x09\x00\x01\x00\x06\x00\x00\x00\ \x0C\x00\x2D\x00Mac OS X 10.13.6, build 17G65 (Darwin 17.7.0)\x00\x00\x00\ \x00\x00\x00\x00\ \x5C\x00\x00\x00"; lazy_static! { static ref INTERFACE_DESCRIPTION: InterfaceDescription<'static> = InterfaceDescription { link_type: LinkType::ETHERNET as u16, reserved: 0, snap_len: 0x080000, options: vec![ if_name("en0"), if_tsresol(1000000), if_os("Mac OS X 10.13.6, build 17G65 (Darwin 17.7.0)"), ], }; } #[test] fn test_parse() { let (remaining, block) = Block::parse(LE_INTERFACE_DESCRIPTION, Endianness::Little).unwrap(); assert_eq!(remaining, b""); assert_eq!(block.ty, BLOCK_TYPE); assert_eq!(block.size(), LE_INTERFACE_DESCRIPTION.len()); let interface_description = block.as_interface_description(Endianness::Little).unwrap(); assert_eq!(interface_description, *INTERFACE_DESCRIPTION); } #[test] fn test_write() { let mut buf = vec![]; let wrote = INTERFACE_DESCRIPTION .write_to::<LittleEndian, _>(&mut buf) .unwrap(); assert_eq!(wrote, INTERFACE_DESCRIPTION.size()); assert_eq!( buf.as_slice(), &LE_INTERFACE_DESCRIPTION[8..LE_INTERFACE_DESCRIPTION.len() - 4] ); } #[test] fn test_options() { let interface_description = InterfaceDescription { link_type: LinkType::ETHERNET as u16, reserved: 0, snap_len: 0x080000, options: vec![ if_name("en0"), if_description("Broadcom NetXtreme"), if_ipv4addr(Ipv4Addr::new(127, 0, 0, 1), Ipv4Addr::new(255, 255, 255, 0)), if_ipv6addr(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 64), if_macaddr([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]), if_euiaddr([0x02, 0x34, 0x56, 0xFF, 0xFE, 0x78, 0x9A, 0xBC]), if_speed::<LittleEndian>(100000000), if_tsresol(1024), if_tzone::<LittleEndian>(8), if_filter("tcp port 23 and host 192.0.2.5"), if_os("Mac OS X 10.13.6, build 17G65 (Darwin 17.7.0)"), if_fcslen(4), if_tsoffset::<LittleEndian>(1234), ], }; let mut buf = vec![]; interface_description .write_to::<LittleEndian, _>(&mut buf) .unwrap(); let (_, interface_description) = InterfaceDescription::parse(&buf, Endianness::Little).unwrap(); assert_eq!(interface_description.name().unwrap(), "en0"); assert_eq!( interface_description.description().unwrap(), "Broadcom NetXtreme" ); assert_eq!( interface_description.ipv4addr(), vec![(Ipv4Addr::new(127, 0, 0, 1), Ipv4Addr::new(255, 255, 255, 0))] ); assert_eq!( interface_description.ipv6addr(), vec![(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 64)] ); assert_eq!( interface_description.macaddr().unwrap(), &[0x00, 0x01, 0x02, 0x03, 0x04, 0x05] ); assert_eq!( interface_description.euiaddr().unwrap(), &[0x02, 0x34, 0x56, 0xFF, 0xFE, 0x78, 0x9A, 0xBC] ); assert_eq!( interface_description.speed::<LittleEndian>().unwrap(), 100000000 ); assert_eq!(interface_description.tsresol().unwrap(), 1024); assert_eq!(interface_description.tzone::<LittleEndian>().unwrap(), 8); assert_eq!( interface_description.filter().unwrap(), "tcp port 23 and host 192.0.2.5" ); assert_eq!( interface_description.os().unwrap(), "Mac OS X 10.13.6, build 17G65 (Darwin 17.7.0)" ); assert_eq!(interface_description.fcslen().unwrap(), 4); assert_eq!( interface_description.tsoffset::<LittleEndian>().unwrap(), 1234 ); } }
use specs::prelude::*; use std::{fs::File, io::BufWriter, iter::once}; use png::{Encoder, HasParameters}; use crate::components::{Image, Name, Frame}; pub struct ImageWriter; impl<'a> System<'a> for ImageWriter { type SystemData = ( ReadStorage<'a, Image>, ReadStorage<'a, Name>, ReadStorage<'a, Frame>, ); fn run(&mut self, (image, name, frame): Self::SystemData) { (&image, &name, &frame).join().for_each(Self::write); } } impl ImageWriter { fn write((image, name, frame): (&Image, &Name, &Frame)) { let suffix = format!("-{:04}.png", frame.number); let filename = name.string.clone() + &suffix; let file = File::create(filename).expect("failed to create image file"); let buffer = BufWriter::new(file); let mut encoder = Encoder::new(buffer, image.resolution.x, image.resolution.y); encoder.set(png::ColorType::RGB).set(png::BitDepth::Eight); let mut writer = encoder.write_header().expect("failed to write png header"); writer.write_image_data(&Self::bytes(image)).expect("failed to write png data"); } fn bytes(image: &Image) -> Vec<u8> { image.pixels.iter().flat_map(|pixel| { once(Self::byte(pixel.x)) .chain(once(Self::byte(pixel.y))) .chain(once(Self::byte(pixel.z))) }).collect() } fn byte(mut channel: f64) -> u8 { if channel > 1.0 { channel = 1.0 } if channel < 0.0 { channel = 0.0 } (channel * 255.0).round() as u8 } } #[cfg(test)] mod test;
use crate::component::{Component, Health, Position, Size}; use super::{store::EntityStore, Entity}; use _const::HEALTH; pub struct FactoryEntities { pub es: EntityStore, } #[allow(dead_code)] impl FactoryEntities { pub fn new() -> Self { let es = EntityStore::new(); FactoryEntities { es } } pub fn create_character(&mut self) -> &mut Entity { // Make entity let entity = self .es .create_entity(String::from("player")) .with_component(Component::Position(Position { x: 0, y: 0 })) .with_component(Component::Health(Health(HEALTH))) .with_component(Component::Size(Size { height: 10, width: 10, })) .end(); entity } pub fn get_entity_by_name(&mut self, name: String) -> Option<&mut Entity> { self.es .entities .iter_mut() .find(|c| if c.name == name { true } else { false }) } pub fn get_entity_by_id(&mut self, id: usize) -> Option<&mut Entity> { self.es .entities .iter_mut() .find(|c| if c.id == id { true } else { false }) } pub fn create_enemy(&mut self) -> &mut Entity { // Make entity let entity = self .es .create_entity(String::from("enemy")) .with_component(Component::Position(Position { x: 0, y: 0 })) .with_component(Component::Health(Health(HEALTH))) .with_component(Component::Size(Size { height: 10, width: 10, })) .end(); entity } }
extern crate envconfig; #[macro_use] extern crate envconfig_derive; #[macro_use] extern crate failure; // when using Rust FFI wrapper // #[macro_use] // pub extern crate indyrs as indy; #[macro_use] extern crate lazy_static; // when using libindy = { git = "https://gitlab.com/PatrikStas/vdr-tools", rev = "1473cea" } #[macro_use] extern crate indy; #[macro_use] extern crate log; extern crate pretty_env_logger as env_logger; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; use std::env; use serde_json::Value; use crate::libindy_async::run_async_vdrtools_fork; #[cfg(feature = "ffi")] use crate::libindy_ffi::run_libindy_ffi; #[cfg(feature = "pg")] use crate::pgwallet::wallet_plugin_loader::{init_wallet_plugin, PluginInitConfig}; use indy::utils::logger::LibindyDefaultLogger; use futures::executor::block_on; mod libindy_async; mod utils; #[cfg(feature = "pg")] mod pgwallet; #[cfg(feature = "ffi")] mod libindy_ffi; fn main() { let pattern = env::var("RUST_LOG").ok(); LibindyDefaultLogger::init(pattern); info!("Indy logger initialized"); // env_logger::try_init() // .expect("Can't init env logger"); // indy_set_default_logger(pattern.as_ref().map(String::as_str)); // utils::logger::set_default_logger(pattern.as_ref().map(String::as_str)).unwrap(); let storage_config = r#" { "read_host": "localhost", "write_host": "localhost", "port": 3306, "db_name": "indycratetest", "default_connection_limit": 50 }"#; let storage_credentials = r#" { "user": "root", "pass": "mysecretpassword" }"#; // pg wallet plugin init ... // let init_config: PluginInitConfig = PluginInitConfig { // storage_type: String::from("postgres_storage"), // plugin_library_path: None, // plugin_init_function: None, // config: storage_config.into(), // credentials: storage_credentials.into() // }; // init_wallet_plugin(&init_config).unwrap(); // info!("Init pgsql storage: Finished."); // run_libindy_ffi(storage_credentials, storage_config) let storage_credentials = Some(serde_json::from_str(storage_credentials).unwrap()); let storage_config = Some(serde_json::from_str(storage_config).unwrap()); block_on(run_async_vdrtools_fork(storage_credentials, storage_config, Some("mysql".into()))); }
//! An animated solar system. //! //! This example showcases how to use a `Canvas` widget with transforms to draw //! using different coordinate systems. //! //! Inspired by the example found in the MDN docs[1]. //! //! [1]: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations#An_animated_solar_system use iced::{ canvas, executor, window, Application, Canvas, Color, Command, Container, Element, Length, Point, Settings, Size, Subscription, Vector, }; use std::time::Instant; pub fn main() { SolarSystem::run(Settings { antialiasing: true, ..Settings::default() }) } struct SolarSystem { state: State, solar_system: canvas::layer::Cache<State>, } #[derive(Debug, Clone, Copy)] enum Message { Tick(Instant), } impl Application for SolarSystem { type Executor = executor::Default; type Message = Message; type Flags = (); fn new(_flags: ()) -> (Self, Command<Message>) { ( SolarSystem { state: State::new(), solar_system: Default::default(), }, Command::none(), ) } fn title(&self) -> String { String::from("Solar system - Iced") } fn update(&mut self, message: Message) -> Command<Message> { match message { Message::Tick(instant) => { self.state.update(instant); self.solar_system.clear(); } } Command::none() } fn subscription(&self) -> Subscription<Message> { time::every(std::time::Duration::from_millis(10)) .map(|instant| Message::Tick(instant)) } fn view(&mut self) -> Element<Message> { let canvas = Canvas::new() .width(Length::Fill) .height(Length::Fill) .push(self.solar_system.with(&self.state)); Container::new(canvas) .width(Length::Fill) .height(Length::Fill) .center_x() .center_y() .into() } } #[derive(Debug)] struct State { start: Instant, current: Instant, stars: Vec<(Point, f32)>, } impl State { const SUN_RADIUS: f32 = 70.0; const ORBIT_RADIUS: f32 = 150.0; const EARTH_RADIUS: f32 = 12.0; const MOON_RADIUS: f32 = 4.0; const MOON_DISTANCE: f32 = 28.0; pub fn new() -> State { let now = Instant::now(); let (width, height) = window::Settings::default().size; State { start: now, current: now, stars: { use rand::Rng; let mut rng = rand::thread_rng(); (0..100) .map(|_| { ( Point::new( rng.gen_range(0.0, width as f32), rng.gen_range(0.0, height as f32), ), rng.gen_range(0.5, 1.0), ) }) .collect() }, } } pub fn update(&mut self, now: Instant) { self.current = now; } } impl canvas::Drawable for State { fn draw(&self, frame: &mut canvas::Frame) { use canvas::{Path, Stroke}; use std::f32::consts::PI; let center = frame.center(); let space = Path::rectangle(Point::new(0.0, 0.0), frame.size()); let stars = Path::new(|path| { for (p, size) in &self.stars { path.rectangle(*p, Size::new(*size, *size)); } }); let sun = Path::circle(center, Self::SUN_RADIUS); let orbit = Path::circle(center, Self::ORBIT_RADIUS); frame.fill(&space, Color::BLACK); frame.fill(&stars, Color::WHITE); frame.fill(&sun, Color::from_rgb8(0xF9, 0xD7, 0x1C)); frame.stroke( &orbit, Stroke { width: 1.0, color: Color::from_rgba8(0, 153, 255, 0.1), ..Stroke::default() }, ); let elapsed = self.current - self.start; let elapsed_seconds = elapsed.as_secs() as f32; let elapsed_millis = elapsed.subsec_millis() as f32; frame.with_save(|frame| { frame.translate(Vector::new(center.x, center.y)); frame.rotate( (2.0 * PI / 60.0) * elapsed_seconds + (2.0 * PI / 60_000.0) * elapsed_millis, ); frame.translate(Vector::new(Self::ORBIT_RADIUS, 0.0)); let earth = Path::circle(Point::ORIGIN, Self::EARTH_RADIUS); let shadow = Path::rectangle( Point::new(0.0, -Self::EARTH_RADIUS), Size::new(Self::EARTH_RADIUS * 4.0, Self::EARTH_RADIUS * 2.0), ); frame.fill(&earth, Color::from_rgb8(0x6B, 0x93, 0xD6)); frame.with_save(|frame| { frame.rotate( ((2.0 * PI) / 6.0) * elapsed_seconds + ((2.0 * PI) / 6_000.0) * elapsed_millis, ); frame.translate(Vector::new(0.0, Self::MOON_DISTANCE)); let moon = Path::circle(Point::ORIGIN, Self::MOON_RADIUS); frame.fill(&moon, Color::WHITE); }); frame.fill( &shadow, Color { a: 0.7, ..Color::BLACK }, ); }); } } mod time { use iced::futures; use std::time::Instant; pub fn every(duration: std::time::Duration) -> iced::Subscription<Instant> { iced::Subscription::from_recipe(Every(duration)) } struct Every(std::time::Duration); impl<H, I> iced_native::subscription::Recipe<H, I> for Every where H: std::hash::Hasher, { type Output = Instant; fn hash(&self, state: &mut H) { use std::hash::Hash; std::any::TypeId::of::<Self>().hash(state); self.0.hash(state); } fn stream( self: Box<Self>, _input: futures::stream::BoxStream<'static, I>, ) -> futures::stream::BoxStream<'static, Self::Output> { use futures::stream::StreamExt; async_std::stream::interval(self.0) .map(|_| Instant::now()) .boxed() } } }
//! Cookie-related functionality for WebDriver. use serde::{Deserialize, Serialize}; use time::OffsetDateTime; use webdriver::command::WebDriverCommand; use crate::client::Client; use crate::error; /// Type alias for a [cookie::Cookie] pub type Cookie<'a> = cookie::Cookie<'a>; /// Representation of a cookie as [defined by WebDriver](https://www.w3.org/TR/webdriver1/#cookies). #[derive(Debug, Deserialize, Serialize)] struct WebDriverCookie { name: String, value: String, path: Option<String>, domain: Option<String>, secure: Option<bool>, #[serde(rename = "httpOnly")] http_only: Option<bool>, expiry: Option<u64>, } impl From<WebDriverCookie> for Cookie<'static> { fn from(webdriver_cookie: WebDriverCookie) -> Self { let mut cookie = cookie::Cookie::new(webdriver_cookie.name, webdriver_cookie.value); if let Some(path) = webdriver_cookie.path { cookie.set_path(path); } if let Some(domain) = webdriver_cookie.domain { cookie.set_domain(domain); } if let Some(secure) = webdriver_cookie.secure { cookie.set_secure(secure); } if let Some(http_only) = webdriver_cookie.http_only { cookie.set_http_only(http_only); } if let Some(expiry) = webdriver_cookie.expiry { let dt = OffsetDateTime::from_unix_timestamp(expiry as i64); cookie.set_expires(dt); } cookie } } impl<'a> From<Cookie<'a>> for WebDriverCookie { fn from(cookie: Cookie<'a>) -> Self { let name = cookie.name().to_string(); let value = cookie.value().to_string(); let path = cookie.path().map(String::from); let domain = cookie.domain().map(String::from); let secure = cookie.secure(); let http_only = cookie.http_only(); let expiry = cookie.expires().map(|dt| dt.unix_timestamp() as u64); Self { name, value, path, domain, secure, http_only, expiry, } } } /// [Cookies](https://www.w3.org/TR/webdriver1/#cookies) impl Client { /// Get all cookies associated with the current document. /// /// See [16.1 Get All Cookies](https://www.w3.org/TR/webdriver1/#get-all-cookies) of the /// WebDriver standard. pub async fn get_all_cookies(&mut self) -> Result<Vec<Cookie<'static>>, error::CmdError> { let resp = self.issue(WebDriverCommand::GetCookies).await?; let webdriver_cookies: Vec<WebDriverCookie> = serde_json::from_value(resp)?; let cookies: Vec<Cookie<'static>> = webdriver_cookies .into_iter() .map(|raw_cookie| raw_cookie.into()) .collect(); Ok(cookies) } /// Get a single named cookie associated with the current document. /// /// See [16.2 Get Named Cookie](https://www.w3.org/TR/webdriver1/#get-named-cookie) of the /// WebDriver standard. pub async fn get_named_cookie( &mut self, name: &str, ) -> Result<Cookie<'static>, error::CmdError> { let resp = self .issue(WebDriverCommand::GetNamedCookie(name.to_string())) .await?; let webdriver_cookie: WebDriverCookie = serde_json::from_value(resp)?; Ok(webdriver_cookie.into()) } /// Delete a single cookie from the current document. /// /// See [16.4 Delete Cookie](https://www.w3.org/TR/webdriver1/#delete-cookie) of the /// WebDriver standard. pub async fn delete_cookie(&mut self, name: &str) -> Result<(), error::CmdError> { self.issue(WebDriverCommand::DeleteCookie(name.to_string())) .await .map(|_| ()) } /// Delete all cookies from the current document. /// /// See [16.5 Delete All Cookies](https://www.w3.org/TR/webdriver1/#delete-all-cookies) of the /// WebDriver standard. pub async fn delete_all_cookies(&mut self) -> Result<(), error::CmdError> { self.issue(WebDriverCommand::DeleteCookies) .await .map(|_| ()) } }
//! Entities related to users. pub mod current_user; pub use self::current_user::{CurrentUserEntity, CurrentUserRepository}; use crate::{ entity::{guild::GuildEntity, Entity}, repository::{ListEntitiesFuture, ListEntityIdsFuture, Repository}, utils, Backend, }; use twilight_model::{ id::{GuildId, UserId}, user::{PremiumType, User, UserFlags}, }; #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct UserEntity { pub avatar: Option<String>, pub bot: bool, pub discriminator: String, pub email: Option<String>, pub flags: Option<UserFlags>, pub id: UserId, pub locale: Option<String>, pub mfa_enabled: Option<bool>, pub name: String, pub premium_type: Option<PremiumType>, pub public_flags: Option<UserFlags>, pub system: Option<bool>, pub verified: Option<bool>, } impl From<User> for UserEntity { fn from(user: User) -> Self { Self { avatar: user.avatar, bot: user.bot, discriminator: user.discriminator, email: user.email, flags: user.flags, id: user.id, locale: user.locale, mfa_enabled: user.mfa_enabled, name: user.name, premium_type: user.premium_type, public_flags: user.public_flags, system: user.system, verified: user.verified, } } } impl Entity for UserEntity { type Id = UserId; /// Return the user's ID. fn id(&self) -> Self::Id { self.id } } pub trait UserRepository<B: Backend>: Repository<UserEntity, B> { /// Retrieve a stream of guild IDs associated with a user. fn guild_ids(&self, user_id: UserId) -> ListEntityIdsFuture<'_, GuildId, B::Error>; /// Retrieve a stream of guilds associated with a user. fn guilds(&self, user_id: UserId) -> ListEntitiesFuture<'_, GuildEntity, B::Error> { utils::stream_ids(self.guild_ids(user_id), self.backend().guilds()) } }
use termion::event::Key; use termion::input::Keys; #[derive(PartialEq, Debug)] pub enum Action { HardExit, Up, Down, Left, Right, } pub fn to_action(c: Key) -> Option<Action> { match c { Key::Esc | Key::Ctrl('c') => Some(Action::HardExit), Key::Up | Key::Char('k') => Some(Action::Up), Key::Down | Key::Char('j') => Some(Action::Down), Key::Right | Key::Char('l') => Some(Action::Right), Key::Left | Key::Char('h') => Some(Action::Left), _ => None, } } pub trait Buffer { fn step(&mut self) -> Vec<Action>; } pub struct Input<R> { keys: Keys<R>, } impl<R> Input<R> { pub fn new(keys: Keys<R>) -> Input<R> { Input { keys } } } impl<R: std::io::Read> Buffer for Input<R> { fn step(&mut self) -> Vec<Action> { let mut result: Vec<Action> = vec![]; loop { match self.keys.next() { Some(a) => match to_action(a.unwrap()) { Some(a) => result.push(a), None => (), }, None => break, } } return result; } } #[cfg(test)] mod tests { use super::*; use termion::input::TermRead; #[test] fn reads_single_key() { let keys = b"k".keys(); let mut input = Input::new(keys); let actions = input.step(); assert_eq!(actions.len(), 1); assert_eq!(actions[0], Action::Up); } #[test] fn reads_same_key_multiple_times() { let keys = b"kkkk".keys(); let mut input = Input::new(keys); let actions = input.step(); assert_eq!(actions.len(), 4); for action in actions { assert_eq!(action, Action::Up); } } #[test] fn reads_nothing_with_unused_keys() { let keys = b"____".keys(); let mut input = Input::new(keys); let actions = input.step(); assert_eq!(actions.len(), 0); } #[test] fn reads_key_after_unused_keys() { let keys = b"____j".keys(); let mut input = Input::new(keys); let actions = input.step(); assert_eq!(actions.len(), 1); assert_eq!(actions[0], Action::Down); } #[test] fn reads_multiple_different_keys() { let keys = b"kj".keys(); let mut input = Input::new(keys); let actions = input.step(); assert_eq!(actions.len(), 2); assert_eq!(actions[0], Action::Up); assert_eq!(actions[1], Action::Down); } }
use crate::cmd::Cmd; use std::fmt::{Display, Error, Formatter}; impl Display for IOTCM { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!( f, "IOTCM {:?} {:?} {:?} {}", self.file, self.level, self.method, self.command ) } } /// How much highlighting should be sent to the user interface? #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum HighlightingLevel { None, NonInteractive, /// This includes both non-interactive highlighting and /// interactive highlighting of the expression that is currently /// being type-checked. Interactive, } impl Default for HighlightingLevel { fn default() -> Self { HighlightingLevel::NonInteractive } } /// How should highlighting be sent to the user interface? #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum HighlightingMethod { /// Via stdout. Direct, /// Both via files and via stdout. Indirect, } impl Default for HighlightingMethod { fn default() -> Self { HighlightingMethod::Direct } } #[derive(Debug, Clone)] pub struct IOTCM { level: HighlightingLevel, file: String, method: HighlightingMethod, pub command: Cmd, } impl IOTCM { pub fn new( level: HighlightingLevel, file: String, method: HighlightingMethod, command: Cmd, ) -> Self { Self { level, file, method, command, } } pub fn simple(file: String, command: Cmd) -> Self { Self::new(Default::default(), file, Default::default(), command) } /// Convert `self` into a command string. pub fn to_string(&self) -> String { format!("{}\n", self) } }
#[derive(Debug, PartialEq, Clone)] pub enum Error { // Illegal redeclaration of a name IllegalRedeclaration { name: String, }, // Name used before it was declared UndeclaredIdentifier { name: String, }, // Tried to declare a zero size variable DeclaredZeroSize { name: String, }, // Declaration contained a size, but it was invalid DeclaredIncorrectSize { name: String, expected: usize, actual: usize, }, // The expression assigned to a variable `name` was the incorrect size IncorrectSizedExpression { name: String, expected: usize, actual: usize, }, // Cannot assign a name to itself since that doesn't make any sense SelfAssignment { name: String, }, // We do not support `in foo[]` since we do not have dynamic strings UnspecifiedInputSizeUnsupported { name: String, }, // We do not support string literals as loop conditions since this doesn't // really make any sense LoopStringLiteralUnsupported {}, // Conditions must be size one so we can tell if they are zero or non-zero ConditionSizeInvalid { expected: usize, actual: usize, }, }
use crate::token; use crate::token::Token; use std::iter::Peekable; use std::str::Chars; pub struct Lexer<'a> { input: Peekable<Chars<'a>>, } impl<'a> Lexer<'a> { pub fn new(input: &'a str) -> Lexer<'_> { Lexer{ input: input.chars().peekable(), } } pub fn next_token(&mut self) -> Token { self.eat_whitespace(); match self.read_char() { Some('=') => { if let Some('=') = self.peek_char() { self.read_char(); Token::Eq } else { Token::Assign } }, Some('+') => Token::Plus, Some('(') => Token::Lparen, Some(')') => Token::Rparen, Some('{') => Token::Lbrace, Some('}') => Token::Rbrace, Some('[') => Token::Lbracket, Some(']') => Token::Rbracket, Some(',') => Token::Comma, Some(';') => Token::Semicolon, Some(':') => Token::Colon, Some('-') => Token::Minus, Some('!') => { if let Some('=') = self.peek_char() { self.read_char(); Token::Neq } else { Token::Bang } }, Some('*') => Token::Asterisk, Some('/') => Token::Slash, Some('<') => Token::Lt, Some('>') => Token::Gt, Some(ch) => { if is_letter(ch) { let ident = self.read_identifier(ch); let tok = token::lookup_ident(ident); tok } else if ch.is_digit(10) { Token::Int(self.read_int(ch)) } else if ch == '"' { Token::String(self.read_string()) } else { Token::Illegal } }, None => Token::EOF, } } fn read_string(&mut self) -> String { let mut str = String::new(); while let Some(ch) = self.read_char() { if ch == '"' { return str; } str.push(ch); } str } fn eat_whitespace(&mut self) { while let Some(&ch) = self.input.peek() { if ch.is_whitespace() { self.read_char(); } else { break; } } } fn read_char(&mut self) -> Option<char> { self.input.next() } fn peek_char(&mut self) -> Option<&char> { self.input.peek() } fn read_int(&mut self, ch: char) -> i64 { let mut s = String::new(); s.push(ch); while let Some(&ch) = self.peek_char() { if ch.is_digit(10) { s.push(self.read_char().unwrap()); } else { break; } } s.parse().unwrap() } fn read_identifier(&mut self, ch: char) -> String { let mut ident = String::new(); ident.push(ch); while let Some(&ch) = self.peek_char() { if is_letter(ch) { ident.push(self.read_char().unwrap()); } else { break; } } ident } } impl<'a> Iterator for Lexer<'a> { type Item = Token; fn next(&mut self) -> Option<Self::Item> { let tok = self.next_token(); if tok == Token::EOF { None } else { Some(tok) } } } fn is_letter(ch: char) -> bool { ch.is_alphabetic() || ch == '_' } #[cfg(test)] mod test { use crate::token::Token; use super::*; #[test] fn next_token() { let input = r#"let five = 5; let ten = 10; let add = fn(x, y) { x + y; }; let result = add(five, ten); !-/*5; 5 < 10 > 5; if (5 < 10) { return true; } else { return false; } 10 == 10; 10 != 9; "foobar" "foo bar" [1, 2]; {"foo": "bar"}"#; let tests = vec![ Token::Let, Token::Ident("five".to_string()), Token::Assign, Token::Int(5), Token::Semicolon, Token::Let, Token::Ident("ten".to_string()), Token::Assign, Token::Int(10), Token::Semicolon, Token::Let, Token::Ident("add".to_string()), Token::Assign, Token::Function, Token::Lparen, Token::Ident("x".to_string()), Token::Comma, Token::Ident("y".to_string()), Token::Rparen, Token::Lbrace, Token::Ident("x".to_string()), Token::Plus, Token::Ident("y".to_string()), Token::Semicolon, Token::Rbrace, Token::Semicolon, Token::Let, Token::Ident("result".to_string()), Token::Assign, Token::Ident("add".to_string()), Token::Lparen, Token::Ident("five".to_string()), Token::Comma, Token::Ident("ten".to_string()), Token::Rparen, Token::Semicolon, Token::Bang, Token::Minus, Token::Slash, Token::Asterisk, Token::Int(5), Token::Semicolon, Token::Int(5), Token::Lt, Token::Int(10), Token::Gt, Token::Int(5), Token::Semicolon, Token::If, Token::Lparen, Token::Int(5), Token::Lt, Token::Int(10), Token::Rparen, Token::Lbrace, Token::Return, Token::True, Token::Semicolon, Token::Rbrace, Token::Else, Token::Lbrace, Token::Return, Token::False, Token::Semicolon, Token::Rbrace, Token::Int(10), Token::Eq, Token::Int(10), Token::Semicolon, Token::Int(10), Token::Neq, Token::Int(9), Token::Semicolon, Token::String("foobar".to_string()), Token::String("foo bar".to_string()), Token::Lbracket, Token::Int(1), Token::Comma, Token::Int(2), Token::Rbracket, Token::Semicolon, Token::Lbrace, Token::String("foo".to_string()), Token::Colon, Token::String("bar".to_string()), Token::Rbrace, Token::EOF, ]; let mut l = Lexer::new(input); for t in tests.iter() { let tok = l.next_token(); assert_eq!(*t, tok, "expected {} token but got {}", t, tok) } } }
#[macro_use] extern crate yew; mod stone; use stone::{Stone, State}; use yew::prelude::*; pub struct Game { // state: State } pub enum Msg { Reverse, } impl<CTX> Component<CTX> for Game { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: &mut Env<CTX, Self>) -> Self { Game { } } fn update(&mut self, _: Self::Message, _: &mut Env<CTX, Self>) -> ShouldRender { true } } fn view_stone<CTX>() -> Html<CTX, Game> where CTX: 'static { html! { <td> <Stone: state=State::Back,/> </td> } } fn view_row<CTX>() -> Html<CTX, Game> where CTX: 'static { html! { <tr> {for (0..3).map(|_|{ view_stone() })} </tr> } } impl<CTX> Renderable<CTX, Game> for Game where CTX: 'static, { fn view(&self) -> Html<CTX, Self> { html! { <table border="1", cellpadding="10",> {for (0..3).map(|_| { view_row() })} </table> } } }
#![cfg(feature = "std")] use tabled::{ grid::util::string::string_width_multiline, settings::{ formatting::{TabSize, TrimStrategy}, object::{Columns, Object, Rows, Segment}, peaker::{PriorityMax, PriorityMin}, width::{Justify, MinWidth, SuffixLimit, Width}, Alignment, Margin, Modify, Padding, Panel, Settings, Span, Style, }, }; use crate::matrix::Matrix; use testing_table::{is_lines_equal, static_table, test_table}; #[cfg(feature = "color")] use ::{ansi_str::AnsiStr, owo_colors::OwoColorize}; #[cfg(all(feature = "derive", feature = "color"))] use ::owo_colors::AnsiColors; test_table!( max_width, Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Columns::new(1..).not(Rows::single(0))).with(Width::truncate(1))), "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | 0 | 0 | 0 |" "| 1 | 1 | 1 | 1 |" "| 2 | 2 | 2 | 2 |" ); test_table!( max_width_with_suffix, Matrix::new(3, 3) .with(Style::markdown()) .with( Modify::new(Columns::new(1..).not(Rows::single(0))) .with(Width::truncate(2).suffix("...")), ), "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | .. | .. | .. |" "| 1 | .. | .. | .. |" "| 2 | .. | .. | .. |" ); test_table!( max_width_doesnt_icrease_width_if_it_is_smaller, Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Columns::new(1..).not(Rows::single(0))).with(Width::truncate(50))), "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ); test_table!( max_width_wrapped, Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Columns::new(1..).not(Rows::single(0))).with(Width::wrap(2))), "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | 0- | 0- | 0- |" "| | 0 | 1 | 2 |" "| 1 | 1- | 1- | 1- |" "| | 0 | 1 | 2 |" "| 2 | 2- | 2- | 2- |" "| | 0 | 1 | 2 |" ); test_table!( max_width_wrapped_does_nothing_if_str_is_smaller, Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Columns::new(1..).not(Rows::single(0))).with(Width::wrap(100))), "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ); test_table!( max_width_wrapped_keep_words_0, { let table = Matrix::iter(vec!["this is a long sentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert!(is_lines_equal(&table, 17 + 2 + 2)); table }, "| &str |" "|-------------------|" "| this is a long |" "| sentence |" ); test_table!( max_width_wrapped_keep_words_1, { let table = Matrix::iter(vec!["this is a long sentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert!(is_lines_equal(&table, 17 + 2 + 2)); table }, "| &str |" "|-------------------|" "| this is a long |" "| sentence |" ); test_table!( max_width_wrapped_keep_words_2, { let table = Matrix::iter(vec!["this is a long sentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert!(is_lines_equal(&table, 17 + 2 + 2)); table }, "| &str |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_3, { let table = Matrix::iter(vec!["this is a long sentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert!(is_lines_equal(&table, 17 + 2 + 2)); table }, // 'sentence' doesn't have a space ' sentence' because we use left alignment "| &str |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(not(feature = "color"))] test_table!( max_width_wrapped_keep_words_3, { let table = Matrix::iter(vec!["this is a long sentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert!(is_lines_equal(&table, 17 + 2 + 2)); table }, // 'sentence' doesn't have a space ' sentence' because we use left alignment "| &str |" "|-------------------|" "| this is a long |" "| sentence |" ); test_table!( max_width_wrapped_keep_words_4, { let table = Matrix::iter(vec!["this"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::wrap(10).keep_words())) .to_string(); assert!(is_lines_equal(&table, 8)); table }, "| &str |" "|------|" "| this |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_0, { let table = Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); AnsiStr::ansi_strip(&table).to_string() }, "| String |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_0_1, Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())), "| String |" "|-------------------|" "| \u{1b}[32m\u{1b}[40mthis is a long \u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40msentence\u{1b}[39m\u{1b}[49m |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_1, { let table = Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); AnsiStr::ansi_strip(&table).to_string() }, "| String |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_1_1, Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())), "| String |" "|-------------------|" "| \u{1b}[32m\u{1b}[40mthis is a long \u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40msentence\u{1b}[39m\u{1b}[49m |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_2, { let table = Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); AnsiStr::ansi_strip(&table).to_string() }, "| String |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_2_1, Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())), "| String |" "|-------------------|" "| \u{1b}[32m\u{1b}[40mthis is a long \u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40msentence\u{1b}[39m\u{1b}[49m |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_3, { let table = Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); AnsiStr::ansi_strip(&table).to_string() }, "| String |" "|-------------------|" "| this is a long |" "| sentence |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_3_1, Matrix::iter(vec!["this is a long sentence".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())), "| String |" "|-------------------|" "| \u{1b}[32m\u{1b}[40mthis is a long \u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40m sentence\u{1b}[39m\u{1b}[49m |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_4, { let table = Matrix::iter(vec!["this".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::wrap(10).keep_words())) .to_string(); AnsiStr::ansi_strip(&table).to_string() }, "| String |" "|--------|" "| this |" ); #[cfg(feature = "color")] test_table!( max_width_wrapped_keep_words_color_4_1, Matrix::iter(vec!["this".on_black().green().to_string()]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::wrap(10).keep_words())), "| String |" "|--------|" "| \u{1b}[32;40mthis\u{1b}[0m |" ); test_table!( max_width_wrapped_keep_words_long_word, Matrix::iter(["this is a long sentencesentencesentence"]) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())), "| &str |" "|-------------------|" "| this is a long se |" "| ntencesentencesen |" "| tence |" ); #[cfg(feature = "color")] #[test] fn max_width_wrapped_keep_words_long_word_color() { let data = vec!["this is a long sentencesentencesentence" .on_black() .green() .to_string()]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Modify::new(Segment::all()).with(Width::wrap(17).keep_words())) .to_string(); assert_eq!( ansi_str::AnsiStr::ansi_strip(&table), static_table!( "| String |" "|-------------------|" "| this is a long se |" "| ntencesentencesen |" "| tence |" ) ); assert_eq!( table, static_table!( "| String |" "|-------------------|" "| \u{1b}[32m\u{1b}[40mthis is a long se\u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40mntencesentencesen\u{1b}[39m\u{1b}[49m |" "| \u{1b}[32m\u{1b}[40mtence\u{1b}[39m\u{1b}[49m |" ) ); } #[cfg(feature = "color")] #[test] fn max_width_keep_words_1() { use tabled::settings::style::HorizontalLine; let table = Matrix::iter(["asdf"]) .with(Width::wrap(7).keep_words()) .to_string(); assert_eq!( table, static_table!( "+-----+" "| &st |" "| r |" "+-----+" "| asd |" "| f |" "+-----+" ) ); let table = Matrix::iter(["qweqw eqwe"]) .with(Width::wrap(8).keep_words()) .to_string(); assert_eq!( table, static_table!( "+------+" "| &str |" "+------+" "| qweq |" "| w |" "| eqwe |" "+------+" ) ); let table = Matrix::iter([ ["123 45678", "qweqw eqwe", "..."], ["0", "1", "..."], ["0", "1", "..."], ]) .with( Style::modern() .remove_horizontal() .horizontals([HorizontalLine::new(1, Style::modern().get_horizontal())]), ) .with(Width::wrap(21).keep_words().priority::<PriorityMax>()) .with(Alignment::center()) .to_string(); assert_eq!( table, static_table!( "โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”" "โ”‚ 0 โ”‚ 1 โ”‚ 2 โ”‚" "โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”ค" "โ”‚ 123 โ”‚ qweq โ”‚ ... โ”‚" "โ”‚ 4567 โ”‚ w โ”‚ โ”‚" "โ”‚ 8 โ”‚ eqwe โ”‚ โ”‚" "โ”‚ 0 โ”‚ 1 โ”‚ ... โ”‚" "โ”‚ 0 โ”‚ 1 โ”‚ ... โ”‚" "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”˜" ) ); } #[cfg(feature = "color")] #[test] fn max_width_wrapped_collored() { let data = &[ "asd".red().to_string(), "zxc2".blue().to_string(), "asdasd".on_black().green().to_string(), ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::wrap(2))) .to_string(); assert_eq!( table, "| St |\n| ri |\n| ng |\n|----|\n| \u{1b}[31mas\u{1b}[39m |\n| \u{1b}[31md\u{1b}[39m |\n| \u{1b}[34mzx\u{1b}[39m |\n| \u{1b}[34mc2\u{1b}[39m |\n| \u{1b}[32m\u{1b}[40mas\u{1b}[39m\u{1b}[49m |\n| \u{1b}[32m\u{1b}[40mda\u{1b}[39m\u{1b}[49m |\n| \u{1b}[32m\u{1b}[40msd\u{1b}[39m\u{1b}[49m |" ); } #[test] fn dont_change_content_if_width_is_less_then_max_width() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::truncate(1000).suffix("..."))) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn max_width_with_emoji() { let data = &["๐Ÿค ", "๐Ÿ˜ณ๐Ÿฅต๐Ÿฅถ๐Ÿ˜ฑ๐Ÿ˜จ", "๐Ÿšด๐Ÿปโ€โ™€๏ธ๐Ÿšด๐Ÿป๐Ÿšด๐Ÿปโ€โ™‚๏ธ๐Ÿšต๐Ÿปโ€โ™€๏ธ๐Ÿšต๐Ÿป๐Ÿšต๐Ÿปโ€โ™‚๏ธ"]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::truncate(6).suffix("..."))) .to_string(); assert_eq!( table, static_table!( "| &str |" "|--------|" "| ๐Ÿค  |" "| ๐Ÿ˜ณ๏ฟฝ... |" "| ๐Ÿšด๏ฟฝ... |" ) ); } #[cfg(feature = "color")] #[test] fn color_chars_are_stripped() { let data = &[ "asd".red().to_string(), "zxc".blue().to_string(), "asdasd".on_black().green().to_string(), ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Width::truncate(4).suffix("..."))) .to_string(); assert_eq!( ansi_str::AnsiStr::ansi_strip(&table), static_table!( "| S... |" "|------|" "| asd |" "| zxc |" "| a... |" ) ); assert_eq!( table, "| S... |\n|------|\n| \u{1b}[31masd\u{1b}[39m |\n| \u{1b}[34mzxc\u{1b}[39m |\n| \u{1b}[32;40ma\u{1b}[39m\u{1b}[49m... |", ); } #[test] fn min_width() { let mut table = Matrix::table(3, 3); table .with(Style::markdown()) .with(Modify::new(Rows::single(0)).with(MinWidth::new(12))); assert_eq!( table.to_string(), static_table!( "| N | column 0 | column 1 | column 2 |" "|--------------|--------------|--------------|--------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ), ); table.with(Modify::new(Segment::all()).with(TrimStrategy::None)); assert_eq!( table.to_string(), static_table!( "| N | column 0 | column 1 | column 2 |" "|--------------|--------------|--------------|--------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ), ); } #[test] fn min_width_with_filler() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Rows::single(0)).with(MinWidth::new(12).fill_with('.'))) .to_string(); assert_eq!( table, static_table!( "| N........... | column 0.... | column 1.... | column 2.... |" "|--------------|--------------|--------------|--------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_width_one_column() { let mut table = Matrix::table(3, 3); table .with(Style::markdown()) .with(Modify::new((0, 0)).with(MinWidth::new(5))); assert_eq!( table.to_string(), static_table!( "| N | column 0 | column 1 | column 2 |" "|-------|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); table.with(Modify::new(Segment::all()).with(TrimStrategy::None)); assert_eq!( table.to_string(), static_table!( "| N | column 0 | column 1 | column 2 |" "|-------|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_width_on_smaller_content() { assert_eq!( Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Rows::single(0)).with(MinWidth::new(1))) .to_string(), Matrix::new(3, 3).with(Style::markdown()).to_string() ); } #[test] fn min_with_max_width() { let mut table = Matrix::table(3, 3); table .with(Style::markdown()) .with(Modify::new(Rows::single(0)).with(MinWidth::new(3))) .with(Modify::new(Rows::single(0)).with(Width::truncate(3))); assert_eq!( table.to_string(), static_table!( "| N | col | col | col |" "|-----|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); table.with(Modify::new(Segment::all()).with(TrimStrategy::None)); assert_eq!( table.to_string(), static_table!( "| N | col | col | col |" "|-----|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_with_max_width_truncate_suffix() { let mut table = Matrix::table(3, 3); table .with(Style::markdown()) .with(Modify::new(Rows::single(0)).with(MinWidth::new(3))) .with(Modify::new(Rows::single(0)).with(Width::truncate(3).suffix("..."))); assert_eq!( table.to_string(), static_table!( "| N | ... | ... | ... |" "|-----|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); table.with(Modify::new(Segment::all()).with(TrimStrategy::None)); assert_eq!( table.to_string(), static_table!( "| N | ... | ... | ... |" "|-----|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_with_max_width_truncate_suffix_limit_replace() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with( Modify::new(Rows::single(0)).with( Width::truncate(3) .suffix("...") .suffix_limit(SuffixLimit::Replace('x')), ), ) .to_string(); assert_eq!( table, static_table!( "| N | xxx | xxx | xxx |" "|---|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_with_max_width_truncate_suffix_limit_cut() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with( Modify::new(Rows::single(0)).with( Width::truncate(3) .suffix("qwert") .suffix_limit(SuffixLimit::Cut), ), ) .to_string(); assert_eq!( table, static_table!( "| N | qwe | qwe | qwe |" "|---|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn min_with_max_width_truncate_suffix_limit_ignore() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with( Modify::new(Rows::single(0)).with( Width::truncate(3) .suffix("qwert") .suffix_limit(SuffixLimit::Ignore), ), ) .to_string(); assert_eq!( table, static_table!( "| N | col | col | col |" "|---|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[cfg(feature = "color")] #[test] fn min_with_max_width_truncate_suffix_try_color() { let data = &[ "asd".red().to_string(), "zxc".blue().to_string(), "asdasd".on_black().green().to_string(), ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Width::truncate(7).suffix("..").suffix_try_color(true)) .to_string(); assert_eq!( table, static_table!( "| S.. |" "|-----|" "| \u{1b}[31masd\u{1b}[39m |" "| \u{1b}[34mzxc\u{1b}[39m |" "| \u{1b}[32;40ma\u{1b}[39m\u{1b}[49m\u{1b}[32m\u{1b}[40m..\u{1b}[39m\u{1b}[49m |" ) ); } #[cfg(feature = "color")] #[test] fn min_width_color() { let data = &[ "asd".red().to_string(), "zxc".blue().to_string(), "asdasd".on_black().green().to_string(), ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(MinWidth::new(10))) .to_string(); assert_eq!( ansi_str::AnsiStr::ansi_strip(&table), static_table!( "| String |" "|------------|" "| asd |" "| zxc |" "| asdasd |" ) ); assert_eq!( table, "| String |\n|------------|\n| \u{1b}[31masd\u{1b}[39m |\n| \u{1b}[34mzxc\u{1b}[39m |\n| \u{1b}[32;40masdasd\u{1b}[0m |", ); } #[cfg(feature = "color")] #[test] fn min_width_color_with_smaller_then_width() { let data = &[ "asd".red().to_string(), "zxc".blue().to_string(), "asdasd".on_black().green().to_string(), ]; assert_eq!( Matrix::iter(data) .with(Modify::new(Segment::all()).with(MinWidth::new(1))) .to_string(), Matrix::iter(data).to_string() ); } #[test] fn total_width_big() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Width::truncate(80)) .with(MinWidth::new(80)) .to_string(); assert_eq!(string_width_multiline(&table), 80); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|--------------|---------------------|--------------------|--------------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(TrimStrategy::None)) .with(Settings::new(Width::truncate(80), Width::increase(80))) .to_string(); assert_eq!(string_width_multiline(&table), 80); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|--------------|---------------------|--------------------|--------------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn total_width_big_with_panel() { let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with( Modify::new(Segment::all()) .with(Alignment::center()) .with(Padding::zero()), ) .with(Style::markdown()) .with(Width::truncate(80)) .with(MinWidth::new(80)) .to_string(); assert!(is_lines_equal(&table, 80)); assert_eq!( table, static_table!( "| Hello World |" "|--------------|---------------------|--------------------|--------------------|" "| N | column 0 | column 1 | column 2 |" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn total_width_big_with_panel_with_wrapping_doesnt_affect_increase() { let table1 = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(80)) .with(MinWidth::new(80)) .to_string(); let table2 = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(80)) .with(MinWidth::new(80)) .to_string(); assert_eq!(table1, table2); } #[test] fn total_width_small() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Width::truncate(14)) .with(MinWidth::new(14)) .to_string(); assert_eq!( table, static_table!( "| | | | c |" "|--|--|--|---|" "| | | | 0 |" "| | | | 1 |" "| | | | 2 |" ) ); assert!(is_lines_equal(&table, 14)); } #[test] fn total_width_smaller_then_content() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Width::truncate(8)) .with(MinWidth::new(8)) .to_string(); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn total_width_small_with_panel() { let table = Matrix::new(3, 3) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(20)) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| | co | co | col |" "|--|----|----|-----|" "| | 0- | 0- | 0-2 |" "| | 1- | 1- | 1-2 |" "| | 2- | 2- | 2-2 |" ) ); assert!(is_lines_equal(&table, 20)); let table = Matrix::iter(Vec::<usize>::new()) .with(Panel::horizontal(0, "Hello World")) .with( Modify::new(Segment::all()) .with(Alignment::center()) .with(Padding::zero()), ) .with(Width::truncate(5)) .with(MinWidth::new(5)) .to_string(); assert_eq!( table, static_table!("+---+" "|Hel|" "+---+" "|usi|" "+---+") ); assert!(is_lines_equal(&table, 5)); let table = Matrix::table(1, 2) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(20)) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| Hello World |" "|--|-------|-------|" "| | colum | colum |" "| | 0-0 | 0-1 |" ) ); assert!(is_lines_equal(&table, 20)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(20)) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| Hello World |" "|--|----|----|-----|" "| | co | co | col |" "| | 0- | 0- | 0-2 |" "| | 1- | 1- | 1-2 |" "| | 2- | 2- | 2-2 |" ) ); assert!(is_lines_equal(&table, 20)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(6)) .with(MinWidth::new(6)) .to_string(); assert_eq!( table, static_table!( "| Hello Wor |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" "| | | | |" ) ); assert!(is_lines_equal(&table, 13)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(14)) .with(MinWidth::new(14)) .to_string(); assert_eq!( table, static_table!( "| Hello Worl |" "|--|--|--|---|" "| | | | c |" "| | | | 0 |" "| | | | 1 |" "| | | | 2 |" ) ); assert!(is_lines_equal(&table, 14)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World 123")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::truncate(14)) .with(MinWidth::new(14)) .to_string(); assert_eq!( table, static_table!( "| Hello Worl |" "|--|--|--|---|" "| | | | c |" "| | | | 0 |" "| | | | 1 |" "| | | | 2 |" ) ); assert!(is_lines_equal(&table, 14)); } #[cfg(feature = "color")] #[test] fn total_width_wrapping() { let table = Matrix::new(3, 3) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(20)) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| | co | co | col |" "| | lu | lu | umn |" "| | mn | mn | 2 |" "| | 0 | 1 | |" "|--|----|----|-----|" "| | 0- | 0- | 0-2 |" "| | 0 | 1 | |" "| | 1- | 1- | 1-2 |" "| | 0 | 1 | |" "| | 2- | 2- | 2-2 |" "| | 0 | 1 | |" ) ); assert!(is_lines_equal(&table, 20)); let table = Matrix::new(3, 3) .insert((3, 2), "some loong string") .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(20).keep_words()) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| | | column | |" "| | | 1 | |" "|--|--|---------|--|" "| | | 0-1 | |" "| | | 1-1 | |" "| | | some | |" "| | | loong | |" "| | | string | |" ) ); assert!(is_lines_equal(&table, 20)); } #[test] fn total_width_small_with_panel_using_wrapping() { let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(20)) .with(MinWidth::new(20)) .to_string(); assert_eq!( table, static_table!( "| Hello World |" "|--|----|----|-----|" "| | co | co | col |" "| | lu | lu | umn |" "| | mn | mn | 2 |" "| | 0 | 1 | |" "| | 0- | 0- | 0-2 |" "| | 0 | 1 | |" "| | 1- | 1- | 1-2 |" "| | 0 | 1 | |" "| | 2- | 2- | 2-2 |" "| | 0 | 1 | |" ) ); assert!(is_lines_equal(&table, 20)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(14)) .with(MinWidth::new(14)) .to_string(); assert_eq!( table, static_table!( "| Hello Worl |" "| d |" "|--|--|--|---|" "| | | | c |" "| | | | o |" "| | | | l |" "| | | | u |" "| | | | m |" "| | | | n |" "| | | | |" "| | | | 2 |" "| | | | 0 |" "| | | | - |" "| | | | 2 |" "| | | | 1 |" "| | | | - |" "| | | | 2 |" "| | | | 2 |" "| | | | - |" "| | | | 2 |" ) ); assert!(is_lines_equal(&table, 14)); let table = Matrix::new(3, 3) .with(Panel::horizontal(0, "Hello World 123")) .with(Modify::new(Segment::all()).with(Alignment::center())) .with(Style::markdown()) .with(Width::wrap(14)) .with(MinWidth::new(14)) .to_string(); assert_eq!( table, static_table!( "| Hello Worl |" "| d 123 |" "|--|--|--|---|" "| | | | c |" "| | | | o |" "| | | | l |" "| | | | u |" "| | | | m |" "| | | | n |" "| | | | |" "| | | | 2 |" "| | | | 0 |" "| | | | - |" "| | | | 2 |" "| | | | 1 |" "| | | | - |" "| | | | 2 |" "| | | | 2 |" "| | | | - |" "| | | | 2 |" ) ); assert!(is_lines_equal(&table, 14)); } #[test] fn max_width_with_span() { let mut table = Matrix::new(3, 3).insert((1, 1), "a long string").to_table(); table .with(Style::psql()) .with(Modify::new((1, 1)).with(Span::column(2))) .with(Modify::new((2, 2)).with(Span::column(2))); table.with(Width::truncate(40)); assert_eq!( table.to_string(), static_table!( " N | column 0 | column 1 | column 2 " "---+----------+----------+----------" " 0 | a long string | 0-2 " " 1 | 1-0 | 1-1 " " 2 | 2-0 | 2-1 | 2-2 " ) ); assert!(is_lines_equal(&table.to_string(), 36)); table.with(Width::truncate(20)); assert_eq!( table.to_string(), static_table!( " | col | col | col " "--+-----+-----+-----" " | a long st | 0-2 " " | 1-0 | 1-1 " " | 2-0 | 2-1 | 2-2 " ) ); assert!(is_lines_equal(&table.to_string(), 20)); table.with(Width::truncate(10)); assert_eq!( table.to_string(), static_table!( " | | | " "--+--+--+--" " | a l | " " | | 1-1 " " | | | " ) ); assert!(is_lines_equal(&table.to_string(), 11)); } #[test] fn min_width_works_with_right_alignment() { let json = r#" { "some": "random", "json": [ { "1": "2" }, { "1": "2" }, { "1": "2" } ] } "#; let mut table = Matrix::iter([json]); table .with(Style::markdown()) .with( Modify::new(Segment::all()) .with(Alignment::right()) .with(TrimStrategy::None), ) .with(MinWidth::new(50)); assert_eq!(string_width_multiline(&table.to_string()), 50); assert_eq!( table.to_string(), static_table!( "| &str |" "|------------------------------------------------|" "| |" "| { |" "| \"some\": \"random\", |" "| \"json\": [ |" "| { \"1\": \"2\" }, |" "| { \"1\": \"2\" }, |" "| { \"1\": \"2\" } |" "| ] |" "| } |" "| |" ) ); table .with(Modify::new(Segment::all()).with(TrimStrategy::Horizontal)) .with(MinWidth::new(50)); assert_eq!( table.to_string(), static_table!( r#"| &str |"# r#"|------------------------------------------------|"# r#"| |"# r#"| { |"# r#"| "some": "random", |"# r#"| "json": [ |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" } |"# r#"| ] |"# r#"| } |"# r#"| |"# ) ); assert!(is_lines_equal(&table.to_string(), 50)); table .with(Modify::new(Segment::all()).with(TrimStrategy::Both)) .with(MinWidth::new(50)); assert_eq!( table.to_string(), static_table!( r#"| &str |"# r#"|------------------------------------------------|"# r#"| { |"# r#"| "some": "random", |"# r#"| "json": [ |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" } |"# r#"| ] |"# r#"| } |"# r#"| |"# r#"| |"# ) ); assert!(is_lines_equal(&table.to_string(), 50)); let mut table = Matrix::iter([json]); table .with(Style::markdown()) .with( Modify::new(Segment::all()) .with(Alignment::center()) .with(TrimStrategy::None), ) .with(MinWidth::new(50)); assert_eq!( table.to_string(), static_table!( "| &str |" "|------------------------------------------------|" "| |" "| { |" "| \"some\": \"random\", |" "| \"json\": [ |" "| { \"1\": \"2\" }, |" "| { \"1\": \"2\" }, |" "| { \"1\": \"2\" } |" "| ] |" "| } |" "| |" ) ); assert_eq!(string_width_multiline(&table.to_string()), 50); table .with(Modify::new(Segment::all()).with(TrimStrategy::Horizontal)) .with(MinWidth::new(50)); assert_eq!( table.to_string(), static_table!( r#"| &str |"# r#"|------------------------------------------------|"# r#"| |"# r#"| { |"# r#"| "some": "random", |"# r#"| "json": [ |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" } |"# r#"| ] |"# r#"| } |"# r#"| |"# ) ); assert!(is_lines_equal(&table.to_string(), 50)); table .with(Modify::new(Segment::all()).with(TrimStrategy::Both)) .with(MinWidth::new(50)); assert_eq!( table.to_string(), static_table!( r#"| &str |"# r#"|------------------------------------------------|"# r#"| { |"# r#"| "some": "random", |"# r#"| "json": [ |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" }, |"# r#"| { "1": "2" } |"# r#"| ] |"# r#"| } |"# r#"| |"# r#"| |"# ) ); assert!(is_lines_equal(&table.to_string(), 50)); } #[test] fn min_width_with_span_1() { let data = [ ["0", "1"], ["a long string which will affect min width logic", ""], ["2", "3"], ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new((1, 0)).with(Span::column(2))) .with(MinWidth::new(100)) .to_string(); assert_eq!(string_width_multiline(&table), 100); assert_eq!( table, static_table!( "| 0 | 1 |" "|------------------------------------------------------------------------|-------------------------|" "| 0 |" "| a long string which will affect min width logic | |" "| 2 | 3 |" ) ); assert!(is_lines_equal(&table, 100)); } #[test] fn min_width_with_span_2() { let data = [ ["0", "1"], ["a long string which will affect min width logic", ""], ["2", "3"], ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new((2, 0)).with(Span::column(2))) .with(MinWidth::new(100)) .to_string(); assert_eq!(string_width_multiline(&table), 100); assert_eq!( table, static_table!( "| 0 | 1 |" "|-------------------------------------------------|------------------------------------------------|" "| 0 | 1 |" "| a long string which will affect min width logic |" "| 2 | 3 |" ) ); } #[test] fn justify_width_constant_test() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Justify::new(3)) .to_string(); assert_eq!( table, static_table!( "| N | col | col | col |" "|-----|-----|-----|-----|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn justify_width_constant_different_sizes_test() { let table = Matrix::new(3, 3) .insert((1, 1), "Hello World") .insert((3, 2), "multi\nline string\n") .with(Style::markdown()) .with(Justify::new(3)) .to_string(); assert_eq!( table, static_table!( "| N | col | col | col |" "|-----|-----|-----|-----|" "| 0 | Hel | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | mul | 2-2 |" ) ); } #[test] fn justify_width_constant_0_test() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Justify::new(0)) .to_string(); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn justify_width_min_test() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Justify::min()) .to_string(); println!("{table}"); assert_eq!( table, static_table!( "| N | c | c | c |" "|---|---|---|---|" "| 0 | 0 | 0 | 0 |" "| 1 | 1 | 1 | 1 |" "| 2 | 2 | 2 | 2 |" ) ); } #[test] fn justify_width_max_test() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Justify::max()) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|----------|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); } #[test] fn max_width_when_cell_has_tabs() { let table = Matrix::new(3, 3) .insert((2, 1), "\tHello\tWorld\t") .with(TabSize::new(4)) .with(Style::markdown()) .with(Modify::new(Columns::new(..)).with(Width::truncate(1))) .to_string(); assert_eq!( table, static_table!( "| N | c | c | c |" "|---|---|---|---|" "| 0 | 0 | 0 | 0 |" "| 1 | | 1 | 1 |" "| 2 | 2 | 2 | 2 |" ) ); } #[test] fn max_width_table_when_cell_has_tabs() { let table = Matrix::new(3, 3) .insert((2, 1), "\tHello\tWorld\t") .with(TabSize::new(4)) .with(Style::markdown()) .with(Width::truncate(15)) .to_string(); assert_eq!( table, static_table!( "| | co | | |" "|--|----|--|--|" "| | 0- | | |" "| | | | |" "| | 2- | | |" ) ); } // WE GOT [["", "column 0", "column 1 ", "column 2 "], ["", "0-0 ", "0-1 ", "0-2 "], ["", "Hello World With Big Line; Here w", "1-1", "1-2"], ["", "2-0 ", "Hello World With Big L", "2-2"]] // [2, 10, 11, 12] // 40 55 40 // BEFORE ADJ [2, 10, 11, 12] // WE GOT [["", "column 0", "column 1", "column 2"], ["", "0-0", "0-1", "0-2"], ["", "Hello World With Big Line; Here w", "1-1", "1-2"], ["", "2-0", "Hello World With Big L", "2-2"]] // [2, 11, 12, 11] // 41 55 40 // adj [2, 10, 10, 10] #[test] fn max_width_truncate_with_big_span() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line; Here we gooooooo") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(3))) .with(Width::truncate(40)) .to_string(); assert_eq!(string_width_multiline(&table), 40); assert_eq!( table, static_table!( "| | column 0 | column 1 | column 2 |" "|--|-----------|-----------|-----------|" "| | 0-0 | 0-1 | 0-2 |" "| | Hello World With Big Line; Here w |" "| | 2-0 | 2-1 | 2-2 |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line; Here we gooooooo") .insert((3, 2), "Hello World With Big Line; Here") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(3))) .with(Modify::new((3, 2)).with(Span::column(2))) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|-----------|----------------|----------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | Hello World With Big Line; Here we gooooooo |" "| 2 | 2-0 | Hello World With Big Line; Here |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line; Here we gooooooo") .insert((3, 2), "Hello World With Big Line; Here") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(3))) .with(Modify::new((3, 2)).with(Span::column(2))) .with(Width::truncate(40)) .to_string(); assert_eq!( table, static_table!( "| | colum | column 1 | column 2 |" "|--|-------|-------------|-------------|" "| | 0-0 | 0-1 | 0-2 |" "| | Hello World With Big Line; Here w |" "| | 2-0 | Hello World With Big Line |" ) ); assert_eq!(string_width_multiline(&table), 40); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line; Here we gooooooo") .insert((3, 2), "Hello World With Big Line; Here") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Modify::new((3, 2)).with(Span::column(2))) .with(Width::truncate(40)) .to_string(); assert_eq!(string_width_multiline(&table), 40); assert_eq!( table, static_table!( "| | column 0 | column 1 | c |" "|--|---------------|---------------|---|" "| | 0-0 | 0-1 | 0 |" "| | Hello World With Big Line; He | 1 |" "| | 2-0 | Hello World With |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line; Here w") .insert((3, 2), "Hello World With Big L") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(3))) .with(Modify::new((3, 2)).with(Span::column(2))) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|----------|------------|-----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | Hello World With Big Line; Here w |" "| 2 | 2-0 | Hello World With Big L |" ) ); } #[test] fn max_width_truncate_priority_max() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(35).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 35)); assert_eq!( table, static_table!( "| N | column | column | column |" "|---|---------|---------|---------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | Hello W | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(20).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 20)); assert_eq!( table, static_table!( "| N | co | co | co |" "|---|----|----|----|" "| 0 | 0- | 0- | 0- |" "| 1 | He | 1- | 1- |" "| 2 | 2- | 2- | 2- |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(0).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 13)); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn max_width_truncate_priority_max_with_span() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Width::truncate(15).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 15)); assert_eq!( table, static_table!( "| N | c | | |" "|---|---|--|--|" "| 0 | 0 | | |" "| 1 | Hell | |" "| 2 | 2 | | |" ) ); } #[test] fn max_width_wrap_priority_max() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(35).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 35)); assert_eq!( table, static_table!( "| N | column | column | column |" "| | 0 | 1 | 2 |" "|---|---------|---------|---------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | Hello W | 1-1 | 1-2 |" "| | orld Wi | | |" "| | th Big | | |" "| | Line | | |" "| 2 | 2-0 | 2-1 | 2-2 |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(20).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 20)); assert_eq!( table, static_table!( "| N | co | co | co |" "| | lu | lu | lu |" "| | mn | mn | mn |" "| | 0 | 1 | 2 |" "|---|----|----|----|" "| 0 | 0- | 0- | 0- |" "| | 0 | 1 | 2 |" "| 1 | He | 1- | 1- |" "| | ll | 1 | 2 |" "| | o | | |" "| | Wo | | |" "| | rl | | |" "| | d | | |" "| | Wi | | |" "| | th | | |" "| | B | | |" "| | ig | | |" "| | L | | |" "| | in | | |" "| | e | | |" "| 2 | 2- | 2- | 2- |" "| | 0 | 1 | 2 |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(0).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 13)); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn max_width_wrap_priority_max_with_span() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Width::wrap(15).priority::<PriorityMax>()) .to_string(); assert!(is_lines_equal(&table, 15)); assert_eq!( table, static_table!( "| N | c | | |" "| | o | | |" "| | l | | |" "| | u | | |" "| | m | | |" "| | n | | |" "| | | | |" "| | 0 | | |" "|---|---|--|--|" "| 0 | 0 | | |" "| | - | | |" "| | 0 | | |" "| 1 | Hell | |" "| | o Wo | |" "| | rld | |" "| | With | |" "| | Big | |" "| | Lin | |" "| | e | |" "| 2 | 2 | | |" "| | - | | |" "| | 0 | | |" ) ); } #[test] fn max_width_truncate_priority_min() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(35).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 35)); assert_eq!( table, static_table!( "| | column 0 | | |" "|--|------------------------|--|--|" "| | 0-0 | | |" "| | Hello World With Big L | | |" "| | 2-0 | | |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(20).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 20)); assert_eq!( table, static_table!( "| | column | | |" "|--|---------|--|--|" "| | 0-0 | | |" "| | Hello W | | |" "| | 2-0 | | |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::truncate(0).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 13)); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn max_width_truncate_priority_min_with_span() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Width::truncate(15).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 15)); assert_eq!( table, static_table!( "| | | co | |" "|--|--|----|--|" "| | | 0- | |" "| | Hello | |" "| | | 2- | |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Width::truncate(17).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 17)); assert_eq!( table, static_table!( "| | | colu | |" "|--|--|------|--|" "| | | 0-1 | |" "| | Hello W | |" "| | | 2-1 | |" ) ); } #[test] fn max_width_wrap_priority_min() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(35).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 35)); assert_eq!( table, static_table!( "| | column 0 | | |" "|--|------------------------|--|--|" "| | 0-0 | | |" "| | Hello World With Big L | | |" "| | ine | | |" "| | 2-0 | | |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(20).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 20)); assert_eq!( table, static_table!( "| | column | | |" "| | 0 | | |" "|--|---------|--|--|" "| | 0-0 | | |" "| | Hello W | | |" "| | orld Wi | | |" "| | th Big | | |" "| | Line | | |" "| | 2-0 | | |" ) ); let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Width::wrap(0).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 13)); assert_eq!( table, static_table!( "| | | | |" "|--|--|--|--|" "| | | | |" "| | | | |" "| | | | |" ) ); } #[test] fn max_width_wrap_priority_min_with_span() { let table = Matrix::new(3, 3) .insert((2, 1), "Hello World With Big Line") .with(Style::markdown()) .with(Modify::new((2, 1)).with(Span::column(2))) .with(Width::wrap(15).priority::<PriorityMin>()) .to_string(); assert!(is_lines_equal(&table, 15)); assert_eq!( table, static_table!( "| | | co | |" "| | | lu | |" "| | | mn | |" "| | | 1 | |" "|--|--|----|--|" "| | | 0- | |" "| | | 1 | |" "| | Hello | |" "| | Worl | |" "| | d Wit | |" "| | h Big | |" "| | Line | |" "| | | 2- | |" "| | | 1 | |" ) ); } #[test] fn min_width_priority_max() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(MinWidth::new(60).priority::<PriorityMax>()) .to_string(); assert_eq!(string_width_multiline(&table), 60); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|----------|----------|--------------------------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ), ); } #[test] fn min_width_priority_min() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(MinWidth::new(60).priority::<PriorityMin>()) .to_string(); assert_eq!(string_width_multiline(&table), 60); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|--------------|--------------|--------------|-------------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ), ); } #[test] fn max_width_tab_0() { let table = Matrix::iter(["\t\tTigre Ecuador\tOMYA Andina\t3824909999\tCalcium carbonate\tColombia\t"]) .with(TabSize::new(4)) .with(Style::markdown()) .with(Width::wrap(60)) .to_string(); assert!(is_lines_equal(&table, 60)); assert_eq!( table, static_table!( "| &str |" "|----------------------------------------------------------|" "| Tigre Ecuador OMYA Andina 3824909999 Ca |" "| lcium carbonate Colombia |" ) ); } #[test] fn min_width_is_not_used_after_padding() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(MinWidth::new(60)) .with(Modify::new((0, 0)).with(Padding::new(2, 2, 0, 0))) .to_string(); assert_eq!(string_width_multiline(&table), 40); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|-----|----------|----------|----------|" "| 0 | 0-0 | 0-1 | 0-2 |" "| 1 | 1-0 | 1-1 | 1-2 |" "| 2 | 2-0 | 2-1 | 2-2 |" ), ); } #[test] fn min_width_is_used_after_margin() { let table = Matrix::new(3, 3) .with(Style::markdown()) .with(Margin::new(1, 1, 1, 1)) .with(Width::increase(60)) .to_string(); assert_eq!(string_width_multiline(&table), 60); assert_eq!( table, static_table!( " " " | N | column 0 | column 1 | column 2 | " " |--------|---------------|---------------|---------------| " " | 0 | 0-0 | 0-1 | 0-2 | " " | 1 | 1-0 | 1-1 | 1-2 | " " | 2 | 2-0 | 2-1 | 2-2 | " " " ), ); } #[test] fn wrap_keeping_words_0() { let data = vec![["Hello world"]]; let table = tabled::Table::new(data) .with(Width::wrap(8).keep_words()) .to_string(); assert_eq!( tabled::grid::util::string::string_width_multiline(&table), 8 ); assert_eq!( table, static_table!( "+------+" "| 0 |" "+------+" "| Hell |" "| o wo |" "| rld |" "+------+" ) ); } #[test] fn cell_truncate_multiline() { let table = Matrix::new(3, 3) .insert((1, 1), "H\nel\nlo World") .insert((3, 2), "multi\nline string\n") .with(Style::markdown()) .with( Modify::new(Columns::new(1..2).not(Rows::single(0))) .with(Width::truncate(1).multiline()), ) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|----------|-------------|----------|" "| 0 | H | 0-1 | 0-2 |" "| | e | | |" "| | l | | |" "| 1 | 1 | 1-1 | 1-2 |" "| 2 | 2 | multi | 2-2 |" "| | | line string | |" "| | | | |" ) ); } #[test] fn cell_truncate_multiline_with_suffix() { let table = Matrix::new(3, 3) .insert((1, 1), "H\nel\nlo World") .insert((3, 2), "multi\nline string\n") .with(Style::markdown()) .with( Modify::new(Columns::new(1..2).not(Rows::single(0))) .with(Width::truncate(1).multiline().suffix(".")), ) .to_string(); assert_eq!( table, static_table!( "| N | column 0 | column 1 | column 2 |" "|---|----------|-------------|----------|" "| 0 | . | 0-1 | 0-2 |" "| | . | | |" "| | . | | |" "| 1 | . | 1-1 | 1-2 |" "| 2 | . | multi | 2-2 |" "| | | line string | |" "| | | | |" ) ); } #[test] fn table_truncate_multiline() { let table = Matrix::new(3, 3) .insert((1, 1), "H\nel\nlo World") .insert((3, 2), "multi\nline string\n") .with(Style::markdown()) .with(Width::truncate(20).multiline()) .to_string(); assert_eq!( table, static_table!( "| | c | colu | co |" "|--|---|------|----|" "| | H | 0-1 | 0- |" "| | e | | |" "| | l | | |" "| | 1 | 1-1 | 1- |" "| | 2 | mult | 2- |" "| | | line | |" "| | | | |" ) ); } #[test] fn table_truncate_multiline_with_suffix() { let table = Matrix::new(3, 3) .insert((1, 1), "H\nel\nlo World") .insert((3, 2), "multi\nline string\n") .with(Style::markdown()) .with(Width::truncate(20).suffix(".").multiline()) .to_string(); assert_eq!( table, static_table!( "| | . | col. | c. |" "|--|---|------|----|" "| | . | 0-1 | 0. |" "| | . | | |" "| | . | | |" "| | . | 1-1 | 1. |" "| | . | mul. | 2. |" "| | | lin. | |" "| | | . | |" ) ); } #[cfg(feature = "derive")] mod derived { use super::*; use tabled::Tabled; #[test] fn wrapping_as_total_multiline() { #[derive(Tabled)] struct D<'a>( #[tabled(rename = "version")] &'a str, #[tabled(rename = "published_date")] &'a str, #[tabled(rename = "is_active")] &'a str, #[tabled(rename = "major_feature")] &'a str, ); let data = vec![ D("0.2.1", "2021-06-23", "true", "#[header(inline)] attribute"), D("0.2.0", "2021-06-19", "false", "API changes"), D("0.1.4", "2021-06-07", "false", "display_with attribute"), ]; let table = Matrix::iter(&data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Width::wrap(57)) .to_string(); assert_eq!( table, static_table!( "| ver | published_d | is_act | major_feature |" "| sio | ate | ive | |" "| n | | | |" "|-----|-------------|--------|--------------------------|" "| 0.2 | 2021-06-23 | true | #[header(inline)] attrib |" "| .1 | | | ute |" "| 0.2 | 2021-06-19 | false | API changes |" "| .0 | | | |" "| 0.1 | 2021-06-07 | false | display_with attribute |" "| .4 | | | |" ) ); assert!(is_lines_equal(&table, 57)); let table = Matrix::iter(&data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Width::wrap(57).keep_words()) .to_string(); assert_eq!( table, static_table!( "| ver | published_d | is_act | major_feature |" "| sio | ate | ive | |" "| n | | | |" "|-----|-------------|--------|--------------------------|" "| 0.2 | 2021-06-23 | true | #[header(inline)] |" "| .1 | | | attribute |" "| 0.2 | 2021-06-19 | false | API changes |" "| .0 | | | |" "| 0.1 | 2021-06-07 | false | display_with attribute |" "| .4 | | | |" ) ); assert!(is_lines_equal(&table, 57)); } #[cfg(feature = "color")] #[test] fn wrapping_as_total_multiline_color() { #[derive(Tabled)] struct D( #[tabled(rename = "version")] String, #[tabled(rename = "published_date")] String, #[tabled(rename = "is_active")] String, #[tabled(rename = "major_feature")] String, ); let data = vec![ D( "0.2.1".red().to_string(), "2021-06-23".red().on_truecolor(8, 10, 30).to_string(), "true".to_string(), "#[header(inline)] attribute" .blue() .on_color(AnsiColors::Green) .to_string(), ), D( "0.2.0".red().to_string(), "2021-06-19".green().on_truecolor(8, 100, 30).to_string(), "false".to_string(), "API changes".yellow().to_string(), ), D( "0.1.4".white().to_string(), "2021-06-07".red().on_truecolor(8, 10, 30).to_string(), "false".to_string(), "display_with attribute" .red() .on_color(AnsiColors::Black) .to_string(), ), ]; let table = Matrix::iter(&data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Width::wrap(57)) .to_string(); assert_eq!( table, static_table!( "| ver | published_d | is_act | major_feature |" "| sio | ate | ive | |" "| n | | | |" "|-----|-------------|--------|--------------------------|" "| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-23\u{1b}[39m\u{1b}[49m | true | \u{1b}[34m\u{1b}[42m#[header(inline)] attrib\u{1b}[39m\u{1b}[49m |" "| \u{1b}[31m.1\u{1b}[39m | | | \u{1b}[34m\u{1b}[42mute\u{1b}[39m\u{1b}[49m |" "| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;100;30m\u{1b}[32m2021-06-19\u{1b}[39m\u{1b}[49m | false | \u{1b}[33mAPI changes\u{1b}[39m |" "| \u{1b}[31m.0\u{1b}[39m | | | |" "| \u{1b}[37m0.1\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-07\u{1b}[39m\u{1b}[49m | false | \u{1b}[31;40mdisplay_with attribute\u{1b}[0m |" "| \u{1b}[37m.4\u{1b}[39m | | | |" ) ); assert_eq!(string_width_multiline(&table), 57); let table = Matrix::iter(&data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Width::wrap(57).keep_words()) .to_string(); assert_eq!( table, static_table!( "| ver | published_d | is_act | major_feature |" "| sio | ate | ive | |" "| n | | | |" "|-----|-------------|--------|--------------------------|" "| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-23\u{1b}[39m\u{1b}[49m | true | \u{1b}[34m\u{1b}[42m#[header(inline)] \u{1b}[39m\u{1b}[49m |" "| \u{1b}[31m.1\u{1b}[39m | | | \u{1b}[34m\u{1b}[42mattribute\u{1b}[39m\u{1b}[49m |" "| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;100;30m\u{1b}[32m2021-06-19\u{1b}[39m\u{1b}[49m | false | \u{1b}[33mAPI changes\u{1b}[39m |" "| \u{1b}[31m.0\u{1b}[39m | | | |" "| \u{1b}[37m0.1\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-07\u{1b}[39m\u{1b}[49m | false | \u{1b}[31;40mdisplay_with attribute\u{1b}[0m |" "| \u{1b}[37m.4\u{1b}[39m | | | |" ) ); assert_eq!(string_width_multiline(&table), 57); } #[cfg(feature = "color")] #[test] fn truncating_as_total_multiline_color() { #[derive(Tabled)] struct D( #[tabled(rename = "version")] String, #[tabled(rename = "published_date")] String, #[tabled(rename = "is_active")] String, #[tabled(rename = "major_feature")] String, ); let data = vec![ D( "0.2.1".red().to_string(), "2021-06-23".red().on_truecolor(8, 10, 30).to_string(), "true".to_string(), "#[header(inline)] attribute" .blue() .on_color(AnsiColors::Green) .to_string(), ), D( "0.2.0".red().to_string(), "2021-06-19".green().on_truecolor(8, 100, 30).to_string(), "false".to_string(), "API changes".yellow().to_string(), ), D( "0.1.4".white().to_string(), "2021-06-07".red().on_truecolor(8, 10, 30).to_string(), "false".to_string(), "display_with attribute" .red() .on_color(AnsiColors::Black) .to_string(), ), ]; let table = Matrix::iter(data) .with(Style::markdown()) .with(Modify::new(Segment::all()).with(Alignment::left())) .with(Width::truncate(57)) .to_string(); assert_eq!( ansi_str::AnsiStr::ansi_strip(&table), static_table!( "| ver | published_d | is_act | major_feature |" "|-----|-------------|--------|--------------------------|" "| 0.2 | 2021-06-23 | true | #[header(inline)] attrib |" "| 0.2 | 2021-06-19 | false | API changes |" "| 0.1 | 2021-06-07 | false | display_with attribute |" ) ); assert_eq!( table, "| ver | published_d | is_act | major_feature |\n|-----|-------------|--------|--------------------------|\n| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-23\u{1b}[39m\u{1b}[49m | true | \u{1b}[34;42m#[header(inline)] attrib\u{1b}[39m\u{1b}[49m |\n| \u{1b}[31m0.2\u{1b}[39m | \u{1b}[48;2;8;100;30m\u{1b}[32m2021-06-19\u{1b}[39m\u{1b}[49m | false | \u{1b}[33mAPI changes\u{1b}[39m |\n| \u{1b}[37m0.1\u{1b}[39m | \u{1b}[48;2;8;10;30m\u{1b}[31m2021-06-07\u{1b}[39m\u{1b}[49m | false | \u{1b}[31;40mdisplay_with attribute\u{1b}[0m |" ); assert_eq!(string_width_multiline(&table), 57); } #[cfg(feature = "color")] fn format_osc8_hyperlink(url: &str, text: &str) -> String { format!( "{osc}8;;{url}{st}{text}{osc}8;;{st}", url = url, text = text, osc = "\x1b]", st = "\x1b\\" ) } #[cfg(feature = "color")] #[test] fn hyperlinks() { #[derive(Tabled)] struct Distribution { name: String, is_hyperlink: bool, } let table = |text: &str| { let data = [Distribution { name: text.to_owned(), is_hyperlink: true, }]; tabled::Table::new(data) .with( Modify::new(Segment::all()) .with(Width::wrap(5).keep_words()) .with(Alignment::left()), ) .to_string() }; let text = format_osc8_hyperlink("https://www.debian.org/", "Debian"); assert_eq!( table(&text), "+-------+-------+\n\ | name | is_hy |\n\ | | perli |\n\ | | nk |\n\ +-------+-------+\n\ | \u{1b}]8;;https://www.debian.org/\u{1b}\\Debia\u{1b}]8;;\u{1b}\\ | true |\n\ | \u{1b}]8;;https://www.debian.org/\u{1b}\\n\u{1b}]8;;\u{1b}\\ | |\n\ +-------+-------+" ); // if there's more text than a link it will be ignored let text = format!( "{} :link", format_osc8_hyperlink("https://www.debian.org/", "Debian"), ); assert_eq!( table(&text), "+-------+-------+\n\ | name | is_hy |\n\ | | perli |\n\ | | nk |\n\ +-------+-------+\n\ | Debia | true |\n\ | n | |\n\ | :link | |\n\ +-------+-------+" ); let text = format!( "asd {} 2 links in a string {}", format_osc8_hyperlink("https://www.debian.org/", "Debian"), format_osc8_hyperlink("https://www.wikipedia.org/", "Debian"), ); assert_eq!( table(&text), static_table!( "+-------+-------+" "| name | is_hy |" "| | perli |" "| | nk |" "+-------+-------+" "| asd D | true |" "| ebian | |" "| 2 | |" "| links | |" "| in a | |" "| stri | |" "| ng De | |" "| bian | |" "+-------+-------+" ) ); } #[cfg(feature = "color")] #[test] fn hyperlinks_with_color() { use owo_colors::OwoColorize; #[derive(Tabled)] struct Distribution { name: String, is_hyperlink: bool, } let table = |text: &str| { let data = [Distribution { name: text.to_owned(), is_hyperlink: true, }]; tabled::Table::new(data) .with( Modify::new(Segment::all()) .with(Width::wrap(6).keep_words()) .with(Alignment::left()), ) .to_string() }; let text = format_osc8_hyperlink( "https://www.debian.org/", "Debian".red().to_string().as_str(), ); assert_eq!( table(&text), static_table!( "+--------+--------+" "| name | is_hyp |" "| | erlink |" "+--------+--------+" "| \u{1b}]8;;https://www.debian.org/\u{1b}\\\u{1b}[31mDebian\u{1b}[39m\u{1b}]8;;\u{1b}\\ | true |" "+--------+--------+" ) ); // if there's more text than a link it will be ignored let text = format!( "{} :link", format_osc8_hyperlink("https://www.debian.org/", "Debian"), ); assert_eq!( table(&text), static_table!( "+--------+--------+" "| name | is_hyp |" "| | erlink |" "+--------+--------+" "| Debian | true |" "| :link | |" "+--------+--------+" ) ); let text = format!( "asd {} 2 links in a string {}", format_osc8_hyperlink("https://www.debian.org/", "Debian"), format_osc8_hyperlink("https://www.wikipedia.org/", "Debian"), ); assert_eq!( table(&text), static_table!( "+--------+--------+" "| name | is_hyp |" "| | erlink |" "+--------+--------+" "| asd | true |" "| Debian | |" "| 2 | |" "| links | |" "| in a | |" "| string | |" "| | |" "| Debian | |" "+--------+--------+" ) ); } }
// Copyright 2018 Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 or MIT license, at your option. // // A copy of the Apache License, Version 2.0 is included in the software as // LICENSE-APACHE and a copy of the MIT license is included in the software // as LICENSE-MIT. You may also obtain a copy of the Apache License, Version 2.0 // at https://www.apache.org/licenses/LICENSE-2.0 and a copy of the MIT license // at https://opensource.org/licenses/MIT. use curve25519_dalek::scalar::Scalar; use blake2; use blake2b_simd::Params; use hkdf; use key::Key; // 5.2 pub(crate) fn hash<'a, I, T>(inputs: I) -> Scalar where I: IntoIterator<Item=T> + Copy, T: AsRef<[u8]> { let mut state = Params::new().hash_length(64).to_state(); for i in inputs { state.update(i.as_ref()); } let hash = state.finalize(); let mut bytes = [0u8; 64]; bytes.copy_from_slice(hash.as_bytes()); Scalar::from_bytes_mod_order_wide(&bytes) } // 5.4 pub(crate) fn kdf(input: &[u8]) -> Key { let kdf = hkdf::Hkdf::<blake2::Blake2b>::extract(None, input); let mut k = [0; 32]; kdf.expand(b"pre", &mut k).expect("32 < 255 * 64"); Key::new(k) }
#[cfg(test)] mod tests { use rstate::*; use std::hash::Hash; #[test] fn hierarchical_lights_machine() { #[derive(Copy, Clone, Debug)] enum Action { Timer, PedestrianTimer, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum Red { Wait, Walk, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum State { Green, Yellow, Red(Red), } #[derive(Debug, Clone, Copy)] struct Context { timer: u8, } let context = Context { timer: 3 }; let mut machine = Machine::<Action, State, Context>::new( "hierarchical-light".to_string(), State::Green, context, ); machine.add_state( State::Green, Transition { context: None, on: Some(|_context, action, state| match action { Action::Timer => State::Yellow, _ => state, }), ..Default::default() }, ); machine.add_state( State::Yellow, Transition { context: None, on: Some(|_context, action, state| match action { Action::Timer => State::Red(Red::Wait), _ => state, }), ..Default::default() }, ); machine.add_state( State::Red(Red::Wait), Transition { context: None, on: Some(|_context, action, state| match action { Action::PedestrianTimer => State::Red(Red::Walk), _ => state, }), ..Default::default() }, ); machine.add_state( State::Red(Red::Walk), Transition { context: Some(|mut context, action, _state| { match action { Action::PedestrianTimer => context.timer -= 1, _ => {} }; context }), on: Some(|context, action, state| match action { Action::PedestrianTimer => State::Red(Red::Walk), Action::Timer => { if context.timer == 0 { State::Green } else { state } } }), ..Default::default() }, ); assert_eq!(machine.value, State::Green); machine.transition(&Action::Timer); assert_eq!(machine.value, State::Yellow); machine.transition(&Action::Timer); assert_eq!(machine.value, State::Red(Red::Wait)); // does not change state machine.transition(&Action::Timer); assert_eq!(machine.value, State::Red(Red::Wait)); // countdown the timer machine.transition(&Action::PedestrianTimer); machine.transition(&Action::Timer); // does not change to green assert_eq!(machine.value, State::Red(Red::Walk)); assert_eq!(machine.context.timer, 3); machine.transition(&Action::PedestrianTimer); machine.transition(&Action::Timer); // does not change to green assert_eq!(machine.value, State::Red(Red::Walk)); assert_eq!(machine.context.timer, 2); machine.transition(&Action::PedestrianTimer); machine.transition(&Action::Timer); // does not change to green assert_eq!(machine.value, State::Red(Red::Walk)); assert_eq!(machine.context.timer, 1); machine.transition(&Action::PedestrianTimer); machine.transition(&Action::Timer); // now ready to change to green assert_eq!(machine.value, State::Green); } }
#[doc = "Reader of register IC_SDA_SETUP"] pub type R = crate::R<u32, super::IC_SDA_SETUP>; #[doc = "Writer for register IC_SDA_SETUP"] pub type W = crate::W<u32, super::IC_SDA_SETUP>; #[doc = "Register IC_SDA_SETUP `reset()`'s with value 0x64"] impl crate::ResetValue for super::IC_SDA_SETUP { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x64 } } #[doc = "Reader of field `SDA_SETUP`"] pub type SDA_SETUP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `SDA_SETUP`"] pub struct SDA_SETUP_W<'a> { w: &'a mut W, } impl<'a> SDA_SETUP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } impl R { #[doc = "Bits 0:7 - SDA Setup. It is recommended that if the required delay is 1000ns, then for an ic_clk frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11. IC_SDA_SETUP must be programmed with a minimum value of 2."] #[inline(always)] pub fn sda_setup(&self) -> SDA_SETUP_R { SDA_SETUP_R::new((self.bits & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - SDA Setup. It is recommended that if the required delay is 1000ns, then for an ic_clk frequency of 10 MHz, IC_SDA_SETUP should be programmed to a value of 11. IC_SDA_SETUP must be programmed with a minimum value of 2."] #[inline(always)] pub fn sda_setup(&mut self) -> SDA_SETUP_W { SDA_SETUP_W { w: self } } }
use syn::{parse_quote, ItemImpl, ItemMod, ItemStruct, ItemType}; use super::context::Context; use crate::parse::channel::Channel; use crate::parse::process::Process; use crate::partition::Partition; impl Partition { pub fn gen_type_alias(&self) -> ItemType { let hyp_name = &self.hypervisor; parse_quote!(type Hypervisor = #hyp_name; ) } pub fn gen_proc_mods(&self) -> syn::Result<impl Iterator<Item = ItemMod> + '_> { Ok(self .processes .iter() .map(Process::gen_process_mod) .collect::<syn::Result<Vec<ItemMod>>>()? .into_iter()) } pub fn gen_channel_mods(&self) -> syn::Result<impl Iterator<Item = ItemMod>> { Ok(self .channel .iter() .map(Channel::gen_channel_mod) .collect::<syn::Result<Vec<ItemMod>>>()? .into_iter()) } pub fn gen_start_mod(&self) -> ItemMod { let ctx = Context::Start.get_context_ident(); parse_quote! { mod start { use super::Hypervisor; pub(super) type Context<'a> = super:: #ctx <'a, Hypervisor>; } } } pub fn gen_struct(&self) -> ItemStruct { parse_quote! { pub struct Partition; } } pub fn gen_impl(&self) -> ItemImpl { let cold_start = &self.cold_start.sig.ident; let warm_start = &self.warm_start.sig.ident; parse_quote! { impl a653rs::prelude::Partition<Hypervisor> for Partition{ fn cold_start(&self, ctx: &mut a653rs::prelude::StartContext<Hypervisor>){ let ctx = start::Context::new(ctx); #cold_start (ctx) } fn warm_start(&self, ctx: &mut a653rs::prelude::StartContext<Hypervisor>){ let ctx = start::Context::new(ctx); #warm_start (ctx) } } } } }
#[macro_use] extern crate graphplan; use graphplan::Proposition; use episodic::{StoryGenerator, Place, NarrativeArc}; fn main() { let init_state = hashset![ Proposition::from("ship enabled"), Proposition::from("in orbit"), Proposition::from("at alien planet"), ]; let place = Place::PlanetOrbit; let narrative_arc = NarrativeArc::Anomaly; println!("{:?}", StoryGenerator::make_story(&init_state, &place, &narrative_arc)); }
#![no_std] #![cfg_attr(feature = "usb", feature(align_offset, ptr_offset_from))] pub extern crate embedded_hal as hal; pub use paste; #[cfg(feature = "samd21e18a")] pub use atsamd21e18a as target_device; #[cfg(feature = "samd21g18a")] pub use atsamd21g18a as target_device; #[cfg(feature = "samd21j18a")] pub use atsamd21j18a as target_device; #[cfg(feature = "samd51g19a")] pub use atsamd51g19a as target_device; #[cfg(feature = "samd51j19a")] pub use atsamd51j19a as target_device; #[cfg(feature = "samd51j20a")] pub use atsamd51j20a as target_device; #[cfg(feature = "use_rtt")] pub use jlink_rtt; #[cfg(feature = "use_rtt")] #[macro_export] macro_rules! dbgprint { ($($arg:tt)*) => { { use core::fmt::Write; let mut out = $crate::jlink_rtt::NonBlockingOutput::new(); writeln!(out, $($arg)*).ok(); } }; } #[cfg(not(feature = "use_rtt"))] #[macro_export] macro_rules! dbgprint { ($($arg:tt)*) => {{}}; } #[macro_use] pub mod common; pub use self::common::*; #[cfg(feature="samd51")] pub mod samd51; #[cfg(feature="samd51")] pub use self::samd51::*; #[cfg(not(feature="samd51"))] pub mod samd21; #[cfg(not(feature="samd51"))] pub use self::samd21::*; #[cfg(feature = "usb")] pub use self::samd21::usb;
use uuid::Uuid; use serde::{Serialize, Deserialize}; use actix_web::web::{Form}; use crate::additional_service::{id_default}; #[derive(Deserialize, Serialize)] pub struct User { pub uuid: Uuid, pub id: i32, pub login: String, pub pass: String, pub email: String, pub phone: String, pub name: String, pub code: String, pub description: String, pub notvalid: bool, } #[derive(Deserialize)] pub struct ReqUser { pub login: String, pub pass: String, pub email: String, pub phone: String, pub name: String } pub struct UserBuilder{} impl UserBuilder{ pub fn new(req_user: ReqUser) -> User{ User { uuid: Uuid::new_v4(), id: id_default(), login: req_user.login, pass: req_user.pass, email: req_user.email, phone: req_user.phone, name: req_user.name, code: "".to_string(), description: "".to_string(), notvalid: false } } pub fn new_from_form(form: Form<ReqUser>)->User{ User { uuid: Uuid::new_v4(), id: id_default(), login: form.login.to_string(), pass: form.pass.to_string(), email: form.email.to_string(), phone: form.phone.to_string(), name: form.name.to_string(), code: "".to_string(), description: "".to_string(), notvalid: false } } }
extern crate libc; use std::slice; use std::ffi::CStr; use libc::c_int; use libc::c_void; use libc::c_char; use libc::c_uint; #[link(name = "varnishapi")] extern { static VSL_tags: *const c_char; pub fn VSM_New() -> *const c_void; pub fn VSM_Delete(vd: *const c_void); pub fn VSM_Error(vd: *const c_void) -> * const c_char; pub fn VSM_ResetError(vd: *const c_void); pub fn VSM_Name(vd: *const c_void) -> * const c_char; pub fn VSM_Open(vd: *const c_void) -> c_int; pub fn VSM_IsOpen(vd: *const c_void) -> c_int; pub fn VSM_Abandoned(vd: *const c_void) -> c_int; pub fn VSM_Close(vd: *const c_void); pub fn VSC_Arg(vd: *const c_void, arg: c_int, opt: *const c_char ) -> c_int; pub fn VSC_Iter(vd: *const c_void, fantom: *const c_void, cb_bounce: extern fn (*mut c_void, *const VSC_point) -> c_int, cb: *const c_void); pub fn VSL_New() -> *const c_void; pub fn VSL_Next(c: *const VSL_cursor) -> c_int; pub fn VSLQ_SetCursor(vslq: *const c_void, cur: *const *const c_void); pub fn VSL_CursorVSM(vsl: *const c_void, vsm: *const c_void, opt: c_uint) -> *const c_void; pub fn VSLQ_New(vsl:*const c_void, c: *const c_void, grouping: c_int, meh: *const c_void) -> *const c_void; pub fn VSLQ_Delete(vslq: *const *const c_void); pub fn VSLQ_Dispatch(vslq: *const c_void, cb_bounce : extern fn (_: *const c_void, pt: *const *const VslTransaction, cb: *const c_void) -> c_int, cb: *const c_void ) -> c_int; pub fn VSL_DeleteCursor(cur:*const c_void); pub fn VSL_Delete(vsl:*const c_void); } macro_rules! conv { ( $( $x:expr ),* ) => { { $( CStr::from_ptr($x as *const i8) .to_str() .unwrap() )* } }; } enum VsmChunk {} #[repr(C)] pub struct VSM_fantom { chunk: *const VsmChunk, b: *const c_char, e: *const c_char, prv: *const c_void, class: [c_char; 8], typ: [c_char; 8], ident: [c_char; 128], } #[repr(C)] pub struct VSC_level_desc { verbosity: *const c_int, label: *const c_char, sdesc: *const c_char, ldesc: *const c_char, } #[repr(C)] pub struct VSC_type_desc { label: *const c_char, sdesc: *const c_char, ldesc: *const c_char, } #[repr(C)] pub struct VSC_section { typ: *const c_char, ident: *const c_char, desc: *const VSC_type_desc, fantom: *const VSM_fantom } #[repr(C)] pub struct VSC_desc { name: *const c_char, ctype: *const c_char, semantics: c_int, format: c_int, level: *const VSC_level_desc, sdesc: *const c_char, ldesc: *const c_char, } #[repr(C)] pub struct VSC_point { desc: *const VSC_desc, ptr: *const c_void, section: *const VSC_section } #[repr(C)] pub struct VSL_cursor { ptr: *const u32, } pub enum VslReason { Unknown, Http1, RxReq, Esi, Restart, Pass, Fetch, BgFetch, Pipe } pub enum VslType { Unknown, Sess, Req, BeReq, Raw, } #[repr(C)] pub struct VslTransaction<'a> { pub level: c_uint, pub vxid: i32, pub vxid_parent: i32, pub typ: c_uint, pub reason: c_uint, c: &'a VSL_cursor } impl<'a> VSL_cursor { pub fn get_string(&self) -> &'a str { unsafe { conv!(self.ptr.offset(2) as *const i8) } } pub fn get_ntag(&self) -> u8 { unsafe { (*(self.ptr) >> 24) as u8 } } pub fn get_stag(&self) -> &str { let p: *const *const c_char= &VSL_tags; unsafe { conv!(*p.offset(self.get_ntag() as isize)) } } } impl<'a> Iterator for &'a VslTransaction<'a> { type Item = &'a VSL_cursor; fn next(&mut self) -> Option<&'a VSL_cursor> { match unsafe { VSL_Next(self.c) } { 0 => None, _ => Some(self.c as &VSL_cursor) } } } pub struct VscSection<'a> { //pub typ: &'a str , pub ident: &'a str, //pub label: &'a str, pub sdesc: &'a str, pub ldesc: &'a str, } pub struct VscDesc<'a> { pub name: &'a str, pub semantics: char, pub format: char, //level pub sdesc: &'a str, pub ldesc: &'a str, } pub struct VsmEntry<'a> { pub t: &'a str, pub ident: &'a str, pub value: u64, pub desc: VscDesc<'a>, pub section: VscSection<'a> } pub extern "C" fn log_bounce<F>(_: *const c_void, pt: *const *const VslTransaction, cb: *const c_void) -> c_int where F: FnMut(& [&VslTransaction]) -> bool { let cb = cb as *mut F; let mut n = 0; let s; unsafe { loop { if (*pt.offset(n)).is_null() { break; } n += 1; } s = slice::from_raw_parts::<&VslTransaction>(pt as *const &VslTransaction, n as usize) ; } match unsafe { (*cb)(s) } { true => 1, false =>1 } } pub extern "C" fn stat_bounce<F>(cb: *mut c_void, pt: *const VSC_point) -> c_int where F: FnMut(&VsmEntry) -> bool { if pt.is_null() { return 0; } let entry; unsafe { assert!(!(*pt).section.is_null()); let fantom = (*(*pt).section).fantom; assert!(!fantom.is_null()); assert!(conv!(&(*fantom).class) == "Stat"); let desc = (*pt).desc; assert!(!desc.is_null()); assert!(conv!((*desc).ctype) == "uint64_t"); let section = (*pt).section; assert!(!section.is_null()); assert!(conv!((*section).typ) == conv!(&(*fantom).typ)); assert!(conv!((*section).ident) == conv!(&(*fantom).ident)); entry = VsmEntry { t: conv!(&(*fantom).typ), ident: conv!(&(*fantom).ident), value: *((*pt).ptr as *const u64), desc: VscDesc { name: conv!((*desc).name), semantics: ((*desc).semantics as u8) as char, format: ((*desc).format as u8) as char, sdesc: conv!((*desc).sdesc), ldesc: conv!((*desc).ldesc) }, section: VscSection { ident: conv!((*section).ident), sdesc: conv!((*(*section).desc).sdesc), ldesc: conv!((*(*section).desc).ldesc) } }; } let cb = cb as *mut F; let r; unsafe { r = (*cb)(&entry); } match r { true => 0, false =>1 } }
use super::layers::*; use super::types::*; use crate::layers::loss_layer::*; use crate::layers::negativ_sampling_layer::*; use crate::util::*; // extern crate ndarray; use itertools::concat; use ndarray::{Array, Array1, Axis, Dimension, Ix2, Ix3}; use ndarray_rand::rand_distr::{StandardNormal, Uniform}; use ndarray_rand::RandomExt; pub mod rnn; pub mod seq2seq; pub trait Model2 { fn forward<D: Dimension>(&mut self, input: Array<usize, D>, target: Array1<usize>) -> f32 { unimplemented!(); } fn backward(&mut self) {} fn params(&mut self) -> Vec<&mut Arr2d> { vec![] } fn params_immut(&self) -> Vec<&Arr2d> { vec![] } fn grads(&self) -> Vec<Arr2d> { vec![] } } pub struct CBOW { in_layer: Embedding, loss_layer: NegativeSamplingLoss, } impl Model2 for CBOW { fn forward<D: Dimension>(&mut self, input: Array<usize, D>, target: Array1<usize>) -> f32 { let input = input .into_dimensionality::<Ix2>() .expect("CBOW: input size must be dim2"); let h = self.in_layer.forward(input); self.loss_layer.forward2(h, target) } fn backward(&mut self) { let dx = self.loss_layer.backward(); // batch_sizeใฏไฝฟใ‚ใชใ„ self.in_layer.backward(dx); } fn params(&mut self) -> Vec<&mut Arr2d> { concat(vec![self.in_layer.params(), self.loss_layer.params()]) } fn params_immut(&self) -> Vec<&Arr2d> { concat(vec![ self.in_layer.params_immut(), self.loss_layer.params_immut(), ]) } fn grads(&self) -> Vec<Arr2d> { concat(vec![self.in_layer.grads(), self.loss_layer.grads()]) } } use rand::distributions::Distribution; use rand::distributions::WeightedIndex; impl InitWithSampler for CBOW { fn new(ws: &[Arr2d], sample_size: usize, distribution: WeightedIndex<f32>) -> Self { Self { in_layer: Embedding::new(ws[0].clone()), loss_layer: NegativeSamplingLoss::new(ws[1].clone(), sample_size, distribution), } } } pub trait Model { /// ๆœ€ๅพŒใฎloss_layerใซใคใ„ใฆใ€ๅ‹พ้…่จˆ็ฎ—ใฏ็›ฎ็š„ใจใ›ใšใ€ใŸใ ๅญฆ็ฟ’ใซๅŸบใฅใไบˆๆƒณใ‚’ๅ‡บๅŠ›ใ•ใ›ใ‚‹ fn predict(&mut self, mut x: Arr2d) -> Arr2d { unimplemented!(); } /// ๆœ€ๅพŒใพใง้€ฒใ‚ใ‚‹ /// ใ‚ฟใƒผใ‚ฒใƒƒใƒˆใฏone_hot fn forward(&mut self, x: Arr2d, t: &Arr2d) -> f32 { unimplemented!(); } /// ใ‚ฟใƒผใ‚ฒใƒƒใƒˆใฏใƒฉใƒ™ใƒซใƒ™ใ‚ฏใƒˆใƒซ fn forwardt(&mut self, x: Arr2d, t: &Array1<usize>) -> f32 { unimplemented!(); } fn forwardx<D: Dimension>(&mut self, x: Array<f32, D>, t: Arr2d) -> f32; /// ่ชคๅทฎ้€†ไผๆ’ญใ•ใ›ใ‚‹ fn backward(&mut self, batch_size: usize); fn params1d(&mut self) -> Vec<&mut Arr1d> { Vec::new() } fn params2d(&mut self) -> Vec<&mut Arr2d>; fn grads1d(&self) -> Vec<Arr1d> { Vec::new() } fn grads2d(&self) -> Vec<Arr2d>; } pub struct TwoLayerNet<L: LayerWithLoss + Default> { input_size: usize, hidden_size: usize, output_size: usize, layers: [Box<dyn Layer>; 3], // loss_layer: Box<dyn LayerWithLoss>, loss_layer: L, } impl<L: LayerWithLoss + Default> TwoLayerNet<L> { pub fn new(input_size: usize, hidden_size: usize, output_size: usize) -> Self { const PARAM_INIT_SCALE: f32 = 1.0; // ใ“ใ‚Œๅค‰ใˆใ‚‹ใจๅพฎๅฆ™ใซๅญฆ็ฟ’ๅŠน็އๅค‰ใ‚ใ‚‹ใฎใ ใŒใ€ใ‚ˆใใ‚ใ‹ใ‚‰ใ‚“ let w1 = randarr2d(input_size, hidden_size) * PARAM_INIT_SCALE; let b1 = randarr1d(hidden_size) * PARAM_INIT_SCALE; let w2 = randarr2d(hidden_size, output_size) * PARAM_INIT_SCALE; let b2 = randarr1d(output_size) * PARAM_INIT_SCALE; let affine1 = Affine::new(w1, b1); let sigmoid: Sigmoid = Default::default(); let affine2 = Affine::new(w2, b2); let layers: [Box<dyn Layer>; 3] = [Box::new(affine1), Box::new(sigmoid), Box::new(affine2)]; Self { input_size, hidden_size, output_size, layers, loss_layer: L::default(), } } } impl<L: LayerWithLoss + Default> Model for TwoLayerNet<L> { fn predict(&mut self, mut x: Arr2d) -> Arr2d { for layer in self.layers.iter_mut() { x = layer.forward(x); } self.loss_layer.predict(x) } fn forward(&mut self, mut x: Arr2d, t: &Arr2d) -> f32 { for layer in self.layers.iter_mut() { x = layer.forward(x); } self.loss_layer.forward(x, &t) } fn forwardx<D: Dimension>(&mut self, x: Array<f32, D>, t: Arr2d) -> f32 { let mut x = x .into_dimensionality::<Ix2>() .expect("failed in converting to arr2d"); for layer in self.layers.iter_mut() { x = layer.forward(x); } self.loss_layer.forward(x, &t) } fn backward(&mut self, batch_size: usize) { let mut dx = self.loss_layer.backward(); 0; for layer in self.layers.iter_mut().rev() { dx = layer.backward(dx); } } fn params1d(&mut self) -> Vec<&mut Arr1d> { concat(self.layers.iter_mut().map(|l| l.params1d())) } fn params2d(&mut self) -> Vec<&mut Arr2d> { concat(self.layers.iter_mut().map(|l| l.params2d())) } fn grads1d(&self) -> Vec<Arr1d> { concat(self.layers.iter().map(|l| l.grads1d())) } fn grads2d(&self) -> Vec<Arr2d> { concat(self.layers.iter().map(|l| l.grads2d())) } } pub struct SimpleCBOW<L: LayerWithLoss + Default> { vocab_size: usize, hidden_size: usize, // layers: [Box<dyn Layer>; 3], loss_layer: L, in_layer_1: MatMul, in_layer_2: MatMul, out_layer: MatMul, } impl<L: LayerWithLoss + Default> SimpleCBOW<L> { pub fn new(vocab_size: usize, hidden_size: usize) -> Self { let (_v, _h) = (vocab_size, hidden_size); let scale = Some(0.01); const PARAM_INIT_SCALE: f32 = 0.01; let in_layer_1 = MatMul::new_from_size(_v, _h, scale); let in_layer_2 = MatMul::new_from_size(_v, _h, scale); let out_layer = MatMul::new_from_size(_h, _v, scale); Self { vocab_size, hidden_size, loss_layer: L::default(), in_layer_1, in_layer_2, out_layer, } } pub fn layers(&mut self) -> Vec<&mut dyn Layer> { vec![ &mut self.in_layer_1, &mut self.in_layer_2, &mut self.out_layer, ] } pub fn word_vecs(&self) -> Arr2d { self.in_layer_1.w.clone() } } impl<L: LayerWithLoss + Default> Model for SimpleCBOW<L> { fn forwardx<D: Dimension>(&mut self, contexts: Array<f32, D>, target: Arr2d) -> f32 { let x = contexts .into_dimensionality::<Ix3>() .expect("contexts array must be dim3"); let h0 = self.in_layer_1.forward(x.index_axis(Axis(1), 0).to_owned()); let h1 = self.in_layer_2.forward(x.index_axis(Axis(1), 1).to_owned()); let h = (h0 + h1) * 0.5; let score = self.out_layer.forward(h); self.loss_layer.forward(score, &target) } fn backward(&mut self, batch_size: usize) { let mut dx = self.loss_layer.backward(); dx = self.out_layer.backward(dx); dx *= 0.5; // in1, in2ใฎๅ…ฅๅŠ›ใ‚’ๅนณๅ‡ใ™ใ‚‹่จญๅฎšใซใชใฃใฆใ„ใ‚‹ใŸใ‚forwardx<D>ๅ‚็…ง self.in_layer_1.backward(dx.clone()); self.in_layer_2.backward(dx); } fn params2d(&mut self) -> Vec<&mut Arr2d> { // ใ‚คใƒ†ใƒฌใƒผใ‚ฟไฝฟใˆใš... // concat(self.layers().iter_mut().map(|l| l.params2d())) // concat([&mut self.in_layer_1, &mut self.in_layer_2, &mut self.out_layer].into_iter().map(|l| l.grads2d())) // vec![self.in_layer_1.grads2d()[0]] // self.in_layer_1.grads2d()[0]; let mut layers = self.layers(); // concat(layers.iter_mut().map(|l| l.params2d())) // concat([&mut self.in_layer_1, &mut self.in_layer_2, &mut self.out_layer].iter_mut().map(|l| l.params2d()).collect::<Vec<Vec<&mut Arr2d>>>()); // let c = concat(self.layers().iter_mut().map(|l| l.params2d()).collect::<Vec<_>>()); concat(vec![ self.in_layer_1.params2d(), self.in_layer_2.params2d(), self.out_layer.params2d(), ]) } fn grads2d(&self) -> Vec<Arr2d> { concat(vec![ self.in_layer_1.grads2d(), self.in_layer_2.grads2d(), self.out_layer.grads2d(), ]) } }
fn gnome_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut i: usize = 1; let mut j: usize = 2; while i < len { if a[i - 1] <= a[i] { // for descending sort, use >= for comparison i = j; j += 1; } else { a.swap(i - 1, i); i -= 1; if i == 0 { i = j; j += 1; } } } } fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); gnome_sort(&mut v); println!("after: {:?}", v); }
use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::video::{GLContext, GLProfile, Window}; use sdl2::{EventPump, Sdl}; pub struct Display { window: Window, event_pump: EventPump, pub is_closed: bool, // both below are just hold to keep context, since their Drop calls the Delete methods on C _gl_context: GLContext, _sdl_context: Sdl, } impl Display { pub fn new(width: usize, heigth: usize, title: &str) -> Self { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(GLProfile::Core); gl_attr.set_context_version(3, 3); gl_attr.set_red_size(8); gl_attr.set_green_size(8); gl_attr.set_blue_size(8); gl_attr.set_buffer_size(32); gl_attr.set_double_buffer(true); // allocates space for atother window let window = video_subsystem .window(title, width as u32, heigth as u32) .position_centered() .opengl() .build() .unwrap(); let _gl_context = window.gl_create_context().unwrap(); // needs to be saved on struct because SDL_GL_DeleteContext is called when it is dropped gl::load_with(|name| video_subsystem.gl_get_proc_address(name) as *const _); debug_assert_eq!(gl_attr.context_version(), (3, 3)); debug_assert_eq!(gl_attr.context_profile(), GLProfile::Core); let event_pump = sdl_context.event_pump().unwrap(); Display { window, event_pump, is_closed: false, _gl_context, _sdl_context: sdl_context, } } pub fn clear(&self) { unsafe { gl::ClearColor(0.0, 0.15, 0.3, 1.0); gl::Clear(gl::COLOR_BUFFER_BIT); } } pub fn update(&mut self) { self.window.gl_swap_window(); for event in self.event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { self.is_closed = true; } _ => {} } } } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfluentAgreementProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub publisher: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<String>, #[serde(rename = "licenseTextLink", default, skip_serializing_if = "Option::is_none")] pub license_text_link: Option<String>, #[serde(rename = "privacyPolicyLink", default, skip_serializing_if = "Option::is_none")] pub privacy_policy_link: Option<String>, #[serde(rename = "retrieveDatetime", default, skip_serializing_if = "Option::is_none")] pub retrieve_datetime: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub signature: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub accepted: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfluentAgreementResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ConfluentAgreementProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfluentAgreementResourceListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ConfluentAgreementResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplay { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplay>, #[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")] pub is_data_action: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationResult>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponseBody { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorResponseBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceProviderDefaultErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorResponseBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Accepted, Creating, Updating, Deleting, Succeeded, Failed, Canceled, Deleted, NotSpecified, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SaaSOfferStatus { Started, PendingFulfillmentStart, InProgress, Subscribed, Suspended, Reinstated, Succeeded, Failed, Unsubscribed, Updating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OfferDetail { #[serde(rename = "publisherId", default, skip_serializing_if = "Option::is_none")] pub publisher_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "planId", default, skip_serializing_if = "Option::is_none")] pub plan_id: Option<String>, #[serde(rename = "planName", default, skip_serializing_if = "Option::is_none")] pub plan_name: Option<String>, #[serde(rename = "termUnit", default, skip_serializing_if = "Option::is_none")] pub term_unit: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<SaaSOfferStatus>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserDetail { #[serde(rename = "firstName", default, skip_serializing_if = "Option::is_none")] pub first_name: Option<String>, #[serde(rename = "lastName", default, skip_serializing_if = "Option::is_none")] pub last_name: Option<String>, #[serde(rename = "emailAddress", default, skip_serializing_if = "Option::is_none")] pub email_address: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrganizationResourceProperties { #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<ProvisioningState>, #[serde(rename = "organizationId", default, skip_serializing_if = "Option::is_none")] pub organization_id: Option<String>, #[serde(rename = "ssoUrl", default, skip_serializing_if = "Option::is_none")] pub sso_url: Option<String>, #[serde(rename = "offerDetail", default, skip_serializing_if = "Option::is_none")] pub offer_detail: Option<serde_json::Value>, #[serde(rename = "userDetail", default, skip_serializing_if = "Option::is_none")] pub user_detail: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrganizationResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrganizationResourceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OrganizationResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrganizationResourceUpdate { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, }
/////////////////////////////////////////////////////////////////////////////// // // Copyright 2018-2019 Airalab <research@aira.life> // // 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. // /////////////////////////////////////////////////////////////////////////////// //! This module exports Robonomics API into ROS namespace. use log::debug; use std::sync::Arc; use futures::{Future, Stream, sync::mpsc}; use network::SyncProvider; use keystore::Store as Keystore; use client::{ Client, CallExecutor, BlockchainEvents, blockchain::HeaderBackend, backend::Backend }; use runtime_primitives::{ codec::{Decode, Encode, Compact}, generic::{BlockId, Era}, traits::{As, Block, Header, BlockNumberToHash} }; use primitives::{ Blake2Hasher, H256, twox_128, sr25519, crypto::Pair, crypto::Ss58Codec, storage::{StorageKey, StorageData, StorageChangeSet} }; use transaction_pool::txpool::{ChainApi, Pool, ExtrinsicFor}; use robonomics_runtime::{ AccountId, Call, UncheckedExtrinsic, EventRecord, Event, robonomics::*, RobonomicsCall, Nonce, Runtime }; mod msg; mod ipfs; mod rosbag_player; use msg::{std_msgs, robonomics_msgs}; use rosbag_player::RosbagPlayer; /// ROS Pub/Sub queue size. /// http://wiki.ros.org/roscpp/Overview/Publishers%20and%20Subscribers#Queueing_and_Lazy_Deserialization const QUEUE_SIZE: usize = 10; /// Simple liability engine. fn liability_stream( stream: mpsc::UnboundedReceiver<robonomics_msgs::Liability>, ros_account: String, ) -> impl Future<Item=(),Error=()> { stream .filter(move |liability| liability.promisor == ros_account) .for_each(|liability| { ipfs::read_file(liability.order.objective.as_str()).then(move |_| { let player = RosbagPlayer::new(liability.order.objective.as_str()); player.play_rosbag().map_err(|_| ()) }) }) } /// Robonomics extrinsic sender. fn extrinsic_stream<B, E, P, RA>( client: Arc<Client<B, E, P::Block, RA>>, key: sr25519::Pair, pool: Arc<Pool<P>>, stream: mpsc::UnboundedReceiver<RobonomicsCall<Runtime>> ) -> impl Future<Item=(),Error=()> where B: Backend<P::Block, Blake2Hasher>, E: CallExecutor<P::Block, Blake2Hasher> + Send + Sync, P: ChainApi, RA: Send + Sync, P::Block: Block<Hash=H256>, { // Get account address from keypair let local_id: AccountId = key.public(); let mut nonce_key = b"System AccountNonce".to_vec(); nonce_key.extend_from_slice(&local_id.0[..]); let storage_key = StorageKey(twox_128(&nonce_key[..]).to_vec()); stream.for_each(move |call| { let block_id = BlockId::hash(client.backend().blockchain().info().unwrap().best_hash); let nonce = if let Some(storage_data) = client.storage(&block_id, &storage_key).unwrap() { let nonce: Nonce = Decode::decode(&mut &storage_data.0[..]).unwrap(); Compact::<Nonce>::from(nonce) } else { Compact::<Nonce>::from(0) }; let payload = ( nonce, Call::Robonomics(call), Era::immortal(), client.genesis_hash(), ); let signature = key.sign(&payload.encode()); let extrinsic = UncheckedExtrinsic::new_signed( payload.0.into(), payload.1, local_id.clone().into(), signature.into(), payload.2, ); let xt: ExtrinsicFor<P> = Decode::decode(&mut &extrinsic.encode()[..]).unwrap(); let res = pool.submit_one(&block_id, xt); debug!("submission result: {:?}", res); Ok(()) }) } /// Storage event listener. fn event_stream<B, C>( client: Arc<C>, liability_tx: mpsc::UnboundedSender<robonomics_msgs::Liability>, ) -> impl Future<Item=(),Error=()> where C: BlockchainEvents<B>, B: Block, { let demand_pub = rosrust::publish("liability/demand/incoming", QUEUE_SIZE).unwrap(); let offer_pub = rosrust::publish("liability/offer/incoming", QUEUE_SIZE).unwrap(); let liability_pub = rosrust::publish("liability/incoming", QUEUE_SIZE).unwrap(); let events_key = StorageKey(twox_128(b"System Events").to_vec()); client.storage_changes_notification_stream(Some(&[events_key])).unwrap() .map(|(block, changes)| StorageChangeSet { block, changes: changes.iter().cloned().collect()}) .for_each(move |change_set| { // Decode events from change set let records: Vec<Vec<EventRecord<Event>>> = change_set.changes.iter() .filter_map(|(_, mbdata)| if let Some(StorageData(data)) = mbdata { Decode::decode(&mut &data[..]) } else { None }) .collect(); let events: Vec<Event> = records.concat().iter().cloned().map(|r| r.event).collect(); // Iterate and dispatch events events.iter().for_each(|event| { if let Event::robonomics(e) = event { match e { RawEvent::NewDemand(hash, demand) => { debug!("NewDemand: {:?} {:?}", hash, demand); let mut msg = robonomics_msgs::Demand::default(); let model = bs58::encode(&demand.order.model); let objective = bs58::encode(&demand.order.objective); msg.order.model = model.into_string(); msg.order.objective = objective.into_string(); msg.order.cost = demand.order.cost.to_string(); msg.sender = demand.sender.to_ss58check(); demand_pub.send(msg).unwrap(); }, RawEvent::NewOffer(hash, offer) => { debug!("NewOffer: {:?} {:?}", hash, offer); let mut msg = robonomics_msgs::Offer::default(); let model = bs58::encode(&offer.order.model); let objective = bs58::encode(&offer.order.objective); msg.order.model = model.into_string(); msg.order.objective = objective.into_string(); msg.order.cost = offer.order.cost.to_string(); msg.sender = offer.sender.to_ss58check(); offer_pub.send(msg).unwrap(); }, RawEvent::NewLiability(id, liability) => { debug!("NewLiability: {:?} {:?}", id, liability); let mut msg = robonomics_msgs::Liability::default(); let model = bs58::encode(&liability.order.model); let objective = bs58::encode(&liability.order.objective); msg.id = *id; msg.order.model = model.into_string(); msg.order.objective = objective.into_string(); msg.order.cost = liability.order.cost.to_string(); msg.promisee = liability.promisee.to_ss58check(); msg.promisor = liability.promisor.to_ss58check(); liability_pub.send(msg.clone()).unwrap(); // Send new liability to engine liability_tx.unbounded_send(msg).unwrap(); }, _ => () } } }); Ok(()) }) } /// Robonomics node status. fn status_stream<B, C, N>( client: Arc<C>, network: Arc<N>, ) -> impl Future<Item=(),Error=()> where C: BlockchainEvents<B> + HeaderBackend<B>, N: SyncProvider<B>, B: Block, { let hash_pub = rosrust::publish("blockchain/best_hash", QUEUE_SIZE).unwrap(); let number_pub = rosrust::publish("blockchain/best_number", QUEUE_SIZE).unwrap(); let peers_pub = rosrust::publish("network/peers", QUEUE_SIZE).unwrap(); client.import_notification_stream().for_each(move |block| { if block.is_new_best { let mut hash_msg = std_msgs::String::default(); hash_msg.data = block.header.hash().to_string(); hash_pub.send(hash_msg).unwrap(); let mut peers_msg = std_msgs::UInt64::default(); peers_msg.data = network.peers().len() as u64; peers_pub.send(peers_msg).unwrap(); let mut number_msg = std_msgs::UInt64::default(); number_msg.data = block.header.number().as_(); number_pub.send(number_msg).unwrap(); } Ok(()) }) } /// ROS API main routine. pub fn start_ros_api<N, B, E, P, RA>( network: Arc<N>, client: Arc<Client<B, E, P::Block, RA>>, pool: Arc<Pool<P>>, keystore: &Keystore, on_exit: impl Future<Item=(),Error=()> + 'static, ) -> impl Future<Item=(),Error=()> + 'static where N: SyncProvider<P::Block> + 'static, B: Backend<P::Block, Blake2Hasher> + 'static, E: CallExecutor<P::Block, Blake2Hasher> + Send + Sync + 'static, P: ChainApi + 'static, RA: Send + Sync + 'static, P::Block: Block<Hash=H256>, { rosrust::try_init_with_options("robonomics", false); ipfs::init(); let keystore_default_public = &keystore.contents().unwrap()[0]; let keystore_default_key = keystore.load(&keystore_default_public, &String::new()).unwrap(); let key = sr25519::Pair::from_seed(*keystore_default_key.seed()); let ros_account = key.public().to_ss58check(); println!("ROS account: {:?}", ros_account); // Create extrinsics channel let (demand_tx, extrinsic_rx) = mpsc::unbounded(); let offer_tx = demand_tx.clone(); let finalize_tx = demand_tx.clone(); // Subscribe for sending demand extrinsics let demand = rosrust::subscribe("liability/demand/send", QUEUE_SIZE, move |v: robonomics_msgs::Order| { let model = bs58::decode(v.model).into_vec().unwrap(); let objective = bs58::decode(v.objective).into_vec().unwrap(); let cost = v.cost.parse().unwrap(); demand_tx.unbounded_send(RobonomicsCall::demand(model, objective, cost)).unwrap(); }).expect("failed to create demand subscriber"); // Subscribe for sending offer extrinsics let offer = rosrust::subscribe("liability/offer/send", QUEUE_SIZE, move |v: robonomics_msgs::Order| { let model = bs58::decode(v.model).into_vec().unwrap(); let objective = bs58::decode(v.objective).into_vec().unwrap(); let cost = v.cost.parse().unwrap(); offer_tx.unbounded_send(RobonomicsCall::offer(model, objective, cost)).unwrap(); }).expect("failed to create demand subscriber"); // Finalize liability let finalize = rosrust::subscribe("liability/finalize", QUEUE_SIZE, move |v: robonomics_msgs::Finalize| { let result = bs58::decode(v.result).into_vec().unwrap(); finalize_tx.unbounded_send(RobonomicsCall::finalize(v.id, result)).unwrap(); }).expect("failed to create liability subscriber"); // Create liability channel let (liability_tx, liability_rx) = mpsc::unbounded(); // Store subscribers in vector let subs = vec![demand, offer, finalize]; extrinsic_stream(client.clone(), key, pool, extrinsic_rx) .join(liability_stream(liability_rx, ros_account)) .join(event_stream(client.clone(), liability_tx)) .join(status_stream(client, network)) .map(|_| ()) .select(on_exit) .then(move |_| { // move subscribers to this closure // subscribers must not be removed until exit subs; Ok(()) }) }
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Stopwatch for tracking how long it takes to run tests. //! //! Tests need to track a start time and a duration. For that we use a combination of a `SystemTime` //! (realtime clock) and an `Instant` (monotonic clock). Once the stopwatch transitions to the "end" //! state, we can report the elapsed time using the monotonic clock. use std::time::{Duration, Instant, SystemTime}; /// The start state of a stopwatch. #[derive(Clone, Debug)] pub(crate) struct StopwatchStart { start_time: SystemTime, instant: Instant, } impl StopwatchStart { pub(crate) fn now() -> Self { Self { // These two syscalls will happen imperceptibly close to each other, which is good // enough for our purposes. start_time: SystemTime::now(), instant: Instant::now(), } } pub(crate) fn end(&self) -> StopwatchEnd { StopwatchEnd { start_time: self.start_time, duration: self.instant.elapsed(), } } } #[derive(Clone, Debug)] pub(crate) struct StopwatchEnd { pub(crate) start_time: SystemTime, pub(crate) duration: Duration, }
use crate::arena::{block, BlockMut, BlockRef}; use crate::libs::js_object::Object; use crate::libs::random_id::U128Id; use crate::libs::three; use std::rc::Rc; use wasm_bindgen::JsCast; pub mod camera; pub mod raycaster; pub mod table_object; pub mod texture_table; pub use camera::Camera; pub use raycaster::Raycaster; pub use texture_table::TextureTable; pub struct Three { canvas: Rc<web_sys::HtmlCanvasElement>, camera: Camera, raycaster: Raycaster, texture_table: TextureTable, scene: three::Scene, renderer: three::WebGLRenderer, object_boxblock: table_object::Boxblock, object_craftboard: table_object::Craftboard, object_character: table_object::Character, object_terran: table_object::Terran, object_textboard: table_object::Textboard, light: CommonLight, device_pixel_ratio: f64, canvas_size: [f64; 2], } struct CommonLight { ambient_light: three::AmbientLight, directional_light: three::DirectionalLight, } impl Three { pub fn new() -> Self { let canvas = web_sys::window() .unwrap() .document() .unwrap() .create_element("canvas") .unwrap() .dyn_into::<web_sys::HtmlCanvasElement>() .unwrap(); let canvas = Rc::new(canvas); let camera = Camera::new(); let raycaster = Raycaster::new(); let scene = three::Scene::new(); let renderer = three::WebGLRenderer::new(&object! { "canvas": canvas.as_ref(), "alpha": true, }); renderer.set_clear_alpha(0.0); let ambient_light = three::AmbientLight::new(); ambient_light.set_intensity(0.3); scene.add(&ambient_light); let directional_light = three::DirectionalLight::new(); directional_light.position().set(3.0, -4.0, 5.0); scene.add(&directional_light); let device_pixel_ratio = web_sys::window().unwrap().device_pixel_ratio(); Self { canvas, camera, raycaster, texture_table: TextureTable::new(), scene, renderer, object_boxblock: table_object::Boxblock::new(), object_craftboard: table_object::Craftboard::new(), object_character: table_object::Character::new(), object_terran: table_object::Terran::new(), object_textboard: table_object::Textboard::new(), light: CommonLight { ambient_light, directional_light, }, device_pixel_ratio, canvas_size: [1.0, 1.0], } } fn coords(&self, coords_px: &[f64; 2]) -> [f64; 2] { let coord_x = coords_px[0] * 2.0 / self.canvas_size[0] - 1.0; let coord_y = coords_px[1] * 2.0 / self.canvas_size[1] - 1.0; let coord_y = -coord_y; [coord_x, coord_y] } fn intersect_objects(&mut self, coords: &[f64; 2], ignored_id: &U128Id) -> Vec<Object> { self.raycaster.set_from_camera(coords, &self.camera); self.raycaster .intersect_objects(&self.scene.children()) .to_vec() .into_iter() .filter_map(|object| object.dyn_into::<Object>().ok()) .filter(|object| { object .get("object") .and_then(|object| object.dyn_into::<three::Object3D>().ok()) .and_then(|object| U128Id::from_jsvalue(&object.user_data())) .map(|block_id| block_id != *ignored_id) .unwrap_or(false) }) .collect() } pub fn get_focused_object_and_position( &mut self, coords_px: &[f64; 2], ignored_id: &U128Id, ) -> (U128Id, [f64; 3], [f64; 3]) { let coords = self.coords(coords_px); let objects = self.intersect_objects(&coords, ignored_id); for object in objects { let block_id = object .get("object") .and_then(|x| x.dyn_into::<three::Object3D>().ok()) .and_then(|x| U128Id::from_jsvalue(&x.user_data())); let point = object .get("point") .and_then(|x| x.dyn_into::<three::Vector3>().ok()); let face = object .get("face") .and_then(|x| x.dyn_into::<Object>().ok()) .and_then(|x| x.get("normal")) .and_then(|x| x.dyn_into::<three::Vector3>().ok()); if let Some((block_id, point, face)) = join_some!(block_id, point, face) { return ( block_id, [point.x(), point.y(), point.z()], [face.x(), face.y(), face.z()], ); } } let ray = self.raycaster.ray(); let origin = ray.origin(); let direction = ray.direction(); let scale = (0.0 - origin.z()) / direction.z(); let x = origin.x() + direction.x() * scale; let y = origin.y() + direction.y() * scale; let z = 0.0; (U128Id::none(), [x, y, z], [0.0, 0.0, 1.0]) } pub fn get_focused_object(&mut self, coords_px: &[f64; 2], ignored_id: &U128Id) -> U128Id { let coords = self.coords(coords_px); let objects = self.intersect_objects(&coords, ignored_id); for object in objects { let block_id = object .get("object") .and_then(|x| x.dyn_into::<three::Object3D>().ok()) .and_then(|x| U128Id::from_jsvalue(&x.user_data())); if let Some(block_id) = block_id { return block_id; } } U128Id::none() } pub fn get_focused_position( &mut self, coords_px: &[f64; 2], ignored_id: &U128Id, ) -> ([f64; 3], [f64; 3]) { let coords = self.coords(coords_px); let objects = self.intersect_objects(&coords, ignored_id); for object in objects { let point = object .get("point") .and_then(|x| x.dyn_into::<three::Vector3>().ok()); let face = object .get("face") .and_then(|x| x.dyn_into::<Object>().ok()) .and_then(|x| x.get("normal")) .and_then(|x| x.dyn_into::<three::Vector3>().ok()); if let Some((point, face)) = join_some!(point, face) { return ( [point.x(), point.y(), point.z()], [face.x(), face.y(), face.z()], ); } } let ray = self.raycaster.ray(); let origin = ray.origin(); let direction = ray.direction(); let scale = (0.0 - origin.z()) / direction.z(); let x = origin.x() + direction.x() * scale; let y = origin.y() + direction.y() * scale; let z = 0.0; ([x, y, z], [0.0, 0.0, 1.0]) } pub fn reset_size(&mut self) { let bb = self.canvas.get_bounding_client_rect(); let w = bb.width(); let h = bb.height(); self.renderer.set_pixel_ratio(1.0); self.renderer .set_size(w * self.device_pixel_ratio, h * self.device_pixel_ratio); self.canvas_size = [w, h]; } pub fn canvas(&self) -> Rc<web_sys::HtmlCanvasElement> { Rc::clone(&self.canvas) } pub fn camera(&self) -> &Camera { &self.camera } pub fn camera_mut(&mut self) -> &mut Camera { &mut self.camera } pub fn render(&mut self, is_2d_mode: bool, world: BlockRef<block::World>) { let scene = world .map(|world| world.selecting_scene().as_ref()) .unwrap_or(BlockRef::<block::Scene>::none()); let table = scene .map(|scene| scene.selecting_table().as_ref()) .unwrap_or(BlockRef::<block::Table>::none()); table.map(|table| { self.object_craftboard.update( &mut self.texture_table, &self.scene, table.craftboards().iter().map(|block| block.as_ref()), ); }); table.map(|table| { self.object_terran.update( &mut self.texture_table, &self.scene, table.craftboards().iter().map(|block| block.as_ref()), ); }); table.map(|table| { self.object_boxblock.update( &mut self.texture_table, &self.scene, table.boxblocks().iter().map(|block| block.as_ref()), ); }); table.map(|table| { self.object_textboard.update( &mut self.texture_table, &self.scene, table.textboards().iter().map(|block| block.as_ref()), ); }); world.map(|world| { self.object_character.update( &mut self.texture_table, &self.scene, world.characters().iter().map(|block| block.as_ref()), ); }); self.camera .set_aspect(self.canvas_size[0] / self.canvas_size[1]); self.camera.update(if is_2d_mode { camera::CameraKind::Orthographic2d } else { camera::CameraKind::Perspective }); self.renderer.render(&self.scene, &self.camera); self.texture_table.update(); } }
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. // FIXME(shirly): remove following later #![allow(dead_code, unused_variables)] mod column; mod constant; mod fncall; mod builtin_cast; mod builtin_control; mod builtin_op; mod compare; mod arithmetic; use self::compare::CmpOp; use std::{error, io}; use std::borrow::Cow; use std::string::FromUtf8Error; use std::str::Utf8Error; use tipb::expression::{Expr, ExprType, FieldType, ScalarFuncSig}; use coprocessor::codec::mysql::{Decimal, Duration, Json, Res, Time, MAX_FSP}; use coprocessor::codec::mysql::decimal::DecimalDecoder; use coprocessor::codec::mysql::types; use coprocessor::codec::Datum; use util; use util::codec::number::NumberDecoder; use util::codec::Error as CError; pub use coprocessor::select::xeval::EvalContext as StatementContext; quick_error! { #[derive(Debug)] pub enum Error { Io(err: io::Error) { from() description("io error") display("I/O error: {}", err) cause(err) } Type { has: &'static str, expected: &'static str } { description("type error") display("type error: cannot get {:?} result from {:?} expression", expected, has) } Codec(err: util::codec::Error) { from() description("codec error") display("codec error: {}", err) cause(err) } ColumnOffset(offset: usize) { description("column offset not found") display("illegal column offset: {}", offset) } Truncated { description("Truncated") display("error Truncated") } Overflow { description("Overflow") display("error Overflow") } Other(err: Box<error::Error + Send + Sync>) { from() cause(err.as_ref()) description(err.description()) display("unknown error {:?}", err) } } } impl From<FromUtf8Error> for Error { fn from(err: FromUtf8Error) -> Error { Error::Codec(CError::Encoding(err.utf8_error().into())) } } impl From<Utf8Error> for Error { fn from(err: Utf8Error) -> Error { Error::Codec(CError::Encoding(err.into())) } } pub type Result<T> = ::std::result::Result<T, Error>; impl<T> Into<Result<T>> for Res<T> { fn into(self) -> Result<T> { match self { Res::Ok(t) => Ok(t), Res::Truncated(_) => Err(Error::Truncated), Res::Overflow(_) => Err(Error::Overflow), } } } #[derive(Debug, Clone, PartialEq)] pub enum Expression { Constant(Constant), ColumnRef(Column), ScalarFn(FnCall), } #[derive(Debug, Clone, PartialEq)] pub struct Column { offset: usize, tp: FieldType, } #[derive(Debug, Clone, PartialEq)] pub struct Constant { val: Datum, tp: FieldType, } /// A single scalar function call #[derive(Debug, Clone, PartialEq)] pub struct FnCall { sig: ScalarFuncSig, children: Vec<Expression>, tp: FieldType, } impl Expression { fn new_const(v: Datum, field_type: FieldType) -> Expression { Expression::Constant(Constant { val: v, tp: field_type, }) } #[inline] fn get_tp(&self) -> &FieldType { match *self { Expression::Constant(ref c) => &c.tp, Expression::ColumnRef(ref c) => &c.tp, Expression::ScalarFn(ref c) => &c.tp, } } #[cfg(test)] #[inline] fn mut_tp(&mut self) -> &mut FieldType { match *self { Expression::Constant(ref mut c) => &mut c.tp, Expression::ColumnRef(ref mut c) => &mut c.tp, Expression::ScalarFn(ref mut c) => &mut c.tp, } } fn eval_int(&self, ctx: &StatementContext, row: &[Datum]) -> Result<Option<i64>> { match *self { Expression::Constant(ref constant) => constant.eval_int(), Expression::ColumnRef(ref column) => column.eval_int(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::LTInt => f.compare_int(ctx, row, CmpOp::LT), ScalarFuncSig::LEInt => f.compare_int(ctx, row, CmpOp::LE), ScalarFuncSig::GTInt => f.compare_int(ctx, row, CmpOp::GT), ScalarFuncSig::GEInt => f.compare_int(ctx, row, CmpOp::GE), ScalarFuncSig::EQInt => f.compare_int(ctx, row, CmpOp::EQ), ScalarFuncSig::NEInt => f.compare_int(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQInt => f.compare_int(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTReal => f.compare_real(ctx, row, CmpOp::LT), ScalarFuncSig::LEReal => f.compare_real(ctx, row, CmpOp::LE), ScalarFuncSig::GTReal => f.compare_real(ctx, row, CmpOp::GT), ScalarFuncSig::GEReal => f.compare_real(ctx, row, CmpOp::GE), ScalarFuncSig::EQReal => f.compare_real(ctx, row, CmpOp::EQ), ScalarFuncSig::NEReal => f.compare_real(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQReal => f.compare_real(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTDecimal => f.compare_decimal(ctx, row, CmpOp::LT), ScalarFuncSig::LEDecimal => f.compare_decimal(ctx, row, CmpOp::LE), ScalarFuncSig::GTDecimal => f.compare_decimal(ctx, row, CmpOp::GT), ScalarFuncSig::GEDecimal => f.compare_decimal(ctx, row, CmpOp::GE), ScalarFuncSig::EQDecimal => f.compare_decimal(ctx, row, CmpOp::EQ), ScalarFuncSig::NEDecimal => f.compare_decimal(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQDecimal => f.compare_decimal(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTString => f.compare_string(ctx, row, CmpOp::LT), ScalarFuncSig::LEString => f.compare_string(ctx, row, CmpOp::LE), ScalarFuncSig::GTString => f.compare_string(ctx, row, CmpOp::GT), ScalarFuncSig::GEString => f.compare_string(ctx, row, CmpOp::GE), ScalarFuncSig::EQString => f.compare_string(ctx, row, CmpOp::EQ), ScalarFuncSig::NEString => f.compare_string(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQString => f.compare_string(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTTime => f.compare_time(ctx, row, CmpOp::LT), ScalarFuncSig::LETime => f.compare_time(ctx, row, CmpOp::LE), ScalarFuncSig::GTTime => f.compare_time(ctx, row, CmpOp::GT), ScalarFuncSig::GETime => f.compare_time(ctx, row, CmpOp::GE), ScalarFuncSig::EQTime => f.compare_time(ctx, row, CmpOp::EQ), ScalarFuncSig::NETime => f.compare_time(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQTime => f.compare_time(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTDuration => f.compare_duration(ctx, row, CmpOp::LT), ScalarFuncSig::LEDuration => f.compare_duration(ctx, row, CmpOp::LE), ScalarFuncSig::GTDuration => f.compare_duration(ctx, row, CmpOp::GT), ScalarFuncSig::GEDuration => f.compare_duration(ctx, row, CmpOp::GE), ScalarFuncSig::EQDuration => f.compare_duration(ctx, row, CmpOp::EQ), ScalarFuncSig::NEDuration => f.compare_duration(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQDuration => f.compare_duration(ctx, row, CmpOp::NullEQ), ScalarFuncSig::LTJson => f.compare_json(ctx, row, CmpOp::LT), ScalarFuncSig::LEJson => f.compare_json(ctx, row, CmpOp::LE), ScalarFuncSig::GTJson => f.compare_json(ctx, row, CmpOp::GT), ScalarFuncSig::GEJson => f.compare_json(ctx, row, CmpOp::GE), ScalarFuncSig::EQJson => f.compare_json(ctx, row, CmpOp::EQ), ScalarFuncSig::NEJson => f.compare_json(ctx, row, CmpOp::NE), ScalarFuncSig::NullEQJson => f.compare_json(ctx, row, CmpOp::NullEQ), ScalarFuncSig::CastIntAsInt => f.cast_int_as_int(ctx, row), ScalarFuncSig::CastRealAsInt => f.cast_real_as_int(ctx, row), ScalarFuncSig::CastDecimalAsInt => f.cast_decimal_as_int(ctx, row), ScalarFuncSig::CastStringAsInt => f.cast_str_as_int(ctx, row), ScalarFuncSig::CastTimeAsInt => f.cast_time_as_int(ctx, row), ScalarFuncSig::CastDurationAsInt => f.cast_duration_as_int(ctx, row), ScalarFuncSig::CastJsonAsInt => f.cast_json_as_int(ctx, row), ScalarFuncSig::PlusInt => f.plus_int(ctx, row), ScalarFuncSig::MinusInt => f.minus_int(ctx, row), ScalarFuncSig::MultiplyInt => f.multiply_int(ctx, row), ScalarFuncSig::LogicalAnd => f.logical_and(ctx, row), ScalarFuncSig::LogicalOr => f.logical_or(ctx, row), ScalarFuncSig::LogicalXor => f.logical_xor(ctx, row), ScalarFuncSig::UnaryNot => f.unary_not(ctx, row), ScalarFuncSig::UnaryMinusInt => f.unary_minus_int(ctx, row), ScalarFuncSig::IntIsNull => f.int_is_null(ctx, row), ScalarFuncSig::IntIsFalse => f.int_is_false(ctx, row), ScalarFuncSig::RealIsTrue => f.real_is_true(ctx, row), ScalarFuncSig::RealIsNull => f.real_is_null(ctx, row), ScalarFuncSig::DecimalIsNull => f.decimal_is_null(ctx, row), ScalarFuncSig::DecimalIsTrue => f.decimal_is_true(ctx, row), ScalarFuncSig::StringIsNull => f.string_is_null(ctx, row), ScalarFuncSig::TimeIsNull => f.time_is_null(ctx, row), ScalarFuncSig::DurationIsNull => f.duration_is_null(ctx, row), ScalarFuncSig::IfNullInt => f.if_null_int(ctx, row), ScalarFuncSig::IfInt => f.if_int(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_real(&self, ctx: &StatementContext, row: &[Datum]) -> Result<Option<f64>> { match *self { Expression::Constant(ref constant) => constant.eval_real(), Expression::ColumnRef(ref column) => column.eval_real(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsReal => f.cast_int_as_real(ctx, row), ScalarFuncSig::CastRealAsReal => f.cast_real_as_real(ctx, row), ScalarFuncSig::CastDecimalAsReal => f.cast_decimal_as_real(ctx, row), ScalarFuncSig::CastStringAsReal => f.cast_str_as_real(ctx, row), ScalarFuncSig::CastTimeAsReal => f.cast_time_as_real(ctx, row), ScalarFuncSig::CastDurationAsReal => f.cast_duration_as_real(ctx, row), ScalarFuncSig::CastJsonAsReal => f.cast_json_as_real(ctx, row), ScalarFuncSig::UnaryMinusReal => f.unary_minus_real(ctx, row), ScalarFuncSig::PlusReal => f.plus_real(ctx, row), ScalarFuncSig::MinusReal => f.minus_real(ctx, row), ScalarFuncSig::MultiplyReal => f.multiply_real(ctx, row), ScalarFuncSig::IfNullReal => f.if_null_real(ctx, row), ScalarFuncSig::IfReal => f.if_real(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_decimal<'a, 'b: 'a>( &'b self, ctx: &StatementContext, row: &'a [Datum], ) -> Result<Option<Cow<'a, Decimal>>> { match *self { Expression::Constant(ref constant) => constant.eval_decimal(), Expression::ColumnRef(ref column) => column.eval_decimal(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsDecimal => f.cast_int_as_decimal(ctx, row), ScalarFuncSig::CastRealAsDecimal => f.cast_real_as_decimal(ctx, row), ScalarFuncSig::CastDecimalAsDecimal => f.cast_decimal_as_decimal(ctx, row), ScalarFuncSig::CastStringAsDecimal => f.cast_str_as_decimal(ctx, row), ScalarFuncSig::CastTimeAsDecimal => f.cast_time_as_decimal(ctx, row), ScalarFuncSig::CastDurationAsDecimal => f.cast_duration_as_decimal(ctx, row), ScalarFuncSig::CastJsonAsDecimal => f.cast_json_as_decimal(ctx, row), ScalarFuncSig::UnaryMinusDecimal => f.unary_minus_decimal(ctx, row), ScalarFuncSig::PlusDecimal => f.plus_decimal(ctx, row), ScalarFuncSig::MinusDecimal => f.minus_decimal(ctx, row), ScalarFuncSig::MultiplyDecimal => f.multiply_decimal(ctx, row), ScalarFuncSig::IfNullDecimal => f.if_null_decimal(ctx, row), ScalarFuncSig::IfDecimal => f.if_decimal(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_string<'a, 'b: 'a>( &'b self, ctx: &StatementContext, row: &'a [Datum], ) -> Result<Option<Cow<'a, Vec<u8>>>> { match *self { Expression::Constant(ref constant) => constant.eval_string(), Expression::ColumnRef(ref column) => column.eval_string(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsString => f.cast_int_as_str(ctx, row), ScalarFuncSig::CastRealAsString => f.cast_real_as_str(ctx, row), ScalarFuncSig::CastDecimalAsString => f.cast_decimal_as_str(ctx, row), ScalarFuncSig::CastStringAsString => f.cast_str_as_str(ctx, row), ScalarFuncSig::CastTimeAsString => f.cast_time_as_str(ctx, row), ScalarFuncSig::CastDurationAsString => f.cast_duration_as_str(ctx, row), ScalarFuncSig::CastJsonAsString => f.cast_json_as_str(ctx, row), ScalarFuncSig::IfNullString => f.if_null_string(ctx, row), ScalarFuncSig::IfString => f.if_string(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_time<'a, 'b: 'a>( &'b self, ctx: &StatementContext, row: &'a [Datum], ) -> Result<Option<Cow<'a, Time>>> { match *self { Expression::Constant(ref constant) => constant.eval_time(), Expression::ColumnRef(ref column) => column.eval_time(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsTime => f.cast_int_as_time(ctx, row), ScalarFuncSig::CastRealAsTime => f.cast_real_as_time(ctx, row), ScalarFuncSig::CastDecimalAsTime => f.cast_decimal_as_time(ctx, row), ScalarFuncSig::CastStringAsTime => f.cast_str_as_time(ctx, row), ScalarFuncSig::CastTimeAsTime => f.cast_time_as_time(ctx, row), ScalarFuncSig::CastDurationAsTime => f.cast_duration_as_time(ctx, row), ScalarFuncSig::CastJsonAsTime => f.cast_json_as_time(ctx, row), ScalarFuncSig::IfNullTime => f.if_null_time(ctx, row), ScalarFuncSig::IfTime => f.if_time(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_duration<'a, 'b: 'a>( &'b self, ctx: &StatementContext, row: &'a [Datum], ) -> Result<Option<Cow<'a, Duration>>> { match *self { Expression::Constant(ref constant) => constant.eval_duration(), Expression::ColumnRef(ref column) => column.eval_duration(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsDuration => f.cast_int_as_duration(ctx, row), ScalarFuncSig::CastRealAsDuration => f.cast_real_as_duration(ctx, row), ScalarFuncSig::CastDecimalAsDuration => f.cast_decimal_as_duration(ctx, row), ScalarFuncSig::CastStringAsDuration => f.cast_str_as_duration(ctx, row), ScalarFuncSig::CastTimeAsDuration => f.cast_time_as_duration(ctx, row), ScalarFuncSig::CastDurationAsDuration => f.cast_duration_as_duration(ctx, row), ScalarFuncSig::CastJsonAsDuration => f.cast_json_as_duration(ctx, row), ScalarFuncSig::IfNullDuration => f.if_null_duration(ctx, row), ScalarFuncSig::IfDuration => f.if_duration(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } fn eval_json<'a, 'b: 'a>( &'b self, ctx: &StatementContext, row: &'a [Datum], ) -> Result<Option<Cow<'a, Json>>> { match *self { Expression::Constant(ref constant) => constant.eval_json(), Expression::ColumnRef(ref column) => column.eval_json(row), Expression::ScalarFn(ref f) => match f.sig { ScalarFuncSig::CastIntAsJson => f.cast_int_as_json(ctx, row), ScalarFuncSig::CastRealAsJson => f.cast_real_as_json(ctx, row), ScalarFuncSig::CastDecimalAsJson => f.cast_decimal_as_json(ctx, row), ScalarFuncSig::CastStringAsJson => f.cast_str_as_json(ctx, row), ScalarFuncSig::CastTimeAsJson => f.cast_time_as_json(ctx, row), ScalarFuncSig::CastDurationAsJson => f.cast_duration_as_json(ctx, row), ScalarFuncSig::CastJsonAsJson => f.cast_json_as_json(ctx, row), _ => Err(box_err!("Unknown signature: {:?}", f.sig)), }, } } /// IsHybridType checks whether a ClassString expression is a hybrid type value which will /// return different types of value in different context. /// For ENUM/SET which is consist of a string attribute `Name` and an int attribute `Value`, /// it will cause an error if we convert ENUM/SET to int as a string value. /// For Bit/Hex, we will get a wrong result if we convert it to int as a string value. /// For example, when convert `0b101` to int, the result should be 5, but we will get /// 101 if we regard it as a string. fn is_hybrid_type(&self) -> bool { match self.get_tp().get_tp() as u8 { types::ENUM | types::BIT | types::SET => { return true; } _ => {} } // TODO:For a constant, the field type will be inferred as `VARCHAR` // when the kind of it is `HEX` or `BIT`. false } } impl Expression { fn build(mut expr: Expr, row_len: usize, ctx: &StatementContext) -> Result<Self> { let tp = expr.take_field_type(); match expr.get_tp() { ExprType::Null => Ok(Expression::new_const(Datum::Null, tp)), ExprType::Int64 => expr.get_val() .decode_i64() .map(Datum::I64) .map(|e| Expression::new_const(e, tp)) .map_err(Error::from), ExprType::Uint64 => expr.get_val() .decode_u64() .map(Datum::U64) .map(|e| Expression::new_const(e, tp)) .map_err(Error::from), ExprType::String | ExprType::Bytes => { Ok(Expression::new_const(Datum::Bytes(expr.take_val()), tp)) } ExprType::Float32 | ExprType::Float64 => expr.get_val() .decode_f64() .map(Datum::F64) .map(|e| Expression::new_const(e, tp)) .map_err(Error::from), ExprType::MysqlTime => expr.get_val() .decode_u64() .and_then(|i| { let fsp = expr.get_field_type().get_decimal() as i8; let tp = expr.get_field_type().get_tp() as u8; Time::from_packed_u64(i, tp, fsp, &ctx.tz) }) .map(|t| Expression::new_const(Datum::Time(t), tp)) .map_err(Error::from), ExprType::MysqlDuration => expr.get_val() .decode_i64() .and_then(|n| Duration::from_nanos(n, MAX_FSP)) .map(Datum::Dur) .map(|e| Expression::new_const(e, tp)) .map_err(Error::from), ExprType::MysqlDecimal => expr.get_val() .decode_decimal() .map(Datum::Dec) .map(|e| Expression::new_const(e, tp)) .map_err(Error::from), ExprType::ScalarFunc => { try!(FnCall::check_args( expr.get_sig(), expr.get_children().len() )); expr.take_children() .into_iter() .map(|child| Expression::build(child, row_len, ctx)) .collect::<Result<Vec<_>>>() .map(|children| { Expression::ScalarFn(FnCall { sig: expr.get_sig(), children: children, tp: tp, }) }) } ExprType::ColumnRef => { let offset = try!(expr.get_val().decode_i64().map_err(Error::from)) as usize; try!(Column::check_offset(offset, row_len)); let column = Column { offset: offset, tp: tp, }; Ok(Expression::ColumnRef(column)) } unhandled => unreachable!("can't handle {:?} expr in DAG mode", unhandled), } } } #[cfg(test)] mod test { use coprocessor::codec::Datum; use coprocessor::codec::mysql::{Time, MAX_FSP}; use coprocessor::select::xeval::evaluator::test::{col_expr, datum_expr}; use tipb::expression::{Expr, ExprType, FieldType, ScalarFuncSig}; use super::{Expression, StatementContext}; #[inline] pub fn str2dec(s: &str) -> Datum { Datum::Dec(s.parse().unwrap()) } pub fn fncall_expr(sig: ScalarFuncSig, children: &[Expr]) -> Expr { let mut expr = Expr::new(); expr.set_tp(ExprType::ScalarFunc); expr.set_sig(sig); expr.set_field_type(FieldType::new()); for child in children { expr.mut_children().push(child.clone()); } expr } #[test] fn test_expression_build() { let colref = col_expr(1); let const_null = datum_expr(Datum::Null); let const_time = datum_expr(Datum::Time( Time::parse_utc_datetime("1970-01-01 12:00:00", MAX_FSP).unwrap(), )); let tests = vec![ (colref.clone(), 1, false), (colref.clone(), 2, true), (const_null.clone(), 0, true), (const_time.clone(), 0, true), ( fncall_expr(ScalarFuncSig::LTInt, &[colref.clone(), const_null.clone()]), 2, true, ), ( fncall_expr(ScalarFuncSig::LTInt, &[colref.clone()]), 0, false, ), ]; let ctx = StatementContext::default(); for tt in tests { let expr = Expression::build(tt.0, tt.1, &ctx); assert_eq!(expr.is_ok(), tt.2); } } }
error_chain! { types { Error, ErrorKind, ResultExt, Result; } foreign_links { CString(::std::ffi::NulError); CStr(::std::ffi::FromBytesWithNulError); } errors { Hidapi(t: ::hidapi::HidError) { description("hidapi error") display("hidapi error: '{}'", t) } NotSuccessful { description("not successful") display("not successful") } NotSupported { description("not supported") display("not supported") } InvalidColorFormat { description("invalid color format") display("invalid color format") } } } impl From<::hidapi::HidError> for Error { fn from(hid_error: ::hidapi::HidError) -> Error { Error::from_kind(ErrorKind::Hidapi(hid_error)) } }
// Copyright (c) 2018 Alexander Fรฆrรธy. 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::fmt; use expression::{Evaluate, Generator}; pub struct EllipticCurve { a: f64, b: f64, } impl EllipticCurve { pub fn new(a: f64, b: f64) -> EllipticCurve { EllipticCurve { a, b } } pub fn generate(generator: &mut Generator) -> Box<dyn Evaluate> { let a = generator.next_f64(); let b = generator.next_f64(); Box::new(EllipticCurve::new(a, b)) } } impl Evaluate for EllipticCurve { fn evaluate(&self, x: f64, y: f64) -> f64 { x.powf(3.0) + self.a * x + self.b - y.powf(2.0) } } impl fmt::Display for EllipticCurve { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "EllipticCurve(x^3 + {} * x + {} - y^2)", self.a, self.b) } }
use std::io; use std::io::Read; use std::ptr; use rand::Rng; pub const FONTSET: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80, // F ]; pub struct CPU { opcode: u16, // current opcode registers: [u8; 16], // 8 bit registers i: u16, // address register sound_timer: u8, delay_timer: u8, stack: [u16; 16], sp: u16, // stack pointer pub memory: Vec<u8>, pc: u16, // program counter pub gfx: [u8; 64 * 32], pub draw_flag: bool, pub keyboard: [bool; 16], rng: rand::prelude::ThreadRng, } impl CPU { pub fn init() -> Self { let mut mem: Vec<u8> = vec![0; 4096]; // yes unsafe { ptr::copy_nonoverlapping(FONTSET.as_ptr(), mem.as_mut_ptr(), FONTSET.len()) }; CPU { opcode: 0, registers: [0; 16], i: 0x200, sound_timer: 0, delay_timer: 0, stack: [0; 16], sp: 0, memory: mem, pc: 0x200, gfx: [0; 64 * 32], draw_flag: false, keyboard: [false; 16], rng: rand::thread_rng(), } } #[inline] pub fn load_rom<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> { reader.read(&mut self.memory[0x200..]) } // separated those to make testing easier #[inline(always)] pub fn cycle(&mut self) { self.fetch(); self.decode(); } #[inline(always)] fn fetch(&mut self) { self.opcode = ((self.memory[self.pc as usize] as u16) << 8) | self.memory[(self.pc + 1) as usize] as u16; // eprintln!("Fetched instruction: {:#x}", self.opcode); } pub fn decode(&mut self) { match self.opcode & 0xF000 { 0x0000 => match self.opcode & 0x00FF { 0x00E0 => { self.gfx.iter_mut().for_each(|x| *x = 0); self.draw_flag = true; self.pc += 2; } //return from subroutine 0x00EE => { self.sp -= 1; self.pc = self.stack[self.sp as usize]; self.pc += 2; } _ => panic!("Unknown instruction {:#x}", self.opcode), }, // goto 0x1000 => { self.pc = self.opcode & 0x0FFF; } //call subroutine 0x2000 => { self.stack[self.sp as usize] = self.pc; self.sp += 1; self.pc = self.opcode & 0x0FFF; } // skip if true 0x3000 => { if self.registers[((self.opcode & 0x0F00) >> 8) as usize] == (self.opcode & 0x00FF) as u8 { self.pc += 4; } else { self.pc += 2; } } // skip if false 0x4000 => { if self.registers[((self.opcode & 0x0F00) >> 8) as usize] != (self.opcode & 0x00FF) as u8 { self.pc += 4; } else { self.pc += 2; } } // skip if true, comparing registers 0x5000 => { if self.registers[((self.opcode & 0x0F00) >> 8) as usize] == self.registers[((self.opcode & 0x00F0) >> 4) as usize] { self.pc += 4; } else { self.pc += 2; } } // sets the value of a register 0x6000 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] = (self.opcode & 0x00FF) as u8; self.pc += 2; } // adds value to a register 0x7000 => { let reg = ((self.opcode & 0x0F00) >> 8) as usize; let res = self.registers[reg].wrapping_add((self.opcode & 0x00FF) as u8); self.registers[reg] = res; self.pc += 2; } 0x8000 => { match self.opcode & 0x000F { // assign values from registers 0x0000 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] = self.registers[((self.opcode & 0x00F0) >> 4) as usize]; self.pc += 2; } // bitwise OR 0x0001 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] |= self.registers[((self.opcode & 0x00F0) >> 4) as usize]; self.pc += 2; } // bitwise AND 0x0002 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] &= self.registers[((self.opcode & 0x00F0) >> 4) as usize]; self.pc += 2; } // bitwise XOR 0x0003 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] ^= self.registers[((self.opcode & 0x00F0) >> 4) as usize]; self.pc += 2; } // plus equal 0x0004 => { let regx = ((self.opcode & 0x0F00) >> 8) as usize; let regy = ((self.opcode & 0x00F0) >> 4) as usize; let (res, overflow) = self.registers[regx].overflowing_add(self.registers[regy]); self.registers[regx] = res; self.registers[0xF] = if !overflow { 0 } else { 1 }; self.pc += 2; } // minus equal 0x0005 => { let regx = ((self.opcode & 0x0F00) >> 8) as usize; let regy = ((self.opcode & 0x00F0) >> 4) as usize; let (res, overflow) = self.registers[regx].overflowing_sub(self.registers[regy]); self.registers[regx] = res; self.registers[0xF] = if !overflow { 1 } else { 0 }; self.pc += 2; } // right shift 0x0006 => { self.registers[0xF] = self.registers[((self.opcode & 0x0F00) >> 8) as usize] & 0x1; self.registers[((self.opcode & 0x0F00) >> 8) as usize] >>= 1; self.pc += 2; } // minus assign, but the terms are reversed 0x0007 => { let regx = ((self.opcode & 0x0F00) >> 8) as usize; let regy = ((self.opcode & 0x00F0) >> 4) as usize; let (res, overflow) = self.registers[regy].overflowing_sub(self.registers[regx]); self.registers[regx] = res; self.registers[0xF] = if !overflow { 1 } else { 0 }; self.pc += 2; } // left shift 0x000E => { self.registers[0xF] = self.registers[((self.opcode & 0x0F00) >> 8) as usize] >> 7; self.registers[((self.opcode & 0x0F00) >> 8) as usize] <<= 1; self.pc += 2; } _ => panic!("Unknown instruction {:#x}", self.opcode), } } // skip if true, registers 0x9000 => { if self.registers[((self.opcode & 0x0F00) >> 8) as usize] != self.registers[((self.opcode & 0x00F0) >> 4) as usize] { self.pc += 4; } else { self.pc += 2; } } // store value on the address pointer 0xA000 => { self.i = self.opcode & 0x0FFF; self.pc += 2; } // jump to 0xB000 => { self.pc = self.registers[0] as u16 + (self.opcode & 0x0FFF); } // rand 0xC000 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] = self.rng.gen::<u8>() & (self.opcode & 0x00FF) as u8; self.pc += 2; } // draw // the ugliest instruction here // TODO refactor this 0xD000 => { let x = self.registers[((self.opcode & 0x0F00) >> 8) as usize] as usize; let y = self.registers[((self.opcode & 0x00F0) >> 4) as usize] as usize; let height = (self.opcode & 0x000F) as usize; let mut pixel; self.registers[0xF] = 0; for yline in 0..height { pixel = self.memory[(self.i as usize + yline)]; for xline in 0..8 { if (pixel & (0x80 >> xline)) != 0 { // if the pixel go out of the screen let gfx_index = 2047_usize.min(x + xline + ((y + yline) * 64)); if self.gfx[gfx_index] == 1 { self.registers[0xF] = 1; } self.gfx[gfx_index] ^= 1; } } } self.draw_flag = true; self.pc += 2; } // keyboard 0xE000 => match self.opcode & 0x000F { 0x000E => { let index = self.registers[((self.opcode & 0x0F00) >> 8) as usize] as usize; if self.keyboard[index] { self.pc += 4; } else { self.pc += 2; } } 0x0001 => { let index = self.registers[((self.opcode & 0x0F00) >> 8) as usize] as usize; if !self.keyboard[index] { self.pc += 4; } else { self.pc += 2; } } _ => panic!("Unknown instruction: {:#x}", self.opcode), }, 0xF000 => { match self.opcode & 0x00FF { // store the delay in a register 0x0007 => { self.registers[((self.opcode & 0x0F00) >> 8) as usize] = self.delay_timer; self.pc += 2; } // get key 0x000A => { let mut pressed = false; for (i, key) in self.keyboard.iter().enumerate() { if *key { self.registers[((self.opcode & 0x0F00) >> 8) as usize] = i as u8; pressed = true; } } if !pressed { return; } self.pc += 2; } // set delay timer 0x0015 => { self.delay_timer = self.registers[((self.opcode & 0x0F00) >> 8) as usize]; self.pc += 2; } // set sound timer 0x0018 => { self.sound_timer = self.registers[((self.opcode & 0x0F00) >> 8) as usize]; self.pc += 2; } // add assign to address register 0x001E => { let res = self.i.wrapping_add( self.registers[((self.opcode & 0x0F00) >> 8) as usize] as u16, ); self.registers[0xF] = if res > 0xFFF { 1 } else { 0 }; self.i = res; self.pc += 2; } // store the sprite address in the adress register 0x0029 => { self.i = self.registers[((self.opcode & 0x0F00) >> 8) as usize] as u16 * 0x5; self.pc += 2; } // store the binary coded decimal somewhere in memory 0x0033 => { let reg_val = self.registers[((self.opcode & 0x0F00) >> 8) as usize]; let address = self.i as usize; self.memory[address] = reg_val / 100; self.memory[address + 1] = (reg_val / 10) % 10; self.memory[address + 2] = reg_val % 10; self.pc += 2; } // store data from registers 0 to register X into some memory area 0x0055 => { let reg_x = ((self.opcode & 0x0F00) >> 8) as usize; let index = self.i as usize; // just a small guarantee assert!(reg_x <= 0xF); // yes, again unsafe { ptr::copy_nonoverlapping( self.registers.as_ptr(), self.memory[index..].as_mut_ptr(), reg_x, ) }; self.i += (reg_x + 1) as u16; self.pc += 2; } // copy a region of memory into the registers 0x0065 => { let reg_x = ((self.opcode & 0x0F00) >> 8) as usize; let index = self.i as usize; // just a small guarantee assert!(reg_x <= 0xF); // YES unsafe { ptr::copy_nonoverlapping( self.memory[index..].as_ptr(), self.registers.as_mut_ptr(), reg_x, ) }; self.i += (reg_x + 1) as u16; self.pc += 2; } _ => panic!("Unknown instruction: {:#x}", self.opcode), } } _ => panic!("Unknown instruction: {:#x}", self.opcode), } if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { self.sound_timer -= 1; } } }
use actix_web::{middleware, web, App, HttpServer}; use form_data::{Field, FilenameGenerator, Form}; use log::info; use pahkat_common::{database::Database, db_path}; use std::path::{Path, PathBuf}; use crate::config::TomlConfig; use crate::handlers::{ download_package, package_stats, packages_index, packages_index_stable, packages_package_index, packages_package_index_stable, repo_index, repo_stats, upload::upload_package, virtuals_index, virtuals_index_stable, virtuals_package_index, virtuals_package_index_stable, }; struct UploadFilenameGenerator { directory: PathBuf, } impl FilenameGenerator for UploadFilenameGenerator { fn next_filename(&self, _: &mime::Mime) -> Option<PathBuf> { let random_fn = format!("{}.tmp", uuid::Uuid::new_v4().to_simple()); Some(self.directory.join(random_fn)) } } #[derive(Clone)] pub struct ServerState { pub path: PathBuf, pub bind: String, pub port: String, pub config: TomlConfig, pub database: Database, pub upload_form: Form, } fn config_db_path(config: &TomlConfig) -> String { config .db_path .clone() .unwrap_or(db_path().as_path().to_str().unwrap().to_string()) } embed_migrations!("../pahkat-common/migrations"); pub fn run_server(config: TomlConfig, path: &Path, bind: &str, port: &str) { let system = actix::System::new("pรกhkat-server"); let database = match Database::new(&config_db_path(&config)) { Ok(database) => database, Err(e) => { panic!("Failed to create database: {}", e); } }; info!("Running migrations"); embedded_migrations::run(&database.get_connection().expect("connection to succeed")) .expect("migrations to run"); let upload_tmp_path = path.join("upload-tmp"); std::fs::create_dir_all(&upload_tmp_path).expect(&format!( "could not create upload temp directory {}", upload_tmp_path.as_path().display() )); std::fs::create_dir_all(&config.artifacts_dir).expect(&format!( "could not create artifacts directory {}", &config.artifacts_dir.as_path().display() )); // TODO(bbqsrc): Delete everything inside temp dir to ensure clean state // TODO(bbqsrc): Check the user access for the temp dir for security let form = Form::new().field("params", Field::text()).field( "payload", Field::file(UploadFilenameGenerator { directory: upload_tmp_path, }), ); let state = ServerState { path: path.to_path_buf(), bind: bind.to_string(), port: port.to_string(), config, database, upload_form: form, }; HttpServer::new(move || { App::new() .data(state.clone()) .wrap(middleware::Logger::default()) .service(web::resource("/index.json").route(web::get().to(repo_index))) .service(web::resource("/repo/stats").route(web::get().to(repo_stats))) .service( web::scope("/packages") .service( web::resource("/index.json").route(web::get().to(packages_index_stable)), ) .service( web::resource("/index.{channel}.json").route(web::get().to(packages_index)), ) .service( web::resource("/{packageId}/index.json") .route(web::get().to(packages_package_index_stable)), ) .service( web::resource("/{packageId}/index.{channel}.json") .route(web::get().to(packages_package_index)), ) .service(web::resource("/{packageId}").route(web::patch().to(upload_package))) // TODO: add channel to download/stats endpoints .service( web::resource("/{packageId}/download") .route(web::get().to(download_package)), ) .service( web::resource("/{packageId}/stats").route(web::get().to(package_stats)), ), ) .service( web::scope("/virtuals") .service( web::resource("/index.json").route(web::get().to(virtuals_index_stable)), ) .service( web::resource("/index.{channel}.json").route(web::get().to(virtuals_index)), ) .service( web::resource("/{packageId}/index.json") .route(web::get().to(virtuals_package_index_stable)), ) .service( web::resource("/{packageId}/index.{channel}.json") .route(web::get().to(virtuals_package_index)), ), ) }) .bind(&format!("{}:{}", bind, port)) .expect(&format!("Can not bind to {}:{}", bind, port)) .start(); let _ = system.run(); }
use std::io::prelude::*; use std::fs::File; use std::error::Error; use std::io::BufReader; use std::cmp; fn main() { let reader = read_file("input.txt"); let result = parse(reader); println!("{}", result) } fn parse(reader: BufReader<File>) -> i32 { let mut total = 0; for line in reader.lines() { let line = line.unwrap(); if line.len() > 1 { total += calculate(line); } } total } fn calculate(line: String) -> i32 { let s: Vec<&str> = line.split('x').collect(); let l = s[0].parse::<i32>().unwrap(); let w = s[1].parse::<i32>().unwrap(); let h = s[2].parse::<i32>().unwrap(); let sidea = l * w; let sideb = w * h; let sidec = h * l; let mut needed = cmp::min(sidea, sideb); needed = cmp::min(needed, sidec); needed + (2 * sidea) + (2 * sideb) + (2 * sidec) } fn read_file(filename: &str) -> BufReader<File> { // Open file let file = match File::open(filename) { // The `description` method of `io::Error` returns a string that // describes the error Err(why) => panic!("couldn't open {}: {}", filename, Error::description(&why)), Ok(file) => file, }; let reader = BufReader::new(file); reader }
//! If+Else pairing ambiguous grammar. use gll_pg_core::*; use gll_pg_macros::gll; use logos::Logos; #[derive(Logos, Debug, Eq, PartialEq, Clone)] pub enum Token { End, #[error] Error, #[token(" ")] _Eps, #[token("if")] If, #[token("else")] Else, } #[derive(Default)] struct Parser {} #[derive(Clone, Debug, Eq, PartialEq)] enum S { Eps, If(Box<S>), IfElse(Box<S>, Box<S>), } #[gll(S, Token)] impl Parser { #[rule(S ->)] fn s1() -> S { S::Eps } #[rule(S -> If S Else S)] fn s2(_: &LogosToken<Token>, s1: &S, _: &LogosToken<Token>, s2: &S) -> S { S::IfElse(Box::new(s1.clone()), Box::new(s2.clone())) } #[rule(S -> If S)] fn s3(_: &LogosToken<Token>, s1: &S) -> S { S::If(Box::new(s1.clone())) } } check_output! {eps, "", [S::Eps]} check_output! {one, "if else", [S::IfElse(Box::new(S::Eps), Box::new(S::Eps))]} check_output! {two, "if if else", [S::If(Box::new(S::IfElse(Box::new(S::Eps), Box::new(S::Eps)))), S::IfElse(Box::new(S::If(Box::new(S::Eps))), Box::new(S::Eps))]}
/// Determine whether a sentence is a pangram. pub fn is_pangram(sentence: &str) -> bool { (b'a'..b'z').all(|c| sentence.to_lowercase().contains(c as char)) }
use std::{ fs::File, io, io::{ErrorKind, Read}, }; fn main() { let username = read_username_from_file_with_shortcut() .expect("Nรฃo consegui ler o nome do usuรกrio pelo arquivo"); println!("Nome do usuรกrio รฉ {:?}", username); } fn read_username_from_file_with_shortcut() -> Result<String, io::Error> { let mut s = String::new(); File::open("hello.txt")?.read_to_string(&mut s)?; Ok(s) } fn _read_username_from_file() -> Result<String, io::Error> { let f = File::open("hello.txt"); let mut f = match f { Ok(file) => file, Err(e) => return Err(e), }; let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } fn _with_expect() { let _f = File::open("hello.txt").expect("Nรฃo consegui abrir o arquivo"); } fn _with_unwrap() { let _f = File::open("hello.txt").unwrap(); } fn _with_unwrap_or_else() { let _f = File::open("hello.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } }); } fn _with_math() { let f = File::open("hello.txt"); let _f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(e) => panic!("Problema creating the file: {:?}", e), }, other_error => { panic!("Problem opening the file: {:?}", other_error); } }, }; }
use crate::*; pub(crate) struct KeyboardState { scankeys: [bool; 300], vkeys: [bool; 300], } impl KeyboardState { pub fn modifiers(&self) -> KeyboardModifiers { KeyboardModifiers { shift: self.vkeys[VirtualKey::LeftShift as usize] || self.vkeys[VirtualKey::RightShift as usize], ctrl: self.vkeys[VirtualKey::LeftControl as usize], alt: self.vkeys[VirtualKey::LeftAlt as usize] || self.vkeys[VirtualKey::RightAlt as usize], } } pub fn key_down(&mut self, scancode: Scancode, vkey: Option<VirtualKey>) { self.scankeys[scancode as usize] = true; if let Some(vkey) = vkey { self.vkeys[vkey as usize] = true; } } pub fn key_up(&mut self, scancode: Scancode, vkey: Option<VirtualKey>) { self.scankeys[scancode as usize] = false; if let Some(vkey) = vkey { self.vkeys[vkey as usize] = false; } } pub fn is_key_down(&self, scancode: Scancode) -> bool { self.scankeys[scancode as usize] } pub fn is_vkey_down(&self, vkey: VirtualKey) -> bool { self.vkeys[vkey as usize] } } impl Default for KeyboardState { fn default() -> Self { KeyboardState { scankeys: [false; 300], vkeys: [false; 300], } } } /// A snapshot of which keyboard modifiers are currently pressed. /// /// Mostly used to provide context for [`InputEvent`] keyboard events. #[derive(Clone, Debug, Eq, PartialEq)] pub struct KeyboardModifiers { pub shift: bool, pub ctrl: bool, pub alt: bool, }
mod errors; mod msg_type; mod notification; mod subscription_confirmation; pub use self::subscription_confirmation::SubscriptionConfirmation;
pub mod abortable; use std::future::Future; pub async fn retry<F, O, E>( fetch: impl Fn() -> F, retry: impl Fn(&E) -> bool, report: impl Fn(usize, E) -> E, limit: Option<usize> ) -> F::Output where F: Future<Output = Result<O, E>>, E: std::error::Error, { let mut attempt: usize = 1; loop { let result = fetch().await; match result { Err(error) if retry(&error) => { let error = report(attempt, error); attempt += 1; let exceeded = limit .map(|l| attempt > l) .unwrap_or(false); if exceeded { return Err(error); } }, other => return other, } }; }
// Copyright 2019 The xi-editor Authors. // // 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. //! GTK implementation of features at the application scope. use crate::clipboard::ClipboardItem; pub struct Application; impl Application { pub fn quit() { // Nothing to do: if this is called, we're already shutting down and GTK will pick it up (I hope?) } pub fn get_clipboard_contents() -> Option<ClipboardItem> { let display = gdk::Display::get_default().unwrap(); let clipboard = gtk::Clipboard::get_default(&display).unwrap(); if let Some(gstring) = clipboard.wait_for_text() { Some(ClipboardItem::Text(gstring.to_string())) } else { None } } }
#[doc = "Register `APB2LPENR` reader"] pub type R = crate::R<APB2LPENR_SPEC>; #[doc = "Register `APB2LPENR` writer"] pub type W = crate::W<APB2LPENR_SPEC>; #[doc = "Field `TIM1LPEN` reader - TIM1 clock enable during sleep mode Set and reset by software."] pub type TIM1LPEN_R = crate::BitReader; #[doc = "Field `TIM1LPEN` writer - TIM1 clock enable during sleep mode Set and reset by software."] pub type TIM1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI1LPEN` reader - SPI1 clock enable during sleep mode Set and reset by software."] pub type SPI1LPEN_R = crate::BitReader; #[doc = "Field `SPI1LPEN` writer - SPI1 clock enable during sleep mode Set and reset by software."] pub type SPI1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM8LPEN` reader - TIM8 clock enable during sleep mode Set and reset by software."] pub type TIM8LPEN_R = crate::BitReader; #[doc = "Field `TIM8LPEN` writer - TIM8 clock enable during sleep mode Set and reset by software."] pub type TIM8LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USART1LPEN` reader - USART1 clock enable during sleep mode Set and reset by software."] pub type USART1LPEN_R = crate::BitReader; #[doc = "Field `USART1LPEN` writer - USART1 clock enable during sleep mode Set and reset by software."] pub type USART1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM15LPEN` reader - TIM15 clock enable during sleep mode Set and reset by software."] pub type TIM15LPEN_R = crate::BitReader; #[doc = "Field `TIM15LPEN` writer - TIM15 clock enable during sleep mode Set and reset by software."] pub type TIM15LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM16LPEN` reader - TIM16 clock enable during sleep mode Set and reset by software."] pub type TIM16LPEN_R = crate::BitReader; #[doc = "Field `TIM16LPEN` writer - TIM16 clock enable during sleep mode Set and reset by software."] pub type TIM16LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TIM17LPEN` reader - TIM17 clock enable during sleep mode Set and reset by software."] pub type TIM17LPEN_R = crate::BitReader; #[doc = "Field `TIM17LPEN` writer - TIM17 clock enable during sleep mode Set and reset by software."] pub type TIM17LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI4LPEN` reader - SPI4 clock enable during sleep mode Set and reset by software."] pub type SPI4LPEN_R = crate::BitReader; #[doc = "Field `SPI4LPEN` writer - SPI4 clock enable during sleep mode Set and reset by software."] pub type SPI4LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SPI6LPEN` reader - SPI6 clock enable during sleep mode Set and reset by software."] pub type SPI6LPEN_R = crate::BitReader; #[doc = "Field `SPI6LPEN` writer - SPI6 clock enable during sleep mode Set and reset by software."] pub type SPI6LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SAI1LPEN` reader - SAI1 clock enable during sleep mode Set and reset by software."] pub type SAI1LPEN_R = crate::BitReader; #[doc = "Field `SAI1LPEN` writer - SAI1 clock enable during sleep mode Set and reset by software."] pub type SAI1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SAI2LPEN` reader - SAI2 clock enable during sleep mode Set and reset by software."] pub type SAI2LPEN_R = crate::BitReader; #[doc = "Field `SAI2LPEN` writer - SAI2 clock enable during sleep mode Set and reset by software."] pub type SAI2LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `USBFSLPEN` reader - USBFS clock enable during sleep mode Set and reset by software."] pub type USBFSLPEN_R = crate::BitReader; #[doc = "Field `USBFSLPEN` writer - USBFS clock enable during sleep mode Set and reset by software."] pub type USBFSLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 11 - TIM1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn tim1lpen(&self) -> TIM1LPEN_R { TIM1LPEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - SPI1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn spi1lpen(&self) -> SPI1LPEN_R { SPI1LPEN_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - TIM8 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn tim8lpen(&self) -> TIM8LPEN_R { TIM8LPEN_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - USART1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn usart1lpen(&self) -> USART1LPEN_R { USART1LPEN_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 16 - TIM15 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn tim15lpen(&self) -> TIM15LPEN_R { TIM15LPEN_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - TIM16 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn tim16lpen(&self) -> TIM16LPEN_R { TIM16LPEN_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - TIM17 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn tim17lpen(&self) -> TIM17LPEN_R { TIM17LPEN_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - SPI4 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn spi4lpen(&self) -> SPI4LPEN_R { SPI4LPEN_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - SPI6 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn spi6lpen(&self) -> SPI6LPEN_R { SPI6LPEN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - SAI1 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn sai1lpen(&self) -> SAI1LPEN_R { SAI1LPEN_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - SAI2 clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn sai2lpen(&self) -> SAI2LPEN_R { SAI2LPEN_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 24 - USBFS clock enable during sleep mode Set and reset by software."] #[inline(always)] pub fn usbfslpen(&self) -> USBFSLPEN_R { USBFSLPEN_R::new(((self.bits >> 24) & 1) != 0) } } impl W { #[doc = "Bit 11 - TIM1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn tim1lpen(&mut self) -> TIM1LPEN_W<APB2LPENR_SPEC, 11> { TIM1LPEN_W::new(self) } #[doc = "Bit 12 - SPI1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn spi1lpen(&mut self) -> SPI1LPEN_W<APB2LPENR_SPEC, 12> { SPI1LPEN_W::new(self) } #[doc = "Bit 13 - TIM8 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn tim8lpen(&mut self) -> TIM8LPEN_W<APB2LPENR_SPEC, 13> { TIM8LPEN_W::new(self) } #[doc = "Bit 14 - USART1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn usart1lpen(&mut self) -> USART1LPEN_W<APB2LPENR_SPEC, 14> { USART1LPEN_W::new(self) } #[doc = "Bit 16 - TIM15 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn tim15lpen(&mut self) -> TIM15LPEN_W<APB2LPENR_SPEC, 16> { TIM15LPEN_W::new(self) } #[doc = "Bit 17 - TIM16 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn tim16lpen(&mut self) -> TIM16LPEN_W<APB2LPENR_SPEC, 17> { TIM16LPEN_W::new(self) } #[doc = "Bit 18 - TIM17 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn tim17lpen(&mut self) -> TIM17LPEN_W<APB2LPENR_SPEC, 18> { TIM17LPEN_W::new(self) } #[doc = "Bit 19 - SPI4 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn spi4lpen(&mut self) -> SPI4LPEN_W<APB2LPENR_SPEC, 19> { SPI4LPEN_W::new(self) } #[doc = "Bit 20 - SPI6 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn spi6lpen(&mut self) -> SPI6LPEN_W<APB2LPENR_SPEC, 20> { SPI6LPEN_W::new(self) } #[doc = "Bit 21 - SAI1 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn sai1lpen(&mut self) -> SAI1LPEN_W<APB2LPENR_SPEC, 21> { SAI1LPEN_W::new(self) } #[doc = "Bit 22 - SAI2 clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn sai2lpen(&mut self) -> SAI2LPEN_W<APB2LPENR_SPEC, 22> { SAI2LPEN_W::new(self) } #[doc = "Bit 24 - USBFS clock enable during sleep mode Set and reset by software."] #[inline(always)] #[must_use] pub fn usbfslpen(&mut self) -> USBFSLPEN_W<APB2LPENR_SPEC, 24> { USBFSLPEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "RCC APB2 sleep clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb2lpenr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb2lpenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB2LPENR_SPEC; impl crate::RegisterSpec for APB2LPENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb2lpenr::R`](R) reader structure"] impl crate::Readable for APB2LPENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb2lpenr::W`](W) writer structure"] impl crate::Writable for APB2LPENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB2LPENR to value 0x017f_7800"] impl crate::Resettable for APB2LPENR_SPEC { const RESET_VALUE: Self::Ux = 0x017f_7800; }
fn main(){ //const are not the same as immutable //consts are always mutable //cannot do shadow const FHD_WIDTH : u32 = 1920; const BAD_PI : f32 = 22.0/7.0; println!("Full HD width is {}, Bad PI is {}", FHD_WIDTH, BAD_PI); }
use aoc_utils::read_file; use day03::Claim; use day03::CLAIM_REGEX; fn overlapped(a: &((i32, i32), (i32, i32)), b: &((i32, i32), (i32, i32))) -> bool { let a_w = a.0; let a_h = a.1; let b_w = b.0; let b_h = b.1; let x_axis_diff = if a_w >= b_w { b_w.1 >= a_w.0 } else { a_w.1 >= b_w.0 }; let y_axis_diff = if a_h >= b_h { b_h.1 >= a_h.0 } else { a_h.1 >= b_h.0 }; x_axis_diff && y_axis_diff } fn main() { if let Ok(contents) = read_file("./input") { let claims: Vec<((i32, i32), (i32, i32))> = contents .lines() .filter_map(|line| { if let Some(caps) = CLAIM_REGEX.captures(line) { return Some(Claim::new( caps["n"].parse::<i32>().unwrap(), caps["x"].parse::<i32>().unwrap(), caps["y"].parse::<i32>().unwrap(), caps["width"].parse::<i32>().unwrap(), caps["height"].parse::<i32>().unwrap(), )); } None }) .map(|claim| { ( (claim.x, claim.x + claim.width - 1), (claim.y, claim.y + claim.height - 1), ) }) .collect(); for i in 0..claims.len() { if claims .clone() .iter() .filter(|&c| *c != claims[i]) .all(|c| !overlapped(&claims[i], c)) { println!("{:?}", i + 1); break; } } } }
use crate::wasm::il::{ exp::{Exp, ExpData, ExpList}, util::WasmType, }; pub fn print_exp(exp: &Exp) -> String { match &exp.data { ExpData::BinOp(oper, lhs, rhs) => format_args!( "({}.{} {} {})", exp.ty.to_string(), oper.to_string(&exp.ty), print_exp(lhs), print_exp(rhs) ) .to_string(), ExpData::CallExp(index, _label, args) => { format_args!("(call {} {})", index, print_explist(args)).to_string() } ExpData::CallIndirect(index, args, type_index) => format_args!( "(call_indirect (type {}) {} {})", type_index, print_explist(args), print_exp(index), ) .to_string(), ExpData::Const(const_data) => { format_args!("({}.const {})", exp.ty.to_string(), const_data.to_string()).to_string() } ExpData::Convert(convert_exp) => match exp.ty { WasmType::F32 => match convert_exp.ty { WasmType::F32 => print_exp(convert_exp), WasmType::F64 => { format_args!("(f32.demote_f64 {})", print_exp(convert_exp)).to_string() } WasmType::I32 => { format_args!("(f32.convert_i32_s {})", print_exp(convert_exp)).to_string() } WasmType::I64 => { format_args!("(f32.convert_i64_s {})", print_exp(convert_exp)).to_string() } WasmType::None => "".to_string(), }, WasmType::F64 => match convert_exp.ty { WasmType::F32 => { format_args!("(f64.promote_f32 {})", print_exp(convert_exp)).to_string() } WasmType::F64 => print_exp(convert_exp), WasmType::I32 => { format_args!("(f64.convert_i32_s {})", print_exp(convert_exp)).to_string() } WasmType::I64 => { format_args!("(f64.convert_i64_s {})", print_exp(convert_exp)).to_string() } WasmType::None => "".to_string(), }, WasmType::I32 => match convert_exp.ty { WasmType::F32 => { format_args!("(i32.trunc_f32_s {})", print_exp(convert_exp)).to_string() } WasmType::F64 => { format_args!("(i32.trunc_f64_s {})", print_exp(convert_exp)).to_string() } WasmType::I32 => print_exp(convert_exp), WasmType::I64 => { format_args!("(i32.wrap_i64 {})", print_exp(convert_exp)).to_string() } WasmType::None => "".to_string(), }, WasmType::I64 => match convert_exp.ty { WasmType::F32 => { format_args!("(i64.trunc_f32_s {})", print_exp(convert_exp)).to_string() } WasmType::F64 => { format_args!("(i64.trunc_f64_s {})", print_exp(convert_exp)).to_string() } WasmType::I32 => { format_args!("(i64.extend_i32_s {})", print_exp(convert_exp)).to_string() } WasmType::I64 => print_exp(convert_exp), WasmType::None => "".to_string(), }, WasmType::None => "".to_string(), }, ExpData::GetGlobal(index) => format_args!("(get_global {})", index).to_string(), ExpData::GetLocal(index) => format_args!("(local.get {})", index).to_string(), ExpData::IfExp(test_exp, then_exp, else_exp) => format_args!( "(if({}) {} (then {}) (else {}))", exp.ty.to_string(), print_exp(test_exp), print_exp(then_exp), print_exp(else_exp) ) .to_string(), ExpData::Load(addr) => { format_args!("({}.load {})", exp.ty.to_string(), print_exp(addr)).to_string() } ExpData::None => "".to_string(), ExpData::UnaryOp(oper, op_exp) => format_args!( "({}.{} {})", exp.ty.to_string(), oper.to_string(), print_exp(op_exp) ) .to_string(), } } pub fn print_explist(explist: &ExpList) -> String { let mut result: String = "".to_string(); for exp in explist { result += &print_exp(exp); } result }
use super::codec::{self, types::AdsCommand, AdsPacket, AmsTcpHeader}; use actix::prelude::*; use futures::oneshot; use futures::sync::{mpsc, oneshot}; use futures::Future; use rand::{self, Rng}; use std::collections::HashMap; use std::io; use tokio_io::io::WriteHalf; use tokio_tcp::TcpStream; use ws_ads::AdsToWsMultiplexer; pub enum WsMultiplexerRegister { Register(Addr<AdsToWsMultiplexer>), Unregister, } impl Message for WsMultiplexerRegister { type Result = Option<mpsc::Receiver<codec::AdsWriteReq>>; } impl Handler<WsMultiplexerRegister> for AdsClient { type Result = Option<mpsc::Receiver<codec::AdsWriteReq>>; fn handle(&mut self, msg: WsMultiplexerRegister, _: &mut Self::Context) -> Self::Result { match msg { WsMultiplexerRegister::Register(a) => { self.ws_ads = Some(a); let (tx, rx) = mpsc::channel(1); self.write_request_sender = Some(tx); Some(rx) } WsMultiplexerRegister::Unregister => { self.ws_ads = None; None } } } } pub struct AdsClient { framed: actix::io::FramedWrite<WriteHalf<TcpStream>, codec::AdsClientCodec>, source: [u8; 8], target: [u8; 8], ws_ads: Option<Addr<AdsToWsMultiplexer>>, request_map: HashMap<u32, oneshot::Sender<AmsTcpHeader<codec::AdsReadRes>>>, write_request_sender: Option<mpsc::Sender<codec::AdsWriteReq>>, } impl AdsClient { pub fn new( framed: actix::io::FramedWrite<WriteHalf<TcpStream>, codec::AdsClientCodec>, source: [u8; 8], target: [u8; 8], ) -> Self { AdsClient { framed, source, target, ws_ads: None, request_map: HashMap::new(), write_request_sender: None, } } } impl Actor for AdsClient { type Context = Context<Self>; fn started(&mut self, _: &mut Self::Context) { println!("ads_client started"); } fn stopped(&mut self, _: &mut Self::Context) { println!("ads_client: stopped"); } } impl AdsClient { fn gen_request<T>(&self, command_id: u16, state_flags: u16, data: T) -> (AmsTcpHeader<T>, u32) where T: AdsCommand, { let r = rand::thread_rng().gen(); ( codec::AmsTcpHeader { length: 32 + data.size() as u32, header: codec::AmsHeader { source: self.source, target: self.target, command_id, inv_id: r, state_flags, data, }, }, r, ) } /*fn gen_write_request( &self, index_group: u32, index_offset: u32, data: Vec<u8>, ) -> (AmsTcpHeader<codec::AdsWriteReq>, u32) { self.gen_request( 3, 4, codec::AdsWriteReq { index_group, index_offset, length: data.len() as u32, data, }, ) } fn gen_read_request( &self, index_group: u32, index_offset: u32, length: u32, ) -> (AmsTcpHeader<codec::AdsReadReq>, u32) { self.gen_request( 2, 4, codec::AdsReadReq { index_group, index_offset, length, }, ) }*/ } impl actix::io::WriteHandler<io::Error> for AdsClient {} impl StreamHandler<codec::AdsPacket, io::Error> for AdsClient { fn handle(&mut self, msg: codec::AdsPacket, _: &mut Context<Self>) { use super::codec::AdsPacket::*; match msg { ReadReq(r) => { println!("read_req: {:?}", r); self.framed.write(codec::AdsPacket::ReadRes(r.gen_res())); } ReadRes(r) => { let rres = self.request_map.remove(&r.header.inv_id).unwrap(); let _ = rres.send(r); //send_to_ws(&self.ws_ads, AdsClientToWs::ReadResult(r)); } WriteReq(w) => { self.framed.write(codec::AdsPacket::WriteRes(w.gen_res())); if let Some(ref mut tx) = &mut self.write_request_sender { let _ = tx.try_send(w.header.data); } //println!("write_req: {:?}", w); //send_to_ws(&self.ws_ads, AdsClientToWs::WriteData(w)); } WriteRes(_w) => {} } //send_to_ws(&self.ws_clients, msg); } } impl Handler<codec::AdsReadReq> for AdsClient { type Result = Box<Future<Item = codec::AdsReadRes, Error = ()>>; fn handle( &mut self, msg: codec::AdsReadReq, _: &mut Self::Context, ) -> Box<Future<Item = codec::AdsReadRes, Error = ()>> { let (req, inv) = self.gen_request(2, 4, msg); let (tx, rx) = oneshot(); self.request_map.insert(inv, tx); self.framed.write(AdsPacket::ReadReq(req)); Box::new(rx.map_err(|_| println!("error")).map(|f| f.header.data)) } } impl Handler<codec::AdsWriteReq> for AdsClient { type Result = (); fn handle(&mut self, msg: codec::AdsWriteReq, _: &mut Self::Context) -> Self::Result { let (req, _) = self.gen_request(3, 4, msg); self.framed.write(AdsPacket::WriteReq(req)); } } /*impl<T: 'static> Handler<T> for AdsClient where T: codec::AdsCommand + Message<Result = ()> + Debug,cls { type Result = (); fn handle(&mut self, msg: T, _: &mut Self::Context) { println!("wrong"); use std::any::Any; let m = Box::new(msg) as Box<Any>; let d = match m.downcast::<codec::AdsReadReq>() { Ok(rr) => { let (req, inv) = ; AdsPacket::ReadReq(req) } Err(m) => match m.downcast::<codec::AdsWriteReq>() { Ok(wr) => { let (req, inv) = self.gen_request(3, 4, *wr); AdsPacket::WriteReq(req) } _ => unreachable!(), }, }; self.framed.write(d); } } */
pub fn encode_utf8(src: &[char]) -> Result<Vec<u8>, EncodeUtf8Error> { let mut result = Vec::new(); for (index, ch) in src.iter().enumerate() { if let Some(error_kind) = encode_char(*ch, &mut result) { return Err(EncodeUtf8Error { src, index, kind: error_kind, }); } } Ok(result) } #[derive(Debug, Clone)] pub struct EncodeUtf8Error<'a> { pub src: &'a [char], pub index: usize, pub kind: EncodeUtf8ErrorKind, } #[derive(Debug, Clone)] pub enum EncodeUtf8ErrorKind { InvalidCodePoint, } const ONE_MAX: u32 = (1 << 7) - 1; const TWO_MAX: u32 = (1 << 11) - 1; const THREE_MAX: u32 = (1 << 16) - 1; const FOUR_MAX: u32 = (1 << 21) - 1; const LOW_6_MASK: u32 = 0b0011_1111; const NON_START_MASK: u8 = 0b1000_0000; const TWO_START_MASK: u8 = 0b1100_0000; const THREE_START_MASK: u8 = 0b1110_0000; const FOUR_START_MASK: u8 = 0b1111_0000; fn encode_char(ch: char, result: &mut Vec<u8>) -> Option<EncodeUtf8ErrorKind> { let raw_char = ch as u32; if raw_char >= FOUR_MAX { Some(EncodeUtf8ErrorKind::InvalidCodePoint) } else { if raw_char < ONE_MAX { encode_one(raw_char, result); } else if raw_char < TWO_MAX { encode_two(raw_char, result); } else if raw_char < THREE_MAX { encode_three(raw_char, result); } else if raw_char < FOUR_MAX { encode_four(raw_char, result); } else { unreachable!() } None } } fn encode_one(raw_char: u32, result: &mut Vec<u8>) { result.push(raw_char as u8); } fn encode_two(raw_char: u32, result: &mut Vec<u8>) { let (raw_char, second) = encode_low_6_bits(raw_char); let first = (raw_char as u8) | TWO_START_MASK; result.push(first); result.push(second); } fn encode_three(raw_char: u32, result: &mut Vec<u8>) { let (raw_char, third) = encode_low_6_bits(raw_char); let (raw_char, second) = encode_low_6_bits(raw_char); let first = (raw_char as u8) | THREE_START_MASK; result.push(first); result.push(second); result.push(third); } fn encode_four(raw_char: u32, result: &mut Vec<u8>) { let (raw_char, forth) = encode_low_6_bits(raw_char); let (raw_char, third) = encode_low_6_bits(raw_char); let (raw_char, second) = encode_low_6_bits(raw_char); let first = (raw_char as u8) | FOUR_START_MASK; result.push(first); result.push(second); result.push(third); result.push(forth); } fn encode_low_6_bits(raw_char: u32) -> (u32, u8) { let low_6_bits = (raw_char & LOW_6_MASK) as u8; (raw_char >> 6, low_6_bits | NON_START_MASK) }
extern crate term; use std::net::{ TcpListener, TcpStream, Shutdown }; fn main() { let listener = TcpListener::bind("127.0.0.1:8888") .expect("not bound"); let mut t = term::stdout().unwrap(); println!("127.0.0.1:8888 running"); for stream in listener.incoming() { match stream { Err(e) => { eprintln!("failed: {}", e); } Ok(stream) => { t.fg(term::color::BRIGHT_GREEN).unwrap(); write!(t, "new client: "); t.reset().unwrap(); println!("{}", stream.peer_addr().expect("wheee, fail")); t.fg(term::color::BRIGHT_RED).unwrap(); write!(t, "client disconnected: ", ); t.reset().unwrap(); println!("{}", stream.peer_addr().expect("wheee, fail")); stream.shutdown(Shutdown::Both).expect("shutdown failed"); } } } } /* TCP server accepts connection diplays peer_addr() and shutdown connection with him */
use serde::{Serialize, Deserialize, Serializer, ser::SerializeStruct}; use mongodb::bson::{oid::ObjectId, DateTime}; #[derive(Deserialize, Debug, Clone)] pub struct Podcast { pub _id: Option<ObjectId>, pub name: Option<String>, pub banner: Option<String>, pub url: Option<String>, pub duration: Option<f32>, pub date: Option<DateTime> } impl Serialize for Podcast { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("Podcast", 6)?; match &self._id { Some(id) => { state.serialize_field("id", &id.to_string())? } None => { state.serialize_field("id", &self._id)?; } } match &self.date { Some(date) => { state.serialize_field("date", &date.to_rfc3339())? } None => { state.serialize_field("date", &self.date)?; } } state.serialize_field("name", &self.name)?; state.serialize_field("banner", &self.banner)?; state.serialize_field("url", &self.url)?; state.serialize_field("duration", &self.duration)?; state.end() } } impl Default for Podcast { fn default() -> Self { return Podcast { _id: None, name: None, banner: None, url: None, duration: None, date: None } } }
use constants::*; use graphics::*; use opengl_graphics::{GlGraphics, OpenGL, Texture}; use piston::input::*; use random::MTRng32; use std::path::Path; pub struct Game { gl: GlGraphics, // OpenGL drawing backend. rand: MTRng32, // TODO other rng generator? cursor_position: (f64, f64), background: Image, bg_texture: Texture, aim_texture: Texture, evil_texture: Texture, hero_texture: Texture, evil_targets: Vec<Target>, hero_targets: Vec<Target>, } impl Game { pub fn new(opengl: OpenGL) -> Self { let mut rand = MTRng32::new(42); // TODO better seed let mut evil_targets: Vec<Target> = Vec::new(); for _ in 0..NUM_EVIL_TARGETS { let t = Target::new_rnd(&mut rand); evil_targets.push(t); } let mut hero_targets: Vec<Target> = Vec::new(); for _ in 0..NUM_HERO_TARGETS { let t = Target::new_rnd(&mut rand); hero_targets.push(t); } Game { gl: GlGraphics::new(opengl), rand: rand, cursor_position: (WINDOW_SIZE.0 / 2.0, WINDOW_SIZE.1 / 2.0), background: Image::new().rect([0.0, 0.0, WINDOW_SIZE.0, WINDOW_SIZE.1]), bg_texture: Texture::from_path(Path::new(TEXTURE_BG)).unwrap(), aim_texture: Texture::from_path(Path::new(TEXTURE_AIM)).unwrap(), evil_texture: Texture::from_path(Path::new(TEXTURE_TRUMP)).unwrap(), hero_texture: Texture::from_path(Path::new(TEXTURE_MEXICAN)).unwrap(), evil_targets: evil_targets, hero_targets: hero_targets, } } pub fn render(&mut self, args: &RenderArgs) { let (x, y) = self.cursor_position; let bg = self.background; let bg_texture = &self.bg_texture; let aim_texture = &self.aim_texture; let hero_texture = &self.hero_texture; let evil_texture = &self.evil_texture; let hero_targets = &self.hero_targets; let evil_targets = &self.evil_targets; self.gl.draw(args.viewport(), |c, gl| { use graphics::draw_state::DrawState; // Clear the screen and redraw background. bg.draw(bg_texture, &DrawState::default(), c.transform, gl); // Draw targets for target in hero_targets { let target_img = Image::new().rect(rectangle::square(target.x, target.y, target.width)); let transform = c.transform.trans(0.0, 0.0).trans(-25.0, -25.0); target_img.draw(hero_texture, &DrawState::default(), transform, gl); } for target in evil_targets { let target_img = Image::new().rect(rectangle::square(target.x, target.y, target.width)); let transform = c.transform.trans(0.0, 0.0).trans(-25.0, -25.0); target_img.draw(evil_texture, &DrawState::default(), transform, gl); } // Draw a crosshair let aim = Image::new().rect(rectangle::square(0.0, 0.0, 50.0)); let transform = c.transform.trans(x, y).trans(-50.0, -50.0); aim.draw(aim_texture, &DrawState::default(), transform, gl); }); } pub fn update(&mut self, args: &UpdateArgs) { self.update_lifetimes(args.dt); for t in &mut [&mut self.evil_targets, &mut self.hero_targets] { for target in t.iter_mut() { target.x += target.movement.0 * args.dt; target.y += target.movement.1 * args.dt; if target.x <= -50.0 { target.x = WINDOW_SIZE.0; } else if target.x >= WINDOW_SIZE.0 { target.x = -50.0; } if target.y <= -50.0 { target.y = WINDOW_SIZE.1; } else if target.y >= WINDOW_SIZE.1 { target.y = -50.0; } } } // create new targets if old ones died while self.hero_targets.len() < NUM_HERO_TARGETS { self.hero_targets.push(Target::new_rnd(&mut self.rand)); } while self.evil_targets.len() < NUM_EVIL_TARGETS { self.evil_targets.push(Target::new_rnd(&mut self.rand)); } } fn update_lifetimes(&mut self, dt: f64) { for targets in &mut [&mut self.evil_targets, &mut self.hero_targets] { for i in (0..targets.len()).rev() { if targets[i].lifetime >= dt { targets[i].lifetime -= dt; } else { // Lifetime is over, remove them targets.remove(i); } } } } pub fn process_mouse(&mut self, m: &MouseButton) { if let MouseButton::Left = *m { for i in Target::check_for_hit(&mut self.evil_targets, self.cursor_position) .iter() .rev() { self.evil_targets.remove(*i); } for i in Target::check_for_hit(&mut self.hero_targets, self.cursor_position) .iter() .rev() { self.hero_targets.remove(*i); } } } pub fn process_else(&mut self, inp: &Input) { inp.mouse_cursor(|x, y| self.cursor_position = (x + 25.0, y + 25.0)); // cursor offset } } pub struct Target { pub x: f64, pub y: f64, pub width: f64, pub height: f64, pub bounty: u16, pub lifetime: f64, pub movement: (f64, f64), } impl Target { pub fn new(x: f64, y: f64, width: f64, height: f64, bounty: u16, lifetime: f64, movement: (f64, f64)) -> Self { Target { x: x, y: y, width: width, height: height, bounty: bounty, lifetime: lifetime, movement: movement, } } pub fn new_rnd(rand: &mut MTRng32) -> Self { //TODO let (x, y) = Self::get_rnd_position(rand); let movement = Self::get_rnd_movement(rand); let lifetime = Self::get_rnd_lifetime(rand, 4.0, 7.0); Target { x: x, y: y, width: 50.0, height: 50.0, bounty: 30, lifetime: lifetime, movement: movement, } } pub fn get_rnd_movement(rand: &mut MTRng32) -> (f64, f64) { let x_sgn = if rand.rand() & 1 == 1 { -1.0 } else { 1.0 }; let x = (rand.rand() % 20 as u32) as f64; let y_sgn = if rand.rand() & 1 == 1 { -1.0 } else { 1.0 }; let y = (rand.rand() % 20 as u32) as f64; (x_sgn * x, y_sgn * y) } fn get_rnd_position(rand: &mut MTRng32) -> (f64, f64) { // TODO: check if rnd_position is okay let x = (rand.rand() % WINDOW_SIZE.0 as u32) as f64; let y = (rand.rand() % WINDOW_SIZE.1 as u32) as f64; (x, y) } fn get_rnd_lifetime(rnd: &mut MTRng32, min: f64, max: f64) -> f64 { let range = max * 1000.0 - min * 1000.0; let rnd = rnd.rand() as f64; min + ((rnd % range) / 1000.0) } fn coord_is_inside(&mut self, x: f64, y: f64) -> bool { x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height } pub fn check_for_hit(targets: &mut [Target], click: (f64, f64)) -> Vec<usize> { let mut indices: Vec<usize> = Vec::new(); for (i, target) in targets.iter_mut().enumerate() { if target.coord_is_inside(click.0, click.1) { indices.push(i); } } indices } }
pub fn add_two(x: i32) -> i32 { x + 2 } #[cfg(test)] mod tests { use super::*; #[test] fn it_works_2() { assert_eq!(9, add_two(7)); } }
extern crate reqwest; mod keys; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; //use std::collections::HashMap; pub fn get_headermap() -> HeaderMap { let mut headers = HeaderMap::new(); let key_id = HeaderName::from_lowercase(b"apca-api-key-id").unwrap(); let sec_key = HeaderName::from_lowercase(b"apca-api-secret-key").unwrap(); headers.insert( key_id, HeaderValue::from_str(keys::APCA_API_KEY_ID).unwrap(), ); headers.insert( sec_key, HeaderValue::from_str(keys::APCA_API_SECRET_KEY).unwrap(), ); headers } #[tokio::main] async fn main() -> Result<(), reqwest::Error> { let req_ep = "account"; let post_ep = "orders"; let pos_ep = "positions"; let request_url = format!("https://paper-api.alpaca.markets/v2/{}", req_ep); let post_url = format!("https://paper-api.alpaca.markets/v2/{}", post_ep); let positions_url = format!("https://paper-api.alpaca.markets/v2/{}", pos_ep); let headers = get_headermap(); let client = reqwest::Client::builder() .default_headers(headers) .build()?; let res = client .get(&request_url) .send() .await? //.json::<Vec<ApcaAsset>>() .json::<ApcaAccount>() .await?; println!("{:#?}", res); let order = ApcaPostOrder { symbol: "AAPL".to_string(), qty: 1, side: "buy".to_string(), type_field: "market".to_string(), time_in_force: "day".to_string(), //limit_price: None, //stop_price: None, //extended_hours: None, }; println!("order struct{:#?}", order); let order_res = client .post(&post_url) .json(&order) .send() .await? .json::<ApcaOrderTmp>() .await?; println!("{:#?}", order_res); let positions = client .get(&positions_url) .send() .await? .json::<Vec<ApcaPosition>>() .await?; println!("{:#?}", positions); Ok(()) } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct FixRoot { pub side: String, pub symbol: String, #[serde(rename = "type")] pub type_field: String, pub qty: String, pub time_in_force: String, pub order_class: String, pub take_profit: TakeProfit, pub stop_loss: StopLoss, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct TakeProfit { pub limit_price: String, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct StopLoss { pub stop_price: String, pub limit_price: String, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaPostOrder { pub symbol: String, pub qty: u64, pub side: String, // buy, sell #[serde(rename = "type")] pub type_field: String, // market, limit, stop, stop_limit pub time_in_force: String, // day, gtc, opg, cls, ioc, fok //pub limit_price: Option<f64>, // if type == limit or stop_limit //pub stop_price: Option<f64>, //if type == stop or stop_limit //pub extended_hours: Option<bool>, // todo take_profit and stop_loss arms // pub order_class = Stiring, // simple, bracket, oco, oto //pub : bool, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaAsset { pub id: String, pub class: String, pub exchange: String, pub symbol: String, pub status: String, pub tradable: bool, pub marginable: bool, pub shortable: bool, pub easy_to_borrow: bool, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaAccount { pub account_blocked: bool, pub account_number: String, pub buying_power: String, pub cash: String, pub created_at: String, pub currency: String, pub daytrade_count: i64, pub daytrading_buying_power: String, pub equity: String, pub id: String, pub initial_margin: String, pub last_equity: String, pub last_maintenance_margin: String, pub long_market_value: String, pub maintenance_margin: String, pub multiplier: String, pub pattern_day_trader: bool, pub portfolio_value: String, pub regt_buying_power: String, pub short_market_value: String, pub shorting_enabled: bool, pub sma: String, pub status: String, pub trade_suspended_by_user: bool, pub trading_blocked: bool, pub transfers_blocked: bool, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaOrder { pub id: String, pub client_order_id: String, pub created_at: String, pub updated_at: String, pub submitted_at: String, pub filled_at: String, pub expired_at: String, pub canceled_at: String, pub failed_at: String, pub replaced_at: String, pub replaced_by: String, pub replaces: ::serde_json::Value, pub asset_id: String, pub symbol: String, pub asset_class: String, pub qty: String, pub filled_qty: String, #[serde(rename = "type")] pub type_field: String, pub side: String, pub time_in_force: String, pub limit_price: String, pub stop_price: String, pub filled_avg_price: String, pub status: String, pub extended_hours: bool, pub legs: ::serde_json::Value, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaOrderTmp { pub id: String, pub client_order_id: String, pub created_at: String, pub updated_at: String, pub submitted_at: String, pub filled_at: ::serde_json::Value, pub expired_at: ::serde_json::Value, pub canceled_at: ::serde_json::Value, pub failed_at: ::serde_json::Value, pub replaced_at: ::serde_json::Value, pub replaced_by: ::serde_json::Value, pub replaces: ::serde_json::Value, pub asset_id: String, pub symbol: String, pub asset_class: String, pub qty: String, pub filled_qty: String, pub filled_avg_price: ::serde_json::Value, pub order_class: String, pub order_type: String, #[serde(rename = "type")] pub type_field: String, pub side: String, pub time_in_force: String, pub limit_price: ::serde_json::Value, pub stop_price: ::serde_json::Value, pub status: String, pub extended_hours: bool, pub legs: ::serde_json::Value, } #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] pub struct ApcaPosition { pub asset_id: String, pub symbol: String, pub exchange: String, pub asset_class: String, pub avg_entry_price: String, pub qty: String, pub side: String, pub market_value: String, pub cost_basis: String, pub unrealized_pl: String, pub unrealized_plpc: String, pub unrealized_intraday_pl: String, pub unrealized_intraday_plpc: String, pub current_price: String, pub lastday_price: String, pub change_today: String, }
// Copyright ยฉ 2017, ACM@UIUC // // This file is part of the Groot Project. // // The Groot Project is open source software, released under the // University of Illinois/NCSA Open Source License. You should have // received a copy of this license in a file with the distribution. extern crate iron; use iron::prelude::*; use iron::{Handler}; use iron::status; use router; fn canopy_server() { let mut router = router::Router::new(); router.add_route("hello".to_string(), |_: &mut Request| { Ok(Response::with((status::Ok, "Hello world !"))) }); router.add_route("hello/again".to_string(), |_: &mut Request| { Ok(Response::with((status::Ok, "Hello again !"))) }); router.add_route("error".to_string(), |_: &mut Request| { Ok(Response::with(status::BadRequest)) }); Iron::new(router).http("localhost:3000").unwrap(); }
// When multiple ownership is needed, `Rc` (Reference Counting) can be used. // `Rc` keeps track of the number of the references which means the number // of owners of the value wrapped inside an `Rc`. // // Reference count of an `Rc` increases by 1 whenever an `Rc` is cloned, // and decreases by 1 whenever one cloned `Rc` is dropped out of the scope. // When an `Rc` reference count becomes zero, which means there are no // owners remained, both the `Rc` and the value are all dropped. // // Cloning an `Rc` never performs a deep copy. Cloning creates just another // pointer to the wrapped value, and increments the count use std::rc::Rc; fn main() { let rc_examples = "Rc examples".to_string(); { println!("--- rc_a is created ---"); let rc_a: Rc<String> = Rc::new(rc_examples); println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); { println!("--- rc_a is cloned to rc_b ---"); let rc_b: Rc<String> = Rc::clone(&rc_a); println!("Reference Count of rc_b: {}", Rc::strong_count(&rc_b)); println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); // two `Rc` are equal if their inner values are equal println!("rc_a and rc_b are equal {}", rc_a.eq(&rc_b)); println!("Length of the value inside rc_a: {}", rc_a.len()); println!("Value of rc_b: {}", rc_b); println!("--- rc_b is dropped out of scope ---"); } println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); println!("--- rc_a is dropped out of scope ---"); } // Error! `rc_examples` already moved into `rc_a` // println!("rc_examples: {}", rc_examples); }
use std::{fs::read_dir, path::PathBuf}; use anyhow::{Context, Result}; use mongodb::{gridfs::GridFsBucket, Client}; use crate::{ bench::{drop_database, Benchmark, DATABASE_NAME}, fs::open_async_read_compat, }; pub struct GridFsMultiUploadBenchmark { uri: String, bucket: GridFsBucket, path: PathBuf, } pub struct Options { pub uri: String, pub path: PathBuf, } #[async_trait::async_trait] impl Benchmark for GridFsMultiUploadBenchmark { type Options = Options; async fn setup(options: Self::Options) -> Result<Self> { let client = Client::with_uri_str(&options.uri).await?; let db = client.database(&DATABASE_NAME); drop_database(&options.uri, &DATABASE_NAME) .await .context("drop database setup")?; Ok(Self { uri: options.uri, bucket: db.gridfs_bucket(None), path: options.path, }) } async fn before_task(&mut self) -> Result<()> { self.bucket.drop().await.context("bucket drop")?; self.bucket .upload_from_futures_0_3_reader("beforetask", &[11u8][..], None) .await .context("single byte upload")?; Ok(()) } async fn do_task(&self) -> Result<()> { let mut tasks = vec![]; for entry in read_dir(&self.path)? { let bucket = self.bucket.clone(); tasks.push(crate::spawn(async move { let path = entry?.path(); let file = open_async_read_compat(&path).await?; bucket .upload_from_futures_0_3_reader(path.display().to_string(), file, None) .await .context("upload file")?; let ok: anyhow::Result<()> = Ok(()); ok })); } for task in tasks { task.await?; } Ok(()) } async fn teardown(&self) -> Result<()> { drop_database(&self.uri, &DATABASE_NAME) .await .context("drop database teardown")?; Ok(()) } }
use super::problem::Problem; #[allow(dead_code)] pub fn eddy<'a>() -> Problem<'a> { Problem::new(5, -2, -6, b"TTCATA", b"TGCTCGTA") } #[allow(dead_code)] pub fn lec_17_slide19<'a>() -> Problem<'a> { Problem::new(3, -1, -3, b"GTAC", b"GATCA") } #[allow(dead_code)] pub fn in_class_a<'a>() -> Problem<'a> { Problem::new(3, -1, -3, b"TCA", b"ATCG") } #[allow(dead_code)] pub fn in_class_b<'a>() -> Problem<'a> { Problem::new(3, -10, -1, b"TCA", b"ATCG") } #[allow(dead_code)] pub fn in_class_c<'a>() -> Problem<'a> { Problem::new(3, -1, -1, b"TCA", b"ATCG") }
#[doc = "Reader of register STAT_CNTS"] pub type R = crate::R<u32, super::STAT_CNTS>; #[doc = "Reader of field `NUM_CONV`"] pub type NUM_CONV_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Current number of conversions remaining when in Sample_* states (note that in AutoZero* states the same down counter is reused to count the cycles)"] #[inline(always)] pub fn num_conv(&self) -> NUM_CONV_R { NUM_CONV_R::new((self.bits & 0xffff) as u16) } }
use std::io::{stdin, stdout, File}; use std::libc::{size_t, free, c_void}; use std::os::args; use std::path::Path; use std::ptr::null; use std::vec::raw::from_buf_raw; extern { fn skr_model(inp: *u8, inlen: size_t, outp: **u8, outlen: size_t, opts: *u32) -> size_t; fn skr_compress(model: *u8, modlen: size_t, inp: *u8, inlen: size_t, outp: **u8, outlen: size_t, opts: *u32) -> size_t; fn skr_decompress(model: *u8, modlen: size_t, inp: *u8, inlen: size_t, outp: **u8, outlen: size_t, opts: *u32) -> size_t; } type Fun = extern "C" unsafe fn(*u8, size_t, **u8, size_t, *u32) -> size_t; type Fun2 = extern "C" unsafe fn(*u8, size_t, *u8, size_t, **u8, size_t, *u32) -> size_t; fn process_vec(inp: &[u8], fun: Fun) -> ~[u8] { unsafe { let default_opts = 0; let buf = null(); let nout = fun(inp.as_ptr(), inp.len() as size_t, &buf, 0, &default_opts); assert!(buf != null() && nout > 0); let out = from_buf_raw(buf, nout as uint); free(buf as *c_void); out } } fn process_vec2(inp: &[u8], inp2: &[u8], fun: Fun2) -> ~[u8] { unsafe { let default_opts = 0; let buf = null(); let nout = fun(inp.as_ptr(), inp.len() as size_t, inp2.as_ptr(), inp2.len() as size_t, &buf, 0, &default_opts); assert!(buf != null() && nout > 0); let out = from_buf_raw(buf, nout as uint); free(buf as *c_void); out } } fn main() { let args = args(); let model = || { assert!(args.len() == 2); let model_file: &str = args[1]; File::open(&Path::new(model_file)).read_to_end() }; let output = { let input = || { stdin().read_to_end() }; if args[0].ends_with("mkskr") { process_vec(input(), skr_model) } else if args[0].ends_with("unskr") { process_vec2(model(), input(), skr_decompress) } else { process_vec2(model(), input(), skr_compress) } }; stdout().write(output) }
mod args; mod checks; mod common; mod fixes; mod flags; mod options; mod output;
use structopt::StructOpt; use hash_storage::storage::Storage; use std::error::Error; use std::fs::File; use std::io; #[derive(StructOpt, Debug)] #[structopt(version = "1.0", author = "Shogo Takata")] struct Opts { #[structopt(short = "o", long = "out_dir")] out_dir: String, #[structopt(short = "i", long = "input_file")] input_file: String, } fn main() -> Result<(), Box<dyn Error>> { let opts: Opts = Opts::from_args(); let storage = Storage::new(&opts.out_dir); let mut writer = storage.new_file_writer(); let mut input = File::open(&opts.input_file)?; io::copy(&mut input, &mut writer)?; Ok(()) }
use actix_web::{ HttpResponse, web, }; use super::super::{ service, request, response, }; pub fn index(payload: web::Query<request::designer::Index>) -> HttpResponse { let (domain_designer, total) = &service::designer::index( payload.page, payload.page_size, ); response::designer_index::response(domain_designer, &total) }
use anyhow::{Context, Result}; use std::path::PathBuf; use std::process::Command; /// Returns default path for scan results pub fn get_default_scan_path() -> Result<PathBuf> { Ok(dirs::home_dir() .context("Failed to get home directory")? .join(".rgit")) } /// Returns current git username pub fn get_git_user_name() -> Result<String> { let user = Command::new("git") .arg("config") .arg("user.name") .output() .context("Failed to execute: git config user.name")?; let user = String::from_utf8(user.stdout)?; Ok(String::from(user.trim())) }
mod hello; mod line; use v6_generics_do_not_use::Point; fn main() { hello::hw(); let p1 = Point::new(1.,1.); let p2 = Point::new(4.,5.); println!("dist = {}",line::dist(&p1,&p2)); local::do_thing(); } mod local { pub fn do_thing() { println!("thing done"); } }
use handlegraph::handle::NodeId; use rustc_hash::FxHashSet; use crate::geometry::*; use super::Node; pub struct Selection { bounding_box: Rect, nodes: FxHashSet<NodeId>, } impl Selection { pub fn singleton(node_positions: &[Node], node: NodeId) -> Self { let ix = (node.0 - 1) as usize; let node_pos = node_positions[ix]; let bounding_box = Rect::new(node_pos.p0, node_pos.p1); let mut nodes = FxHashSet::default(); nodes.insert(node); Self { bounding_box, nodes, } } pub fn from_iter<I>(node_positions: &[Node], nodes_iter: I) -> Self where I: Iterator<Item = NodeId>, { let mut bounding_box = Rect::nowhere(); let mut nodes = FxHashSet::default(); for node in nodes_iter { let ix = (node.0 - 1) as usize; let node_pos = node_positions[ix]; let rect = Rect::new(node_pos.p0, node_pos.p1); bounding_box = bounding_box.union(rect); nodes.insert(node); } Self { bounding_box, nodes, } } pub fn union(self, other: Self) -> Self { let bounding_box = self.bounding_box.union(other.bounding_box); let nodes = self .nodes .union(&other.nodes) .copied() .collect::<FxHashSet<_>>(); Self { bounding_box, nodes, } } pub fn union_from(&mut self, other: &Self) { self.bounding_box = self.bounding_box.union(other.bounding_box); self.nodes.extend(other.nodes.iter().copied()); } }
#[doc = "Register `AHB3ENR` reader"] pub type R = crate::R<AHB3ENR_SPEC>; #[doc = "Register `AHB3ENR` writer"] pub type W = crate::W<AHB3ENR_SPEC>; #[doc = "Field `QSPIEN` reader - QSPIEN"] pub type QSPIEN_R = crate::BitReader; #[doc = "Field `QSPIEN` writer - QSPIEN"] pub type QSPIEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PKAEN` reader - PKAEN"] pub type PKAEN_R = crate::BitReader; #[doc = "Field `PKAEN` writer - PKAEN"] pub type PKAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AES2EN` reader - AES2EN"] pub type AES2EN_R = crate::BitReader; #[doc = "Field `AES2EN` writer - AES2EN"] pub type AES2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RNGEN` reader - RNGEN"] pub type RNGEN_R = crate::BitReader; #[doc = "Field `RNGEN` writer - RNGEN"] pub type RNGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSEMEN` reader - HSEMEN"] pub type HSEMEN_R = crate::BitReader; #[doc = "Field `HSEMEN` writer - HSEMEN"] pub type HSEMEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `IPCCEN` reader - IPCCEN"] pub type IPCCEN_R = crate::BitReader; #[doc = "Field `IPCCEN` writer - IPCCEN"] pub type IPCCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `FLASHEN` reader - FLASHEN"] pub type FLASHEN_R = crate::BitReader; #[doc = "Field `FLASHEN` writer - FLASHEN"] pub type FLASHEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 8 - QSPIEN"] #[inline(always)] pub fn qspien(&self) -> QSPIEN_R { QSPIEN_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 16 - PKAEN"] #[inline(always)] pub fn pkaen(&self) -> PKAEN_R { PKAEN_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - AES2EN"] #[inline(always)] pub fn aes2en(&self) -> AES2EN_R { AES2EN_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - RNGEN"] #[inline(always)] pub fn rngen(&self) -> RNGEN_R { RNGEN_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - HSEMEN"] #[inline(always)] pub fn hsemen(&self) -> HSEMEN_R { HSEMEN_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - IPCCEN"] #[inline(always)] pub fn ipccen(&self) -> IPCCEN_R { IPCCEN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 25 - FLASHEN"] #[inline(always)] pub fn flashen(&self) -> FLASHEN_R { FLASHEN_R::new(((self.bits >> 25) & 1) != 0) } } impl W { #[doc = "Bit 8 - QSPIEN"] #[inline(always)] #[must_use] pub fn qspien(&mut self) -> QSPIEN_W<AHB3ENR_SPEC, 8> { QSPIEN_W::new(self) } #[doc = "Bit 16 - PKAEN"] #[inline(always)] #[must_use] pub fn pkaen(&mut self) -> PKAEN_W<AHB3ENR_SPEC, 16> { PKAEN_W::new(self) } #[doc = "Bit 17 - AES2EN"] #[inline(always)] #[must_use] pub fn aes2en(&mut self) -> AES2EN_W<AHB3ENR_SPEC, 17> { AES2EN_W::new(self) } #[doc = "Bit 18 - RNGEN"] #[inline(always)] #[must_use] pub fn rngen(&mut self) -> RNGEN_W<AHB3ENR_SPEC, 18> { RNGEN_W::new(self) } #[doc = "Bit 19 - HSEMEN"] #[inline(always)] #[must_use] pub fn hsemen(&mut self) -> HSEMEN_W<AHB3ENR_SPEC, 19> { HSEMEN_W::new(self) } #[doc = "Bit 20 - IPCCEN"] #[inline(always)] #[must_use] pub fn ipccen(&mut self) -> IPCCEN_W<AHB3ENR_SPEC, 20> { IPCCEN_W::new(self) } #[doc = "Bit 25 - FLASHEN"] #[inline(always)] #[must_use] pub fn flashen(&mut self) -> FLASHEN_W<AHB3ENR_SPEC, 25> { FLASHEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "AHB3 peripheral clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ahb3enr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ahb3enr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct AHB3ENR_SPEC; impl crate::RegisterSpec for AHB3ENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ahb3enr::R`](R) reader structure"] impl crate::Readable for AHB3ENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`ahb3enr::W`](W) writer structure"] impl crate::Writable for AHB3ENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets AHB3ENR to value 0x0208_0000"] impl crate::Resettable for AHB3ENR_SPEC { const RESET_VALUE: Self::Ux = 0x0208_0000; }
use crate::prelude::*; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Range { from: u32, to: u32, } impl Debug for Range { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}..={}", self.from, self.to) } } pub fn pt1(mut ranges: Vec<Range>) -> Result<u32> { ranges.sort_unstable(); let mut lowest_allowed = 0; for range in ranges { if lowest_allowed >= range.from && lowest_allowed <= range.to { lowest_allowed = range.to + 1; } } Ok(lowest_allowed) } fn coalesce_ranges(mut old: Vec<Range>) -> Vec<Range> { assert!(!old.is_empty()); old.sort_unstable(); let mut new = Vec::new(); new.push(old[0]); for &range in old.iter().skip(1) { if range.from > range.to { continue; } let last = new.last_mut().unwrap(); if (range.from as u64) <= (last.to as u64) + 1 { // Combine the ranges last.to = last.to.max(range.to); } else { // New range new.push(range); } } new } pub fn pt2(ranges: Vec<Range>) -> Result<u32> { let ranges = coalesce_ranges(ranges); let mut total = 0; if ranges[0].from != 0 { total += ranges[0].from - 1; } for (a, b) in ranges.iter().zip(ranges.iter().skip(1)) { total += b.from - a.to - 1; } if ranges.last().unwrap().to != std::u32::MAX { total += std::u32::MAX - ranges.last().unwrap().to; } Ok(total) } pub fn parse(s: &str) -> IResult<&str, Vec<Range>> { use parsers::*; separated_list1( line_ending, map(pair(u32_str, preceded(char('-'), u32_str)), |(from, to)| { Range { from, to } }), )(s) } #[test] fn day20() -> Result<()> { test_part!(parse, pt2, "\ 5-8 0-2 4-7" => std::u32::MAX - 8); Ok(()) }
extern crate iced; use iced::{button, Button, window, text_input, TextInput, Align, Column, Settings, Element, Text, Sandbox}; extern crate libloading as lib; extern crate server; use server::router::Router; use std::env; use std::net::TcpListener; use std::path::Path; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; #[derive(Default)] struct Server { ip_address: String, port: String, directory: String, filename: String, log: String, state: State, } #[derive(Default)] struct State { ip_input: text_input::State, port_input: text_input::State, dir_input: text_input::State, filename_input: text_input::State, start_button: button::State, } #[derive(Debug, Clone)] pub enum Message { Start, IpAddress(String), Port(String), Directory(String), FileName(String), } impl Sandbox for Server { type Message = Message; fn new() -> Self { Self::default() } fn title(&self) -> String { String::from("ะ’ะตะฑ-ัะตั€ะฒะตั€") } fn view(&mut self) -> Element<Message>{ let font_size = 20; let ip_address = TextInput::new( &mut self.state.ip_input, "ะ’ะฒะตะดะธั‚ะต ip-ะฐะดั€ะตั", &self.ip_address, Message::IpAddress ) .size(font_size) .padding(5); let port = TextInput::new( &mut self.state.port_input, "ะ’ะฒะตะดะธั‚ะต ะฟะพั€ั‚", &self.port, Message::Port ) .size(font_size) .padding(5); let directory = TextInput::new( &mut self.state.dir_input, "ะ’ะฒะตะดะธั‚ะต ะฟัƒั‚ัŒ ะบ ะดะธั€ะตะบั‚ะพั€ะธะธ ัะฐะนั‚ะฐ", &self.directory, Message::Directory, ) .size(font_size) .padding(5); let filename = TextInput::new( &mut self.state.filename_input, "ะ’ะฒะตะดะธั‚ะต ะฝะฐะทะฒะฐะฝะธะต ั„ะฐะนะปะฐ", &self.filename, Message::FileName, ) .size(font_size) .padding(5); let start_button = Button::new( &mut self.state.start_button, Text::new("ะ—ะฐะฟัƒัะบ") ) .on_press(Message::Start); Column::new() .spacing(20) .padding(10) .align_items(Align::Center) .push(ip_address) .push(port) .push(directory) .push(filename) .push(start_button) .push(Text::new(&self.log).size(14)) .into() } fn update(&mut self, message: Message) { match message { Message::IpAddress(s) => { self.ip_address = s; } Message::Port(s) => { self.port = s; } Message::Directory(s) => { self.directory = s; } Message::FileName(s) => { self.filename = s; } Message::Start => { self.log = start( self.ip_address.clone(), self.port.clone(), self.directory.clone(), self.filename.clone() ); } } } } fn start(ip: String, port: String, directory: String, name: String) -> String { let site = if directory.ends_with("/") { format!("{}{}", directory, name) } else { format!("{}/{}", directory, name) }; let dir = Path::new(&directory); match env::set_current_dir(&dir) { Err(_) => return "ะะต ัƒะดะฐะปะพััŒ ะพั‚ะบั€ั‹ั‚ัŒ ะดะธั€ะตะบั‚ะพั€ะธัŽ".into(), _ => {} } if port.is_empty() || ip.is_empty() || directory.is_empty() || name.is_empty() { return "ะ’ั‹ ะฝะต ะฒะฒะตะปะธ ะฒัะต ะฝัƒะถะฝั‹ะต ะดะฐะฝะฝั‹ะต".into(); } let file = Path::new(&site); if !file.exists() { return "ะคะฐะนะป ัะฐะนั‚ะฐ ะฝะต ััƒั‰ะตัั‚ะฒัƒะตั‚".into(); } if !site.ends_with(".so") && !site.ends_with(".dll") && !site.ends_with(".dylib") { return "ะคะฐะนะป ะดะพะปะถะตะฝ ะฑั‹ั‚ัŒ ะฒ ั„ะพั€ะผะฐั‚ะต .so, .dll ะธะปะธ .dylibw".into(); } match TcpListener::bind(format!("{}:{}", ip, port)) { Err(_) => { return "IP-ะฐะดั€ะตั ะฝะตะดะพัั‚ัƒะฟะตะฝ".into(); } _ => {} } let file = lib::Library::new(site.as_str()).unwrap(); let mut server = server::Server::new(&ip, &port); let (sender, reciever): (Sender<bool>, Receiver<bool>) = mpsc::channel(); unsafe { let thread_s = sender.clone(); thread::spawn(move || { let site: lib::Symbol<unsafe extern "C" fn() -> Router> = match file.get(b"site") { Ok(site) => { thread_s.send(true).unwrap(); site } Err(_) => { thread_s.send(false).unwrap(); return; } }; let router = site(); server.start(router); }); } let success: bool = reciever.recv().unwrap(); if !success { return "ะžัˆะธะฑะบะฐ. ะฝะต ะฑั‹ะปะฐ ะฝะฐะนะดะตะฝะฐ ั„ัƒะฝะบั†ะธั site".into(); } format!("ะกะตั€ะฒะตั€ ะทะฐะฟัƒั‰ะตะฝ ะฟะพ ะฐะดั€ะตััƒ http://{}:{}", ip, port) } type Flags = (); pub fn main() { Server::run(Settings { window: window::Settings{ size: (320, 300), resizable: false, decorations: true, }, flags: Flags::default(), default_font: None, antialiasing: false, }); }
// This took a very long time to run. But it worked eventually... fn main() { let corridor = [0,0,0,0,0,0,0,0,0,0,0]; let mut a_room = Room::from(1, 2, true); let mut b_room = Room::from(2, 4, true); let mut c_room = Room::from(3, 6, true); let mut d_room = Room::from(4, 8, true); //let mut a_room = Room::from(1, 2); //let mut b_room = Room::from(2, 4); //let mut c_room = Room::from(3, 6); //let mut d_room = Room::from(4, 8); // setup //a_room.deeper = char_to_num('A'); //a_room.near_entrance = char_to_num('B'); //b_room.deeper = char_to_num('D'); //b_room.near_entrance = char_to_num('C'); //c_room.deeper = char_to_num('C'); //c_room.near_entrance = char_to_num('B'); //d_room.deeper = char_to_num('A'); //d_room.near_entrance = char_to_num('D'); a_room.deeper = char_to_num('C'); a_room.near_entrance = char_to_num('B'); b_room.deeper = char_to_num('D'); b_room.near_entrance = char_to_num('A'); c_room.deeper = char_to_num('D'); c_room.near_entrance = char_to_num('B'); d_room.deeper = char_to_num('A'); d_room.near_entrance = char_to_num('C'); a_room.extra_near = char_to_num('D'); a_room.extra_deeper = char_to_num('D'); b_room.extra_near = char_to_num('C'); b_room.extra_deeper = char_to_num('B'); c_room.extra_near = char_to_num('B'); c_room.extra_deeper = char_to_num('A'); d_room.extra_near = char_to_num('A'); d_room.extra_deeper = char_to_num('C'); let mut w = Worker::new(); w.go_for_it(State { corridor: corridor, rooms: [a_room, b_room, c_room, d_room], energy: 0, worthy: 0, potential_energy: 0 }); } #[derive(Clone, PartialEq, Debug)] struct State { corridor: [i32; 11], rooms: [Room; 4], energy: u64, worthy: i32, potential_energy: u64 } impl State { fn count_occupants(&self) -> i32 { self.corridor.iter().fold(0, |iter, item| iter + one_if_true(*item > 0)) + self.rooms[0].count_occupants() + self.rooms[1].count_occupants() + self.rooms[2].count_occupants() + self.rooms[3].count_occupants() } fn minimum_completion(&self) -> u64 { let mut score: u64 = 0; for i in self.corridor { if i > 0 { score += ((i - corridor_location_for_room(i) as i32).abs() as u64 * energy_for_char(i)) as u64; } } for room in &self.rooms { if room.near_entrance != room.room_type { score += ((room.corridor_location - corridor_location_for_room(room.near_entrance)).abs() as u64 * energy_for_char(room.near_entrance)) as u64; } if room.deeper != room.room_type { score += ((room.corridor_location - corridor_location_for_room(room.deeper)).abs() as u64 * energy_for_char(room.deeper)) as u64; } } score } } fn is_available_stop(from: i8, to: i8, corridor: &[i32; 11]) -> bool { let mut range = from+1..to+1; if to < from { range = to..from; } //println!("{} {}", from, to); for pos in range { //println!("{}", pos); if corridor[pos as usize] != 0 { //println!("{} {:?}", pos, corridor); return false; } } true } struct Worker { best_score: u64, beens: Vec<State> } impl Worker { fn new() -> Worker { Worker { best_score: 0, beens: Vec::new() } } fn go_for_it(&mut self, state: State) { let mut options = vec![state]; loop { if options.len() == 0 { break; } let option = options.remove(0); if options.len() % 50 == 0 { println!("option {} {} {} {}", options.len(), self.best_score, option.energy, option.worthy); } options.append(&mut self.get_options(option).to_vec()); options.sort_by(|item, item2| item.potential_energy.cmp(&item2.potential_energy)); options.sort_by(|item, item2| item2.worthy.cmp(&item.worthy)); if options.len() > 1000 { //break; } } //println!("{:?}", options); println!("{}", self.best_score); } fn get_options(&mut self, state: State) -> Vec<State> { if self.beens.contains(&state) { //println!("Been here before"); return Vec::new(); } if self.best_score != 0 && state.potential_energy > self.best_score { return Vec::new(); } self.beens.push(state.clone()); if state.rooms.iter().fold(true, |iter, item| iter && item.is_complete()) { println!("complete"); if self.best_score == 0 || self.best_score > state.energy { println!("great"); self.best_score = state.energy; } return Vec::new(); } let mut states = Vec::new(); // For each room, is there anything that can come out? Can it go anywhere? let mut room_i = 0; for room in &state.rooms { room_i += 1; if room.is_complete() { continue; } if room.is_ready_for_end() { continue; } let coming_out = room.first_one_out(); if coming_out == None { continue; } let coming_out = coming_out.unwrap(); for i in 0..=10 { //println!("cycling"); if is_available_stop(room.corridor_location, i, &state.corridor) && i != 2 && i != 4 && i != 6 && i != 8 { //println!("Moving {} from {} to {} {} {:?}", coming_out.char, room.corridor_location, i, room_i, state); let new_energy = state.energy + ((coming_out.moves + (i as i32 - room.corridor_location as i32).abs()) as u64 * energy_for_char(coming_out.char)); let mut new_state = state.clone(); if new_state.corridor.iter().filter(|item| **item == coming_out.char).count() > 1 { //println!("Already done {:?}", new_state.corridor); } new_state.corridor[i as usize] = coming_out.char; new_state.rooms[room_i - 1].remove_first_one_out(); new_state.energy = new_energy; new_state.potential_energy = new_energy + new_state.minimum_completion(); new_state.worthy = new_state.rooms.iter().fold(0, |iter, item| iter + one_if_true(item.is_ready_for_end()) + one_if_true(item.is_complete()) * 2); //println!("A {} {}", new_state.count_occupants(), room_i); //if new_state.count_occupants() != 8 { // println!("Moving {:?}", new_state); // panic!("AAAAAA"); // } if self.best_score == 0 || new_state.potential_energy < self.best_score { states.push(new_state); } } } if state.rooms[coming_out.char as usize - 1].is_ready_for_end() { if is_available_stop(room.corridor_location, state.rooms[coming_out.char as usize - 1].corridor_location, &state.corridor) { //println!("p"); let new_energy = state.energy + ((state.rooms[coming_out.char as usize - 1].moves_to_in() + (state.rooms[coming_out.char as usize - 1].corridor_location as i32 - room.corridor_location as i32).abs() + coming_out.moves) as u64 * energy_for_char(coming_out.char)); let mut new_state = state.clone(); new_state.rooms[room_i - 1].remove_first_one_out(); new_state.rooms[coming_out.char as usize - 1].put_in(coming_out.char); new_state.energy = new_energy; new_state.potential_energy = new_energy + new_state.minimum_completion(); new_state.worthy = new_state.rooms.iter().fold(0, |iter, item| iter + one_if_true(item.is_ready_for_end()) + one_if_true(item.is_complete()) * 2); //println!("B {}", new_state.count_occupants()); if self.best_score == 0 || new_state.potential_energy < self.best_score { states.push(new_state); } } } } // For each corridor location, is there anything in there? Can it go to its destination? for i in 0..=10 { if state.corridor[i] > 0 { //println!("m"); let char = state.corridor[i]; let r = state.rooms.iter().find(|item| item.room_type == char); if r.is_some() { let r = r.unwrap(); //println!("s {} {:?} {:?}", char, r, state.corridor); if r.is_ready_for_end() { //println!("e {} {}", i, r.corridor_location); if is_available_stop(i as i8, r.corridor_location, &state.corridor) { //println!("p"); let new_energy = state.energy + ((r.moves_to_in() + (i as i32 - r.corridor_location as i32).abs()) as u64 * energy_for_char(char)); let mut new_state = state.clone(); new_state.corridor[i] = 0; new_state.rooms[char as usize - 1].put_in(char); new_state.energy = new_energy; new_state.potential_energy = new_energy + new_state.minimum_completion(); new_state.worthy = new_state.rooms.iter().fold(0, |iter, item| iter + one_if_true(item.is_ready_for_end()) + one_if_true(item.is_complete()) * 2); //println!("B {}", new_state.count_occupants()); if self.best_score == 0 || new_state.potential_energy < self.best_score { states.push(new_state); } } } } } } states } } fn one_if_true(t: bool) -> i32 { if t == true { return 1; } 0 } #[derive(Clone, PartialEq, Debug)] struct Room { room_type: i32, corridor_location: i8, near_entrance: i32, extra_near: i32, extra_deeper: i32, deeper: i32, part_two: bool } impl Room { fn from(room_type: i32, corridor_location: i8, part_two: bool) -> Room { Room { room_type, corridor_location, near_entrance: 0, deeper: 0, extra_deeper: 0, extra_near: 0, part_two } } fn is_complete(&self) -> bool { //println!("{} {} {} {}", self.room_type == self.near_entrance && self.room_type == self.deeper, self.room_type, self.near_entrance, self.deeper); if self.part_two { self.room_type == self.near_entrance && self.room_type == self.deeper && self.room_type == self.extra_near && self.room_type == self.extra_deeper } else { self.room_type == self.near_entrance && self.room_type == self.deeper } } fn is_empty(&self) -> bool { if self.part_two { self.near_entrance == 0 && self.deeper == 0 && self.extra_near == 0 && self.extra_deeper == 0 } else { self.near_entrance == 0 && self.deeper == 0 } } fn is_ready_for_end(&self) -> bool { //println!("{} {} {} {}", (self.room_type == self.near_entrance || self.near_entrance == 0) && (self.room_type == self.deeper || self.deeper == 0), self.room_type, self.near_entrance, self.deeper); if self.part_two { (self.room_type == self.near_entrance || self.near_entrance == 0) && (self.room_type == self.deeper || self.deeper == 0) && (self.room_type == self.extra_near || self.extra_near == 0) && (self.room_type == self.extra_deeper || self.extra_deeper == 0) } else { (self.room_type == self.near_entrance || self.near_entrance == 0) && (self.room_type == self.deeper || self.deeper == 0) } } fn count_occupants(&self) -> i32 { one_if_true(self.deeper > 0) + one_if_true(self.near_entrance > 0) + one_if_true(self.extra_near > 0) + one_if_true(self.extra_deeper > 0) } fn first_one_out(&self) -> Option<Out> { if self.near_entrance != 0 { return Some(Out { char: self.near_entrance, moves: 1 }); } else if self.part_two && self.extra_near != 0 { return Some(Out { char: self.extra_near, moves: 2 }); } else if self.part_two && self.extra_deeper != 0 { return Some(Out { char: self.extra_deeper, moves: 3 }); } else if self.deeper != 0 { if self.part_two { return Some(Out { char: self.deeper, moves: 4 }); } else { return Some(Out { char: self.deeper, moves: 2 }); } } None } fn remove_first_one_out(&mut self) { if self.part_two { if self.near_entrance != 0 { self.near_entrance = 0; } else if self.extra_near != 0 { self.extra_near = 0; } else if self.extra_deeper != 0 { self.extra_deeper = 0; } else if self.deeper != 0 { self.deeper = 0; } } else { if self.near_entrance != 0 { self.near_entrance = 0; } else if self.deeper != 0 { self.deeper = 0; } } } fn moves_to_in(&self) -> i32 { if self.part_two { if self.deeper == 0 { return 4; } else if self.extra_deeper == 0 { return 3; } else if self.extra_near == 0 { return 2; } else if self.near_entrance == 0 { return 1; } } else { if self.deeper == 0 { return 2; } else if self.near_entrance == 0 { return 1; } } 0 } fn put_in(&mut self, char: i32) { if self.part_two { if self.deeper == 0 { self.deeper = char; } else if self.extra_deeper == 0 { self.extra_deeper = char; } else if self.extra_near == 0 { self.extra_near = char; } else if self.near_entrance == 0 { self.near_entrance = char; } } else { if self.deeper == 0 { self.deeper = char; } else if self.near_entrance == 0 { self.near_entrance = char; } } } } #[derive(PartialEq)] struct Out { char: i32, moves: i32 } fn char_to_num(c: char) -> i32 { match c { 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, _ => 0 } } fn energy_for_char(c: i32) -> u64 { match c { 1 => 1, 2 => 10, 3 => 100, 4 => 1000, _ => 0 } } fn corridor_location_for_room(c: i32) -> i8 { match c { 1 => 2, 2 => 4, 3 => 6, 4 => 8, _ => 0 } }
use crate::ast::parser; use crate::ast::rules; use crate::ast::stack; use crate::utils; use crate::interpreter::environment; use crate::interpreter::types; #[allow(dead_code)] pub fn interpret(source_code: &str) -> (types::Type, utils::Shared<environment::Environment>) { interpret_rule(source_code, rules::chunk) } pub fn interpret_rule<F>( source_code: &str, func: F, ) -> (types::Type, utils::Shared<environment::Environment>) where F: Fn(&mut parser::Parser, &mut stack::Stack) -> bool, { let mut parser = parser::Parser::new(source_code.to_string()); let mut stack = stack::Stack::default(); func(&mut parser, &mut stack); assert!( parser.peek().is_none(), format!("Parser contains tokens after parsing: {:?}", parser) ); let mut env = utils::Shared::new(environment::Environment::new( None, environment::BreakFlag::None, )); (stack.pop_single().eval(&mut env), env) } pub fn interpret_rule_env<F>( source_code: &str, func: F, env: &mut utils::Shared<environment::Environment>, ) -> (types::Type, utils::Shared<environment::Environment>) where F: Fn(&mut parser::Parser, &mut stack::Stack) -> bool, { let mut parser = parser::Parser::new(source_code.to_string()); let mut stack = stack::Stack::default(); func(&mut parser, &mut stack); assert!( parser.peek().is_none(), format!("Parser contains tokens after parsing: {:?}", parser) ); let result = stack.pop_single().eval(env); (result, env.clone()) }
//! Rust pg_query &emsp; [![Build Status]][actions] [![Latest Version]][crates.io] [![Docs Badge]][docs] //! =========== //! //! [Build Status]: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fpaupino%2Fpg_query%2Fbadge&label=build&logo=none //! [actions]: https://actions-badge.atrox.dev/paupino/pg_query/goto //! [Latest Version]: https://img.shields.io/crates/v/pg_query.svg //! [crates.io]: https://crates.io/crates/pg_query //! [Docs Badge]: https://docs.rs/pg_query/badge.svg //! [docs]: https://docs.rs/pg_query //! //! PostgreSQL parser that uses the [actual PostgreSQL server source]((https://github.com/pganalyze/libpg_query)) to parse //! SQL queries and return the internal PostgreSQL parse tree. //! //! Warning! This library is in early stages of development so any APIs exposed are subject to change. //! //! ## Getting started //! //! Add the following to your `Cargo.toml` //! //! ```toml //! [dependencies] //! pg_query = "0.1" //! ``` //! //! # Example: Parsing a query //! //! ```rust //! use pg_query::ast::Node; //! //! let result = pg_query::parse("SELECT * FROM contacts"); //! assert!(result.is_ok()); //! let result = result.unwrap(); //! assert!(matches!(*&result[0], Node::SelectStmt(_))); //! ``` //! /// Generated structures representing the PostgreSQL AST. pub mod ast; mod bindings; mod error; mod query; pub use error::*; pub use query::*;
use anyhow::Result; use serde::{Deserialize, Serialize}; use sqlx::mysql::{MySqlPoolOptions, MySqlQueryResult}; use sqlx::{Connection, MySql, Pool, Transaction}; use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, SystemTime}; use tokio::sync::Mutex; type UserIdType = u32; #[derive(Serialize, Default)] pub struct Balances { pub free: i64, pub blocked: i64, pub total: i64, } #[derive(Deserialize, Serialize, Default)] struct DatabaseBalances { free: i64, total: i64, } pub struct Database { pool: Pool<MySql>, lock_map: Mutex<HashMap<UserIdType, Arc<Mutex<()>>>>, } macro_rules! read_balances { ($executor:expr,$id:expr) => {{ let ex = &mut *$executor; // this was the key! https://stackoverflow.com/a/30539264/4213397 let db_balances_raw = read_raw_balances!(ex, $id)?; let mut result = HashMap::with_capacity(db_balances_raw.capacity()); for (currency, data) in db_balances_raw { result.insert( currency, Balances { free: data.free, blocked: data.total - data.free, total: data.total, }, ); } Ok(result) } as anyhow::Result<HashMap<String, Balances>>}; } macro_rules! read_raw_balances { ($executor:expr,$id:expr) => {{ let ex = &mut *$executor; // this was the key! https://stackoverflow.com/a/30539264/4213397 let db_balances_json: (String,) = sqlx::query_as("SELECT `balances` FROM `current_balance` WHERE `user_id`=?") .bind($id) .fetch_one(ex) .await?; let db_balances_raw = serde_json::from_str::<HashMap<String, DatabaseBalances>>(db_balances_json.0.as_str())?; Ok(db_balances_raw) } as anyhow::Result<HashMap<String, DatabaseBalances>>}; } /// Checks an Result and rolls back a transaction and returns from function if the result is Err /// /// # Arguments /// First argument must be transaction and the second one must be result /// /// # Example /// /// ``` /// let mut tx = conn.begin().await?; /// try_rollback!(tx, Database::my_function(&mut tx, id).await); /// ``` macro_rules! try_rollback { ($tx:expr,$result:expr) => {{ if let Err(err) = $result { let _ = $tx.rollback().await; return Err(err.into()); } }}; } impl Database { pub async fn new(uri: &str) -> Self { let pool = MySqlPoolOptions::new() .max_connections(150) .connect_timeout(Duration::from_secs(2)) .connect(uri) .await .expect("cannot connect to database"); Self { pool, lock_map: Mutex::new(HashMap::new()), } } async fn move_to_past( tx: &mut Transaction<'_, sqlx::MySql>, user_id: UserIdType, ) -> Result<MySqlQueryResult, sqlx::Error> { sqlx::query("INSERT INTO `past_balance` (`user_id`,`balances`,`changed`) SELECT `user_id`, `balances`, UNIX_TIMESTAMP() FROM `current_balance` WHERE `user_id`=?") .bind(user_id) .execute(tx) .await } /// Registers a new user in database /// Returns an error if the user already exists in database /// /// # Arguments /// /// * `id`: The user ID to register in database /// /// returns: Result<(), Error> Nothing on success, otherwise an error /// pub async fn register_user(&self, id: UserIdType) -> Result<()> { // Create a connection let mut conn = self.pool.acquire().await?; sqlx::query("INSERT INTO `current_balance` (`user_id`) VALUES (?)") .bind(id) .execute(&mut conn) .await?; // automatically returns an error if user_id is not unique Ok(()) } /// /// /// # Arguments /// /// * `id`: /// /// returns: Result<HashMap<String, Balances, RandomState>, Error> /// /// # Examples /// /// ``` /// /// ``` #[lock_master::locker(id)] pub async fn get_balances(&self, id: UserIdType) -> Result<HashMap<String, Balances>> { // Get the balance with a connection let mut conn = self.pool.acquire().await?; let result = read_balances!(&mut conn, id)?; Ok(result) } #[lock_master::locker(id)] pub async fn get_past_balance(&self, id: UserIdType, time: u64) -> Result<HashMap<String, Balances>> { // Get the balance with a connection let mut conn = self.pool.acquire().await?; // Get current time and check if the time provided is after now if SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).expect("IM-FUCKING-POSSIBLE").as_secs() <= time { return read_balances!(&mut conn, id); } // Get the balance let db_balances_json: sqlx::Result<(String,)> = sqlx::query_as("SELECT `balances` FROM `past_balance` WHERE `user_id`=? AND `changed` <= ?") .bind(id) .bind(time) .fetch_one(&mut conn) .await; if let Err(err) = db_balances_json { return if let sqlx::Error::RowNotFound = err { Ok(HashMap::new()) } else { Err(err.into()) } } let db_balances_json = db_balances_json.unwrap(); let db_balances_raw = serde_json::from_str::<HashMap<String, DatabaseBalances>>(db_balances_json.0.as_str())?; // Convert the data let mut result = HashMap::with_capacity(db_balances_raw.capacity()); for (currency, data) in db_balances_raw { result.insert( currency, Balances { free: data.free, blocked: data.total - data.free, total: data.total, }, ); } Ok(result) } #[lock_master::locker(id)] pub async fn add_free_balance(&self, id: UserIdType, currency: String, volume: i64) -> Result<()> { // Start a transaction let mut conn = self.pool.acquire().await?; let mut tx = conn.begin().await?; // Move balance to past try_rollback!(tx, Database::move_to_past(&mut tx, id).await); // Add free balance try_rollback!(tx, Database::edit_current_balance(&mut tx, id, currency, volume, volume).await); tx.commit().await?; Ok(()) } #[lock_master::locker(id)] pub async fn block_free_balance(&self, id: UserIdType, currency: String, volume: i64) -> Result<()> { // Start a transaction let mut conn = self.pool.acquire().await?; let mut tx = conn.begin().await?; // Move balance to past try_rollback!(tx, Database::move_to_past(&mut tx, id).await); // Block balance by only removing free balance try_rollback!(tx, Database::edit_current_balance(&mut tx, id, currency, -volume, 0).await); tx.commit().await?; Ok(()) } #[lock_master::locker(id)] pub async fn unblock_blocked_balance(&self, id: UserIdType, currency: String, volume: i64) -> Result<()> { // Start a transaction let mut conn = self.pool.acquire().await?; let mut tx = conn.begin().await?; // Move balance to past try_rollback!(tx, Database::move_to_past(&mut tx, id).await); // Block balance by only adding free balance try_rollback!(tx, Database::edit_current_balance(&mut tx, id, currency, volume, 0).await); tx.commit().await?; Ok(()) } #[lock_master::locker(id)] pub async fn withdraw_blocked_balance(&self, id: UserIdType, currency: String, volume: i64) -> Result<()> { // Start a transaction let mut conn = self.pool.acquire().await?; let mut tx = conn.begin().await?; // Move balance to past try_rollback!(tx, Database::move_to_past(&mut tx, id).await); // Just remove from total try_rollback!(tx, Database::edit_current_balance(&mut tx, id, currency, 0, -volume).await); tx.commit().await?; Ok(()) } async fn edit_current_balance(tx: &mut Transaction<'_, sqlx::MySql>, id: UserIdType, currency: String, free_delta: i64, total_delta: i64) -> Result<()> { // Read old balance let mut balances = read_raw_balances!(tx, id)?; let mut balance = balances.entry(currency).or_default(); // Change balance balance.total += total_delta; balance.free += free_delta; // Check balance if balance.free < 0 || balance.total < 0 || balance.total - balance.free < 0 { return Err(anyhow::Error::msg("insufficient balance")); } // Insert it into database sqlx::query("UPDATE `current_balance` SET `balances`=? WHERE `user_id`=?") .bind(serde_json::to_string(&balances).unwrap()) .bind(id) .execute(tx) .await?; // Everything good Ok(()) } }
fn main() { let input = std::fs::read_to_string("../input.txt").unwrap(); let max = input .split("\n") .filter(|f| !f.is_empty()) .map(|seat| { let mut rows = 0..128; for c in seat.chars() { let len = (rows.end - rows.start) / 2; let start = match c { 'F' => rows.start, 'B' => rows.end - len, _ => break, }; rows = start..(start + len); } let row = rows.start; let mut cols = 0..8; for c in seat.chars().skip(7) { let len = (cols.end - cols.start) / 2; let start = match c { 'L' => cols.start, 'R' => cols.end - len, _ => break, }; cols = start..(start + len); } let col = cols.start; (row * 8) + col }) .max() .unwrap(); println!("{}", max); }
use super::bonuses::{LetterBonus, WordBonus}; use super::Tile; /// Describe a place on the `Board` /// /// Its structure is public. That means you don't want players to get /// access to it. #[derive(Debug, Clone)] pub struct Spot { /// It might have a tile on it pub tile : Option<Tile>, /// Some bonus applicable to a letter pub bonus_letter : LetterBonus, /// Some bonus applicable to a word pub bonus_word : WordBonus, } impl Spot { /// Create a new empty spot pub fn new() -> Spot { Spot { tile: None, bonus_letter : LetterBonus::None, bonus_word : WordBonus::None, } } /// Get integer factors for bonuses /// /// # Return Value /// A tuple with the (letter, word) bonus factor. pub fn get_bonuses_value(&self) -> (u32, u32) { let letter = match self.bonus_letter { LetterBonus::None => 1, LetterBonus::Double => 2, LetterBonus::Triple => 3, }; let word = match self.bonus_word { WordBonus::None => 1, WordBonus::Double => 2, WordBonus::Triple => 3, }; return (letter, word); } /// Get the bonus in a tuple /// /// # Return value /// A tuple with the (letter, word) bonus. pub fn get_bonuses(&self) -> (LetterBonus, WordBonus) { return (self.bonus_letter, self.bonus_word); } }
#[derive(PartialEq)] struct Foo { a: [[[u32; 4]; 8]; 32], } fn main() {} /* [2021-08-12T07:59:06Z ERROR viper::verifier] The verification aborted due to the following exception: java.lang.RuntimeException: Domain name Snap$Array$4$u32 not found in program. at scala.sys.package$.error(package.scala:27) at viper.silver.ast.Program.findDomain(Program.scala:277) at viper.silver.ast.utility.DomainInstances$DomainInstanceTypeCoordinate.collectTypes(DomainInstances.scala:474) at viper.silver.ast.utility.DomainInstances$.findNecessaryTypeInstances(DomainInstances.scala:242) at viper.silver.ast.Program.groundTypeInstances$lzycompute(Program.scala:240) at viper.silver.ast.Program.groundTypeInstances(Program.scala:240) at viper.silicon.supporters.BuiltinDomainsContributor.computeGroundTypeInstances(BuiltinDomainsContributor.scala:95) at viper.silicon.supporters.BuiltinDomainsContributor.analyze(BuiltinDomainsContributor.scala:58) at viper.silicon.verifier.DefaultMasterVerifier.$anonfun$analyzeProgramAndEmitPreambleContributions$1(DefaultMasterVerifier.scala:397) at viper.silicon.verifier.DefaultMasterVerifier.$anonfun$analyzeProgramAndEmitPreambleContributions$1$adapted(DefaultMasterVerifier.scala:396) at scala.collection.immutable.List.foreach(List.scala:333) at viper.silicon.verifier.DefaultMasterVerifier.analyzeProgramAndEmitPreambleContributions(DefaultMasterVerifier.scala:396) at viper.silicon.verifier.DefaultMasterVerifier.verify(DefaultMasterVerifier.scala:177) at viper.silicon.Silicon.viper$silicon$Silicon$$runVerifier(Silicon.scala:245) at viper.silicon.Silicon$$anon$1.call(Silicon.scala:198) at viper.silicon.Silicon$$anon$1.call(Silicon.scala:197) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) thread 'rustc' panicked at 'internal error: entered unreachable code: The verifier returned an unknown error of type viper.silver.verifier.AbortedExceptionally: Verification aborted exceptionally (<no position>)', viper/src/verifier.rs:205:21 stack backtrace: 0: rust_begin_unwind at /rustc/4e282795d7d1d28a4c6c1c6521045ae2b59f3519/library/std/src/panicking.rs:516:5 1: core::panicking::panic_fmt at /rustc/4e282795d7d1d28a4c6c1c6521045ae2b59f3519/library/core/src/panicking.rs:93:14 2: viper::verifier::Verifier<viper::verifier::state::Started>::verify 3: prusti_server::verifier_runner::VerifierRunner::verify 4: prusti_server::verifier_runner::VerifierRunner::with_default_configured_runner 5: prusti_viper::verifier::Verifier::verify 6: prusti_driver::verifier::verify 7: <prusti_driver::callbacks::PrustiCompilerCalls as rustc_driver::Callbacks>::after_analysis 8: rustc_interface::queries::<impl rustc_interface::interface::Compiler>::enter 9: rustc_span::with_source_map 10: rustc_interface::interface::create_compiler_and_run 11: scoped_tls::ScopedKey<T>::set note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. */
// cortex-m-quickstart build.rs // Copyright ยฉ 2017 Jorge Aparicio // Licensed under the Apache license v2.0, or the MIT license. // See https://github.com/japaric/cortex-m-quickstart for details. use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; fn main() { // Put the linker script somewhere the linker can find it let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); File::create(out.join("memory.x")) .unwrap() .write_all(include_bytes!("memory.x")) .unwrap(); println!("cargo:rustc-link-search={}", out.display()); println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=memory.x"); }
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] extern crate libc; mod hw_io; pub mod elev_io;
#![feature(custom_derive, plugin)] /* The fishermon strategy is setting up 2 nets both for buying and selling. * We start by delimiting a series of prices to serve as 'steps'. * Then we set up a strategy to take a stronger position at each step. * The progression of the orders to be placed can be either linear or exponential. */ extern crate bitex; #[macro_use] extern crate fishermon; #[macro_use] extern crate log; extern crate env_logger; extern crate toml; extern crate rustc_serialize; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::path::Path; use fishermon::{Trader, Strategy}; #[derive(RustcDecodable, Debug)] struct Config { api_key: String, sleep_for: u64, production: bool, bids: Strategy, asks: Strategy, } fn load_config() -> Config { let path = Path::new("fishermon.toml"); let display = path.display(); let mut file = match File::open(&path) { Err(why) => panic!("couldn't open {}: {}", display, why.description()), Ok(file) => file, }; // Read the file contents into a string, returns `io::Result<usize>` let mut s = String::new(); let config = match file.read_to_string(&mut s) { Err(why) => panic!("couldn't read {}: {}", display, why.description()), Ok(_) => toml::decode(s.parse().unwrap()), }; config.expect("Config format was invalid") } fn main() { env_logger::init().unwrap(); info!("starting up"); let config = load_config(); let api = if config.production { bitex::Api::prod().key(&config.api_key) } else { bitex::Api::sandbox().key(&config.api_key) }; let trader = Trader::new(api, config.sleep_for, 300, config.bids, config.asks); loop { trader.trade() } }
use query_builder::{CombinableQuery, UnionQuery}; pub trait UnionDsl<U: CombinableQuery<SqlType = Self::SqlType>>: CombinableQuery { type Output: CombinableQuery<SqlType = Self::SqlType>; fn union(self, query: U) -> Self::Output; } impl<T, U> UnionDsl<U> for T where T: CombinableQuery, U: CombinableQuery<SqlType = T::SqlType> { type Output = UnionQuery<T, U>; fn union(self, other: U) -> Self::Output { UnionQuery::new(self, other) } }