text
stringlengths
8
4.13M
use clap::{crate_version, App, Arg}; /// Creates a static clap application for parsing the arguments pub fn get_app() -> clap::App<'static> { let default_exec = if cfg!(windows) { "start" } else if cfg!(macos) { "open" } else { "xdg-open" }; App::new("fuzzy-pdf") .version(crate_version!()) .author("MarioJim <mario.emilio.j@gmail.com>") .about("Fuzzy finder for a collection of pdf files") .arg( Arg::new("PATH") .about("The path to recursively search for pdf files") .default_value(".") .index(1), ) .arg( Arg::new("COMMAND") .about("The command to execute when an item has been selected") .long_about(COMMAND_LONG_ABOUT) .default_value(default_exec) .index(2), ) .arg( Arg::new("hidden") .about("Search hidden files also") .short('H') .long("hidden"), ) .arg( Arg::new("context") .about("Surrounding lines to show in the preview") .short('c') .long("context") .takes_value(true), ) .arg( Arg::new("max-pages") .about("Only parse documents with at most this number of pages. Pass '0' to parse documents with any number of pages") .short('m') .long("max-pages") .takes_value(true), ) .arg( Arg::new("quiet") .about("Omit printing error messages") .short('q') .long("quiet"), ) } static COMMAND_LONG_ABOUT: &str = "After selecting a file, use \ this option to either: - Pass a '-' to print the file path to stdout (pair this with -q \ option for better results) - Pass a string with placeholders to be executed. You can use {} \ or {f} to pass the file path, and {q} for the query typed into the \ search box. If you don't use any placeholders, the string will be \ appended with the file path and executed. If you don't pass this argument, the program will open the pdf in \ the system's default pdf viewer, using 'start' for Windows, 'open' \ for MacOS, and 'xdg-open' for anything else.";
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt, ByteOrder}; use super::*; use super::sodium; use std::io::{Read, Write}; use openssl; use std::cmp::min; use std::num::Wrapping; use algorithm::*; use encoding::{ReadValue, WriteValue}; pub enum PublicKey { RSAEncryptSign(openssl::crypto::rsa::RSA), Ed25519(sodium::ed25519::OwnedPublicKey), } pub enum SecretKey { RSAEncryptSign(openssl::crypto::rsa::RSA), Ed25519 { pk: sodium::ed25519::OwnedPublicKey, sk: sodium::ed25519::OwnedSecretKey, }, } pub enum Key { Public(PublicKey), Secret(SecretKey), } impl Key { pub fn unwrap_secret(&self) -> &SecretKey { match self { &Key::Secret(ref k) => k, _ => panic!("This key is not a secret key") } } pub fn unwrap_public(&self) -> &PublicKey { match self { &Key::Public(ref k) => k, _ => panic!("This key is not a public key") } } } fn write_rsa_public_key<W: Write>(w: &mut W, k: &openssl::crypto::rsa::RSA) -> Result<(), Error> { try!(w.write_u8(PublicKeyAlgorithm::RSAEncryptSign as u8)); let n = k.n().unwrap(); let e = k.e().unwrap(); let n_v = n.to_vec(); let e_v = e.to_vec(); try!(w.write_mpi(n.num_bits() as usize, &n_v)); try!(w.write_mpi(e.num_bits() as usize, &e_v)); Ok(()) } fn write_ed25519_public_key<W: Write>(w: &mut W, k: &sodium::ed25519::OwnedPublicKey) -> Result<(), Error> { try!(w.write_u8(PublicKeyAlgorithm::Ed25519 as u8)); try!(w.write_u8(ED25519_OID.len() as u8)); try!(w.write(ED25519_OID)); let mut mpi = [0; 33]; mpi[0] = 0x40; (&mut mpi[1..]).clone_from_slice(k); try!(w.write_mpi(263, &mpi)); Ok(()) } const PK_VERSION: u8 = 4; const ED25519_OID: &'static [u8] = &[43, 6, 1, 4, 1, 218, 71, 15, 1]; // Public key packets. impl PublicKey { pub fn read(body: &mut &[u8]) -> Result<(u32, PublicKey), Error> { // signature::read(p.body, contents).unwrap() let version = try!(body.read_u8()); assert_eq!(version, PK_VERSION); let creation_time = try!(body.read_u32::<BigEndian>()); let algo = try!(PublicKeyAlgorithm::from_byte(try!(body.read_u8()))); match algo { PublicKeyAlgorithm::Ed25519 => { // https://trac.tools.ietf.org/id/draft-koch-eddsa-for-openpgp-04.html let oid_len = try!(body.read_u8()) as usize; let (oid, b) = body.split_at(oid_len); *body = b; assert_eq!(oid, ED25519_OID); let mut pk = try!(body.read_mpi()); assert_eq!(try!(pk.read_u8()), 0x40); Ok((creation_time, PublicKey::Ed25519(sodium::ed25519::PublicKey(pk).to_owned()))) } PublicKeyAlgorithm::RSAEncryptSign => { use openssl::crypto::rsa::*; use openssl::bn::BigNum; let n = try!(body.read_mpi()); let n = try!(BigNum::new_from_slice(n)); let e = try!(body.read_mpi()); let e = try!(BigNum::new_from_slice(e)); Ok((creation_time, PublicKey::RSAEncryptSign(try!(RSA::from_public_components(n, e))))) } p => Err(Error::UnsupportedPublicKey(p)), } } pub fn write<W: Write>(w: &mut W, k: &PublicKey, creation_time: u32) -> Result<(), Error> { try!(w.write_u8(PK_VERSION)); try!(w.write_u32::<BigEndian>(creation_time)); match *k { PublicKey::RSAEncryptSign(ref k) => try!(write_rsa_public_key(w, k)), PublicKey::Ed25519(ref k) => try!(write_ed25519_public_key(w, k)), } Ok(()) } } fn generate_key(hash_algo: HashAlgorithm, salt: &[u8], c: u8, password: &[u8]) -> Vec<u8> { debug!("generate_key: {:?} {:?} {:?}", salt, c, password); let c = c as u32; let count = (16 + (c & 15)) << ((c >> 4) + 6); let count = count as usize; let mut s = salt.to_vec(); s.extend(password); use openssl::crypto::hash::{Hasher, Type}; let mut hasher = match hash_algo { HashAlgorithm::SHA1 => Hasher::new(Type::SHA1), HashAlgorithm::SHA256 => Hasher::new(Type::SHA256), _ => unimplemented!(), }; hasher.write(&s).unwrap(); let mut byte_count = s.len();; while byte_count < count - s.len() { hasher.write_all(&s).unwrap(); byte_count += s.len() } let s = &s[0..min(s.len(), count - byte_count)]; hasher.write_all(&s).unwrap(); hasher.finish() } // Secret key packets. impl SecretKey { pub fn read<'a>(body: &mut &'a [u8], password: &[u8]) -> Result<(u32, SecretKey), Error> { let (creation_time, public_key) = try!(PublicKey::read(body)); let string_to_key = try!(body.read_u8()); if string_to_key >= 0xfe { let sym_algo = try!(SymmetricKeyAlgorithm::from_byte(try!(body.read_u8()))); match sym_algo { SymmetricKeyAlgorithm::AES128 => {} _ => unimplemented!(), } match try!(body.read_u8()) { 0 => { // simple s2k unimplemented!() } 1 => unimplemented!(), 3 => { let hash_algo = try!(HashAlgorithm::from_byte(try!(body.read_u8()))); match hash_algo { HashAlgorithm::SHA1 | HashAlgorithm::SHA256 => {} _ => unimplemented!(), } let (salt, b) = body.split_at(8); *body = b; let c = try!(body.read_u8()); let key = generate_key(hash_algo, salt, c, password); let v = { use openssl::crypto::symm::*; let (iv, b) = body.split_at(16); *body = b; decrypt(Type::AES_128_CFB128, &key[0..16], &iv, body) }; let mut s = &v[..]; if string_to_key == 0xfe { use openssl::crypto::hash::{hash, Type}; let (a, b) = s.split_at(s.len() - 20); assert_eq!(b, &hash(Type::SHA1, a)[..]) } else { let mut checksum: Wrapping<u16> = Wrapping(0); let (a, mut b) = s.split_at(s.len() - 2); for &byte in a { checksum += Wrapping(byte as u16) } assert_eq!(checksum.0, try!(b.read_u16::<BigEndian>())) } match public_key { PublicKey::RSAEncryptSign(ref pk) => { use openssl::crypto::rsa::RSA; use openssl::bn::BigNum; let d = BigNum::new_from_slice(try!(s.read_mpi())).unwrap(); let p = BigNum::new_from_slice(try!(s.read_mpi())).unwrap(); let q = BigNum::new_from_slice(try!(s.read_mpi())).unwrap(); let _ = try!(s.read_mpi()); let mut p_1 = p.clone(); p_1.sub_word(1).unwrap(); let dp = d.checked_nnmod(&p_1).unwrap(); let mut q_1 = q.clone(); q_1.sub_word(1).unwrap(); let dq = d.checked_nnmod(&q_1).unwrap(); let di = q_1.checked_mod_inv(&p).unwrap(); Ok((creation_time, SecretKey::RSAEncryptSign( RSA::from_private_components( pk.n().unwrap(), pk.e().unwrap(), d, p, q, dp, dq, di ).unwrap() ))) } PublicKey::Ed25519(pk) => { let sk = try!(s.read_mpi()); Ok((creation_time, SecretKey::Ed25519 { sk: sodium::ed25519::SecretKey(sk).to_owned(), pk: pk, })) } } } _ => unimplemented!(), } } else { // cleartext secret key. unimplemented!() } } pub fn write<W: Write>(&self, w: &mut W, creation_time: u32, algo: SymmetricKeyAlgorithm, password: &[u8]) -> Result<(), Error> { let hash_algorithm = HashAlgorithm::SHA256; // Public key try!(w.write_u8(PK_VERSION)); try!(w.write_u32::<BigEndian>(creation_time)); match *self { SecretKey::RSAEncryptSign(ref k) => try!(write_rsa_public_key(w, k)), SecretKey::Ed25519 { ref pk, .. } => try!(write_ed25519_public_key(w, pk)), } // Secret key try!(w.write_u8(0xfe)); try!(w.write_u8(algo as u8)); try!(w.write_u8(3)); // iterated salted try!(w.write_u8(hash_algorithm as u8)); let mut c = [0; 9 + 16]; sodium::randombytes::into(&mut c); c[8] |= 0x80; // large enough count. try!(w.write(&c)); let key = generate_key(hash_algorithm, &c[..8], c[8], password); let mut body = Vec::new(); match *self { SecretKey::RSAEncryptSign(ref k) => { let d = k.d().unwrap(); let p = k.p().unwrap(); let q = k.q().unwrap(); let u = p.checked_mod_inv(&q).unwrap(); try!(body.write_mpi(d.num_bits() as usize, &d.to_vec())); try!(body.write_mpi(p.num_bits() as usize, &p.to_vec())); try!(body.write_mpi(q.num_bits() as usize, &q.to_vec())); try!(body.write_mpi(u.num_bits() as usize, &u.to_vec())); } SecretKey::Ed25519 { ref sk, .. } => { try!(body.write(sk)); } } let digest = { use openssl::crypto::hash::{hash, Type}; hash(Type::SHA1, &body) }; body.extend(&digest); use openssl::crypto::symm::*; try!(w.write(&encrypt(Type::AES_128_CFB128, &key[0..16], &c[9..], &body))); Ok(()) } }
use nix::unistd::{Gid, Uid}; use std::fs::File; use std::io::{self, BufRead}; #[derive(Clone)] pub struct User { pub name: String, pub password: String, pub uid: Uid, pub gid: Gid, pub sgids: Vec<Gid>, pub comment: String, pub home: String, pub shell: String, } macro_rules! system { ($p:expr) => { use nix::NixPath; $p.with_nix_path(|t| unsafe { libc::system(t.as_ptr()); }); }; } impl User { pub fn find_user(uid: Uid, gid: Gid) -> io::Result<User> { let users = User::parse_from_file("/etc/passwd")?; let groups = Group::parse_from_file("/etc/group")?; if let Some(match_user) = users.iter().find(|user| user.uid == uid && user.gid == gid) { let mut user = match_user.clone(); user.sgids = groups .iter() .filter(|g| g.users.contains(&user.name)) .map(|g| g.gid) .collect(); Ok(user) } else { Err(io::Error::from(io::ErrorKind::NotFound)) } } pub fn parse_from_file(passwd_path: &str) -> io::Result<Vec<User>> { let mut result: Vec<User> = Vec::new(); let file = File::open(passwd_path)?; for line in io::BufReader::new(file).lines() { let ok_line = line?; let splitted: Vec<&str> = ok_line.split(":").collect(); if splitted.len() != 7 { continue; } result.push(User { name: String::from(splitted[0]), password: String::from(splitted[1]), uid: match splitted[2].parse::<libc::uid_t>() { Ok(uid) => Uid::from_raw(uid), Err(_) => { return Err(io::Error::new( io::ErrorKind::InvalidData, "expect integral", )) } }, gid: match splitted[3].parse::<libc::gid_t>() { Ok(gid) => Gid::from_raw(gid), Err(_) => { return Err(io::Error::new( io::ErrorKind::InvalidData, "expect integral", )) } }, sgids: vec![], // TODO comment: String::from(splitted[4]), home: String::from(splitted[5]), shell: String::from(splitted[6]), }); } Ok(result) } } pub struct Group { pub name: String, pub password: String, pub gid: Gid, pub users: Vec<String>, } impl Group { pub fn parse_from_file(group_path: &str) -> io::Result<Vec<Group>> { let mut result: Vec<Group> = Vec::new(); let file = File::open(group_path)?; for line in io::BufReader::new(file).lines() { let ok_line = line?; let splitted: Vec<&str> = ok_line.split(":").collect(); if splitted.len() != 4 { continue; } result.push(Group { name: String::from(splitted[0]), password: String::from(splitted[1]), gid: match splitted[2].parse::<libc::gid_t>() { Ok(gid) => Gid::from_raw(gid), Err(_) => { return Err(io::Error::new( io::ErrorKind::InvalidData, "expect integral", )) } }, users: String::from(splitted[3]) .split(":") .map(|s| String::from(s)) .collect::<Vec<String>>(), }); } Ok(result) } }
use crate::doctor::Doctor; use crate::error::AppError; use crate::tickets::Ticket; use actix_session::Session; use actix_web::{get, post, web, HttpResponse, Result}; use deadpool_postgres::Client; use deadpool_postgres::Pool; use scrypt::{scrypt_check, scrypt_simple, ScryptParams}; use serde::Deserialize; use serde_json::json; pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(login); cfg.service(get_me); cfg.service(logout); } pub async fn create_user(db_conn: &Client, password: &str) -> Result<i32, AppError> { let params = ScryptParams::new(15, 8, 1).unwrap(); let hashed_password = scrypt_simple(password, &params).expect("OS RNG should not fail"); let sql = "INSERT into users (hsecret) values ($1) RETURNING id"; let row = db_conn.query_one(sql, &[&hashed_password]).await?; let id: i32 = row.get("id"); Ok(id) } #[get("/api/v2/me")] async fn get_me(db_pool: web::Data<Pool>, session: Session) -> Result<HttpResponse, AppError> { let id: Option<i32> = session.get("azap")?; let location: Option<i32> = session.get("azap-location")?; let doctor: Option<i32> = session.get("azap-doctor")?; let db_conn = db_pool.get().await?; let doctors: Vec<Doctor> = if location.is_some() { db_conn .query("SELECT * from doctors where location_id=$1", &[&location]) .await? .iter() .map(|row| row.into()) .collect() } else { vec![] }; let tickets: Vec<Ticket> = if location.is_some() && doctor.is_some() { db_conn .query( "SELECT * from tickets where location_id=$1 and doctor_id=$2", &[&location.unwrap(), &doctor.unwrap()], ) .await? .iter() .map(|row| row.into()) .collect() } else if location.is_some() && doctor.is_none() { db_conn .query( "SELECT * from tickets where location_id=$1", &[&location.unwrap()], ) .await? .iter() .map(|row| row.into()) .collect() } else { vec![] }; if id.is_some() { Ok(HttpResponse::Ok().json(json!({ "status": "sucess", "id": id, "locationId":location, "doctorId":doctor, "doctors":doctors, "tickets":tickets }))) } else { Ok(HttpResponse::Unauthorized() .json(json!({ "status": "error", "error":"invalid session" }))) } } #[derive(Deserialize)] struct Identity { secret: String, id: i32, } #[post("/api/v2/login")] async fn login( user: web::Json<Identity>, db_pool: web::Data<Pool>, session: Session, ) -> Result<HttpResponse, AppError> { let user = user.into_inner(); let id = user.id; let db_conn = db_pool.get().await?; let row = db_conn .query_one("SELECT id,hsecret from users where id=$1", &[&id]) .await?; let id: i32 = row.get("id"); let hsecret: String = row.get("hsecret"); if scrypt_check(&user.secret, &hsecret).is_ok() { session.set("azap", id)?; //check if is location let res = db_conn .query("SELECT id from locations where id=$1", &[&id]) .await?; if !res.is_empty() { let id: i32 = res[0].get("id"); session.set("azap-location", id)?; } // check if is doctor let res = db_conn .query("SELECT id from doctors where id=$1", &[&id]) .await?; if !res.is_empty() { let id: i32 = res[0].get("id"); session.set("azap-doctor", id)?; } session.renew(); return Ok(HttpResponse::Ok().json(json!({"status": "sucess","id": id}))); } session.purge(); Ok(HttpResponse::Unauthorized().json(json!({"error": "error"}))) } #[post("/api/v2/logout")] async fn logout(session: Session) -> Result<HttpResponse, AppError> { let id: Option<i32> = session.get("azap")?; if id.is_some() { session.remove("azap"); Ok(HttpResponse::Ok().json(json!({ "status": "sucess" }))) } else { Ok(HttpResponse::Ok().json(json!({ "status": "error" }))) } }
pub struct ProcessedRoute { pub head: String, pub tail: Option<String> } pub fn process_route(route: String) -> Option<ProcessedRoute> { if route.len() == 0 { return None } let mut split = route.split("/"); match split.next() { Some(head) => { match split.next() { Some(tail) => { let mut joined = tail.to_owned(); for part in split { joined = format!("{}/{}", joined, part); } if head == "" { return process_route(joined) } Some(ProcessedRoute { head: head.to_owned(), tail: Some(joined) }) }, None => Some(ProcessedRoute { head: head.to_owned(), tail: None }) } }, None => None } }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ pub trait Scratch { fn clear(&mut self); }
use std::collections::HashMap; fn main() { let input ="F6J)1YB 6LV)SG3 K7G)GD2 JC1)Y2W 43D)SP2 YQV)JKG TD4)7SZ H8T)43D T1S)H8Y 1BW)H7F PDV)93Q 2HK)Z93 37L)1FF 35Y)MZH 7NY)DWF YLS)5B6 N66)QLD T9K)TMS JZF)7TC 9QD)YRG 5T2)CYY DBP)FG7 JVN)N7N Q78)K9T 6CZ)D66 WD3)LNP 7YB)Y9T Z3S)115 2PD)RC7 XZS)DZD PCP)3YG QYH)3CV F3M)1SZ 37W)C4L W1Y)T5F S9V)TD7 L52)81R 7F1)45V 858)YN9 4JB)RMY NL4)F8R V6D)KPP ZMR)KXH X7Y)N3G TRT)W5B FHH)MNV 725)W9Y QYG)D7S LQX)ZQK KTL)G6X Z93)GZS W28)BFC PR1)9B6 MNX)Y76 YZG)1WK X6S)H9M GPY)HLS 7XR)G7Q 5B1)MVF 3GK)XTS KFK)36G 5B6)PD9 TL4)NXV 265)84G Z5T)B78 JBB)LG9 GLM)1H1 H6F)P9N DZP)MFM ZNL)FHH QRZ)M8Q QQ6)1KW SG3)GPW D85)QX4 W85)Y98 4SF)R39 7RL)54X GX8)6QS MD4)6ZK 5ST)NHM 6GS)9G6 6M7)8FF GZS)XFJ NHM)SMF Y8X)KTL V8R)9N5 PVX)G41 JP5)TRV 29T)LVJ B78)9FH HGW)MXC D3K)PX5 BMQ)7KP 5FP)CSK X7T)2JP TD7)5BW 9BG)2LR DQS)FKY XZC)W1J 3LR)DVC FMK)3WS Y7C)177 C7X)LSN HG3)SZM P9N)KNV YW9)WL7 MD7)XZC RC1)S1N M8Q)LDZ 23V)ZPH NR2)WYF VN8)2XR 44R)KH9 BHZ)ZMG G89)38T 8CC)6VK 7YS)3LL KZG)V5V G1B)GNM KPP)64T B8P)W9T 2VT)FL6 WWC)Y6F KHT)GHX 83D)NZK 64T)JD7 VVL)7RB 3WK)1NW H36)Z4K 8L8)M2Y 7R5)RSS N8V)V8G NG4)YKB SHH)PVX PN2)2L5 ZRT)J2C LDZ)73H CSK)H47 QDB)9W9 2D4)26N YJT)7YS DX8)X7Y MW3)6YY TLC)KJM B58)5XY Q6R)WXJ P8F)QNY Y6F)JWT CRD)FVT KLW)TMQ 9M1)TWB NHZ)3CS 9ZL)CRD R9H)HM1 YD5)TX1 FPR)4P4 GR6)T1S 7NZ)X1G WJZ)4LY QCG)D3G 685)PTQ FZJ)4NP 56S)78G CC7)ZWF XBT)7ZQ BH3)MRP 2W1)P61 QS6)M4N X2P)Y28 5TG)VW5 DM7)893 X2P)JY1 XKV)WLK XFJ)QP3 PNH)7GL DNH)FPN ZTK)9H9 FFN)M3W FZR)741 54S)C1Z S2M)ZNL 7DW)TWY FKY)RLH SKG)KLW ML8)6PR PS2)FS6 WSV)R4R MYQ)3JX ZYP)LRB 96X)Q7Z 7M9)RC1 QKQ)QYH TPB)YHM TX1)4PK X9Q)3RC ZZ3)ZJT HF3)HPL ZPH)G7G T6N)QG1 ZJT)FVH J2L)DT4 6LP)HKV TJJ)83L CNH)6M7 B55)V2V 1TK)FGT NLQ)968 37H)F7V SZM)XKV 5ZF)JL1 2C6)YVD Y55)H3N TJZ)R1D F79)NJT XC3)QTM 1RX)WMY L5N)ZTK N43)TSG PFC)61H WD7)WH2 11D)68G NXV)84Z NMG)MNX LRZ)N31 8PQ)MJC W15)WZ3 V5H)21N DXX)Z79 L8M)57F GYD)WQ6 4FH)P7L W3L)1M2 F7V)Y3L 64K)6LP GBK)J1M GNM)BMQ FMP)H36 865)ZMW 5ZH)931 4P4)2DN 7PT)DM7 F4X)1VY BSM)JWV V1J)W15 HGW)SS8 JK5)MD5 Z79)WQZ 1V6)PN2 3Z1)VQR G2B)333 C5D)F3M W5B)RBC 3R9)C7X 115)5JK KMG)9G9 DYR)1QX GLR)KNJ C59)W28 V5M)FMP DGY)LQN WVY)JLW 376)YJT LBK)ZCV JWD)YPX 98D)CWQ P3H)9ZL VJG)596 R62)QDK KC6)5B1 WDF)MN4 4D8)K74 BXF)6RY FNX)SKG FPN)2DB 3KH)H87 YFW)FVN 8JS)6J8 C4G)MMV TD3)FGL 1TX)Z9M 18G)Y55 RCS)ZMR 4F2)CNX YKP)54S RWG)4DH RR7)JQL N6H)3YV BLL)PCP DJP)MJR 7ZK)4HV 9H6)BMX DT4)GK5 WYF)P59 QPX)NKZ 177)BMY LHK)4ZZ HN7)JWD 1TL)RX6 WD5)SNT R4R)CVL 4JN)DC9 JXW)1RX VBR)99Q T53)KLR 5T1)7HH 6MH)3H4 HHN)PHL BNM)RJ4 7XM)QYG V9L)TJN Y79)BSP LLF)5KJ VS5)5S9 DJY)KTQ Q57)37H HPL)9M1 YWN)YTR FW4)8Y4 T4F)NHZ WQ6)61N 8LF)BVP 5MQ)Z5F KG5)N99 NZK)YNY 8FM)9ZM 27V)C2V VXT)KMG 5W6)B2N X2R)VJT JQL)J91 YWP)89X T42)V5M 2Z2)H63 GXJ)YWN JJG)L7H S3V)TL4 RFC)4LJ YD5)QJ5 TNW)BWL 1B9)7NZ P8G)6D1 YVD)BGV GXX)RR7 C8W)CFB YHM)J4D FZX)SFP D5S)FS2 FZC)YGK PJL)Z8G SF6)YG5 R42)414 57F)SF6 LRD)F9T 6YV)75H 1NW)ZK6 XN5)9HM MN4)TRT DKG)NF8 6PN)PS2 Y76)CNS XWF)85R D63)J9M 235)CYJ 414)R62 NQM)9JM D9V)JP5 LVJ)WTF D94)RYS 6H7)DHN RBW)B1W 7SS)S2M GT8)278 PWL)L9V MXC)3K6 7HB)Q9M 9L5)DYR TMS)4MC 9XQ)TD3 65K)Q6R LTG)ZF1 WKK)RX3 ST3)6K3 YS6)7ZK G9C)8YP GHB)8Y6 PP4)QDD QLD)7CF QMG)KNS WZ3)F31 PS3)KFB FQC)YS2 HM1)T68 VYS)PDD J8S)GR9 BWS)7M9 7RM)9QD DWM)MFX RQK)X2P RGF)9FR 9KL)L48 7FG)PS3 2V1)7BJ TFW)X4T WHD)7ZF YNY)72H 78D)9MZ LG9)YBL 5BT)725 6B1)81D MPD)MZN KJM)YLS XTS)GBK MD5)RDS 2QV)8P3 45V)LTG 8KR)GYW H9J)7V5 MJL)FFN 5SB)JD3 L7N)GDY J1M)HSF FVN)LTQ NCN)T2H R3X)C1Q YFJ)S54 WXJ)HN7 38T)JNF 9RM)RBN WCP)9M8 PZ9)BB4 RBM)9X7 CGM)8PQ GQG)5G9 968)D3N YKB)C59 JWT)MLP RDD)XNY KLR)S9V COM)LGH LY2)JC8 S6Z)LRG WTX)7DF HN7)BY5 8CC)NL4 655)TWM 6JV)NH2 GRG)SV3 5G8)NRZ XG9)172 6GG)B7D QCK)2RJ NY3)QKQ TRV)KVC B92)83D V21)Z1S 3LP)18M 3BX)LTN 3YV)VZZ 829)SS6 4SM)H6F CCF)DZP MBJ)SLW XS2)V5H HVR)4BC R23)XZV 931)XGD 5DZ)W1N 3RB)VKY JD3)F1W B99)4F4 464)12L 9DV)2Z2 YTR)6J7 2VY)N86 4F4)NXW 6V5)YFW KQP)BKJ 9H9)G91 KC6)4W2 7Q8)YOU 1M2)88F 9G4)JPD 9QD)YVF T1S)DYD NJ7)4SF M94)3PJ 8GS)5JW 5G9)W7W GPW)LN8 SDN)K7G 16X)CHH 1GQ)4KJ SM5)6M4 D3N)31J R9B)QBF MVF)L7T JPR)K1B J6L)CC7 92N)BSM TT5)RHW NMF)18G LTQ)LLF 9WS)9XQ BMX)B5V 73P)8NF SS8)JQT NRF)JBB L6D)SDN 6NX)QYW VWR)G9C 4WL)KV4 YN9)D9V X1G)6YW XJV)NGK ZSN)9H6 14S)9J3 Z9M)CZW CYJ)FBT 347)WBN JS9)6LX DD2)293 738)7JR V5V)5ZF 9FR)C5D 12L)VS5 84T)CR1 RN6)M5N 4W2)YWG PXL)1B1 Q6R)7JF PFK)Y79 TT2)7NM WZ3)WD3 26C)X4J PJL)69B HJS)G95 W9T)H1W TSN)6PN PF1)NLV 7YL)VCS 52Q)G6P 3BZ)QS6 7KD)T6N 21X)MGN 5JV)DL7 ZPR)2C6 NYH)NPD CGG)NG4 K8K)CKJ 1ZC)Y7C NH2)HGW YBW)5MR 7NM)T1J X6H)DNH TZ2)C13 F5G)VBR WDX)K2S 486)858 76P)TNG C4G)D5S D4D)TSN QX4)493 VQR)KKK BJS)CM6 QX7)RCS M15)7PT KHD)F3B 4F2)49P RP2)KSN F9L)FZC WXV)LRZ M2Y)BHZ XNY)DWM D82)GMP BHQ)GT8 5T1)XP9 3JX)BPM 38R)CS7 X4J)DTZ X94)9WS MGN)WKQ 9GV)TLC 8BX)TKM ZRT)HXH J4D)JK5 2B9)3RB 6B8)GHJ 16W)7XR PD7)32Q CNS)KQP WZ7)5SB CFB)K8H LWS)2M1 2WF)G4B BSP)J48 QYF)F9L GD2)1TK BFC)8FM 21N)4D8 4W5)7Z9 T68)C3N GNY)X93 KSX)ZYP ZYZ)LTW 37L)PP4 KDG)2B9 LRB)4WL HNZ)BX5 2LR)MJL GGB)THL DLV)C3M 1V8)WDX 9MZ)FR7 NZ7)L5N NRZ)GLM TKM)7YB 8SW)7Q8 KV4)4FH MC8)SVW 8SW)5KB RMY)X6L 3PB)XBQ RMW)5BT BB4)VVL F3S)TPB BFG)KYX 3CV)F4K B15)7PY G4Y)JVN P7L)Y3K QTM)98D D28)5TG C1Z)J2L VY2)V36 V1J)GW9 CKJ)WTX LSN)TW9 CNX)ZHM 5Q7)1MV MZN)4BX H78)LSH G7G)YXK 3HB)ZZN ZRB)FW4 D69)6JD PCN)MQH N8C)TZ2 KNJ)HWR MYQ)265 37S)GPY 7RB)B7Q 6YW)BKS W2L)LXD 73H)K2H G7G)1Q8 J2C)6GM 7ZF)ZRT CWJ)7NY 3F6)CNH VQB)D63 596)31R SLW)FLV Y3L)MYQ XB2)FF3 8HQ)S2H Z1S)NKR 8MX)HTX N84)F6J 4WK)R1B DPG)78D K2S)8GS VVB)63J 8CT)9F1 RNS)RY9 FGT)DN2 TWB)PYS NVD)Z6T 7XM)R3X R14)SBV 8Y4)Z5T J48)PFC Z5F)GRG Z9R)X6H SQX)8Q3 D5F)M7V BX5)1G1 D82)RP2 N31)KWX 14J)BXB SH6)41V J6L)X9Q XVS)S88 4KH)D85 72S)WMH 1K1)G4Y MBZ)T4F DYD)P8V BBZ)GW2 FQC)S5H TX1)WHD R4T)N8L KH9)6GZ R1B)77D JC8)3N6 C13)VV9 4PK)S33 KG5)6LV 9ZM)F5N WMS)X6D H8Y)BLL NQH)W66 N8L)FZJ YG5)5RN TWM)LHK DPD)DLV Q9M)6LG 4PQ)PZD DHN)SB4 X43)9L5 X9C)8W5 8KJ)GQG CVY)F5Y T5F)QPX 5F5)SQX 2XR)YBW RY9)5R2 54K)CWR KRD)BTB YTY)NVP 6J7)KX5 3LL)L7N 1FP)LBK V3R)K3Q G2B)B62 K8H)MBJ 7TC)BJX C8V)R14 1KW)L21 ZB2)JPR P3W)C8V GQ4)TT2 TWV)HBK 2XR)QJP L8J)FNX K14)KWL F4J)KHT 49P)56S GMT)K4S FZ1)NSY QYW)RMW FVK)F3S Q7Z)RGF Q44)23V C3K)TPY 5RN)D7B QBN)11W 1S1)QVG MFM)D7G W4H)4CN JVJ)4GB 1KQ)P1B W4H)35Y J4B)RFC T95)RDF Q9G)NYH Y28)RTL WWL)363 6DT)9YR G95)G4J R4S)YFL C1Q)MC8 7DJ)72S 55B)5ZD 9R7)8VZ 9VH)JS9 41M)N43 KSN)6B8 RYS)1BW 5LY)88G ZHD)CY2 4MC)P3H YFL)PW3 69B)5DZ S1X)LBB B7D)PDF 9HM)S3V WH2)M94 PX5)29T K2N)TZT VK9)VN8 JNF)3KH DN2)H8F 8W4)FQ9 ZVB)B8W FZX)5T1 X3Q)T42 3YT)21X NGK)KFG G91)8R2 8LS)C9P 6LG)N8C JJZ)BJS TNG)829 493)P7G WLK)CWJ 4BX)G2B 81R)SNG ZK6)SCN L9D)7F1 S88)3Z1 53D)ZJV 6RY)PBD 8W5)2VL JL1)MBZ RJ4)RFX LRG)QSB QP3)HG3 HXH)DX8 4MC)R2C NRZ)1LK H9V)347 9N5)YRH RWG)MKC 9G6)Z9R 3CS)FMK 5LF)JS8 5S9)MXQ D7S)3WK K3Q)HVR DVC)DWN 3WS)WWC F9T)2V1 GRP)4JN 3R9)2PD 4GB)WTB H47)76P WHM)R21 FR7)14H 5WP)64K HLS)K14 LD6)KSX NQM)9NM NKR)DG3 WTB)ZRB BVS)TCC 5JK)1ZC GNV)ZHD M7V)8CC ZZN)9BG C3S)2YC RQW)TFW QG1)QM6 D85)D3K BCP)1TX 1XP)HF3 5LY)RN6 FZJ)37S KF3)73P MMV)55B 835)DBP KFG)WKW 7BL)7VX G6P)VP8 5H3)L8M J91)3B5 1QX)3BX QNC)PK6 MBC)BD3 Y9T)3F6 3N6)YS6 7SZ)3LP XXH)655 C44)J3G ZWF)41D H7F)TK6 ZLD)5Q7 JWV)835 78K)ML8 LWR)1TL GMJ)53D ZNL)486 SBH)DY6 3LR)8LF 7Y3)7KK 6M4)JMM PD9)GV9 CY2)XQP ZYP)ZP9 5GV)CKM M6M)FK8 SCN)GRN PFK)JT8 C13)B92 QDX)JJZ HJ8)QRZ W7J)J4G 6YY)TRH XCD)L8J 5MP)5N5 TMQ)9DV SNV)65K SWZ)TYL HWR)K2N PZD)CJ3 CYY)PXW 414)TWR 63J)X9C W85)S8Z VV9)LRD VQY)MW3 H6M)QCK PTQ)R29 688)YFJ CC8)KF3 YRG)KZG PBQ)XB2 9M8)WYD Y3K)4JW 9FH)H9J QPX)VK9 68G)9HZ FVC)JWR H1M)8KJ BTB)FPR 6LX)ZLT 83L)7LJ ZP9)CLH 246)MZ9 ZQK)246 LTW)LVK 88F)JNT BXB)2VM 2TW)PZM BQX)CGG WKW)WDF PPH)GYD RTL)B99 J9M)M6P LGH)BNM MBQ)16W G7Q)1XP LBB)XVS FS2)P68 L9V)85V 3PJ)RWJ HX4)8HQ FGD)3CR D66)GXX 41V)T3N RY5)2C9 DX6)J5T TWR)8KR KNV)VTM 2D4)92N MZH)4H8 KTQ)VY2 6JD)BBZ 741)7BD C2V)VQB 7Z9)NQH LL9)B14 32Q)BBM W2L)YZG 6ZK)RNQ WWM)376 XQP)DXX 1LK)DW8 FQ9)6XK YPX)5ZH ZWX)8SW 1SJ)9L7 QY1)CGM 9NM)V8R 1K5)2VT GRN)256 CFK)HJ8 V36)3BM 18M)LWS 1FP)PFK 2Y4)BD2 WQ6)QSK VTM)FCP GW9)ZWX QNY)SJG T3N)5W6 L56)QFS L7T)WKK JPD)7RM 4GB)153 7VX)RQQ FKT)ZZ3 YGK)HZY Z65)PBQ MJC)CGN PCN)5GV V2V)2D4 R29)V97 C4L)DC5 26N)8JS 1VY)4KH 56S)FGD QDK)G71 5KB)W2L XN5)J2D THL)HHN YJ6)NCN BT7)YVH DWF)V1J P1B)FQC 256)1XN CS7)D53 NF8)B23 JPV)8J4 8Z8)GLR LG9)9G4 N99)44R 3BM)8BX QL6)16H CR1)KRC VW5)1K1 L7H)2W1 GYH)ZSN XNT)ZM7 THL)L5C KPP)5FP CM6)J9S RBM)VXT 5H6)JFH 8YP)ZB2 2M1)FVK K9N)YYN G4J)LY2 7LJ)DRS JFH)7FG R42)89T KQR)182 BGV)CCF 7HS)3P9 CWR)BBG C3N)GNY 2V3)3R9 331)PWL GYW)5N2 CW1)T56 7MF)F4J 97J)14J LSH)426 W1N)8Z8 K14)ZNJ ZJV)DJY 7KK)V6D M5N)2Y4 TYL)8TY Y4K)78K S2H)PP3 LNH)YYR PDF)97J NSY)2V3 WKT)F7Q V4Z)PD7 ZPM)K5Z QJ5)7MF C3M)ZPR 4DH)MBC 426)JXW F5N)PJL 6GZ)6GS ZRH)G1B KTQ)3PB KMG)F56 JQT)C3K HKV)SWQ 4JW)XR4 5NY)P8G 7H5)7DW 1Q8)464 CDP)SBH FMH)8MX H1W)WJZ DC5)HJS J2D)3LR K4S)L56 SVW)XR9 RFX)G59 KRC)ZLD JRP)6MH 5FP)KQD JF8)M6M DGY)5H3 5R2)1B9 3N6)VJG 2TY)N3Q TD3)J3X J4G)5MP 52D)6NX R4P)L52 Z8G)4F2 L5C)37W NVP)FZ1 1RX)3ZH LPL)6DT 278)9Z7 M3W)W4H 84Z)Z51 RSS)KC6 7JF)11D ZV3)QYF TCC)L9D 1V6)C4G XZV)LQX 8TY)N8B 13W)R23 Y6S)8KQ LXD)1S1 85V)PNB SNT)JPV 153)FZX 1G1)NR2 KVC)VY8 641)8RG 1HG)CDY BK1)Q9G W67)WZ5 ZPH)GYH W9Y)GRP BKS)V4Z NZ7)SNV NTK)XCY 9D1)26C HZY)5F5 WYD)GT3 MZ9)JJX QDD)P3W X4T)13K P2J)N84 YWG)22P VJW)39N 14H)LPL 293)VQY FJY)C1P JMM)K4H 6GM)27M BBM)LGD ZF1)V7T G41)XR2 JVN)FYP WQ2)YQV LN8)BQY 17R)TR1 4H8)W85 1WK)B8P QPD)7Y3 6J8)XCD 21L)NZV PC7)KQR DL7)HK6 B62)NQM CGM)D94 RLH)TT5 ZDK)J6L 32P)96X T1J)5H6 B2D)4JB VV7)6WC QTM)VWR ZXS)9GV 7ZQ)8L4 Z51)685 G71)H6M JBB)37L 3CR)B58 HNC)T1P 89T)ZJ8 RBC)CFK 7V5)SWZ 5XY)54K YYN)VTX KYX)7KD D94)LL9 FVH)KHD B78)89G 8FF)NLQ TQB)6V7 Z3Q)MD4 WL7)3GK 6K3)NWK TLK)PCN 3M1)GMJ Y79)C1G RBN)52Q JS8)TCF VVL)XS2 H9M)FMB Z6Y)768 J3G)3M1 M6P)XBP 2VL)KRD 439)R4S 5ZF)QDX TK6)TNW PY2)439 1XN)BXF WS3)YWP 11W)SCQ 9HZ)JZF 8T4)WDD SFP)XBT PHL)15K YSL)R36 F1W)CVY YS6)M15 1SJ)RQK CJ3)6GG 1MV)PXL 8W5)KBF 6GS)641 L6M)4PQ WWZ)WWM M4Y)3CY CKM)NMG C1G)Y6S ZLT)QNC WSB)TWV H8F)D5F DG3)NVD RC7)6CZ 9Z7)X13 5TG)V25 KFB)27V 4HV)6JV P68)TJZ 2SX)KCP QM6)FR2 2Y1)H6S RDF)GGB XBQ)N62 ZMW)RNS DTZ)WHM F4K)VB9 W66)1HG C1G)FJV CWQ)7R5 61N)WS3 CLH)H9V P3W)DD2 7GG)ZBZ PXW)DQ8 GDY)2WF KNS)X3Q 6WC)BFG 9MT)XH8 KBF)6H7 V97)Z4D QJP)3BF KWX)DPD FS6)7SP N3G)4WK NSY)VV7 4V5)F79 11D)2SX 6NX)FMH MQH)VYS SV3)RY5 FJV)GLS WDD)NX5 FT7)NRF GT3)2VY PW3)5LF H6S)X43 18X)XC3 MJR)Y8X TKM)KFK Y9D)WZ7 9B6)GQ4 4HV)X2R NWK)5WP XGD)MXK JT8)MJX P8V)W1Y 6B1)TQB J5T)PJD RQQ)QCG PNH)FJY ZKC)8T4 TW9)17R 8L3)M4Y K2H)FKT N7N)YYX 3H4)X94 4CN)2TW XKQ)WFS R23)T9K YVF)ZKC BD2)QBN QSK)5VG DW8)V3R N3Q)PPH FYP)GMT 1P7)L6D 8J4)F5G 8Y6)RQW N8V)M2J ZM7)HDW XG9)3YT 9G6)T53 P7G)38R C9P)9D1 XM5)WBJ FVT)ST3 NX5)YKP 8R2)4SM LCL)8CT WCP)5JM 221)J18 MLP)N6H 18X)K9N 393)GDS 182)Z3Q WMY)WGJ 9JM)QQ6 FZZ)RDD 6YW)CDP 9X7)VGQ PK6)41M 8P3)YD5 9SV)W3L M4N)W67 F7Q)ZRH VCS)P2J QSB)T95 NXW)MG7 SS6)HNS V8G)R4P 2DB)BVL 7DF)WMS 6QS)RGC 9D1)865 54X)JF8 81D)FZZ 172)Y9D 8VZ)WSB GDS)M14 MG7)P8F 7RB)H1M TPY)XXH 9L7)VVB BD3)ZPM 369)13W TRH)MD7 MFX)QMG 8KQ)FZR LXP)XN5 BVP)H78 P5T)SP4 Z6T)4V5 KYX)PDV NZV)1MW 9YR)ZKH M2J)QY1 6V7)5T2 W9H)SAN BZX)7RL QQ6)52D HBK)9KL 78K)XJV NKZ)X7T Z51)C44 JWR)BHQ JLW)CVV 9RM)N8V WRL)6V5 BBL)DGZ PJD)DJP RX3)KDG XR9)D69 2Y4)YW9 TJN)7RC CHH)SQL 72H)WCP M14)16J 2N2)XM5 TWY)XZS JD7)R9H 6XK)738 YRH)18X CZW)LCL K1B)ZV3 BQY)W1L 61H)ZVB YYR)XG9 WBN)4W5 N62)BBL 5LL)KG5 7LX)DR3 KQD)C7V 5ZD)CW1 2L5)MPD F8R)X6S QVG)21L KHD)SNC 7SP)N9L J9S)7HS 8NF)2TY GHJ)9SV C7V)3HB JKG)1P7 7KP)V21 YBL)2QV HTX)TJJ V7T)LXP DX6)JWZ RNQ)TD4 333)Z65 768)16X 7L5)WX7 6VK)1SJ 39N)WRL R5R)RBW YW1)JJG SP2)2N2 GV9)WL6 P59)JGV PDF)G89 NDD)WVY 2JP)MZW QJP)7SS WL6)VJW B2N)B55 BBZ)H8T PYS)DGY BPM)HS8 5MR)RYC FLV)K8K SNG)YSL ZJ8)8L3 WGJ)DX6 MNV)H27 7JR)NZ7 GLS)YJ6 3RC)NJ7 FJV)R42 B7D)SM5 WQZ)D4D KKK)7L5 78G)K9D XP9)1FP ZV6)F4X FGL)2Y1 VP8)M93 5SB)38X RN3)N66 CDY)LWR WMH)L6M KX5)5G8 JWZ)W7J DR3)SH6 5N5)5NY ZHM)MBQ K4H)YTY 4LJ)14S PMB)2HK MRP)C8W 27M)CC8 PDD)JYW 1FF)GR6 KXH)BZ1 7RC)1GQ FMB)PNH MJX)1V6 BBG)QK6 V25)J4B PP3)PC7 D7B)WSV 3B5)PR1 7BD)XVB N9L)8L8 61H)DQS K9D)1V8 LQN)393 89X)BK1 B14)ZYZ 4KJ)NRK ZCV)FVC X6D)WQ2 13K)7LX 7Z9)RWG 1YB)BH3 6MH)3ZT XR2)6B1 3P9)H4S SBV)SHH XM2)1K5 VB9)NMF 2RJ)HHB 89G)QDB TD4)9R7 L21)BT7 9G9)LNH G59)FFQ SWQ)XWF FBT)688 FFQ)JVJ D7G)GHB K9T)7YL MKC)235 5JM)WD5 SMF)TLK F31)9MT 8LF)BQX 5N2)4QW 2VM)R4T FMK)HH2 W1N)Q44 JY1)7HB 8L4)B2D CVL)7H5 SHH)GKP TSG)FT7 WBJ)G1Z HS8)5JV BY5)RBM LNP)PZ9 3BF)WD7 RDS)5ST JYW)LD6 XBP)XNT 7HH)84T 93Q)1S2 ZV3)9RM J3X)Y36 LD6)S1X JWZ)NDD TZT)8LS W7W)P5T K5Z)ZXS WZ5)7GG ZMG)QL4 HDW)JC1 GK5)NTK VCS)V9L VZZ)QPD FL6)BZX SNC)HNC S6Z)Q57 FZC)BVS S5H)GNV T8B)5MQ FF3)BWS SCQ)PF1 41D)3Y2 Z4D)Y4K FCP)DPG N9L)J8S H63)GXJ T9K)S6Z BWL)DKG PZM)JRP SP4)WWL ZKH)PMB DVC)5LL LVK)QL6 PBD)2C2 Y98)8W4 1SZ)ZV6 SNC)331 R2C)W9H KWL)NY3 893)221 DZD)32P T1P)WKT C1P)BCP 5KJ)R9B YWN)369 FK8)9VH 31R)R5R 38X)Z6Y S8Z)PY2 S33)RN3 16J)D28 JRP)T8B 77D)1XW K4H)3BZ DWN)GX8 QBF)WXV 31J)7BL Y2W)D82 WTF)Q78 VTX)5LY 75H)WWZ 9VH)YW1 S54)XKQ BZ1)7DJ DGZ)7XM MXQ)B15 HH2)1KQ N86)QX7 FPR)ZDK 2C2)HX4 YYX)Z3S GMP)XM2 F56)C3S 3YG)ZGD 7YS)HNZ B2D)6YV R36)S8M"; println!("total orbits: {}", total_orbits(input)); } fn total_orbits(input: &str) -> i32 { // Build a hash map of orbiter to their parent orbitee // Sum up total, using: // For each hash map pair: // count 1 for direct orbit // count 1 for each indirect orbit // First build an array of direct orbits let mut direct_orbits: HashMap<String, String> = HashMap::new(); for orbit_string in input.split("\n") { let mut input_parts = orbit_string.split(")"); let orbitee = input_parts.next().expect("Invalid input").to_string(); let orbiter = input_parts.next().expect("Invalid input").to_string(); direct_orbits.insert(orbiter, orbitee); } let direct_and_indirect_orbit_counts = direct_orbits.values().map(|orbitee| { let mut direct_and_indirect_orbit_count = 1; let mut current_orbitee = orbitee.clone(); while let Some(indirect_orbitee) = direct_orbits.get(&current_orbitee) { direct_and_indirect_orbit_count += 1; current_orbitee = indirect_orbitee.to_string(); } return direct_and_indirect_orbit_count; }); return direct_and_indirect_orbit_counts.sum(); } #[cfg(test)] mod tests { use super::*; #[test] fn test_example_one() { let input = "COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L"; let answer = total_orbits(input); assert_eq!(answer, 42); } }
use crate::error::*; use crate::file::*; use crate::tables::*; use winmd_macros::*; #[type_code(2)] pub enum TypeDefOrRef { TypeDef, TypeRef, TypeSpec, } #[type_code(5)] pub enum HasCustomAttribute { MethodDef, Field, TypeRef, TypeDef, Param, InterfaceImpl, MemberRef, TypeSpec = 13, GenericParam = 19, } #[type_code(3)] pub enum MemberRefParent { TypeDef, TypeRef, MethodDef = 3, TypeSpec, } #[type_code(2)] pub enum HasConstant { Field, Param, } #[type_code(3)] pub enum CustomAttributeType { MethodDef = 2, MemberRef, } impl<'a> TypeDefOrRef<'a> { pub fn name(&'a self) -> ParseResult<&'a str> { match self { Self::TypeDef(value) => value.name(), Self::TypeRef(value) => value.name(), Self::TypeSpec(_) => panic!("Cannot call name() function on a TypeSpec"), } } pub fn namespace(&'a self) -> ParseResult<&'a str> { match self { Self::TypeDef(value) => value.namespace(), Self::TypeRef(value) => value.namespace(), Self::TypeSpec(_) => panic!("Cannot call namespace() function on a TypeSpec"), } } } impl<'a> std::fmt::Display for TypeDefOrRef<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TypeDefOrRef::TypeDef(value) => write!(f, "{}.{}", value.namespace()?, value.name()?), TypeDefOrRef::TypeRef(value) => write!(f, "{}.{}", value.namespace()?, value.name()?), TypeDefOrRef::TypeSpec(_) => panic!("Cannot format a TypeSpec"), } } }
// =============================================================================================== // Imports // =============================================================================================== use super::{PMM, Page, Frame}; use core::ops::{Index, IndexMut}; use core::ptr::Unique; use x86::current::paging::*; use x86::shared::control_regs::{cr3, cr3_write}; // =============================================================================================== // Extern Labels // =============================================================================================== extern "C" { fn page_map_level4(); } // =============================================================================================== // Constants // =============================================================================================== /// Recursive mapped PageMapLevel4 Table pub const P4: Unique<L4Table> = unsafe { Unique::new(0xffffffff_fffff000 as *mut _) }; /// Kernel map created on boot const KERNEL_MAP: Unique<L4Table> = unsafe { Unique::new(page_map_level4 as *mut _) }; // =============================================================================================== // Page Map Level 4 (512GiB) // =============================================================================================== pub struct L4Table(PML4); impl L4Table { // ---------------------------------------------------- // Init Table // ---------------------------------------------------- pub fn init(page: &mut Page) { // Clone Kernel PML4 let kmap = KERNEL_MAP; let ktable = unsafe { kmap.get() }; let table = page.get_mut::<L4Table>(); for index in 0..511 { table[0][index] = ktable[index]; } // Reverse Map table[0][511] = PML4Entry::new(PAddr::from_u64(page.paddr() as u64), PML4_P | PML4_RW); // Remove User Space Tables table[0][1].remove(PML4_P); table[0][257].remove(PML4_P); } // ---------------------------------------------------- // Cleanup Usperspace Tables // ---------------------------------------------------- pub fn user_cleanup() { // Get active table let p4 = P4; let table = unsafe { p4.get() }; // Check and clean user space tables if table[1].contains(PML4_P) { // Cleanup table.l3_mut(1).unwrap().cleanup(); // Free memory by dropping a Frame Frame { paddr: table[1].get_address(), size: BASE_PAGE_SIZE as usize, }; } if table[257].contains(PML4_P) { // Cleanup table.l3_mut(1).unwrap().cleanup(); // Free memory by dropping a Frame Frame { paddr: table[1].get_address(), size: BASE_PAGE_SIZE as usize, }; } } // ---------------------------------------------------- // Level 3 Getter // ---------------------------------------------------- pub fn l3(&self, index: usize) -> Option<&L3Table> { assert!(index < 512); if self.0[index].contains(PML4_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &*(address as *const _) }) } else { None } } pub fn l3_mut(&self, index: usize) -> Option<&mut L3Table> { assert!(index < 512); if self.0[index].contains(PML4_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &mut *(address as *mut _) }) } else { None } } pub fn l3_mut_or_new(&mut self, index: usize) -> &mut L3Table { assert!(index < 512); if self.0[index].contains(PML4_P) == false { let frame = PMM.write().alloc_static(BASE_PAGE_SIZE as usize).expect("Out of memory!"); self.0[index] = PML4Entry::new(frame.0, PML4_P | PML4_RW); self.l3_mut(index).expect("Failed to add new L3Table").zero() } else { self.l3_mut(index).expect("Failed to add new L3Table") } } // ---------------------------------------------------- // Activate // ---------------------------------------------------- pub unsafe fn activate(&self) -> &'static L4Table { // Get current table let current = cr3(); // Check if inactive if self.0[511].get_address().as_u64() as usize != cr3() { // Activate debug!("Switch to {:016x} L4Table", self.0[511].get_address()); cr3_write(self.0[511].get_address().as_u64() as usize); } &*(current as *const _) } pub unsafe fn activate_kernel_map() -> &'static L4Table { let kmap = KERNEL_MAP; let ktable = kmap.get(); // Get current table let current = cr3(); // Check if kernel is inactive if ktable[511].get_address().as_u64() as usize != current { // Activate debug!("Switch to {:016x} L4Table (K)", ktable[511].get_address()); cr3_write(ktable[511].get_address().as_u64() as usize); } &*(current as *const _) } } impl Index<usize> for L4Table { type Output = PML4Entry; fn index(&self, index: usize) -> &PML4Entry { &self.0[index] } } impl IndexMut<usize> for L4Table { fn index_mut(&mut self, index: usize) -> &mut PML4Entry { &mut self.0[index] } } // =============================================================================================== // Page Directory Pointer (1GiB) // =============================================================================================== pub struct L3Table(PDPT); impl L3Table { // ---------------------------------------------------- // Level 2 Getter // ---------------------------------------------------- pub fn l2(&self, index: usize) -> Option<&L2Table> { assert!(index < 512); if self.0[index].contains(PDPT_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &*(address as *const _) }) } else { None } } pub fn l2_mut(&self, index: usize) -> Option<&mut L2Table> { assert!(index < 512); if self.0[index].contains(PDPT_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &mut *(address as *mut _) }) } else { None } } pub fn l2_mut_or_new(&mut self, index: usize) -> &mut L2Table { assert!(index < 512); if self.0[index].contains(PDPT_P) == false { let frame = PMM.write().alloc_static(BASE_PAGE_SIZE as usize).expect("Out of memory!"); self.0[index] = PDPTEntry::new(frame.0, PDPT_P | PDPT_RW); self.l2_mut(index).expect("Failed to add new L2Table").zero() } else { self.l2_mut(index).expect("Failed to add new L2Table") } } // ---------------------------------------------------- // Zero // ---------------------------------------------------- pub fn zero(&mut self) -> &mut L3Table { for index in 0..512 { self[index] = PDPTEntry::from_bits_truncate(0); } self } // ---------------------------------------------------- // Cleanup Table // ---------------------------------------------------- fn cleanup(&mut self) { for index in 0..512 { if self.0[index].contains(PDPT_P) { // Cleanup self.l2_mut(index).unwrap().cleanup(); // Free memory by dropping a Frame Frame { paddr: self.0[index].get_address(), size: BASE_PAGE_SIZE as usize, }; } } } } impl Index<usize> for L3Table { type Output = PDPTEntry; fn index(&self, index: usize) -> &PDPTEntry { &self.0[index] } } impl IndexMut<usize> for L3Table { fn index_mut(&mut self, index: usize) -> &mut PDPTEntry { &mut self.0[index] } } // =============================================================================================== // Page Directory (2MiB) // =============================================================================================== pub struct L2Table(PD); impl L2Table { // ---------------------------------------------------- // Level 1 Getter // ---------------------------------------------------- pub fn l1(&self, index: usize) -> Option<&L1Table> { assert!(index < 512); if self.0[index].contains(PD_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &*(address as *const _) }) } else { None } } pub fn l1_mut(&self, index: usize) -> Option<&mut L1Table> { assert!(index < 512); if self.0[index].contains(PD_P) { let address = ((self as *const _ as usize) << 9) | (index << 12); Some(unsafe { &mut *(address as *mut _) }) } else { None } } pub fn l1_mut_or_new(&mut self, index: usize) -> &mut L1Table { assert!(index < 512); if self.0[index].contains(PD_P) == false { let frame = PMM.write().alloc_static(BASE_PAGE_SIZE as usize).expect("Out of memory!"); self.0[index] = PDEntry::new(frame.0, PD_P | PD_RW); self.l1_mut(index).expect("Failed to add new L1Table").zero() } else { self.l1_mut(index).expect("Failed to add new L1Table") } } // ---------------------------------------------------- // Zero // ---------------------------------------------------- pub fn zero(&mut self) -> &mut L2Table { for index in 0..512 { self[index] = PDEntry::from_bits_truncate(0); } self } // ---------------------------------------------------- // Cleanup Table // ---------------------------------------------------- fn cleanup(&mut self) { for index in 0..512 { // Large Pages getting freed by Page -> Frame dropping if self.0[index].contains(PD_P) && !self.0[index].contains(PD_PS) { // Dont need to cleanup l1 as it is the same as a large page in l2 // Free memory by dropping a Frame Frame { paddr: self.0[index].get_address(), size: BASE_PAGE_SIZE as usize, }; } } } } impl Index<usize> for L2Table { type Output = PDEntry; fn index(&self, index: usize) -> &PDEntry { &self.0[index] } } impl IndexMut<usize> for L2Table { fn index_mut(&mut self, index: usize) -> &mut PDEntry { &mut self.0[index] } } // =============================================================================================== // Page Table (4KiB) // =============================================================================================== pub struct L1Table(PT); impl L1Table { // ---------------------------------------------------- // Zero // ---------------------------------------------------- pub fn zero(&mut self) -> &mut L1Table { for index in 0..512 { self[index] = PTEntry::from_bits_truncate(0); } self } } impl Index<usize> for L1Table { type Output = PTEntry; fn index(&self, index: usize) -> &PTEntry { &self.0[index] } } impl IndexMut<usize> for L1Table { fn index_mut(&mut self, index: usize) -> &mut PTEntry { &mut self.0[index] } }
fn main() { another_function(5); print_labeled_measurement(5, 'h'); let r = five(); println!("The value of r is: {r}"); } fn another_function(x: i32) { println!("The value of x is: {x}"); } fn print_labeled_measurement(value: i32, unit_label: char) { println!("The measurement is: {value}{unit_label}"); } fn five() -> i32 { let x = { let y = 4; y + 1 }; x } fn six() -> i32 { 6 }
pub mod toml; pub mod dependencies;
use std::io::stdin; fn main() { exec("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."); } fn exec(code: &str) { let mut memory: [u8; 30000] = [0; 30000]; let mut pointer: usize = 0; let code_arr = code_to_char_array(code); let mut i = 0; while i < code_arr.len() { let current = code_arr[i]; match current { '>' => ptr_right(&mut pointer), '<' => ptr_left(&mut pointer), '+' => inc_at_pointer(&pointer, &mut memory), '-' => dec_at_pointer(&pointer, &mut memory), '.' => output(&pointer, &memory), ',' => input(&pointer, &mut memory), '[' => jmp_past(&pointer, &mut memory, &code_arr, &mut i), ']' => jmp_back(&pointer, &mut memory, &code_arr, &mut i), _ => (), } i += 1; } } fn code_to_char_array(code: &str) -> Vec<char> { code.chars().collect() } fn ptr_right(ptr: &mut usize) { *ptr += 1; } fn ptr_left(ptr: &mut usize) { *ptr -= 1; } fn inc_at_pointer(ptr: &usize, mem: &mut [u8]) { mem[*ptr] += 1; } fn dec_at_pointer(ptr: &usize, mem: &mut [u8]) { mem[*ptr] -= 1; } fn output(ptr: &usize, mem: &[u8]) { print!("{}", mem[*ptr] as char); } fn input(ptr: &usize, mem: &mut [u8]) { let mut input = String::new(); stdin().read_line(&mut input).expect("Incorrect input"); let input = input.chars().nth(0).unwrap(); mem[*ptr] = input as u8; } fn jmp_past(ptr: &usize, mem: &[u8], arr: &Vec<char>, i: &mut usize) { if mem[*ptr] == 0 { let mut non_closing_braces = 0; for j in *i + 1..arr.len() - 1 { let current = arr[j]; match current { '[' => non_closing_braces += 1, ']' => { if non_closing_braces > 0 { non_closing_braces -= 1; } else { *i = j; break; } } _ => (), } } } } fn jmp_back(ptr: &usize, mem: &[u8], arr: &Vec<char>, i: &mut usize) { if mem[*ptr] != 0 { let mut non_opening_braces = 0; for j in (0..*i - 1).rev() { let current = arr[j]; match current { ']' => non_opening_braces += 1, '[' => { if non_opening_braces > 0 { non_opening_braces -= 1; } else { *i = j; break; } } _ => (), } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_code_to_char_array() { let code = "++<."; let expected = vec!['+', '+', '<', '.']; assert_eq!(expected, code_to_char_array(code)); } #[test] fn test_ptr_right() { let mut pointer: usize = 0; ptr_right(&mut pointer); assert_eq!(1, pointer); } #[test] fn test_ptr_left() { let mut pointer: usize = 1; ptr_left(&mut pointer); assert_eq!(0, pointer); } #[test] fn test_inc_at_pointer() { let mut pointer: usize = 0; let mut memory: [u8; 30000] = [0; 30000]; inc_at_pointer(&mut pointer, &mut memory); assert_eq!(1, memory[0]); } #[test] fn test_dec_at_pointer() { let mut pointer: usize = 0; let mut memory: [u8; 30000] = [1; 30000]; dec_at_pointer(&mut pointer, &mut memory); assert_eq!(0, memory[0]); } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SyntheticsCiTestMetadata : Metadata for the Synthetics tests run #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyntheticsCiTestMetadata { #[serde(rename = "ci", skip_serializing_if = "Option::is_none")] pub ci: Option<Box<crate::models::SyntheticsCiTestMetadataCi>>, #[serde(rename = "git", skip_serializing_if = "Option::is_none")] pub git: Option<Box<crate::models::SyntheticsCiTestMetadataGit>>, } impl SyntheticsCiTestMetadata { /// Metadata for the Synthetics tests run pub fn new() -> SyntheticsCiTestMetadata { SyntheticsCiTestMetadata { ci: None, git: None, } } }
extern crate csv; extern crate elma; use WR; use Targets; use DataRow; use std::io::prelude::*; use elma::Time; pub fn read_targets_table() -> Vec<Targets> { let mut tst = Vec::new(); let mut r = csv::Reader::from_file("targets.csv").unwrap(); for record in r.records() { if let Ok(row) = record { tst.push(Targets { godlike: Time::from(&row[0]), legendary: Time::from(&row[1]), world_class: Time::from(&row[2]), professional: Time::from(&row[3]), good: Time::from(&row[4]), ok: Time::from(&row[5]), beginner: Time::from(&row[6]), }); } } tst } pub fn read_wr_tables() -> Vec<WR> { let mut wrt = Vec::new(); let mut r = csv::Reader::from_file("2018-04-19_elma_wrs.csv").unwrap(); for record in r.records() { let row = record.unwrap(); wrt.push(WR { table: row[0].parse::<i32>().unwrap(), lev: row[1].parse::<i32>().unwrap(), time: Time::from(&row[3]), kuski: row[4].to_string(), }); } wrt } pub fn read_state() -> Result<Vec<Time>, elma::ElmaError> { let mut prt = Vec::new(); let state = elma::state::State::load("state.dat")?; for lev in state.times.iter().take(54) { if let Some(t) = lev.single.first() { prt.push(t.time); } else { prt.push(Time::from("10:00,00")) } } Ok(prt) } pub fn populate_table_data(pr_table: &[Time], wr_tables: &[WR]) -> Vec<DataRow> { let mut data: Vec<DataRow> = Vec::new(); let level_names = vec![ "Warm Up", "Flat Track", "Twin Peaks", "Over and Under", "Uphill Battle", "Long Haul", "Hi Flyer", "Tag", "Tunnel Terror", "The Steppes", "Gravity Ride", "Islands in the Sky", "Hill Legend", "Loop-de-Loop", "Serpents Tale", "New Wave", "Labyrinth", "Spiral", "Turnaround", "Upside Down", "Hangman", "Slalom", "Quick Round", "Ramp Frenzy", "Precarious", "Circuitous", "Shelf Life", "Bounce Back", "Headbanger", "Pipe", "Animal Farm", "Steep Corner", "Zig-Zag", "Bumpy Journey", "Labyrinth Pro", "Fruit in the Den", "Jaws", "Curvaceous", "Haircut", "Double Trouble", "Framework", "Enduro", "He He", "Freefall", "Sink", "Bowling", "Enigma", "Downhill", "What the Heck", "Expert System", "Tricks Abound", "Hang Tight", "Hooked", "Apple Harvest", ]; for (i, lev_name) in level_names.iter().enumerate() { //this if is unnecessary but ... let t = if i < pr_table.len() { pr_table[i] } else { Time::from("10:00,00") }; let lev = i as i32 + 1; let last_wr_beat = wr_tables .iter() .filter(|x| (x.lev == lev) && (t <= x.time)) .last(); let first_wr_not_beat = wr_tables .iter() .filter(|x| (x.lev == lev) && !(t <= x.time)) .nth(0); data.push(DataRow { lev_number: lev, lev_name: lev_name.to_string(), pr: t, wr_beat: last_wr_beat.cloned(), wr_not_beat: first_wr_not_beat.cloned(), }); } data } pub fn read_stats() -> Vec<Time> { let mut prt = Vec::new(); let mut f = ::std::fs::File::open("stats.txt").expect("Cannot open file: stats.txt"); let mut c = String::new(); f.read_to_string(&mut c) .expect("Cannot read file: stats.txt"); let mut level_counter = 0; let mut level_found = false; for line in c.lines() { let mut data: Vec<&str> = line.trim().split_whitespace().collect(); if data.len() != 0 && level_found { prt.push(Time::from(data[0].as_ref())); level_counter += 1; level_found = false; } if data.len() != 0 && data[0] == "Level" { level_found = true; } if level_counter == 54 { break; } } prt }
use std::collections::BTreeSet; use std::fmt; use std::path::{Path, PathBuf}; use anyhow::Result; use clap::{ArgAction, Parser, ValueEnum}; use fs_err as fs; use crate::build_options::find_bridge; use crate::project_layout::ProjectResolver; use crate::{BridgeModel, CargoOptions}; /// CI providers #[derive(Debug, Clone, Copy, ValueEnum)] #[clap(rename_all = "lower")] pub enum Provider { /// GitHub GitHub, } /// Platform #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] #[clap(rename_all = "lower")] pub enum Platform { /// All All, /// Linux Linux, /// Windows Windows, /// macOS Macos, /// Emscripten Emscripten, } impl Platform { fn defaults() -> Vec<Self> { vec![Platform::Linux, Platform::Windows, Platform::Macos] } fn all() -> Vec<Self> { vec![ Platform::Linux, Platform::Windows, Platform::Macos, Platform::Emscripten, ] } } impl fmt::Display for Platform { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Platform::All => write!(f, "all"), Platform::Linux => write!(f, "linux"), Platform::Windows => write!(f, "windows"), Platform::Macos => write!(f, "macos"), Platform::Emscripten => write!(f, "emscripten"), } } } /// Generate CI configuration #[derive(Debug, Parser)] pub struct GenerateCI { /// CI provider #[arg(value_enum, value_name = "CI")] pub ci: Provider, /// Path to Cargo.toml #[arg(short = 'm', long, value_name = "PATH")] pub manifest_path: Option<PathBuf>, /// Output path #[arg(short = 'o', long, value_name = "PATH", default_value = "-")] pub output: PathBuf, /// Platform support #[arg( id = "platform", long, action = ArgAction::Append, num_args = 1.., default_values_t = vec![Platform::Linux, Platform::Windows, Platform::Macos], )] pub platforms: Vec<Platform>, /// Enable pytest #[arg(long)] pub pytest: bool, /// Use zig to do cross compilation #[arg(long)] pub zig: bool, } impl Default for GenerateCI { fn default() -> Self { Self { ci: Provider::GitHub, manifest_path: None, output: PathBuf::from("-"), platforms: vec![Platform::Linux, Platform::Windows, Platform::Macos], pytest: false, zig: false, } } } impl GenerateCI { /// Execute this command pub fn execute(&self) -> Result<()> { let conf = self.generate()?; self.print(&conf) } /// Generate CI configuration pub fn generate(&self) -> Result<String> { let cargo_options = CargoOptions { manifest_path: self.manifest_path.clone(), ..Default::default() }; let ProjectResolver { cargo_metadata, pyproject_toml, project_layout, .. } = ProjectResolver::resolve(self.manifest_path.clone(), cargo_options)?; let pyproject = pyproject_toml.as_ref(); let bridge = find_bridge(&cargo_metadata, pyproject.and_then(|x| x.bindings()))?; let project_name = pyproject .and_then(|project| project.project_name()) .unwrap_or(&project_layout.extension_name); let sdist = pyproject_toml.is_some(); match self.ci { Provider::GitHub => self.generate_github(project_name, &bridge, sdist), } } pub(crate) fn generate_github( &self, project_name: &str, bridge_model: &BridgeModel, sdist: bool, ) -> Result<String> { let is_abi3 = matches!(bridge_model, BridgeModel::BindingsAbi3(..)); let is_bin = bridge_model.is_bin(); let setup_python = self.pytest || matches!( bridge_model, BridgeModel::Bin(Some(_)) | BridgeModel::Bindings(..) | BridgeModel::BindingsAbi3(..) | BridgeModel::Cffi | BridgeModel::UniFfi ); let mut gen_cmd = std::env::args() .enumerate() .map(|(i, arg)| { if i == 0 { env!("CARGO_PKG_NAME").to_string() } else { arg } }) .collect::<Vec<String>>() .join(" "); if gen_cmd.starts_with("maturin new") || gen_cmd.starts_with("maturin init") { gen_cmd = format!("{} generate-ci github", env!("CARGO_PKG_NAME")); } let mut conf = format!( "# This file is autogenerated by maturin v{version} # To update, run # # {gen_cmd} # name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs:\n", version = env!("CARGO_PKG_VERSION"), ); let mut needs = Vec::new(); let platforms: BTreeSet<_> = self .platforms .iter() .flat_map(|p| { if matches!(p, Platform::All) { if !bridge_model.is_bin() { Platform::all() } else { Platform::defaults() } } else { vec![*p] } }) .collect(); for platform in &platforms { if bridge_model.is_bin() && matches!(platform, Platform::Emscripten) { continue; } let plat_name = platform.to_string(); let os_name = match platform { Platform::Linux | Platform::Emscripten => "ubuntu", _ => &plat_name, }; needs.push(platform.to_string()); conf.push_str(&format!( " {plat_name}: runs-on: {os_name}-latest\n" )); // target matrix let targets = match platform { Platform::Linux => vec!["x86_64", "x86", "aarch64", "armv7", "s390x", "ppc64le"], Platform::Windows => vec!["x64", "x86"], Platform::Macos => vec!["x86_64", "aarch64"], _ => Vec::new(), }; if !targets.is_empty() { conf.push_str(&format!( " strategy: matrix: target: [{targets}]\n", targets = targets.join(", ") )); } // job steps conf.push_str( " steps: - uses: actions/checkout@v3\n", ); // install pyodide-build for emscripten if matches!(platform, Platform::Emscripten) { // install stable pyodide-build conf.push_str(" - run: pip install pyodide-build\n"); // get the current python version for the installed pyodide-build conf.push_str( " - name: Get Emscripten and Python version info shell: bash run: | echo EMSCRIPTEN_VERSION=$(pyodide config get emscripten_version) >> $GITHUB_ENV echo PYTHON_VERSION=$(pyodide config get python_version | cut -d '.' -f 1-2) >> $GITHUB_ENV pip uninstall -y pyodide-build\n", ); conf.push_str( " - uses: mymindstorm/setup-emsdk@v12 with: version: ${{ env.EMSCRIPTEN_VERSION }} actions-cache-folder: emsdk-cache\n", ); conf.push_str( " - uses: actions/setup-python@v4 with: python-version: ${{ env.PYTHON_VERSION }}\n", ); // install pyodide-build again in the right Python version conf.push_str(" - run: pip install pyodide-build\n"); } else { // setup python on demand if setup_python { conf.push_str( " - uses: actions/setup-python@v4 with: python-version: '3.10'\n", ); if matches!(platform, Platform::Windows) { conf.push_str(" architecture: ${{ matrix.target }}\n"); } } } // build wheels let mut maturin_args = if is_abi3 || (is_bin && !setup_python) { Vec::new() } else if matches!(platform, Platform::Emscripten) { vec!["-i".to_string(), "${{ env.PYTHON_VERSION }}".to_string()] } else { vec!["--find-interpreter".to_string()] }; if let Some(manifest_path) = self.manifest_path.as_ref() { if manifest_path != Path::new("Cargo.toml") { maturin_args.push("--manifest-path".to_string()); maturin_args.push(manifest_path.display().to_string()) } } if self.zig && matches!(platform, Platform::Linux) { maturin_args.push("--zig".to_string()); } let maturin_args = if maturin_args.is_empty() { String::new() } else { format!(" {}", maturin_args.join(" ")) }; let maturin_target = if matches!(platform, Platform::Emscripten) { "wasm32-unknown-emscripten" } else { "${{ matrix.target }}" }; conf.push_str(&format!( " - name: Build wheels uses: PyO3/maturin-action@v1 with: target: {maturin_target} args: --release --out dist{maturin_args} sccache: 'true' " )); if matches!(platform, Platform::Linux) { conf.push_str(" manylinux: auto\n"); } else if matches!(platform, Platform::Emscripten) { conf.push_str(" rust-toolchain: nightly\n"); } // upload wheels let artifact_name = if matches!(platform, Platform::Emscripten) { "wasm-wheels" } else { "wheels" }; conf.push_str(&format!( " - name: Upload wheels uses: actions/upload-artifact@v3 with: name: {artifact_name} path: dist " )); // pytest let mut chdir = String::new(); if let Some(manifest_path) = self.manifest_path.as_ref() { if manifest_path != Path::new("Cargo.toml") { let parent = manifest_path.parent().unwrap(); chdir = format!("cd {} && ", parent.display()); } } if self.pytest { if matches!(platform, Platform::Linux) { // Test on host for x86_64 conf.push_str(&format!( " - name: pytest if: ${{{{ startsWith(matrix.target, 'x86_64') }}}} shell: bash run: | set -e pip install {project_name} --find-links dist --force-reinstall pip install pytest {chdir}pytest " )); // Test on QEMU for other architectures conf.push_str(&format!( " - name: pytest if: ${{{{ !startsWith(matrix.target, 'x86') && matrix.target != 'ppc64' }}}} uses: uraimo/run-on-arch-action@v2.5.0 with: arch: ${{{{ matrix.target }}}} distro: ubuntu22.04 githubToken: ${{{{ github.token }}}} install: | apt-get update apt-get install -y --no-install-recommends python3 python3-pip pip3 install -U pip pytest run: | set -e pip3 install {project_name} --find-links dist --force-reinstall {chdir}pytest " )); } else if matches!(platform, Platform::Emscripten) { conf.push_str( " - uses: actions/setup-node@v3 with: node-version: '18' ", ); conf.push_str(&format!( " - name: pytest run: | set -e pyodide venv .venv source .venv/bin/activate pip install {project_name} --find-links dist --force-reinstall pip install pytest {chdir}python -m pytest " )); } else { conf.push_str(&format!( " - name: pytest if: ${{{{ !startsWith(matrix.target, 'aarch64') }}}} shell: bash run: | set -e pip install {project_name} --find-links dist --force-reinstall pip install pytest {chdir}pytest " )); } } conf.push('\n'); } // build sdist if sdist { needs.push("sdist".to_string()); let maturin_args = self .manifest_path .as_ref() .map(|manifest_path| { if manifest_path != Path::new("Cargo.toml") { format!(" --manifest-path {}", manifest_path.display()) } else { String::new() } }) .unwrap_or_default(); conf.push_str(&format!( r#" sdist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist{maturin_args} "# )); conf.push_str( " - name: Upload sdist uses: actions/upload-artifact@v3 with: name: wheels path: dist ", ); conf.push('\n'); } conf.push_str(&format!( r#" release: name: Release runs-on: ubuntu-latest if: "startsWith(github.ref, 'refs/tags/')" needs: [{needs}] "#, needs = needs.join(", ") )); if platforms.contains(&Platform::Emscripten) { conf.push_str( r#" permissions: # Used to upload release artifacts contents: write "#, ); } conf.push_str( r#" steps: - uses: actions/download-artifact@v3 with: name: wheels - name: Publish to PyPI uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload args: --non-interactive --skip-existing * "#, ); if platforms.contains(&Platform::Emscripten) { conf.push_str( " - uses: actions/download-artifact@v3 with: name: wasm-wheels path: wasm - name: Upload to GitHub Release uses: softprops/action-gh-release@v1 with: files: | wasm/*.whl prerelease: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') }} ", ); } Ok(conf) } fn print(&self, conf: &str) -> Result<()> { if self.output == Path::new("-") { print!("{conf}"); } else { fs::write(&self.output, conf)?; } Ok(()) } } #[cfg(test)] mod tests { use super::GenerateCI; use crate::BridgeModel; use expect_test::expect; #[test] fn test_generate_github() { let conf = GenerateCI::default() .generate_github( "example", &BridgeModel::Bindings("pyo3".to_string(), 7), true, ) .unwrap() .lines() .skip(5) .collect::<Vec<_>>() .join("\n"); let expected = expect![[r#" name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs: linux: runs-on: ubuntu-latest strategy: matrix: target: [x86_64, x86, aarch64, armv7, s390x, ppc64le] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter sccache: 'true' manylinux: auto - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist windows: runs-on: windows-latest strategy: matrix: target: [x64, x86] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' architecture: ${{ matrix.target }} - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist macos: runs-on: macos-latest strategy: matrix: target: [x86_64, aarch64] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist sdist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist - name: Upload sdist uses: actions/upload-artifact@v3 with: name: wheels path: dist release: name: Release runs-on: ubuntu-latest if: "startsWith(github.ref, 'refs/tags/')" needs: [linux, windows, macos, sdist] steps: - uses: actions/download-artifact@v3 with: name: wheels - name: Publish to PyPI uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload args: --non-interactive --skip-existing *"#]]; expected.assert_eq(&conf); } #[test] fn test_generate_github_abi3() { let conf = GenerateCI::default() .generate_github("example", &BridgeModel::BindingsAbi3(3, 7), false) .unwrap() .lines() .skip(5) .collect::<Vec<_>>() .join("\n"); let expected = expect![[r#" name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs: linux: runs-on: ubuntu-latest strategy: matrix: target: [x86_64, x86, aarch64, armv7, s390x, ppc64le] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' manylinux: auto - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist windows: runs-on: windows-latest strategy: matrix: target: [x64, x86] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' architecture: ${{ matrix.target }} - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist macos: runs-on: macos-latest strategy: matrix: target: [x86_64, aarch64] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist release: name: Release runs-on: ubuntu-latest if: "startsWith(github.ref, 'refs/tags/')" needs: [linux, windows, macos] steps: - uses: actions/download-artifact@v3 with: name: wheels - name: Publish to PyPI uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload args: --non-interactive --skip-existing *"#]]; expected.assert_eq(&conf); } #[test] fn test_generate_github_zig_pytest() { let gen = GenerateCI { zig: true, pytest: true, ..Default::default() }; let conf = gen .generate_github( "example", &BridgeModel::Bindings("pyo3".to_string(), 7), true, ) .unwrap() .lines() .skip(5) .collect::<Vec<_>>() .join("\n"); let expected = expect![[r#" name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs: linux: runs-on: ubuntu-latest strategy: matrix: target: [x86_64, x86, aarch64, armv7, s390x, ppc64le] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter --zig sccache: 'true' manylinux: auto - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist - name: pytest if: ${{ startsWith(matrix.target, 'x86_64') }} shell: bash run: | set -e pip install example --find-links dist --force-reinstall pip install pytest pytest - name: pytest if: ${{ !startsWith(matrix.target, 'x86') && matrix.target != 'ppc64' }} uses: uraimo/run-on-arch-action@v2.5.0 with: arch: ${{ matrix.target }} distro: ubuntu22.04 githubToken: ${{ github.token }} install: | apt-get update apt-get install -y --no-install-recommends python3 python3-pip pip3 install -U pip pytest run: | set -e pip3 install example --find-links dist --force-reinstall pytest windows: runs-on: windows-latest strategy: matrix: target: [x64, x86] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' architecture: ${{ matrix.target }} - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist - name: pytest if: ${{ !startsWith(matrix.target, 'aarch64') }} shell: bash run: | set -e pip install example --find-links dist --force-reinstall pip install pytest pytest macos: runs-on: macos-latest strategy: matrix: target: [x86_64, aarch64] steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.10' - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist --find-interpreter sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist - name: pytest if: ${{ !startsWith(matrix.target, 'aarch64') }} shell: bash run: | set -e pip install example --find-links dist --force-reinstall pip install pytest pytest sdist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist - name: Upload sdist uses: actions/upload-artifact@v3 with: name: wheels path: dist release: name: Release runs-on: ubuntu-latest if: "startsWith(github.ref, 'refs/tags/')" needs: [linux, windows, macos, sdist] steps: - uses: actions/download-artifact@v3 with: name: wheels - name: Publish to PyPI uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload args: --non-interactive --skip-existing *"#]]; expected.assert_eq(&conf); } #[test] fn test_generate_github_bin_no_binding() { let conf = GenerateCI::default() .generate_github("example", &BridgeModel::Bin(None), true) .unwrap() .lines() .skip(5) .collect::<Vec<_>>() .join("\n"); let expected = expect![[r#" name: CI on: push: branches: - main - master tags: - '*' pull_request: workflow_dispatch: permissions: contents: read jobs: linux: runs-on: ubuntu-latest strategy: matrix: target: [x86_64, x86, aarch64, armv7, s390x, ppc64le] steps: - uses: actions/checkout@v3 - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' manylinux: auto - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist windows: runs-on: windows-latest strategy: matrix: target: [x64, x86] steps: - uses: actions/checkout@v3 - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist macos: runs-on: macos-latest strategy: matrix: target: [x86_64, aarch64] steps: - uses: actions/checkout@v3 - name: Build wheels uses: PyO3/maturin-action@v1 with: target: ${{ matrix.target }} args: --release --out dist sccache: 'true' - name: Upload wheels uses: actions/upload-artifact@v3 with: name: wheels path: dist sdist: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build sdist uses: PyO3/maturin-action@v1 with: command: sdist args: --out dist - name: Upload sdist uses: actions/upload-artifact@v3 with: name: wheels path: dist release: name: Release runs-on: ubuntu-latest if: "startsWith(github.ref, 'refs/tags/')" needs: [linux, windows, macos, sdist] steps: - uses: actions/download-artifact@v3 with: name: wheels - name: Publish to PyPI uses: PyO3/maturin-action@v1 env: MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} with: command: upload args: --non-interactive --skip-existing *"#]]; expected.assert_eq(&conf); } }
use crate::connection::Throughput; use crate::estimate::{ChangeEstimates, Estimates}; use crate::report::{BenchmarkId, ComparisonData, MeasurementData}; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use linked_hash_map::LinkedHashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::fs::File; use std::path::{Path, PathBuf}; use walkdir::WalkDir; #[derive(Debug)] pub struct Benchmark { pub latest_stats: SavedStatistics, pub previous_stats: Option<SavedStatistics>, pub target: Option<String>, } impl Benchmark { fn new(stats: SavedStatistics) -> Self { Benchmark { latest_stats: stats, previous_stats: None, target: None, } } fn add_stats(&mut self, stats: SavedStatistics) { let previous_stats = std::mem::replace(&mut self.latest_stats, stats); self.previous_stats = Some(previous_stats); } } #[derive(Debug)] pub struct BenchmarkGroup { pub benchmarks: LinkedHashMap<BenchmarkId, Benchmark>, pub target: Option<String>, } impl Default for BenchmarkGroup { fn default() -> Self { BenchmarkGroup { benchmarks: LinkedHashMap::new(), target: None, } } } /// The Model struct stores everything that we keep in-memory about the benchmarks and their /// performance. It's loaded from disk at the beginning of a run and updated as benchmarks /// are executed. #[derive(Debug)] pub struct Model { // Path to output directory data_directory: PathBuf, // Track all of the unique benchmark titles and directories we've seen, so we can uniquify them. all_titles: HashSet<String>, all_directories: HashSet<PathBuf>, // All of the known benchmark groups, stored in execution order (where possible). pub groups: LinkedHashMap<String, BenchmarkGroup>, history_id: Option<String>, history_description: Option<String>, } impl Model { /// Load the model from disk. The output directory is scanned for benchmark files. Any files /// found are loaded into the model so that we can include them in the reports even if this /// run doesn't execute that particular benchmark. pub fn load( criterion_home: PathBuf, timeline: PathBuf, history_id: Option<String>, history_description: Option<String>, ) -> Model { let mut model = Model { data_directory: path!(criterion_home, "data", timeline), all_titles: HashSet::new(), all_directories: HashSet::new(), groups: LinkedHashMap::new(), history_id, history_description, }; for entry in WalkDir::new(&model.data_directory) .into_iter() // Ignore errors. .filter_map(::std::result::Result::ok) .filter(|entry| entry.file_name() == OsStr::new("benchmark.cbor")) { if let Err(e) = model.load_stored_benchmark(entry.path()) { error!("Encountered error while loading stored data: {}", e) } } model } fn load_stored_benchmark(&mut self, benchmark_path: &Path) -> Result<()> { if !benchmark_path.is_file() { return Ok(()); } let mut benchmark_file = File::open(&benchmark_path) .with_context(|| format!("Failed to open benchmark file {:?}", benchmark_path))?; let benchmark_record: BenchmarkRecord = serde_cbor::from_reader(&mut benchmark_file) .with_context(|| format!("Failed to read benchmark file {:?}", benchmark_path))?; let measurement_path = benchmark_path.with_file_name(benchmark_record.latest_record); if !measurement_path.is_file() { return Ok(()); } let mut measurement_file = File::open(&measurement_path) .with_context(|| format!("Failed to open measurement file {:?}", measurement_path))?; let saved_stats: SavedStatistics = serde_cbor::from_reader(&mut measurement_file) .with_context(|| format!("Failed to read measurement file {:?}", measurement_path))?; self.groups .entry(benchmark_record.id.group_id.clone()) .or_insert_with(Default::default) .benchmarks .insert(benchmark_record.id.into(), Benchmark::new(saved_stats)); Ok(()) } pub fn add_benchmark_id(&mut self, target: &str, id: &mut BenchmarkId) { id.ensure_directory_name_unique(&self.all_directories); self.all_directories .insert(id.as_directory_name().to_owned()); id.ensure_title_unique(&self.all_titles); self.all_titles.insert(id.as_title().to_owned()); let group = self .groups .entry(id.group_id.clone()) .or_insert_with(Default::default); if let Some(mut benchmark) = group.benchmarks.remove(id) { if let Some(target) = &benchmark.target { warn!("Benchmark ID {} encountered multiple times. Benchmark IDs must be unique. First seen in the benchmark target '{}'", id.as_title(), target); } else { benchmark.target = Some(target.to_owned()); } // Remove and re-insert to move the benchmark to the end of its list. group.benchmarks.insert(id.clone(), benchmark); } } pub fn benchmark_complete( &mut self, id: &BenchmarkId, analysis_results: &MeasurementData, ) -> Result<()> { let dir = path!(&self.data_directory, id.as_directory_name()); std::fs::create_dir_all(&dir) .with_context(|| format!("Failed to create directory {:?}", dir))?; let measurement_name = chrono::Local::now() .format("measurement_%y%m%d%H%M%S.cbor") .to_string(); let saved_stats = SavedStatistics { datetime: chrono::Utc::now(), iterations: analysis_results.iter_counts().to_vec(), values: analysis_results.sample_times().to_vec(), avg_values: analysis_results.avg_times.to_vec(), estimates: analysis_results.absolute_estimates.clone(), throughput: analysis_results.throughput.clone(), changes: analysis_results .comparison .as_ref() .map(|c| c.relative_estimates.clone()), change_direction: analysis_results .comparison .as_ref() .map(get_change_direction), history_id: self.history_id.clone(), history_description: self.history_description.clone(), }; let measurement_path = dir.join(&measurement_name); let mut measurement_file = File::create(&measurement_path) .with_context(|| format!("Failed to create measurement file {:?}", measurement_path))?; serde_cbor::to_writer(&mut measurement_file, &saved_stats).with_context(|| { format!("Failed to save measurements to file {:?}", measurement_path) })?; let record = BenchmarkRecord { id: id.into(), latest_record: PathBuf::from(&measurement_name), }; let benchmark_path = dir.join("benchmark.cbor"); let mut benchmark_file = File::create(&benchmark_path) .with_context(|| format!("Failed to create benchmark file {:?}", benchmark_path))?; serde_cbor::to_writer(&mut benchmark_file, &record) .with_context(|| format!("Failed to save benchmark file {:?}", benchmark_path))?; let benchmark_entry = self .groups .get_mut(&id.group_id) .unwrap() .benchmarks .entry(id.clone()); match benchmark_entry { vacant @ linked_hash_map::Entry::Vacant(_) => { vacant.or_insert(Benchmark::new(saved_stats)); } linked_hash_map::Entry::Occupied(mut occupied) => { occupied.get_mut().add_stats(saved_stats) } }; Ok(()) } pub fn get_last_sample(&self, id: &BenchmarkId) -> Option<&SavedStatistics> { self.groups .get(&id.group_id) .and_then(|g| g.benchmarks.get(id)) .map(|b| &b.latest_stats) } pub fn check_benchmark_group(&self, current_target: &str, group: &str) { if let Some(benchmark_group) = self.groups.get(group) { if let Some(target) = &benchmark_group.target { if target != current_target { warn!("Benchmark group {} encountered again. Benchmark group IDs must be unique. First seen in the benchmark target '{}'", group, target); } } } } pub fn add_benchmark_group(&mut self, target: &str, group_name: &str) -> &BenchmarkGroup { // Remove and reinsert so that the group will be at the end of the map. let mut group = self.groups.remove(group_name).unwrap_or_default(); group.target = Some(target.to_owned()); self.groups.insert(group_name.to_owned(), group); self.groups.get(group_name).unwrap() } pub fn load_history(&self, id: &BenchmarkId) -> Result<Vec<SavedStatistics>> { let dir = path!(&self.data_directory, id.as_directory_name()); fn load_from(measurement_path: &Path) -> Result<SavedStatistics> { let mut measurement_file = File::open(&measurement_path).with_context(|| { format!("Failed to open measurement file {:?}", measurement_path) })?; serde_cbor::from_reader(&mut measurement_file) .with_context(|| format!("Failed to read measurement file {:?}", measurement_path)) } let mut stats = Vec::new(); for entry in WalkDir::new(dir) .max_depth(1) .into_iter() // Ignore errors. .filter_map(::std::result::Result::ok) { let name_str = entry.file_name().to_string_lossy(); if name_str.starts_with("measurement_") && name_str.ends_with(".cbor") { match load_from(entry.path()) { Ok(saved_stats) => stats.push(saved_stats), Err(e) => error!( "Unexpected error loading benchmark history from file {}: {:?}", entry.path().display(), e ), } } } stats.sort_unstable_by_key(|st| st.datetime); Ok(stats) } } // These structs are saved to disk and may be read by future versions of cargo-criterion, so // backwards compatibility is important. #[derive(Debug, Deserialize, Serialize)] pub struct SavedBenchmarkId { group_id: String, function_id: Option<String>, value_str: Option<String>, throughput: Option<Throughput>, } impl From<BenchmarkId> for SavedBenchmarkId { fn from(other: BenchmarkId) -> Self { SavedBenchmarkId { group_id: other.group_id, function_id: other.function_id, value_str: other.value_str, throughput: other.throughput, } } } impl From<&BenchmarkId> for SavedBenchmarkId { fn from(other: &BenchmarkId) -> Self { other.clone().into() } } impl From<SavedBenchmarkId> for BenchmarkId { fn from(other: SavedBenchmarkId) -> Self { BenchmarkId::new( other.group_id, other.function_id, other.value_str, other.throughput, ) } } impl From<&SavedBenchmarkId> for BenchmarkId { fn from(other: &SavedBenchmarkId) -> Self { other.into() } } #[derive(Debug, Serialize, Deserialize)] struct BenchmarkRecord { id: SavedBenchmarkId, latest_record: PathBuf, } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum ChangeDirection { NoChange, NotSignificant, Improved, Regressed, } fn get_change_direction(comp: &ComparisonData) -> ChangeDirection { if comp.p_value < comp.significance_threshold { return ChangeDirection::NoChange; } let ci = &comp.relative_estimates.mean.confidence_interval; let lb = ci.lower_bound; let ub = ci.upper_bound; let noise = comp.noise_threshold; if lb < -noise && ub < -noise { ChangeDirection::Improved } else if lb > noise && ub > noise { ChangeDirection::Regressed } else { ChangeDirection::NotSignificant } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct SavedStatistics { // The timestamp of when these measurements were saved. pub datetime: DateTime<Utc>, // The number of iterations in each sample pub iterations: Vec<f64>, // The measured values from each sample pub values: Vec<f64>, // The average values from each sample, ie. values / iterations pub avg_values: Vec<f64>, // The statistical estimates from this run pub estimates: Estimates, // The throughput of this run pub throughput: Option<Throughput>, // The statistical differences compared to the last run. We save these so we don't have to // recompute them later for the history report. pub changes: Option<ChangeEstimates>, // Was the change (if any) significant? pub change_direction: Option<ChangeDirection>, // An optional user-provided identifier string. This might be a version control commit ID or // something custom pub history_id: Option<String>, // An optional user-provided description. This might be a version control commit message or // something custom. pub history_description: Option<String>, }
use ash::vk; use ash::extensions::khr; use ash::version::DeviceV1_0; use super::{ Instance, Surface, Device }; pub struct Swapchain { loader: khr::Swapchain, handle: vk::SwapchainKHR, format: vk::SurfaceFormatKHR, images: Vec<vk::Image>, views: Vec<vk::ImageView>, } pub enum SwapchainCreationError { SurfaceQueryFailed(SurfaceQueryError), InsufficientSurfaceFormatSupport, WindowMinimized, CreationFailed(vk::Result), GettingImagesFailed, ImageViewCreationFailed(Vec<Result<vk::ImageView, vk::Result>>), } pub enum SurfaceQueryError { Capabilities(vk::Result), Formats(vk::Result), PresentModes(vk::Result), } impl Swapchain { #[inline] pub fn format(&self) -> vk::Format { self.format.format } pub fn new(instance: &Instance, surface: &Surface, device: &Device, format: vk::SurfaceFormatKHR) -> Result<Self, SwapchainCreationError> { let loader = khr::Swapchain::new(instance.handle(), device.handle()); let mut swapchain = Self { loader, handle: vk::SwapchainKHR::null(), format, images: Vec::new(), views: Vec::new(), }; swapchain.recreate(surface, device)?; Ok(swapchain) } pub fn recreate(&mut self, surface: &Surface, device: &Device) -> Result<(), SwapchainCreationError> { unsafe { let image_usage = Self::image_usage(); let present_mode = Self::present_mode(); let capabilities = surface .loader() .get_physical_device_surface_capabilities(device.physical().handle(), surface.handle()) .map_err(|e| SwapchainCreationError::from(SurfaceQueryError::Capabilities(e)))?; assert!(capabilities.supported_usage_flags.contains(image_usage)); surface .loader() .get_physical_device_surface_formats(device.physical().handle(), surface.handle()) .map_err(|e| SwapchainCreationError::from(SurfaceQueryError::Formats(e)))? .iter() .find(|&&f| f == self.format) .ok_or(SwapchainCreationError::InsufficientSurfaceFormatSupport)?; let fifo_support = surface .loader() .get_physical_device_surface_present_modes(device.physical().handle(), surface.handle()) .map_err(|e| SwapchainCreationError::from(SurfaceQueryError::PresentModes(e)))? .contains(&present_mode); assert!(fifo_support); if let vk::Extent2D { width: 0, height: 0 } = capabilities.max_image_extent { Err(SwapchainCreationError::WindowMinimized)?; } for &view in self.views.iter() { device.handle().destroy_image_view(view, None); } let info = vk::SwapchainCreateInfoKHR::builder() .surface(surface.handle()) .image_extent(capabilities.current_extent) .image_format(self.format.format) .image_color_space(self.format.color_space) .image_usage(image_usage) .image_sharing_mode(Self::image_sharing_mode()) .image_array_layers(Self::image_array_layers()) .min_image_count(Self::min_image_count(&capabilities)) .clipped(Self::clipped()) .present_mode(present_mode) .pre_transform(Self::pre_transform()) .composite_alpha(Self::composite_alpha()) .old_swapchain(self.handle); self.handle = self.loader .create_swapchain(&info, None) .map_err(|e| SwapchainCreationError::CreationFailed(e))?; self.images = self.loader .get_swapchain_images(self.handle) .map_err(|e| { self.loader.destroy_swapchain(self.handle, None); SwapchainCreationError::GettingImagesFailed })?; let view_results: Vec<_> = self.images .iter() .map(|&image| { let components = vk::ComponentMapping::builder() .r(vk::ComponentSwizzle::IDENTITY) .g(vk::ComponentSwizzle::IDENTITY) .b(vk::ComponentSwizzle::IDENTITY) .a(vk::ComponentSwizzle::IDENTITY) .build(); let range = vk::ImageSubresourceRange::builder() .aspect_mask(vk::ImageAspectFlags::COLOR) .base_array_layer(0) .layer_count(1) .base_mip_level(0) .level_count(1) .build(); let info = vk::ImageViewCreateInfo::builder() .image(image) .format(self.format.format) .view_type(vk::ImageViewType::TYPE_2D) .components(components) .subresource_range(range); device.handle().create_image_view(&info, None) }) .collect(); if view_results.iter().any(|r| r.is_err()) { view_results .iter() .filter(|r| r.is_ok()) .for_each(|v| device.handle().destroy_image_view(v.unwrap(), None)); return Err(SwapchainCreationError::ImageViewCreationFailed(view_results)); } self.views = view_results .into_iter() .map(|vr| vr.unwrap()) .collect(); }; Ok(()) } pub unsafe fn destroy(&mut self, device: &Device) { for &view in self.views.iter() { device.handle().destroy_image_view(view, None); } self.loader.destroy_swapchain(self.handle, None); } fn min_image_count(cap: &vk::SurfaceCapabilitiesKHR) -> u32 { let (min, max) = (cap.min_image_count, cap.max_image_count); let range = match (min, max) { (min, 0) => min ..= u32::max_value(), (min, max) => min ..= max, }; if range.contains(&(min + 1)) { min + 1 } else { min } } fn image_usage() -> vk::ImageUsageFlags { vk::ImageUsageFlags::COLOR_ATTACHMENT } fn present_mode() -> vk::PresentModeKHR { vk::PresentModeKHR::FIFO } fn image_sharing_mode() -> vk::SharingMode { vk::SharingMode::EXCLUSIVE } fn image_array_layers() -> u32 { 1 } fn clipped() -> bool { true } fn pre_transform() -> vk::SurfaceTransformFlagsKHR { vk::SurfaceTransformFlagsKHR::IDENTITY } fn composite_alpha() -> vk::CompositeAlphaFlagsKHR { vk::CompositeAlphaFlagsKHR::OPAQUE } } impl From<SurfaceQueryError> for SwapchainCreationError { fn from(e: SurfaceQueryError) -> Self { SwapchainCreationError::SurfaceQueryFailed(e) } }
pub mod sharedlock; pub use sharedlock::SharedLock; #[derive(Debug)] pub enum Error { DeadLockError, Poisoned, } pub type Result<T> = std::result::Result<T, Error>; impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::DeadLockError => { write!(f, "DeadLock") } Error::Poisoned => { write!(f, "Poisoned") } } } }
use crate::Ray; use crate::Vec3; #[derive(Clone, Debug, PartialEq, Copy)] pub struct AABB { pub min: Vec3, pub max: Vec3, } impl AABB { pub fn new(a: Vec3, b: Vec3) -> Self { Self { min: a, max: b } } pub fn min(a: f64, b: f64) -> f64 { if a < b { a } else { b } } pub fn max(a: f64, b: f64) -> f64 { if a > b { a } else { b } } pub fn hit(self, r: Ray, tmin: f64, tmax: f64) -> bool { let tmi = tmin; let tma = tmax; for i in 0..3 { let inv_d = 1.0 / r.dir.get(i); let mut t0 = (self.min.get(i) - r.beg.get(i)) * inv_d; let mut t1 = (self.max.get(i) - r.beg.get(i)) * inv_d; if inv_d < 0.0 { std::mem::swap(&mut t0, &mut t1); } let tmi = { if t0 > tmi { t0 } else { tmi } }; let tma = { if t1 < tma { t1 } else { tma } }; if tma <= tmi { return false; } } true } pub fn surrounding_box(box1: AABB, box2: AABB) -> AABB { let small = Vec3::new( AABB::min(box1.min.x, box2.min.x), AABB::min(box1.min.y, box2.min.y), AABB::min(box1.min.z, box2.min.z), ); let big = Vec3::new( AABB::max(box1.max.x, box2.max.x), AABB::max(box1.max.y, box2.max.y), AABB::max(box1.max.z, box2.max.z), ); AABB::new(small, big) } }
use std::{ fmt::Debug, ops::{Deref, DerefMut}, }; use crate::util::{impl_deref_wrapped, impl_from_repeated}; use librespot_core::FileId; use librespot_protocol as protocol; use protocol::metadata::VideoFile as VideoFileMessage; #[derive(Debug, Clone, Default)] pub struct VideoFiles(pub Vec<FileId>); impl_deref_wrapped!(VideoFiles, Vec<FileId>); impl_from_repeated!(VideoFileMessage, VideoFiles);
extern crate cgmath; #[macro_use] extern crate glium; extern crate aperture; use cgmath::prelude::*; use glium::glutin; use glium::Surface; use std::thread::sleep; use std::time::{Duration, SystemTime}; #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], } implement_vertex!(Vertex, position); fn main() { let mut events_loop = glutin::EventsLoop::new(); let window = glutin::WindowBuilder::new() .with_title("Cube Example") .with_dimensions(1024, 1024); let context = glutin::ContextBuilder::new(); let display = glium::Display::new(window, context, &events_loop).unwrap(); // We statically include the shader sources, and build the shader program let vertex_shader_src = " #version 400 in vec3 position; uniform mat4 rotation_matrix; uniform vec4 u_color; out vec4 f_color; void main() { f_color = u_color; gl_Position = rotation_matrix * vec4(position, 1.0); }"; let fragment_shader_src = " #version 400 in vec4 f_color; out vec4 color; void main() { color = f_color; }"; let shader_program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None) .unwrap(); // Build up the outline of a cube // // 1.) Make a vertex buffer with all the corners let mut vertices = Vec::new(); for x in vec![-1.0, 1.0] { for y in vec![-1.0, 1.0] { for z in vec![-1.0, 1.0] { vertices.push(Vertex { position: [x, y, z], }) } } } let vertex_buffer = glium::VertexBuffer::new(&display, &vertices).unwrap(); // 2.) Make an index buffer with all the appropriate endpoints let indices = glium::IndexBuffer::new( &display, glium::index::PrimitiveType::LinesList, #[cfg_attr(rustfmt, rustfmt_skip)] &[0, 1, 1, 3, 3, 2, 2, 0, 4, 5, 5, 7, 7, 6, 6, 4, 0, 4, 1, 5, 3, 7, 2, 6u16], ).unwrap(); // Drawing parameters let params = glium::DrawParameters { line_width: Some(5.0), blend: glium::Blend::alpha_blending(), ..Default::default() }; let mut closed = false; let mut cam = aperture::Camera::new(); let fps: f32 = 60.0; let frame_duration_cap = Duration::from_millis(((1.0 / fps) * 1000.0) as u64); let mut current_time = SystemTime::now(); while !closed { let mut target = display.draw(); // listing the events produced by application and waiting to be received events_loop.poll_events(|ev| match ev { glutin::Event::WindowEvent { event: glutin::WindowEvent::Closed, .. } => { closed = true; } event => { aperture::camera_event_handler(&mut cam, event); } }); let new_time = SystemTime::now(); let frame_time = current_time.elapsed().unwrap(); let elapsed_millis = (1000 * frame_time.as_secs() + frame_time.subsec_millis() as u64) as f32; current_time = new_time; let (window_width, window_height) = { let (window_width_i, window_height_i) = target.get_dimensions(); (window_width_i as f32, window_height_i as f32) }; cam.update(elapsed_millis, window_width, window_height); let world_transform = cam.get_clipspace_transform(); // A weird yellow background target.clear_color(0.7654, 0.567, 0.1245, 1.0); // Lets make an interesting nested cube thing let segments: u16 = 50; for i in (1..segments) { let frac = i as f32 / segments as f32; let scale = cgmath::Matrix4::from_scale(frac); let object_transform: [[f32; 4]; 4] = (world_transform * scale).into(); let uniforms = uniform!{ rotation_matrix: object_transform, u_color: [frac, 0.134 * frac, 1.0 - frac, 0.5] }; // Clear the screen, draw, and swap the buffers target .draw( &vertex_buffer, &indices, &shader_program, &uniforms, &params, ) .unwrap(); } // Here we limit the framerate to avoid consuming uneeded CPU time let elapsed = current_time.elapsed().unwrap(); if elapsed < frame_duration_cap { let sleep_time = frame_duration_cap - elapsed; sleep(sleep_time); } target.finish().unwrap(); } }
#[link(name="hello", kind="static")] extern{ fn hello(); fn c_add( a: i32, b: i32 ) -> i32 ; } fn main() { unsafe { hello(); } let a = 10 ; let b = 20 ; let ans = unsafe { c_add( a, b ) }; println!("ans is {}", ans ); }
#[doc = "Register `APB1FZR1` reader"] pub type R = crate::R<APB1FZR1_SPEC>; #[doc = "Register `APB1FZR1` writer"] pub type W = crate::W<APB1FZR1_SPEC>; #[doc = "Field `DBG_TIMER2_STOP` reader - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_R = crate::BitReader<DBG_TIMER2_STOP_A>; #[doc = "Debug Timer 2 stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_TIMER2_STOP_A { #[doc = "0: The counter clock of TIMx is fed even if the core is halted"] Continue = 0, #[doc = "1: The counter clock of TIMx is stopped when the core is halted"] Stop = 1, } impl From<DBG_TIMER2_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_TIMER2_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_TIMER2_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_TIMER2_STOP_A { match self.bits { false => DBG_TIMER2_STOP_A::Continue, true => DBG_TIMER2_STOP_A::Stop, } } #[doc = "The counter clock of TIMx is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_TIMER2_STOP_A::Continue } #[doc = "The counter clock of TIMx is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_TIMER2_STOP_A::Stop } } #[doc = "Field `DBG_TIMER2_STOP` writer - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_TIMER2_STOP_A>; impl<'a, REG, const O: u8> DBG_TIMER2_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The counter clock of TIMx is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_TIMER2_STOP_A::Continue) } #[doc = "The counter clock of TIMx is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_TIMER2_STOP_A::Stop) } } #[doc = "Field `DBG_TIM3_STOP` reader - TIM3 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIM3_STOP_R; #[doc = "Field `DBG_TIM4_STOP` reader - TIM4 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIM4_STOP_R; #[doc = "Field `DBG_TIM5_STOP` reader - TIM5 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIM5_STOP_R; #[doc = "Field `DBG_TIMER6_STOP` reader - Debug Timer 6 stopped when Core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIMER6_STOP_R; #[doc = "Field `DBG_TIM7_STOP` reader - TIM7 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIM7_STOP_R; #[doc = "Field `DBG_TIM3_STOP` writer - TIM3 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIM3_STOP_W; #[doc = "Field `DBG_TIM4_STOP` writer - TIM4 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIM4_STOP_W; #[doc = "Field `DBG_TIM5_STOP` writer - TIM5 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIM5_STOP_W; #[doc = "Field `DBG_TIMER6_STOP` writer - Debug Timer 6 stopped when Core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIMER6_STOP_W; #[doc = "Field `DBG_TIM7_STOP` writer - TIM7 counter stopped when core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIM7_STOP_W; #[doc = "Field `DBG_RTC_STOP` reader - Debug RTC stopped when Core is halted"] pub type DBG_RTC_STOP_R = crate::BitReader<DBG_RTC_STOP_A>; #[doc = "Debug RTC stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_RTC_STOP_A { #[doc = "0: The clock of the RTC counter is fed even if the core is halted"] Continue = 0, #[doc = "1: The clock of the RTC counter is stopped when the core is halted"] Stop = 1, } impl From<DBG_RTC_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_RTC_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_RTC_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_RTC_STOP_A { match self.bits { false => DBG_RTC_STOP_A::Continue, true => DBG_RTC_STOP_A::Stop, } } #[doc = "The clock of the RTC counter is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_RTC_STOP_A::Continue } #[doc = "The clock of the RTC counter is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_RTC_STOP_A::Stop } } #[doc = "Field `DBG_RTC_STOP` writer - Debug RTC stopped when Core is halted"] pub type DBG_RTC_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_RTC_STOP_A>; impl<'a, REG, const O: u8> DBG_RTC_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The clock of the RTC counter is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_RTC_STOP_A::Continue) } #[doc = "The clock of the RTC counter is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_RTC_STOP_A::Stop) } } #[doc = "Field `DBG_WWDG_STOP` reader - Debug Window Wachdog stopped when Core is halted"] pub type DBG_WWDG_STOP_R = crate::BitReader<DBG_WWDG_STOP_A>; #[doc = "Debug Window Wachdog stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_WWDG_STOP_A { #[doc = "0: The window watchdog counter clock continues even if the core is halted"] Continue = 0, #[doc = "1: The window watchdog counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_WWDG_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_WWDG_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_WWDG_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_WWDG_STOP_A { match self.bits { false => DBG_WWDG_STOP_A::Continue, true => DBG_WWDG_STOP_A::Stop, } } #[doc = "The window watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_WWDG_STOP_A::Continue } #[doc = "The window watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_WWDG_STOP_A::Stop } } #[doc = "Field `DBG_WWDG_STOP` writer - Debug Window Wachdog stopped when Core is halted"] pub type DBG_WWDG_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_WWDG_STOP_A>; impl<'a, REG, const O: u8> DBG_WWDG_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The window watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_WWDG_STOP_A::Continue) } #[doc = "The window watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_WWDG_STOP_A::Stop) } } #[doc = "Field `DBG_IWDG_STOP` reader - Debug Independent Wachdog stopped when Core is halted"] pub type DBG_IWDG_STOP_R = crate::BitReader<DBG_IWDG_STOP_A>; #[doc = "Debug Independent Wachdog stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_IWDG_STOP_A { #[doc = "0: The independent watchdog counter clock continues even if the core is halted"] Continue = 0, #[doc = "1: The independent watchdog counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_IWDG_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_IWDG_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_IWDG_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_IWDG_STOP_A { match self.bits { false => DBG_IWDG_STOP_A::Continue, true => DBG_IWDG_STOP_A::Stop, } } #[doc = "The independent watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_IWDG_STOP_A::Continue } #[doc = "The independent watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_IWDG_STOP_A::Stop } } #[doc = "Field `DBG_IWDG_STOP` writer - Debug Independent Wachdog stopped when Core is halted"] pub type DBG_IWDG_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_IWDG_STOP_A>; impl<'a, REG, const O: u8> DBG_IWDG_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The independent watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_IWDG_STOP_A::Continue) } #[doc = "The independent watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_IWDG_STOP_A::Stop) } } #[doc = "Field `DBG_I2C1_STOP` reader - I2C1 SMBUS timeout mode stopped when core is halted"] pub type DBG_I2C1_STOP_R = crate::BitReader<DBG_I2C1_STOP_A>; #[doc = "I2C1 SMBUS timeout mode stopped when core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_I2C1_STOP_A { #[doc = "0: Same behavior as in normal mode"] NormalMode = 0, #[doc = "1: I2Cx SMBUS timeout is frozen"] SmbusTimeoutFrozen = 1, } impl From<DBG_I2C1_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_I2C1_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_I2C1_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_I2C1_STOP_A { match self.bits { false => DBG_I2C1_STOP_A::NormalMode, true => DBG_I2C1_STOP_A::SmbusTimeoutFrozen, } } #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn is_normal_mode(&self) -> bool { *self == DBG_I2C1_STOP_A::NormalMode } #[doc = "I2Cx SMBUS timeout is frozen"] #[inline(always)] pub fn is_smbus_timeout_frozen(&self) -> bool { *self == DBG_I2C1_STOP_A::SmbusTimeoutFrozen } } #[doc = "Field `DBG_I2C1_STOP` writer - I2C1 SMBUS timeout mode stopped when core is halted"] pub type DBG_I2C1_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_I2C1_STOP_A>; impl<'a, REG, const O: u8> DBG_I2C1_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn normal_mode(self) -> &'a mut crate::W<REG> { self.variant(DBG_I2C1_STOP_A::NormalMode) } #[doc = "I2Cx SMBUS timeout is frozen"] #[inline(always)] pub fn smbus_timeout_frozen(self) -> &'a mut crate::W<REG> { self.variant(DBG_I2C1_STOP_A::SmbusTimeoutFrozen) } } #[doc = "Field `DBG_I2C2_STOP` reader - I2C2 SMBUS timeout mode stopped when core is halted"] pub use DBG_I2C1_STOP_R as DBG_I2C2_STOP_R; #[doc = "Field `DBG_I2C3_STOP` reader - I2C3 SMBUS timeout counter stopped when core is halted"] pub use DBG_I2C1_STOP_R as DBG_I2C3_STOP_R; #[doc = "Field `DBG_I2C2_STOP` writer - I2C2 SMBUS timeout mode stopped when core is halted"] pub use DBG_I2C1_STOP_W as DBG_I2C2_STOP_W; #[doc = "Field `DBG_I2C3_STOP` writer - I2C3 SMBUS timeout counter stopped when core is halted"] pub use DBG_I2C1_STOP_W as DBG_I2C3_STOP_W; #[doc = "Field `DBG_CAN1_STOP` reader - bxCAN stopped when core is halted"] pub type DBG_CAN1_STOP_R = crate::BitReader<DBG_CAN1_STOP_A>; #[doc = "bxCAN stopped when core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_CAN1_STOP_A { #[doc = "0: Same behavior as in normal mode"] NormalMode = 0, #[doc = "1: The bxCAN1 receive registers are frozen"] ReceiveRegistersFrozen = 1, } impl From<DBG_CAN1_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_CAN1_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_CAN1_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_CAN1_STOP_A { match self.bits { false => DBG_CAN1_STOP_A::NormalMode, true => DBG_CAN1_STOP_A::ReceiveRegistersFrozen, } } #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn is_normal_mode(&self) -> bool { *self == DBG_CAN1_STOP_A::NormalMode } #[doc = "The bxCAN1 receive registers are frozen"] #[inline(always)] pub fn is_receive_registers_frozen(&self) -> bool { *self == DBG_CAN1_STOP_A::ReceiveRegistersFrozen } } #[doc = "Field `DBG_CAN1_STOP` writer - bxCAN stopped when core is halted"] pub type DBG_CAN1_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_CAN1_STOP_A>; impl<'a, REG, const O: u8> DBG_CAN1_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn normal_mode(self) -> &'a mut crate::W<REG> { self.variant(DBG_CAN1_STOP_A::NormalMode) } #[doc = "The bxCAN1 receive registers are frozen"] #[inline(always)] pub fn receive_registers_frozen(self) -> &'a mut crate::W<REG> { self.variant(DBG_CAN1_STOP_A::ReceiveRegistersFrozen) } } #[doc = "Field `DBG_LPTIM1_STOP` reader - LPTIM1 counter stopped when core is halted"] pub type DBG_LPTIM1_STOP_R = crate::BitReader<DBG_LPTIM1_STOP_A>; #[doc = "LPTIM1 counter stopped when core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_LPTIM1_STOP_A { #[doc = "0: LPTIMx counter clock is fed even if the core is halted"] Continue = 0, #[doc = "1: LPTIMx counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_LPTIM1_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_LPTIM1_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_LPTIM1_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_LPTIM1_STOP_A { match self.bits { false => DBG_LPTIM1_STOP_A::Continue, true => DBG_LPTIM1_STOP_A::Stop, } } #[doc = "LPTIMx counter clock is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_LPTIM1_STOP_A::Continue } #[doc = "LPTIMx counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_LPTIM1_STOP_A::Stop } } #[doc = "Field `DBG_LPTIM1_STOP` writer - LPTIM1 counter stopped when core is halted"] pub type DBG_LPTIM1_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_LPTIM1_STOP_A>; impl<'a, REG, const O: u8> DBG_LPTIM1_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "LPTIMx counter clock is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_LPTIM1_STOP_A::Continue) } #[doc = "LPTIMx counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_LPTIM1_STOP_A::Stop) } } impl R { #[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"] #[inline(always)] pub fn dbg_timer2_stop(&self) -> DBG_TIMER2_STOP_R { DBG_TIMER2_STOP_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TIM3 counter stopped when core is halted"] #[inline(always)] pub fn dbg_tim3_stop(&self) -> DBG_TIM3_STOP_R { DBG_TIM3_STOP_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - TIM4 counter stopped when core is halted"] #[inline(always)] pub fn dbg_tim4_stop(&self) -> DBG_TIM4_STOP_R { DBG_TIM4_STOP_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - TIM5 counter stopped when core is halted"] #[inline(always)] pub fn dbg_tim5_stop(&self) -> DBG_TIM5_STOP_R { DBG_TIM5_STOP_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"] #[inline(always)] pub fn dbg_timer6_stop(&self) -> DBG_TIMER6_STOP_R { DBG_TIMER6_STOP_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TIM7 counter stopped when core is halted"] #[inline(always)] pub fn dbg_tim7_stop(&self) -> DBG_TIM7_STOP_R { DBG_TIM7_STOP_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 10 - Debug RTC stopped when Core is halted"] #[inline(always)] pub fn dbg_rtc_stop(&self) -> DBG_RTC_STOP_R { DBG_RTC_STOP_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"] #[inline(always)] pub fn dbg_wwdg_stop(&self) -> DBG_WWDG_STOP_R { DBG_WWDG_STOP_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"] #[inline(always)] pub fn dbg_iwdg_stop(&self) -> DBG_IWDG_STOP_R { DBG_IWDG_STOP_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"] #[inline(always)] pub fn dbg_i2c1_stop(&self) -> DBG_I2C1_STOP_R { DBG_I2C1_STOP_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 SMBUS timeout mode stopped when core is halted"] #[inline(always)] pub fn dbg_i2c2_stop(&self) -> DBG_I2C2_STOP_R { DBG_I2C2_STOP_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - I2C3 SMBUS timeout counter stopped when core is halted"] #[inline(always)] pub fn dbg_i2c3_stop(&self) -> DBG_I2C3_STOP_R { DBG_I2C3_STOP_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 25 - bxCAN stopped when core is halted"] #[inline(always)] pub fn dbg_can1_stop(&self) -> DBG_CAN1_STOP_R { DBG_CAN1_STOP_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"] #[inline(always)] pub fn dbg_lptim1_stop(&self) -> DBG_LPTIM1_STOP_R { DBG_LPTIM1_STOP_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_timer2_stop(&mut self) -> DBG_TIMER2_STOP_W<APB1FZR1_SPEC, 0> { DBG_TIMER2_STOP_W::new(self) } #[doc = "Bit 1 - TIM3 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_tim3_stop(&mut self) -> DBG_TIM3_STOP_W<APB1FZR1_SPEC, 1> { DBG_TIM3_STOP_W::new(self) } #[doc = "Bit 2 - TIM4 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_tim4_stop(&mut self) -> DBG_TIM4_STOP_W<APB1FZR1_SPEC, 2> { DBG_TIM4_STOP_W::new(self) } #[doc = "Bit 3 - TIM5 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_tim5_stop(&mut self) -> DBG_TIM5_STOP_W<APB1FZR1_SPEC, 3> { DBG_TIM5_STOP_W::new(self) } #[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_timer6_stop(&mut self) -> DBG_TIMER6_STOP_W<APB1FZR1_SPEC, 4> { DBG_TIMER6_STOP_W::new(self) } #[doc = "Bit 5 - TIM7 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_tim7_stop(&mut self) -> DBG_TIM7_STOP_W<APB1FZR1_SPEC, 5> { DBG_TIM7_STOP_W::new(self) } #[doc = "Bit 10 - Debug RTC stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_rtc_stop(&mut self) -> DBG_RTC_STOP_W<APB1FZR1_SPEC, 10> { DBG_RTC_STOP_W::new(self) } #[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_wwdg_stop(&mut self) -> DBG_WWDG_STOP_W<APB1FZR1_SPEC, 11> { DBG_WWDG_STOP_W::new(self) } #[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_iwdg_stop(&mut self) -> DBG_IWDG_STOP_W<APB1FZR1_SPEC, 12> { DBG_IWDG_STOP_W::new(self) } #[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_i2c1_stop(&mut self) -> DBG_I2C1_STOP_W<APB1FZR1_SPEC, 21> { DBG_I2C1_STOP_W::new(self) } #[doc = "Bit 22 - I2C2 SMBUS timeout mode stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_i2c2_stop(&mut self) -> DBG_I2C2_STOP_W<APB1FZR1_SPEC, 22> { DBG_I2C2_STOP_W::new(self) } #[doc = "Bit 23 - I2C3 SMBUS timeout counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_i2c3_stop(&mut self) -> DBG_I2C3_STOP_W<APB1FZR1_SPEC, 23> { DBG_I2C3_STOP_W::new(self) } #[doc = "Bit 25 - bxCAN stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_can1_stop(&mut self) -> DBG_CAN1_STOP_W<APB1FZR1_SPEC, 25> { DBG_CAN1_STOP_W::new(self) } #[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_lptim1_stop(&mut self) -> DBG_LPTIM1_STOP_W<APB1FZR1_SPEC, 31> { DBG_LPTIM1_STOP_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 = "APB Low Freeze Register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1fzr1::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 [`apb1fzr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB1FZR1_SPEC; impl crate::RegisterSpec for APB1FZR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb1fzr1::R`](R) reader structure"] impl crate::Readable for APB1FZR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb1fzr1::W`](W) writer structure"] impl crate::Writable for APB1FZR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB1FZR1 to value 0"] impl crate::Resettable for APB1FZR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalActorIdentity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "principalType", default, skip_serializing_if = "Option::is_none")] pub principal_type: Option<role_assignment_approval_actor_identity::PrincipalType>, #[serde(rename = "principalName", default, skip_serializing_if = "Option::is_none")] pub principal_name: Option<String>, #[serde(rename = "userPrincipalName", default, skip_serializing_if = "Option::is_none")] pub user_principal_name: Option<String>, } pub mod role_assignment_approval_actor_identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PrincipalType { #[serde(rename = "user")] User, #[serde(rename = "servicePrincipal")] ServicePrincipal, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApproval { #[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<RoleAssignmentApprovalProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub stages: Vec<RoleAssignmentApprovalStep>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RoleAssignmentApproval>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalStep { #[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<RoleAssignmentApprovalStepProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalStepProperties { #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<role_assignment_approval_step_properties::Status>, #[serde(rename = "assignedToMe", default, skip_serializing_if = "Option::is_none")] pub assigned_to_me: Option<bool>, #[serde(rename = "reviewedBy", default, skip_serializing_if = "Option::is_none")] pub reviewed_by: Option<RoleAssignmentApprovalActorIdentity>, #[serde(rename = "reviewedDateTime", default, skip_serializing_if = "Option::is_none")] pub reviewed_date_time: Option<String>, #[serde(rename = "reviewResult", default, skip_serializing_if = "Option::is_none")] pub review_result: Option<role_assignment_approval_step_properties::ReviewResult>, #[serde(default, skip_serializing_if = "Option::is_none")] pub justification: Option<String>, } pub mod role_assignment_approval_step_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { NotStarted, InProgress, Completed, Expired, Initializing, Escalating, Completing, Escalated, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReviewResult { Approve, Deny, NotReviewed, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoleAssignmentApprovalStepListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RoleAssignmentApprovalStep>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDefinitionProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDefinitionProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")] pub is_data_action: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplay>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: 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 OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, }
use crate::distribution::{Continuous, ContinuousCDF}; use crate::function::{beta, gamma}; use crate::is_zero; use crate::statistics::*; use crate::{Result, StatsError}; use rand::Rng; use std::f64; /// Implements the [Student's /// T](https://en.wikipedia.org/wiki/Student%27s_t-distribution) distribution /// /// # Examples /// /// ``` /// use statrs::distribution::{StudentsT, Continuous}; /// use statrs::statistics::Distribution; /// use statrs::prec; /// /// let n = StudentsT::new(0.0, 1.0, 2.0).unwrap(); /// assert_eq!(n.mean().unwrap(), 0.0); /// assert!(prec::almost_eq(n.pdf(0.0), 0.353553390593274, 1e-15)); /// ``` #[derive(Debug, Copy, Clone, PartialEq)] pub struct StudentsT { location: f64, scale: f64, freedom: f64, } impl StudentsT { /// Constructs a new student's t-distribution with location `location`, /// scale `scale`, /// and `freedom` freedom. /// /// # Errors /// /// Returns an error if any of `location`, `scale`, or `freedom` are `NaN`. /// Returns an error if `scale <= 0.0` or `freedom <= 0.0` /// /// # Examples /// /// ``` /// use statrs::distribution::StudentsT; /// /// let mut result = StudentsT::new(0.0, 1.0, 2.0); /// assert!(result.is_ok()); /// /// result = StudentsT::new(0.0, 0.0, 0.0); /// assert!(result.is_err()); /// ``` pub fn new(location: f64, scale: f64, freedom: f64) -> Result<StudentsT> { let is_nan = location.is_nan() || scale.is_nan() || freedom.is_nan(); if is_nan || scale <= 0.0 || freedom <= 0.0 { Err(StatsError::BadParams) } else { Ok(StudentsT { location, scale, freedom, }) } } /// Returns the location of the student's t-distribution /// /// # Examples /// /// ``` /// use statrs::distribution::StudentsT; /// /// let n = StudentsT::new(0.0, 1.0, 2.0).unwrap(); /// assert_eq!(n.location(), 0.0); /// ``` pub fn location(&self) -> f64 { self.location } /// Returns the scale of the student's t-distribution /// /// # Examples /// /// ``` /// use statrs::distribution::StudentsT; /// /// let n = StudentsT::new(0.0, 1.0, 2.0).unwrap(); /// assert_eq!(n.scale(), 1.0); /// ``` pub fn scale(&self) -> f64 { self.scale } /// Returns the freedom of the student's t-distribution /// /// # Examples /// /// ``` /// use statrs::distribution::StudentsT; /// /// let n = StudentsT::new(0.0, 1.0, 2.0).unwrap(); /// assert_eq!(n.freedom(), 2.0); /// ``` pub fn freedom(&self) -> f64 { self.freedom } } impl ::rand::distributions::Distribution<f64> for StudentsT { fn sample<R: Rng + ?Sized>(&self, r: &mut R) -> f64 { // based on method 2, section 5 in chapter 9 of L. Devroye's // "Non-Uniform Random Variate Generation" let gamma = super::gamma::sample_unchecked(r, 0.5 * self.freedom, 0.5); super::normal::sample_unchecked( r, self.location, self.scale * (self.freedom / gamma).sqrt(), ) } } impl ContinuousCDF<f64, f64> for StudentsT { /// Calculates the cumulative distribution function for the student's /// t-distribution /// at `x` /// /// # Formula /// /// ```ignore /// if x < μ { /// (1 / 2) * I(t, v / 2, 1 / 2) /// } else { /// 1 - (1 / 2) * I(t, v / 2, 1 / 2) /// } /// ``` /// /// where `t = v / (v + k^2)`, `k = (x - μ) / σ`, `μ` is the location, /// `σ` is the scale, `v` is the freedom, and `I` is the regularized /// incomplete /// beta function fn cdf(&self, x: f64) -> f64 { if self.freedom.is_infinite() { super::normal::cdf_unchecked(x, self.location, self.scale) } else { let k = (x - self.location) / self.scale; let h = self.freedom / (self.freedom + k * k); let ib = 0.5 * beta::beta_reg(self.freedom / 2.0, 0.5, h); if x <= self.location { ib } else { 1.0 - ib } } } /// Calculates the inverse cumulative distribution function for the /// Student's T-distribution at `x` fn inverse_cdf(&self, x: f64) -> f64 { // first calculate inverse_cdf for normal Student's T assert!((0.0..=1.0).contains(&x)); let x = 2. * x.min(1. - x); let a = 0.5 * self.freedom; let b = 0.5; let mut y = beta::inv_beta_reg(a, b, x); y = (self.freedom * (1. - y) / y).sqrt(); y = if x <= 0.5 { y } else { -y }; // generalised Student's T is related to normal Student's T by `Y = μ + σ X` // where `X` is distributed as Student's T, so this result has to be scaled and shifted back // formally: F_Y(t) = P(Y <= t) = P(X <= (t - μ) / σ) = F_X((t - μ) / σ) // F_Y^{-1}(p) = inf { t' | F_Y(t') >= p } = inf { t' = μ + σ t | F_X((t' - μ) / σ) >= p } // because scale is positive: loc + scale * t is strictly monotonic function // = μ + σ inf { t | F_X(t) >= p } = μ + σ F_X^{-1}(p) self.location + self.scale * y } } impl Min<f64> for StudentsT { /// Returns the minimum value in the domain of the student's t-distribution /// representable by a double precision float /// /// # Formula /// /// ```ignore /// -INF /// ``` fn min(&self) -> f64 { f64::NEG_INFINITY } } impl Max<f64> for StudentsT { /// Returns the maximum value in the domain of the student's t-distribution /// representable by a double precision float /// /// # Formula /// /// ```ignore /// INF /// ``` fn max(&self) -> f64 { f64::INFINITY } } impl Distribution<f64> for StudentsT { /// Returns the mean of the student's t-distribution /// /// # None /// /// If `freedom <= 1.0` /// /// # Formula /// /// ```ignore /// μ /// ``` /// /// where `μ` is the location fn mean(&self) -> Option<f64> { if self.freedom <= 1.0 { None } else { Some(self.location) } } /// Returns the variance of the student's t-distribution /// /// # None /// /// If `freedom <= 2.0` /// /// # Formula /// /// ```ignore /// if v == INF { /// Some(σ^2) /// } else if freedom > 2.0 { /// Some(v * σ^2 / (v - 2)) /// } else { /// None /// } /// ``` /// /// where `σ` is the scale and `v` is the freedom fn variance(&self) -> Option<f64> { if self.freedom.is_infinite() { Some(self.scale * self.scale) } else if self.freedom > 2.0 { Some(self.freedom * self.scale * self.scale / (self.freedom - 2.0)) } else { None } } /// Returns the entropy for the student's t-distribution /// /// # Formula /// /// ```ignore /// - ln(σ) + (v + 1) / 2 * (ψ((v + 1) / 2) - ψ(v / 2)) + ln(sqrt(v) * B(v / 2, 1 / /// 2)) /// ``` /// /// where `σ` is the scale, `v` is the freedom, `ψ` is the digamma function, and `B` is the /// beta function fn entropy(&self) -> Option<f64> { // generalised Student's T is related to normal Student's T by `Y = μ + σ X` // where `X` is distributed as Student's T, plugging into the definition // of entropy shows scaling affects the entropy by an additive constant `- ln σ` let shift = -self.scale.ln(); let result = (self.freedom + 1.0) / 2.0 * (gamma::digamma((self.freedom + 1.0) / 2.0) - gamma::digamma(self.freedom / 2.0)) + (self.freedom.sqrt() * beta::beta(self.freedom / 2.0, 0.5)).ln(); Some(result + shift) } /// Returns the skewness of the student's t-distribution /// /// # None /// /// If `x <= 3.0` /// /// # Formula /// /// ```ignore /// 0 /// ``` fn skewness(&self) -> Option<f64> { if self.freedom <= 3.0 { None } else { Some(0.0) } } } impl Median<f64> for StudentsT { /// Returns the median of the student's t-distribution /// /// # Formula /// /// ```ignore /// μ /// ``` /// /// where `μ` is the location fn median(&self) -> f64 { self.location } } impl Mode<Option<f64>> for StudentsT { /// Returns the mode of the student's t-distribution /// /// # Formula /// /// ```ignore /// μ /// ``` /// /// where `μ` is the location fn mode(&self) -> Option<f64> { Some(self.location) } } impl Continuous<f64, f64> for StudentsT { /// Calculates the probability density function for the student's /// t-distribution /// at `x` /// /// # Formula /// /// ```ignore /// Γ((v + 1) / 2) / (sqrt(vπ) * Γ(v / 2) * σ) * (1 + k^2 / v)^(-1 / 2 * (v /// + 1)) /// ``` /// /// where `k = (x - μ) / σ`, `μ` is the location, `σ` is the scale, `v` is /// the freedom, /// and `Γ` is the gamma function fn pdf(&self, x: f64) -> f64 { if x.is_infinite() { 0.0 } else if self.freedom >= 1e8 { super::normal::pdf_unchecked(x, self.location, self.scale) } else { let d = (x - self.location) / self.scale; (gamma::ln_gamma((self.freedom + 1.0) / 2.0) - gamma::ln_gamma(self.freedom / 2.0)) .exp() * (1.0 + d * d / self.freedom).powf(-0.5 * (self.freedom + 1.0)) / (self.freedom * f64::consts::PI).sqrt() / self.scale } } /// Calculates the log probability density function for the student's /// t-distribution /// at `x` /// /// # Formula /// /// ```ignore /// ln(Γ((v + 1) / 2) / (sqrt(vπ) * Γ(v / 2) * σ) * (1 + k^2 / v)^(-1 / 2 * /// (v + 1))) /// ``` /// /// where `k = (x - μ) / σ`, `μ` is the location, `σ` is the scale, `v` is /// the freedom, /// and `Γ` is the gamma function fn ln_pdf(&self, x: f64) -> f64 { if x.is_infinite() { f64::NEG_INFINITY } else if self.freedom >= 1e8 { super::normal::ln_pdf_unchecked(x, self.location, self.scale) } else { let d = (x - self.location) / self.scale; gamma::ln_gamma((self.freedom + 1.0) / 2.0) - 0.5 * ((self.freedom + 1.0) * (1.0 + d * d / self.freedom).ln()) - gamma::ln_gamma(self.freedom / 2.0) - 0.5 * (self.freedom * f64::consts::PI).ln() - self.scale.ln() } } } #[rustfmt::skip] #[cfg(test)] mod tests { use std::panic; use crate::statistics::*; use crate::distribution::{ContinuousCDF, Continuous, StudentsT}; use crate::distribution::internal::*; use crate::consts::ACC; fn try_create(location: f64, scale: f64, freedom: f64) -> StudentsT { let n = StudentsT::new(location, scale, freedom); assert!(n.is_ok()); n.unwrap() } fn create_case(location: f64, scale: f64, freedom: f64) { let n = try_create(location, scale, freedom); assert_eq!(n.location(), location); assert_eq!(n.scale(), scale); assert_eq!(n.freedom(), freedom); } fn bad_create_case(location: f64, scale: f64, freedom: f64) { let n = StudentsT::new(location, scale, freedom); assert!(n.is_err()); } fn get_value<T, F>(location: f64, scale: f64, freedom: f64, eval: F) -> T where F: Fn(StudentsT) -> T { let n = try_create(location, scale, freedom); eval(n) } fn test_case<T, F>(location: f64, scale: f64, freedom: f64, expected: T, eval: F) where F: Fn(StudentsT) -> T, T: std::fmt::Debug + PartialEq, { let x = get_value(location, scale, freedom, eval); assert_eq!(expected, x); } fn test_almost<F>(location: f64, scale: f64, freedom: f64, expected: f64, acc: f64, eval: F) where F: Fn(StudentsT) -> f64 { let x = get_value(location, scale, freedom, eval); assert_almost_eq!(expected, x, acc); } fn test_panic<F>(location: f64, scale: f64, freedom: f64, eval: F) where F : Fn(StudentsT) -> f64, F : panic::UnwindSafe { let result = panic::catch_unwind(|| { get_value(location, scale, freedom, eval) }); assert!(result.is_err()); } #[test] fn test_create() { create_case(0.0, 0.1, 1.0); create_case(0.0, 1.0, 1.0); create_case(-5.0, 1.0, 3.0); create_case(10.0, 10.0, f64::INFINITY); } #[test] fn test_bad_create() { bad_create_case(f64::NAN, 1.0, 1.0); bad_create_case(0.0, f64::NAN, 1.0); bad_create_case(0.0, 1.0, f64::NAN); bad_create_case(0.0, -10.0, 1.0); bad_create_case(0.0, 10.0, -1.0); } #[test] fn test_mean() { let mean = |x: StudentsT| x.mean().unwrap(); test_panic(0.0, 1.0, 1.0, mean); test_panic(0.0, 0.1, 1.0, mean); test_case(0.0, 1.0, 3.0, 0.0, mean); test_panic(0.0, 10.0, 1.0, mean); test_case(0.0, 10.0, 2.0, 0.0, mean); test_case(0.0, 10.0, f64::INFINITY, 0.0, mean); test_panic(10.0, 1.0, 1.0, mean); test_case(-5.0, 100.0, 1.5, -5.0, mean); test_panic(0.0, f64::INFINITY, 1.0, mean); } #[test] #[should_panic] fn test_mean_freedom_lte_1() { let mean = |x: StudentsT| x.mean().unwrap(); get_value(1.0, 1.0, 0.5, mean); } #[test] fn test_variance() { let variance = |x: StudentsT| x.variance().unwrap(); test_case(0.0, 1.0, 3.0, 3.0, variance); test_case(0.0, 10.0, 2.5, 500.0, variance); test_case(10.0, 1.0, 2.5, 5.0, variance); let variance = |x: StudentsT| x.variance(); test_case(0.0, 10.0, 2.0, None, variance); test_case(0.0, 1.0, 1.0, None, variance); test_case(0.0, 0.1, 1.0, None, variance); test_case(0.0, 10.0, 1.0, None, variance); test_case(10.0, 1.0, 1.0, None, variance); test_case(-5.0, 100.0, 1.5, None, variance); test_case(0.0, f64::INFINITY, 1.0, None, variance); } #[test] #[should_panic] fn test_variance_freedom_lte1() { let variance = |x: StudentsT| x.variance().unwrap(); get_value(1.0, 1.0, 0.5, variance); } // TODO: valid skewness tests #[test] #[should_panic] fn test_skewness_freedom_lte_3() { let skewness = |x: StudentsT| x.skewness().unwrap(); get_value(1.0, 1.0, 1.0, skewness); } #[test] fn test_mode() { let mode = |x: StudentsT| x.mode().unwrap(); test_case(0.0, 1.0, 1.0, 0.0, mode); test_case(0.0, 0.1, 1.0, 0.0, mode); test_case(0.0, 1.0, 3.0, 0.0, mode); test_case(0.0, 10.0, 1.0, 0.0, mode); test_case(0.0, 10.0, 2.0, 0.0, mode); test_case(0.0, 10.0, 2.5, 0.0, mode); test_case(0.0, 10.0, f64::INFINITY, 0.0, mode); test_case(10.0, 1.0, 1.0, 10.0, mode); test_case(10.0, 1.0, 2.5, 10.0, mode); test_case(-5.0, 100.0, 1.5, -5.0, mode); test_case(0.0, f64::INFINITY, 1.0, 0.0, mode); } #[test] fn test_median() { let median = |x: StudentsT| x.median(); test_case(0.0, 1.0, 1.0, 0.0, median); test_case(0.0, 0.1, 1.0, 0.0, median); test_case(0.0, 1.0, 3.0, 0.0, median); test_case(0.0, 10.0, 1.0, 0.0, median); test_case(0.0, 10.0, 2.0, 0.0, median); test_case(0.0, 10.0, 2.5, 0.0, median); test_case(0.0, 10.0, f64::INFINITY, 0.0, median); test_case(10.0, 1.0, 1.0, 10.0, median); test_case(10.0, 1.0, 2.5, 10.0, median); test_case(-5.0, 100.0, 1.5, -5.0, median); test_case(0.0, f64::INFINITY, 1.0, 0.0, median); } #[test] fn test_min_max() { let min = |x: StudentsT| x.min(); let max = |x: StudentsT| x.max(); test_case(0.0, 1.0, 1.0, f64::NEG_INFINITY, min); test_case(2.5, 100.0, 1.5, f64::NEG_INFINITY, min); test_case(10.0, f64::INFINITY, 3.5, f64::NEG_INFINITY, min); test_case(0.0, 1.0, 1.0, f64::INFINITY, max); test_case(2.5, 100.0, 1.5, f64::INFINITY, max); test_case(10.0, f64::INFINITY, 5.5, f64::INFINITY, max); } #[test] fn test_pdf() { let pdf = |arg: f64| move |x: StudentsT| x.pdf(arg); test_almost(0.0, 1.0, 1.0, 0.318309886183791, 1e-15, pdf(0.0)); test_almost(0.0, 1.0, 1.0, 0.159154943091895, 1e-15, pdf(1.0)); test_almost(0.0, 1.0, 1.0, 0.159154943091895, 1e-15, pdf(-1.0)); test_almost(0.0, 1.0, 1.0, 0.063661977236758, 1e-15, pdf(2.0)); test_almost(0.0, 1.0, 1.0, 0.063661977236758, 1e-15, pdf(-2.0)); test_almost(0.0, 1.0, 2.0, 0.353553390593274, 1e-15, pdf(0.0)); test_almost(0.0, 1.0, 2.0, 0.192450089729875, 1e-15, pdf(1.0)); test_almost(0.0, 1.0, 2.0, 0.192450089729875, 1e-15, pdf(-1.0)); test_almost(0.0, 1.0, 2.0, 0.068041381743977, 1e-15, pdf(2.0)); test_almost(0.0, 1.0, 2.0, 0.068041381743977, 1e-15, pdf(-2.0)); test_almost(0.0, 1.0, f64::INFINITY, 0.398942280401433, 1e-15, pdf(0.0)); test_almost(0.0, 1.0, f64::INFINITY, 0.241970724519143, 1e-15, pdf(1.0)); test_almost(0.0, 1.0, f64::INFINITY, 0.053990966513188, 1e-15, pdf(2.0)); } #[test] fn test_ln_pdf() { let ln_pdf = |arg: f64| move |x: StudentsT| x.ln_pdf(arg); test_almost(0.0, 1.0, 1.0, -1.144729885849399, 1e-14, ln_pdf(0.0)); test_almost(0.0, 1.0, 1.0, -1.837877066409348, 1e-14, ln_pdf(1.0)); test_almost(0.0, 1.0, 1.0, -1.837877066409348, 1e-14, ln_pdf(-1.0)); test_almost(0.0, 1.0, 1.0, -2.754167798283503, 1e-14, ln_pdf(2.0)); test_almost(0.0, 1.0, 1.0, -2.754167798283503, 1e-14, ln_pdf(-2.0)); test_almost(0.0, 1.0, 2.0, -1.039720770839917, 1e-14, ln_pdf(0.0)); test_almost(0.0, 1.0, 2.0, -1.647918433002166, 1e-14, ln_pdf(1.0)); test_almost(0.0, 1.0, 2.0, -1.647918433002166, 1e-14, ln_pdf(-1.0)); test_almost(0.0, 1.0, 2.0, -2.687639203842085, 1e-14, ln_pdf(2.0)); test_almost(0.0, 1.0, 2.0, -2.687639203842085, 1e-14, ln_pdf(-2.0)); test_almost(0.0, 1.0, f64::INFINITY, -0.918938533204672, 1e-14, ln_pdf(0.0)); test_almost(0.0, 1.0, f64::INFINITY, -1.418938533204674, 1e-14, ln_pdf(1.0)); test_almost(0.0, 1.0, f64::INFINITY, -2.918938533204674, 1e-14, ln_pdf(2.0)); } #[test] fn test_cdf() { let cdf = |arg: f64| move |x: StudentsT| x.cdf(arg); test_case(0.0, 1.0, 1.0, 0.5, cdf(0.0)); test_almost(0.0, 1.0, 1.0, 0.75, 1e-15, cdf(1.0)); test_almost(0.0, 1.0, 1.0, 0.25, 1e-15, cdf(-1.0)); test_almost(0.0, 1.0, 1.0, 0.852416382349567, 1e-15, cdf(2.0)); test_almost(0.0, 1.0, 1.0, 0.147583617650433, 1e-15, cdf(-2.0)); test_case(0.0, 1.0, 2.0, 0.5, cdf(0.0)); test_almost(0.0, 1.0, 2.0, 0.788675134594813, 1e-15, cdf(1.0)); test_almost(0.0, 1.0, 2.0, 0.211324865405187, 1e-15, cdf(-1.0)); test_almost(0.0, 1.0, 2.0, 0.908248290463863, 1e-15, cdf(2.0)); test_almost(0.0, 1.0, 2.0, 0.091751709536137, 1e-15, cdf(-2.0)); test_case(0.0, 1.0, f64::INFINITY, 0.5, cdf(0.0)); // TODO: these are curiously low accuracy and should be re-examined test_almost(0.0, 1.0, f64::INFINITY, 0.841344746068543, 1e-10, cdf(1.0)); test_almost(0.0, 1.0, f64::INFINITY, 0.977249868051821, 1e-11, cdf(2.0)); } #[test] fn test_continuous() { test::check_continuous_distribution(&try_create(0.0, 1.0, 3.0), -30.0, 30.0); test::check_continuous_distribution(&try_create(0.0, 1.0, 10.0), -10.0, 10.0); test::check_continuous_distribution(&try_create(20.0, 0.5, 10.0), 10.0, 30.0); } #[test] fn test_inv_cdf() { let test = |x: f64, freedom: f64, expected: f64| { use approx::*; let d = StudentsT::new(0., 1., freedom).unwrap(); // Checks that left == right to 4 significant figures, unlike // test_almost() which uses decimal places assert_relative_eq!(d.inverse_cdf(x), expected, max_relative = 0.001); }; // This test checks our implementation against the whole t-table // copied from https://en.wikipedia.org/wiki/Student's_t-distribution test(0.75, 1.0, 1.000); test(0.8, 1.0, 1.376); test(0.85, 1.0, 1.963); test(0.9, 1.0, 3.078); test(0.95, 1.0, 6.314); test(0.975, 1.0, 12.71); test(0.99, 1.0, 31.82); test(0.995, 1.0, 63.66); test(0.9975, 1.0, 127.3); test(0.999, 1.0, 318.3); test(0.9995, 1.0, 636.6); test(0.75, 002.0, 0.816); // test(0.8, 002.0, 1.080); // We get 1.061 for some reason... test(0.85, 002.0, 1.386); test(0.9, 002.0, 1.886); test(0.95, 002.0, 2.920); test(0.975, 002.0, 4.303); test(0.99, 002.0, 6.965); test(0.995, 002.0, 9.925); test(0.9975, 002.0, 14.09); test(0.999, 002.0, 22.33); test(0.9995, 002.0, 31.60); test(0.75, 003.0, 0.765); test(0.8, 003.0, 0.978); test(0.85, 003.0, 1.250); test(0.9, 003.0, 1.638); test(0.95, 003.0, 2.353); test(0.975, 003.0, 3.182); test(0.99, 003.0, 4.541); test(0.995, 003.0, 5.841); test(0.9975, 003.0, 7.453); test(0.999, 003.0, 10.21); test(0.9995, 003.0, 12.92); test(0.75, 004.0, 0.741); test(0.8, 004.0, 0.941); test(0.85, 004.0, 1.190); test(0.9, 004.0, 1.533); test(0.95, 004.0, 2.132); test(0.975, 004.0, 2.776); test(0.99, 004.0, 3.747); test(0.995, 004.0, 4.604); test(0.9975, 004.0, 5.598); test(0.999, 004.0, 7.173); test(0.9995, 004.0, 8.610); test(0.75, 005.0, 0.727); test(0.8, 005.0, 0.920); test(0.85, 005.0, 1.156); test(0.9, 005.0, 1.476); test(0.95, 005.0, 2.015); test(0.975, 005.0, 2.571); test(0.99, 005.0, 3.365); test(0.995, 005.0, 4.032); test(0.9975, 005.0, 4.773); test(0.999, 005.0, 5.893); test(0.9995, 005.0, 6.869); test(0.75, 006.0, 0.718); test(0.8, 006.0, 0.906); test(0.85, 006.0, 1.134); test(0.9, 006.0, 1.440); test(0.95, 006.0, 1.943); test(0.975, 006.0, 2.447); test(0.99, 006.0, 3.143); test(0.995, 006.0, 3.707); test(0.9975, 006.0, 4.317); test(0.999, 006.0, 5.208); test(0.9995, 006.0, 5.959); test(0.75, 007.0, 0.711); test(0.8, 007.0, 0.896); test(0.85, 007.0, 1.119); test(0.9, 007.0, 1.415); test(0.95, 007.0, 1.895); test(0.975, 007.0, 2.365); test(0.99, 007.0, 2.998); test(0.995, 007.0, 3.499); test(0.9975, 007.0, 4.029); test(0.999, 007.0, 4.785); test(0.9995, 007.0, 5.408); test(0.75, 008.0, 0.706); test(0.8, 008.0, 0.889); test(0.85, 008.0, 1.108); test(0.9, 008.0, 1.397); test(0.95, 008.0, 1.860); test(0.975, 008.0, 2.306); test(0.99, 008.0, 2.896); test(0.995, 008.0, 3.355); test(0.9975, 008.0, 3.833); test(0.999, 008.0, 4.501); test(0.9995, 008.0, 5.041); test(0.75, 009.0, 0.703); test(0.8, 009.0, 0.883); test(0.85, 009.0, 1.100); test(0.9, 009.0, 1.383); test(0.95, 009.0, 1.833); test(0.975, 009.0, 2.262); test(0.99, 009.0, 2.821); test(0.995, 009.0, 3.250); test(0.9975, 009.0, 3.690); test(0.999, 009.0, 4.297); test(0.9995, 009.0, 4.781); test(0.75, 010.0, 0.700); test(0.8, 010.0, 0.879); test(0.85, 010.0, 1.093); test(0.9, 010.0, 1.372); test(0.95, 010.0, 1.812); test(0.975, 010.0, 2.228); test(0.99, 010.0, 2.764); test(0.995, 010.0, 3.169); test(0.9975, 010.0, 3.581); test(0.999, 010.0, 4.144); test(0.9995, 010.0, 4.587); test(0.75, 011.0, 0.697); test(0.8, 011.0, 0.876); test(0.85, 011.0, 1.088); test(0.9, 011.0, 1.363); test(0.95, 011.0, 1.796); test(0.975, 011.0, 2.201); test(0.99, 011.0, 2.718); test(0.995, 011.0, 3.106); test(0.9975, 011.0, 3.497); test(0.999, 011.0, 4.025); test(0.9995, 011.0, 4.437); test(0.75, 012.0, 0.695); test(0.8, 012.0, 0.873); test(0.85, 012.0, 1.083); test(0.9, 012.0, 1.356); test(0.95, 012.0, 1.782); test(0.975, 012.0, 2.179); test(0.99, 012.0, 2.681); test(0.995, 012.0, 3.055); test(0.9975, 012.0, 3.428); test(0.999, 012.0, 3.930); test(0.9995, 012.0, 4.318); test(0.75, 013.0, 0.694); test(0.8, 013.0, 0.870); test(0.85, 013.0, 1.079); test(0.9, 013.0, 1.350); test(0.95, 013.0, 1.771); test(0.975, 013.0, 2.160); test(0.99, 013.0, 2.650); test(0.995, 013.0, 3.012); test(0.9975, 013.0, 3.372); test(0.999, 013.0, 3.852); test(0.9995, 013.0, 4.221); test(0.75, 014.0, 0.692); test(0.8, 014.0, 0.868); test(0.85, 014.0, 1.076); test(0.9, 014.0, 1.345); test(0.95, 014.0, 1.761); test(0.975, 014.0, 2.145); test(0.99, 014.0, 2.624); test(0.995, 014.0, 2.977); test(0.9975, 014.0, 3.326); test(0.999, 014.0, 3.787); test(0.9995, 014.0, 4.140); test(0.75, 015.0, 0.691); test(0.8, 015.0, 0.866); test(0.85, 015.0, 1.074); test(0.9, 015.0, 1.341); test(0.95, 015.0, 1.753); test(0.975, 015.0, 2.131); test(0.99, 015.0, 2.602); test(0.995, 015.0, 2.947); test(0.9975, 015.0, 3.286); test(0.999, 015.0, 3.733); test(0.9995, 015.0, 4.073); test(0.75, 016.0, 0.690); test(0.8, 016.0, 0.865); test(0.85, 016.0, 1.071); test(0.9, 016.0, 1.337); test(0.95, 016.0, 1.746); test(0.975, 016.0, 2.120); test(0.99, 016.0, 2.583); test(0.995, 016.0, 2.921); test(0.9975, 016.0, 3.252); test(0.999, 016.0, 3.686); test(0.9995, 016.0, 4.015); test(0.75, 017.0, 0.689); test(0.8, 017.0, 0.863); test(0.85, 017.0, 1.069); test(0.9, 017.0, 1.333); test(0.95, 017.0, 1.740); test(0.975, 017.0, 2.110); test(0.99, 017.0, 2.567); test(0.995, 017.0, 2.898); test(0.9975, 017.0, 3.222); test(0.999, 017.0, 3.646); test(0.9995, 017.0, 3.965); test(0.75, 018.0, 0.688); test(0.8, 018.0, 0.862); test(0.85, 018.0, 1.067); test(0.9, 018.0, 1.330); test(0.95, 018.0, 1.734); test(0.975, 018.0, 2.101); test(0.99, 018.0, 2.552); test(0.995, 018.0, 2.878); test(0.9975, 018.0, 3.197); test(0.999, 018.0, 3.610); test(0.9995, 018.0, 3.922); test(0.75, 019.0, 0.688); test(0.8, 019.0, 0.861); test(0.85, 019.0, 1.066); test(0.9, 019.0, 1.328); test(0.95, 019.0, 1.729); test(0.975, 019.0, 2.093); test(0.99, 019.0, 2.539); test(0.995, 019.0, 2.861); test(0.9975, 019.0, 3.174); test(0.999, 019.0, 3.579); test(0.9995, 019.0, 3.883); test(0.75, 020.0, 0.687); test(0.8, 020.0, 0.860); test(0.85, 020.0, 1.064); test(0.9, 020.0, 1.325); test(0.95, 020.0, 1.725); test(0.975, 020.0, 2.086); test(0.99, 020.0, 2.528); test(0.995, 020.0, 2.845); test(0.9975, 020.0, 3.153); test(0.999, 020.0, 3.552); test(0.9995, 020.0, 3.850); test(0.75, 021.0, 0.686); test(0.8, 021.0, 0.859); test(0.85, 021.0, 1.063); test(0.9, 021.0, 1.323); test(0.95, 021.0, 1.721); test(0.975, 021.0, 2.080); test(0.99, 021.0, 2.518); test(0.995, 021.0, 2.831); test(0.9975, 021.0, 3.135); test(0.999, 021.0, 3.527); test(0.9995, 021.0, 3.819); test(0.75, 022.0, 0.686); test(0.8, 022.0, 0.858); test(0.85, 022.0, 1.061); test(0.9, 022.0, 1.321); test(0.95, 022.0, 1.717); test(0.975, 022.0, 2.074); test(0.99, 022.0, 2.508); test(0.995, 022.0, 2.819); test(0.9975, 022.0, 3.119); test(0.999, 022.0, 3.505); test(0.9995, 022.0, 3.792); test(0.75, 023.0, 0.685); test(0.8, 023.0, 0.858); test(0.85, 023.0, 1.060); test(0.9, 023.0, 1.319); test(0.95, 023.0, 1.714); test(0.975, 023.0, 2.069); test(0.99, 023.0, 2.500); test(0.995, 023.0, 2.807); test(0.9975, 023.0, 3.104); test(0.999, 023.0, 3.485); test(0.9995, 023.0, 3.767); test(0.75, 024.0, 0.685); test(0.8, 024.0, 0.857); test(0.85, 024.0, 1.059); test(0.9, 024.0, 1.318); test(0.95, 024.0, 1.711); test(0.975, 024.0, 2.064); test(0.99, 024.0, 2.492); test(0.995, 024.0, 2.797); test(0.9975, 024.0, 3.091); test(0.999, 024.0, 3.467); test(0.9995, 024.0, 3.745); test(0.75, 025.0, 0.684); test(0.8, 025.0, 0.856); test(0.85, 025.0, 1.058); test(0.9, 025.0, 1.316); test(0.95, 025.0, 1.708); test(0.975, 025.0, 2.060); test(0.99, 025.0, 2.485); test(0.995, 025.0, 2.787); test(0.9975, 025.0, 3.078); test(0.999, 025.0, 3.450); test(0.9995, 025.0, 3.725); test(0.75, 026.0, 0.684); test(0.8, 026.0, 0.856); test(0.85, 026.0, 1.058); test(0.9, 026.0, 1.315); test(0.95, 026.0, 1.706); test(0.975, 026.0, 2.056); test(0.99, 026.0, 2.479); test(0.995, 026.0, 2.779); test(0.9975, 026.0, 3.067); test(0.999, 026.0, 3.435); test(0.9995, 026.0, 3.707); test(0.75, 027.0, 0.684); test(0.8, 027.0, 0.855); test(0.85, 027.0, 1.057); test(0.9, 027.0, 1.314); test(0.95, 027.0, 1.703); test(0.975, 027.0, 2.052); test(0.99, 027.0, 2.473); test(0.995, 027.0, 2.771); test(0.9975, 027.0, 3.057); test(0.999, 027.0, 3.421); test(0.9995, 027.0, 3.690); test(0.75, 028.0, 0.683); test(0.8, 028.0, 0.855); test(0.85, 028.0, 1.056); test(0.9, 028.0, 1.313); test(0.95, 028.0, 1.701); test(0.975, 028.0, 2.048); test(0.99, 028.0, 2.467); test(0.995, 028.0, 2.763); test(0.9975, 028.0, 3.047); test(0.999, 028.0, 3.408); test(0.9995, 028.0, 3.674); test(0.75, 029.0, 0.683); test(0.8, 029.0, 0.854); test(0.85, 029.0, 1.055); test(0.9, 029.0, 1.311); test(0.95, 029.0, 1.699); test(0.975, 029.0, 2.045); test(0.99, 029.0, 2.462); test(0.995, 029.0, 2.756); test(0.9975, 029.0, 3.038); test(0.999, 029.0, 3.396); test(0.9995, 029.0, 3.659); test(0.75, 030.0, 0.683); test(0.8, 030.0, 0.854); test(0.85, 030.0, 1.055); test(0.9, 030.0, 1.310); test(0.95, 030.0, 1.697); test(0.975, 030.0, 2.042); test(0.99, 030.0, 2.457); test(0.995, 030.0, 2.750); test(0.9975, 030.0, 3.030); test(0.999, 030.0, 3.385); test(0.9995, 030.0, 3.646); test(0.75, 040.0, 0.681); test(0.8, 040.0, 0.851); test(0.85, 040.0, 1.050); test(0.9, 040.0, 1.303); test(0.95, 040.0, 1.684); test(0.975, 040.0, 2.021); test(0.99, 040.0, 2.423); test(0.995, 040.0, 2.704); test(0.9975, 040.0, 2.971); test(0.999, 040.0, 3.307); test(0.9995, 040.0, 3.551); test(0.75, 050.0, 0.679); test(0.8, 050.0, 0.849); test(0.85, 050.0, 1.047); test(0.9, 050.0, 1.299); test(0.95, 050.0, 1.676); test(0.975, 050.0, 2.009); test(0.99, 050.0, 2.403); test(0.995, 050.0, 2.678); test(0.9975, 050.0, 2.937); test(0.999, 050.0, 3.261); test(0.9995, 050.0, 3.496); test(0.75, 060.0, 0.679); test(0.8, 060.0, 0.848); test(0.85, 060.0, 1.045); test(0.9, 060.0, 1.296); test(0.95, 060.0, 1.671); test(0.975, 060.0, 2.000); test(0.99, 060.0, 2.390); test(0.995, 060.0, 2.660); test(0.9975, 060.0, 2.915); test(0.999, 060.0, 3.232); test(0.9995, 060.0, 3.460); test(0.75, 080.0, 0.678); test(0.8, 080.0, 0.846); test(0.85, 080.0, 1.043); test(0.9, 080.0, 1.292); test(0.95, 080.0, 1.664); test(0.975, 080.0, 1.990); test(0.99, 080.0, 2.374); test(0.995, 080.0, 2.639); test(0.9975, 080.0, 2.887); test(0.999, 080.0, 3.195); test(0.9995, 080.0, 3.416); test(0.75, 100.0, 0.677); test(0.8, 100.0, 0.845); test(0.85, 100.0, 1.042); test(0.9, 100.0, 1.290); test(0.95, 100.0, 1.660); test(0.975, 100.0, 1.984); test(0.99, 100.0, 2.364); test(0.995, 100.0, 2.626); test(0.9975, 100.0, 2.871); test(0.999, 100.0, 3.174); test(0.9995, 100.0, 3.390); test(0.75, 120.0, 0.677); test(0.8, 120.0, 0.845); test(0.85, 120.0, 1.041); test(0.9, 120.0, 1.289); test(0.95, 120.0, 1.658); test(0.975, 120.0, 1.980); test(0.99, 120.0, 2.358); test(0.995, 120.0, 2.617); test(0.9975, 120.0, 2.860); test(0.999, 120.0, 3.160); test(0.9995, 120.0, 3.373); } }
use crate::{ define_node_command, get_set_swap, scene::commands::{Command, SceneContext}, }; use rg3d::{ core::{color::Color, pool::Handle}, resource::texture::Texture, scene::{graph::Graph, node::Node}, }; define_node_command!(SetDecalDiffuseTextureCommand("Set Decal Diffuse Texture", Option<Texture>) where fn swap(self, node) { get_set_swap!(self, node.as_decal_mut(), diffuse_texture_value, set_diffuse_texture); }); define_node_command!(SetDecalNormalTextureCommand("Set Decal Normal Texture", Option<Texture>) where fn swap(self, node) { get_set_swap!(self, node.as_decal_mut(), normal_texture_value, set_normal_texture); }); define_node_command!(SetDecalColorCommand("Set Decal Color", Color) where fn swap(self, node) { get_set_swap!(self, node.as_decal_mut(), color, set_color); }); define_node_command!(SetDecalLayerIndexCommand("Set Decal Layer Index", u8) where fn swap(self, node) { get_set_swap!(self, node.as_decal_mut(), layer, set_layer); });
use radmin::uuid::Uuid; use serde::{Deserialize, Serialize}; use crate::schema::organizations; use radmin::chrono::{DateTime, Utc}; #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Queryable, Identifiable, AsChangeset)] #[table_name = "organizations"] pub struct OrganizationInfo { pub id: Uuid, pub name: String, pub updated_at: DateTime<Utc>, pub created_at: DateTime<Utc>, }
use std::collections::BTreeMap; use crate::db::Db; use crate::db::entities::Candidate; pub async fn tally(db: &Db) -> sqlx::Result<(String, Vec<(String, String, bool)>)>{ let mut tally = Tally::new(db).await?; //TODO: use a transaction to prevent the data from changing while we read it let mut round_id = 1; let description; let mut fields = Vec::new(); loop{ let field_title = format!("The results from round {} are:", round_id); let provisional_tally = tally.tally_current_round(); let mut sorted_tally = provisional_tally.iter().collect::<Vec<(&(String, u32), &u32)>>(); sorted_tally.sort_by(|a, b|{ a.0.1.partial_cmp(&(b.0.1)).unwrap() }); let mut field_description = String::new(); for ((name, _id), count) in sorted_tally{ field_description.push_str(&format!(" - {} with {} votes\n", name, count)); } let majority = Tally::majority(&provisional_tally); if let Some(majority) = majority{ description = format!("\n**A winner has been selected after {} rounds: __{}__\n**", round_id, majority); fields.push((field_title, field_description, false)); break; } let least_popular = tally.least_popular(&provisional_tally); match least_popular{ Some(least_popular) => { let name = &tally.options.get(&least_popular).unwrap().name; field_description.push_str(&format!("\nRedistributing votes from the least popular option: {}\n\n", name)); tally.eliminate(least_popular).await?; fields.push((field_title, field_description, false)); }, None => { description = "It looks like no votes are left, aborting.\n".into(); fields.push((field_title, field_description, false)); break; } } round_id += 1; } Ok((description, fields)) } struct VoterData{ choice_number: u32, option: Option<u32> } struct Tally<'a>{ db: &'a Db, options: BTreeMap<u32, Candidate>, data: BTreeMap<u64, VoterData> } impl<'a> Tally<'a>{ async fn new(db: &'a Db) -> sqlx::Result<Tally<'a>>{ let mut options = BTreeMap::new(); for candidate in db.list_candidates().await?{ options.insert(candidate.id, candidate); } let mut data = BTreeMap::new(); for vote in db.get_1st_votes().await?.iter(){ data.insert(vote.user, VoterData{ choice_number: 1, option: Some(vote.option) }); } Ok( Self{ db, options, data } ) } fn tally_current_round(&self) -> BTreeMap<(String, u32), u32>{ //count let mut running_totals = BTreeMap::new(); for key in self.options.keys(){ running_totals.insert(*key, 0); } for value in self.data.values(){ if let Some(option) = &value.option{ *running_totals.get_mut(option).unwrap() += 1; } } //convert to strings let mut strings = BTreeMap::new(); for (id, candidate) in &self.options{ strings.insert((candidate.name.clone(), *id), *running_totals.get(id).unwrap()); } strings } fn majority(tally: &BTreeMap<(String, u32), u32>) -> Option<String>{ //calculate total votes let mut total_votes = 0; for (_, count) in tally{ total_votes += count; } //determine number of needed votes let needed = ((total_votes as f64)/2.0).ceil() as u32; //determine if the threshold is reached let mut majority = None; for ((name, _id), count) in tally{ if *count >= needed{ if majority.is_some(){ return None; } majority = Some(name.into()); } } majority } fn least_popular(&self, tally: &BTreeMap<(String, u32), u32>) -> Option<u32>{ let mut least_popular_count = 0; let mut least_popular = None; for ((_name, id), count) in tally{ if *count != 0 && (least_popular.is_none() || *count < least_popular_count){ least_popular = Some(*id); least_popular_count = *count; } } least_popular } async fn eliminate(&mut self, id: u32) -> sqlx::Result<()>{ for (user_id, data) in &mut self.data{ if let Some(option) = data.option{ if option == id { data.choice_number += 1; data.option = self.db.get_nth_vote(*user_id, data.choice_number).await?; } } } Ok(()) } }
use slotmap::{Key, SlotMap}; // ------------------------------------------------------------------------------------------------- // TODO lots of unwraps here, should at least give useful error messages pub struct Forest<K, I> where K: Key { nodes: SlotMap<K, ForestNode<K, I>>, } impl<K, I> Forest<K, I> where K: Key { pub fn new() -> Forest<K, I> { Forest { nodes: SlotMap::with_key() } } pub fn get(&self, node: K) -> &I { &self.nodes.get(node).unwrap().item } pub fn get_mut(&mut self, node: K) -> &mut I { &mut self.nodes.get_mut(node).unwrap().item } pub fn get_parent(&self, node: K) -> K { self.nodes.get(node).unwrap().parent } pub fn set_parent(&mut self, node: K, parent: K) { let old_parent = self.nodes.get(node).unwrap().parent; if old_parent == parent { return; } if !old_parent.is_null() { self.nodes.get_mut(old_parent).unwrap().remove_child(node); } self.nodes.get_mut(node).unwrap().parent = parent; if !parent.is_null() { self.nodes.get_mut(parent).unwrap().children.push(node); } } pub fn contains(&self, node: K) -> bool { self.nodes.contains_key(node) } pub fn add(&mut self, item: I) -> K { self.nodes.insert(ForestNode::new(item, K::null())) } pub fn remove(&mut self, node: K) -> I { self.set_parent(node, K::null()); self.remove_node_and_children(node) } fn remove_node_and_children(&mut self, node: K) -> I { let mut node_data = self.nodes.remove(node).unwrap(); for child in node_data.children.drain(..) { self.remove_node_and_children(child); } node_data.item } pub fn add_child(&mut self, parent: K, item: I) -> K { let node = self.nodes.insert(ForestNode::new(item, parent)); if !parent.is_null() { self.nodes.get_mut(parent).unwrap().children.push(node); } node } pub fn get_child_count(&self, node: K) -> usize { self.nodes.get(node).unwrap().children.len() } pub fn get_children(&self, node: K) -> Vec<K> { self.nodes.get(node).unwrap().children.clone() } pub fn iter_children(&self, node: K) -> std::slice::Iter<'_, K> { self.nodes.get(node).unwrap().children.iter() } } pub struct ForestNode<K, I> where K: Key { parent: K, children: Vec<K>, item: I, } impl<K, I> ForestNode<K, I> where K: Key { fn new(item: I, parent: K) -> ForestNode<K, I> { ForestNode { parent, children: Vec::new(), item, } } fn remove_child(&mut self, child: K) { self.children.remove(self.children.iter().position(|x| *x == child).unwrap()); } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ models::{DisplayInfo, Suggestion}, story_context_store::ContextEntity, story_manager::StoryManager, suggestions_manager::SearchSuggestionsProvider, }, failure::Error, futures::future::LocalFutureObj, parking_lot::Mutex, std::sync::Arc, }; pub struct StorySuggestionsProvider { story_manager: Arc<Mutex<StoryManager>>, } impl StorySuggestionsProvider { pub fn new(story_manager: Arc<Mutex<StoryManager>>) -> Self { StorySuggestionsProvider { story_manager } } fn new_story_suggestion(story_name: String, story_title: String) -> Suggestion { Suggestion::new_story_suggestion( story_name, DisplayInfo::new().with_title(format!("Restore {}", story_title).as_str()), ) } } impl SearchSuggestionsProvider for StorySuggestionsProvider { fn request<'a>( &'a self, _query: &'a str, _context: &'a Vec<&'a ContextEntity>, ) -> LocalFutureObj<'a, Result<Vec<Suggestion>, Error>> { LocalFutureObj::new(Box::new(async move { let story_manager = self.story_manager.lock(); let name_titles = story_manager.get_name_titles().await?; let result = name_titles .into_iter() .map(|(name, title)| StorySuggestionsProvider::new_story_suggestion(name, title)) .collect::<Vec<Suggestion>>(); Ok(result) })) } } #[cfg(test)] mod tests { use {super::*, crate::models::SuggestedAction}; #[test] fn new_story_suggestion() { let suggestion = StorySuggestionsProvider::new_story_suggestion( "story_name".to_string(), "story_title".to_string(), ); assert_eq!( suggestion.display_info().title.clone().unwrap(), "Restore story_title".to_string() ); match suggestion.action() { SuggestedAction::RestoreStory(restore_story_info) => { assert_eq!(restore_story_info.story_name.to_string(), "story_name"); } SuggestedAction::AddMod(_) => { assert!(false); } } } }
use crate::Rolls; #[cfg(test)] mod unit_tests; pub fn score(rolls: &Rolls) -> u16 { foo(rolls.0.iter(), 1) } // variable-width fold // Item is an associated type fn foo<'a>(mut rolls: impl Iterator<Item = &'a u8> + Clone, frame_number: usize) -> u16 { // base case: if frame_number > 10 { return 0; } let mut frame_score = 0; let roll_count = rolls // by_ref ("by_ref_mut") helps us keep ownership by giving // exclusive "unique access" via mutable borrowing - // (different than transferring ownership) .by_ref() .enumerate() // double ref here with take_while: Because the closure passed // to take_while() takes a reference, and many iterators // iterate over references, this leads to a possibly confusing // situation, where the type of the closure is a double // reference: .take_while(|&(i, &roll)| { // This is our "predicate" - a single variable function that returns a bool frame_score += roll; // take_while will throw away the item if predicate returns false!!! i == 0 && roll < 10 }).count() // +1 accounts for the last take_while iteration, which is // dropped when the predicate returns false. + 1; // take_while drops the borrow here. let bonus = rolls .clone() .take(match (roll_count, frame_score) { (1, 10) => 2, (2, 10) => 1, _ => 0, }) .sum::<u8>(); // recusive case - tail recursion // rolls still owns the data u16::from(frame_score + bonus) + foo(rolls, frame_number + 1) }
use crate::utils::file2vec; pub fn day11(filename: &String){ let contents = file2vec::<String>(filename); let contents:Vec<Vec<Seat>> = contents.iter().map(|x| x.to_owned().unwrap().chars().fold(Vec::new(), |mut acc, c| { acc.push(Seat::from_char(&c)); acc }) ).collect(); let mut ferry = Ferry::new(contents); let mut loops = 0; loop { loops +=1; ferry.tick(); if ferry.diff(){ break }; ferry.update(); } println!("part 1 ans {}", ferry.count_occupied_seats()); ferry.reset(); let mut loops = 0; loop { loops +=1; ferry.tick_part2(); if ferry.diff(){ break }; ferry.update(); } println!("part 2 ans {}", ferry.count_occupied_seats()); } #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum State { Occupied = 1, Unnocupied = 0, Floor = -1 } #[derive(Debug, Copy, Clone)] struct Seat { state: State, next_state: Option<State> } impl Seat { fn from_char(ch: &char)->Self{ let state = match ch { 'L' => State::Unnocupied, '#' => State::Occupied, _ => State::Floor }; Seat { state, next_state: None } } } #[derive(Debug)] struct Ferry { seats: Vec<Vec<Seat>>, h: usize, w: usize } impl Ferry { fn new(seats: Vec<Vec<Seat>>)->Ferry { let h = seats.len(); let w = seats[0].len(); Ferry { seats, h, w } } fn occupied_neighbours(&mut self, row: usize, col: usize)->i8 { let mut count = 0; for delta_row in [-1, 0, 1].iter().cloned() { for delta_col in [-1, 0, 1].iter().cloned() { if delta_row == 0 && delta_col == 0 { continue; } let neighbor_row = row as i16 + delta_row ; let neighbor_col = col as i16 + delta_col ; if (neighbor_col< self.w as i16) & (neighbor_col>=0) & (neighbor_row< self.h as i16) & (neighbor_row>=0){ count += 0.max(self.seats[neighbor_row as usize][neighbor_col as usize].state as i8); } } } count } fn diff(&self)->bool { for row in 0..self.h { for col in 0..self.w { if let Some(x) = self.seats[row][col].next_state { return false } } }; true } fn tick(&mut self){ for row in 0..self.h{ for col in 0..self.w{ match self.seats[row][col].state { State::Occupied => { if &self.occupied_neighbours(row, col) >= &4 { self.seats[row][col].next_state = Some(State::Unnocupied); } }, State::Unnocupied => { if &self.occupied_neighbours(row, col) == &0 { self.seats[row][col].next_state = Some(State::Occupied); } }, _ => () }; } } } fn update(&mut self){ for row in 0..self.h{ for col in 0..self.w{ if let Some(state) = self.seats[row][col].next_state { self.seats[row][col].state = state; self.seats[row][col].next_state = None; } } } } fn count_occupied_seats(&self)->i16 { let mut count: i16 = 0; for row in 0..self.h{ for col in 0..self.w{ if self.seats[row][col].state == State::Occupied { count +=1; } } } count } fn occupied_neighbours_part2(&mut self, row: usize, col: usize)->i8 { let mut count = 0; let mut look_row = row ; let mut look_col = col; //look right look_col += 1; while look_col < self.w { match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => {look_col += 1;}, _ => { break } } } look_col = col; //look left // look_col -= 1; while look_col > 0 { look_col -= 1; match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => (), _ => { break } } } look_col = col; //look down look_row += 1; while look_row < self.h { match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => {look_row += 1;}, _ => { break } } } look_row = row; //look up while look_row > 0 { look_row -= 1; match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => (), _ => { break } } } look_row = row; //look down & right look_row += 1; look_col += 1; while (look_col < self.w) & (look_row < self.h){ match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => { look_row += 1; look_col += 1; }, _ => { break } } } look_row = row; look_col = col; //look down & left look_row += 1; while (look_col >0) & (look_row < self.h){ look_col -= 1; match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => { look_row += 1; }, _ => { break } } } look_row = row; look_col = col; //look up & right look_col += 1; while (look_col < self.w) & (look_row > 0){ look_row -= 1; match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => { // look_row -= 1; look_col += 1; }, _ => { break } } } look_row = row; look_col = col; //look up & left while (look_col > 0) & (look_row > 0){ look_row -= 1; look_col -= 1; match self.seats[look_row][look_col].state { State::Occupied => { count +=1; break }, State::Floor => (), _ => { break } } } count } fn tick_part2(&mut self){ for row in 0..self.h{ for col in 0..self.w{ match self.seats[row][col].state { State::Occupied => { if &self.occupied_neighbours_part2(row, col) >= &5 { self.seats[row][col].next_state = Some(State::Unnocupied); } }, State::Unnocupied => { if &self.occupied_neighbours_part2(row, col) == &0 { self.seats[row][col].next_state = Some(State::Occupied); } }, _ => () }; } } } fn reset(&mut self){ for row in 0..self.h{ for col in 0..self.w{ self.seats[row][col].next_state = None; match self.seats[row][col].state { State::Occupied => { self.seats[row][col].state = State::Unnocupied; } _ => () } } } } }
fn main() { panic!("panicking furiously"); }
/// CreateStatusOption holds the information needed to create a new Status for a Commit #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CreateStatusOption { pub context: Option<String>, pub description: Option<String>, pub state: Option<String>, pub target_url: Option<String>, } impl CreateStatusOption { /// Create a builder for this object. #[inline] pub fn builder() -> CreateStatusOptionBuilder { CreateStatusOptionBuilder { body: Default::default(), } } #[inline] pub fn repo_create_status() -> CreateStatusOptionPostBuilder<crate::generics::MissingOwner, crate::generics::MissingRepo, crate::generics::MissingSha> { CreateStatusOptionPostBuilder { inner: Default::default(), _param_owner: core::marker::PhantomData, _param_repo: core::marker::PhantomData, _param_sha: core::marker::PhantomData, } } } impl Into<CreateStatusOption> for CreateStatusOptionBuilder { fn into(self) -> CreateStatusOption { self.body } } impl Into<CreateStatusOption> for CreateStatusOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists> { fn into(self) -> CreateStatusOption { self.inner.body } } /// Builder for [`CreateStatusOption`](./struct.CreateStatusOption.html) object. #[derive(Debug, Clone)] pub struct CreateStatusOptionBuilder { body: self::CreateStatusOption, } impl CreateStatusOptionBuilder { #[inline] pub fn context(mut self, value: impl Into<String>) -> Self { self.body.context = Some(value.into()); self } #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.body.description = Some(value.into()); self } #[inline] pub fn state(mut self, value: impl Into<String>) -> Self { self.body.state = Some(value.into()); self } #[inline] pub fn target_url(mut self, value: impl Into<String>) -> Self { self.body.target_url = Some(value.into()); self } } /// Builder created by [`CreateStatusOption::repo_create_status`](./struct.CreateStatusOption.html#method.repo_create_status) method for a `POST` operation associated with `CreateStatusOption`. #[repr(transparent)] #[derive(Debug, Clone)] pub struct CreateStatusOptionPostBuilder<Owner, Repo, Sha> { inner: CreateStatusOptionPostBuilderContainer, _param_owner: core::marker::PhantomData<Owner>, _param_repo: core::marker::PhantomData<Repo>, _param_sha: core::marker::PhantomData<Sha>, } #[derive(Debug, Default, Clone)] struct CreateStatusOptionPostBuilderContainer { body: self::CreateStatusOption, param_owner: Option<String>, param_repo: Option<String>, param_sha: Option<String>, } impl<Owner, Repo, Sha> CreateStatusOptionPostBuilder<Owner, Repo, Sha> { /// owner of the repo #[inline] pub fn owner(mut self, value: impl Into<String>) -> CreateStatusOptionPostBuilder<crate::generics::OwnerExists, Repo, Sha> { self.inner.param_owner = Some(value.into()); unsafe { std::mem::transmute(self) } } /// name of the repo #[inline] pub fn repo(mut self, value: impl Into<String>) -> CreateStatusOptionPostBuilder<Owner, crate::generics::RepoExists, Sha> { self.inner.param_repo = Some(value.into()); unsafe { std::mem::transmute(self) } } /// sha of the commit #[inline] pub fn sha(mut self, value: impl Into<String>) -> CreateStatusOptionPostBuilder<Owner, Repo, crate::generics::ShaExists> { self.inner.param_sha = Some(value.into()); unsafe { std::mem::transmute(self) } } #[inline] pub fn context(mut self, value: impl Into<String>) -> Self { self.inner.body.context = Some(value.into()); self } #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.inner.body.description = Some(value.into()); self } #[inline] pub fn state(mut self, value: impl Into<String>) -> Self { self.inner.body.state = Some(value.into()); self } #[inline] pub fn target_url(mut self, value: impl Into<String>) -> Self { self.inner.body.target_url = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateStatusOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists> { type Output = crate::status::Status; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { format!("/repos/{owner}/{repo}/statuses/{sha}", owner=self.inner.param_owner.as_ref().expect("missing parameter owner?"), repo=self.inner.param_repo.as_ref().expect("missing parameter repo?"), sha=self.inner.param_sha.as_ref().expect("missing parameter sha?")).into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.inner.body)) } } impl crate::client::ResponseWrapper<crate::status::Status, CreateStatusOptionPostBuilder<crate::generics::OwnerExists, crate::generics::RepoExists, crate::generics::ShaExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } }
use std::env; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn get_file_content(file_path: &str) -> Vec<char> { let work_dir = env::current_dir().unwrap(); let full_file_path = work_dir.join(Path::new(file_path)); let mut file = File::open(full_file_path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); contents.chars().collect() }
//! # The XML `<BlockLibrary>` format //! //! This is use in: //! - The `res/ui/ingame/blocksdef.xml` file
#[doc = "Register `APB1_FZ` reader"] pub type R = crate::R<APB1_FZ_SPEC>; #[doc = "Register `APB1_FZ` writer"] pub type W = crate::W<APB1_FZ_SPEC>; #[doc = "Field `DBG_TIMER2_STOP` reader - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_R = crate::BitReader<DBG_TIMER2_STOP_A>; #[doc = "Debug Timer 2 stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_TIMER2_STOP_A { #[doc = "0: The counter clock of TIMx is fed even if the core is halted"] Continue = 0, #[doc = "1: The counter clock of TIMx is stopped when the core is halted"] Stop = 1, } impl From<DBG_TIMER2_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_TIMER2_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_TIMER2_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_TIMER2_STOP_A { match self.bits { false => DBG_TIMER2_STOP_A::Continue, true => DBG_TIMER2_STOP_A::Stop, } } #[doc = "The counter clock of TIMx is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_TIMER2_STOP_A::Continue } #[doc = "The counter clock of TIMx is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_TIMER2_STOP_A::Stop } } #[doc = "Field `DBG_TIMER2_STOP` writer - Debug Timer 2 stopped when Core is halted"] pub type DBG_TIMER2_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_TIMER2_STOP_A>; impl<'a, REG, const O: u8> DBG_TIMER2_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The counter clock of TIMx is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_TIMER2_STOP_A::Continue) } #[doc = "The counter clock of TIMx is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_TIMER2_STOP_A::Stop) } } #[doc = "Field `DBG_TIMER6_STOP` reader - Debug Timer 6 stopped when Core is halted"] pub use DBG_TIMER2_STOP_R as DBG_TIMER6_STOP_R; #[doc = "Field `DBG_TIMER6_STOP` writer - Debug Timer 6 stopped when Core is halted"] pub use DBG_TIMER2_STOP_W as DBG_TIMER6_STOP_W; #[doc = "Field `DBG_RTC_STOP` reader - Debug RTC stopped when Core is halted"] pub type DBG_RTC_STOP_R = crate::BitReader<DBG_RTC_STOP_A>; #[doc = "Debug RTC stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_RTC_STOP_A { #[doc = "0: The clock of the RTC counter is fed even if the core is halted"] Continue = 0, #[doc = "1: The clock of the RTC counter is stopped when the core is halted"] Stop = 1, } impl From<DBG_RTC_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_RTC_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_RTC_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_RTC_STOP_A { match self.bits { false => DBG_RTC_STOP_A::Continue, true => DBG_RTC_STOP_A::Stop, } } #[doc = "The clock of the RTC counter is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_RTC_STOP_A::Continue } #[doc = "The clock of the RTC counter is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_RTC_STOP_A::Stop } } #[doc = "Field `DBG_RTC_STOP` writer - Debug RTC stopped when Core is halted"] pub type DBG_RTC_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_RTC_STOP_A>; impl<'a, REG, const O: u8> DBG_RTC_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The clock of the RTC counter is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_RTC_STOP_A::Continue) } #[doc = "The clock of the RTC counter is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_RTC_STOP_A::Stop) } } #[doc = "Field `DBG_WWDG_STOP` reader - Debug Window Wachdog stopped when Core is halted"] pub type DBG_WWDG_STOP_R = crate::BitReader<DBG_WWDG_STOP_A>; #[doc = "Debug Window Wachdog stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_WWDG_STOP_A { #[doc = "0: The window watchdog counter clock continues even if the core is halted"] Continue = 0, #[doc = "1: The window watchdog counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_WWDG_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_WWDG_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_WWDG_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_WWDG_STOP_A { match self.bits { false => DBG_WWDG_STOP_A::Continue, true => DBG_WWDG_STOP_A::Stop, } } #[doc = "The window watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_WWDG_STOP_A::Continue } #[doc = "The window watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_WWDG_STOP_A::Stop } } #[doc = "Field `DBG_WWDG_STOP` writer - Debug Window Wachdog stopped when Core is halted"] pub type DBG_WWDG_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_WWDG_STOP_A>; impl<'a, REG, const O: u8> DBG_WWDG_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The window watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_WWDG_STOP_A::Continue) } #[doc = "The window watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_WWDG_STOP_A::Stop) } } #[doc = "Field `DBG_IWDG_STOP` reader - Debug Independent Wachdog stopped when Core is halted"] pub type DBG_IWDG_STOP_R = crate::BitReader<DBG_IWDG_STOP_A>; #[doc = "Debug Independent Wachdog stopped when Core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_IWDG_STOP_A { #[doc = "0: The independent watchdog counter clock continues even if the core is halted"] Continue = 0, #[doc = "1: The independent watchdog counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_IWDG_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_IWDG_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_IWDG_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_IWDG_STOP_A { match self.bits { false => DBG_IWDG_STOP_A::Continue, true => DBG_IWDG_STOP_A::Stop, } } #[doc = "The independent watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_IWDG_STOP_A::Continue } #[doc = "The independent watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_IWDG_STOP_A::Stop } } #[doc = "Field `DBG_IWDG_STOP` writer - Debug Independent Wachdog stopped when Core is halted"] pub type DBG_IWDG_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_IWDG_STOP_A>; impl<'a, REG, const O: u8> DBG_IWDG_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "The independent watchdog counter clock continues even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_IWDG_STOP_A::Continue) } #[doc = "The independent watchdog counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_IWDG_STOP_A::Stop) } } #[doc = "Field `DBG_I2C1_STOP` reader - I2C1 SMBUS timeout mode stopped when core is halted"] pub type DBG_I2C1_STOP_R = crate::BitReader<DBG_I2C1_STOP_A>; #[doc = "I2C1 SMBUS timeout mode stopped when core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_I2C1_STOP_A { #[doc = "0: Same behavior as in normal mode"] NormalMode = 0, #[doc = "1: I2C3 SMBUS timeout is frozen"] SmbusTimeoutFrozen = 1, } impl From<DBG_I2C1_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_I2C1_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_I2C1_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_I2C1_STOP_A { match self.bits { false => DBG_I2C1_STOP_A::NormalMode, true => DBG_I2C1_STOP_A::SmbusTimeoutFrozen, } } #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn is_normal_mode(&self) -> bool { *self == DBG_I2C1_STOP_A::NormalMode } #[doc = "I2C3 SMBUS timeout is frozen"] #[inline(always)] pub fn is_smbus_timeout_frozen(&self) -> bool { *self == DBG_I2C1_STOP_A::SmbusTimeoutFrozen } } #[doc = "Field `DBG_I2C1_STOP` writer - I2C1 SMBUS timeout mode stopped when core is halted"] pub type DBG_I2C1_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_I2C1_STOP_A>; impl<'a, REG, const O: u8> DBG_I2C1_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Same behavior as in normal mode"] #[inline(always)] pub fn normal_mode(self) -> &'a mut crate::W<REG> { self.variant(DBG_I2C1_STOP_A::NormalMode) } #[doc = "I2C3 SMBUS timeout is frozen"] #[inline(always)] pub fn smbus_timeout_frozen(self) -> &'a mut crate::W<REG> { self.variant(DBG_I2C1_STOP_A::SmbusTimeoutFrozen) } } #[doc = "Field `DBG_I2C2_STOP` reader - I2C2 SMBUS timeout mode stopped when core is halted"] pub use DBG_I2C1_STOP_R as DBG_I2C2_STOP_R; #[doc = "Field `DBG_I2C2_STOP` writer - I2C2 SMBUS timeout mode stopped when core is halted"] pub use DBG_I2C1_STOP_W as DBG_I2C2_STOP_W; #[doc = "Field `DBG_LPTIMER_STOP` reader - LPTIM1 counter stopped when core is halted"] pub type DBG_LPTIMER_STOP_R = crate::BitReader<DBG_LPTIMER_STOP_A>; #[doc = "LPTIM1 counter stopped when core is halted\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DBG_LPTIMER_STOP_A { #[doc = "0: LPTIM1 counter clock is fed even if the core is halted"] Continue = 0, #[doc = "1: LPTIM1 counter clock is stopped when the core is halted"] Stop = 1, } impl From<DBG_LPTIMER_STOP_A> for bool { #[inline(always)] fn from(variant: DBG_LPTIMER_STOP_A) -> Self { variant as u8 != 0 } } impl DBG_LPTIMER_STOP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DBG_LPTIMER_STOP_A { match self.bits { false => DBG_LPTIMER_STOP_A::Continue, true => DBG_LPTIMER_STOP_A::Stop, } } #[doc = "LPTIM1 counter clock is fed even if the core is halted"] #[inline(always)] pub fn is_continue(&self) -> bool { *self == DBG_LPTIMER_STOP_A::Continue } #[doc = "LPTIM1 counter clock is stopped when the core is halted"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == DBG_LPTIMER_STOP_A::Stop } } #[doc = "Field `DBG_LPTIMER_STOP` writer - LPTIM1 counter stopped when core is halted"] pub type DBG_LPTIMER_STOP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, DBG_LPTIMER_STOP_A>; impl<'a, REG, const O: u8> DBG_LPTIMER_STOP_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "LPTIM1 counter clock is fed even if the core is halted"] #[inline(always)] pub fn continue_(self) -> &'a mut crate::W<REG> { self.variant(DBG_LPTIMER_STOP_A::Continue) } #[doc = "LPTIM1 counter clock is stopped when the core is halted"] #[inline(always)] pub fn stop(self) -> &'a mut crate::W<REG> { self.variant(DBG_LPTIMER_STOP_A::Stop) } } impl R { #[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"] #[inline(always)] pub fn dbg_timer2_stop(&self) -> DBG_TIMER2_STOP_R { DBG_TIMER2_STOP_R::new((self.bits & 1) != 0) } #[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"] #[inline(always)] pub fn dbg_timer6_stop(&self) -> DBG_TIMER6_STOP_R { DBG_TIMER6_STOP_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 10 - Debug RTC stopped when Core is halted"] #[inline(always)] pub fn dbg_rtc_stop(&self) -> DBG_RTC_STOP_R { DBG_RTC_STOP_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"] #[inline(always)] pub fn dbg_wwdg_stop(&self) -> DBG_WWDG_STOP_R { DBG_WWDG_STOP_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"] #[inline(always)] pub fn dbg_iwdg_stop(&self) -> DBG_IWDG_STOP_R { DBG_IWDG_STOP_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"] #[inline(always)] pub fn dbg_i2c1_stop(&self) -> DBG_I2C1_STOP_R { DBG_I2C1_STOP_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 SMBUS timeout mode stopped when core is halted"] #[inline(always)] pub fn dbg_i2c2_stop(&self) -> DBG_I2C2_STOP_R { DBG_I2C2_STOP_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"] #[inline(always)] pub fn dbg_lptimer_stop(&self) -> DBG_LPTIMER_STOP_R { DBG_LPTIMER_STOP_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_timer2_stop(&mut self) -> DBG_TIMER2_STOP_W<APB1_FZ_SPEC, 0> { DBG_TIMER2_STOP_W::new(self) } #[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_timer6_stop(&mut self) -> DBG_TIMER6_STOP_W<APB1_FZ_SPEC, 4> { DBG_TIMER6_STOP_W::new(self) } #[doc = "Bit 10 - Debug RTC stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_rtc_stop(&mut self) -> DBG_RTC_STOP_W<APB1_FZ_SPEC, 10> { DBG_RTC_STOP_W::new(self) } #[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_wwdg_stop(&mut self) -> DBG_WWDG_STOP_W<APB1_FZ_SPEC, 11> { DBG_WWDG_STOP_W::new(self) } #[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"] #[inline(always)] #[must_use] pub fn dbg_iwdg_stop(&mut self) -> DBG_IWDG_STOP_W<APB1_FZ_SPEC, 12> { DBG_IWDG_STOP_W::new(self) } #[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_i2c1_stop(&mut self) -> DBG_I2C1_STOP_W<APB1_FZ_SPEC, 21> { DBG_I2C1_STOP_W::new(self) } #[doc = "Bit 22 - I2C2 SMBUS timeout mode stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_i2c2_stop(&mut self) -> DBG_I2C2_STOP_W<APB1_FZ_SPEC, 22> { DBG_I2C2_STOP_W::new(self) } #[doc = "Bit 31 - LPTIM1 counter stopped when core is halted"] #[inline(always)] #[must_use] pub fn dbg_lptimer_stop(&mut self) -> DBG_LPTIMER_STOP_W<APB1_FZ_SPEC, 31> { DBG_LPTIMER_STOP_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 = "APB Low Freeze Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1_fz::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 [`apb1_fz::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB1_FZ_SPEC; impl crate::RegisterSpec for APB1_FZ_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb1_fz::R`](R) reader structure"] impl crate::Readable for APB1_FZ_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb1_fz::W`](W) writer structure"] impl crate::Writable for APB1_FZ_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB1_FZ to value 0"] impl crate::Resettable for APB1_FZ_SPEC { const RESET_VALUE: Self::Ux = 0; }
use util::*; const LEN: usize = 'z' as usize - 'a' as usize + 1; fn main() { let timer = Timer::new(); let count: usize = input::vec::<String>(&std::env::args().nth(1).unwrap(), "\n\n") .iter() .map(|s| { let mut answered: [bool; LEN] = [false; LEN]; for c in s.replace('\n', "").bytes() { answered[c as usize - 'a' as usize] = true; } answered.iter().filter(|&b| *b).count() }) .sum(); timer.print(); println!("{}", count); }
// 借用和生命周期 // 生命周期 // 一个变量的生命周期就是它从创建到销毁的整个过程。 pub fn first() { let v = vec![1, 2, 3, 4, 5]; // v 的生命周期开始 { let center = v[2]; // center 的生命周期开始 println!("{}", center); } // center 的生命周期结束 println!("{:?}", v); } // v 的生命周期结束 // 如果一个变量永远只能有唯一一个入口可以访问的话,那就太难使用了。 // 因此,所有权还可以借用。 // 所有权借用 // 变量对其管理的内存拥有所有权。这个所有权不仅可以被转移(move),还可以被借用(borrow)。 // 借用指针的语法使用 & 符号或者 &mut 符号表示。前者表示只读借用,后者表示可读写借用。 // 借用指针(borrow pointer)也可以称作“引用”(reference)。借用指针与普通指针的内 // 部数据是一模一样的,唯一的区别是语义层面上的。它的作用是告诉编译器,它对指向的这 // 块内存区域没有所有权。 // 借用指针在编译后,就是一个普通的指针,它的意义只能在编译阶段的静态检查中体现。 pub fn second() { // 形参类型: 可变的借用指针 fn foo(v: &mut Vec<i32>) { // Vec::push 函数的作用是对动态数组添加元素,它的签名是 pub fn push(&mut self, value: T) // 它要求 self 参数是一个 &mut Self 类型。 v.push(5); } fn test1() { // 需要动态数组本身是可变的 let mut v = vec![]; // 获取可变借用指针 foo(&mut v); println!("{:?}", v); } test1(); // 对于 &mut 型指针,不要混淆它与变量绑定之间的语法。 // 如果 mut 修饰的是变量名,那么它代表这个变量可以被重新绑定; // 如果 mut 修饰的是 “借用指针 &”,那么它代表的是被指向的对象可以被修改。 fn test2() { let mut var = 0; { // p1 指针本身不能被重新绑定,可以通过 p1 改变变量 var 的值 let p1 = &mut var; *p1 = 1; } { let temp = 2; // 不能通过 p2 改变变量 var 的值,但 p2 指针本身指向的位置可以被改变 let mut p2 = &var; p2 = &temp; } { let mut temp = 3; // 既可以通过 p3 改变变量 var 的值, // 而且 p3 指针本身指向的位置也可以改变 let mut p3 = &mut var; *p3 = 13; p3 = &mut temp; } println!("{}", var); } test2(); } // 借用规则 // 关于借用指针,有以下几条规则: // 1. 借用指针不能比它指向的变量存在的时间更长。 // 2. &mut 型借用只能指向本身具有 mut 修饰的变量,对于只读变量,不可以有 &mut 型借用。 // 3. &mut 型借用指针存在的时候,被借用的变量本身会处于“冻结”状态。 // 4. 如果只有 & 型借用指针,那么能同时存在多个;如果存在 &mut 型借用指针,那么只能存在一个; // 如果同时有其他的 & 或者 &mut 型借用指针存在,那么会出现编译错误。 // 5. 借用指针只能临时地拥有对这个变量读或写的权限,没有权力管理这个变量的生命周期。 // 因此,借用指针的生命周期绝对不能大于它所引用的原来变量的生命周期, // 否则就是悬空指针,会导致内存不安全。 pub fn third() { // 参数采用的“引用传递”,实参并未丢失对内存的管理权 fn borrow_semantics(v: &Vec<i32>) { // 打印参数占用空间的大小,在 64 位系统上, 结果为 8, // 表明该指针与普通裸指针的内部表示方法相同 println!("size of param: {}", std::mem::size_of::<&Vec<i32>>()); for item in v { print!("{} ", item); } println!(); } // 参数采用的“值传递”,而 Vec 没有实现 Copy trait,意味着它将执行 move 语义 fn move_semantics(v: Vec<i32>) { // 打印参数占用空间的大小,结果为 24, // 表明实参中栈上分配的内存空间复制到了函数的形参中 println!("size of param: {}", std::mem::size_of::<Vec<i32>>()); for item in v { print!("{} ", item); } println!(); } fn test1() { let array = vec![1, 2, 3, 4, 5]; // 需要注意的是,如果使用引用传递,不仅在函数声明的地方需要使用 & 标记 // 函数调用的地方同样需要使用 & 标记,否则会出现语法错误 // 小数点方式的成员函数调用,对于 self 参数,会“自动转换”,不必显式借用 borrow_semantics(&array); // 在使用引用传递给上面的函数后,array 本身依然有效,还能在下面的函数中使用 move_semantics(array); // 在使用 move 语义传递后,array 在这个函数调用后,它的生命周期就已经完结 } test1(); // 一般情况下,函数参数使用引用传递的时候,不仅在函数声明这里要写上类型参数, // 在函数调用这里也要显式地使用引用运算符。 // 但是,有一个例外,那就是当参数为 self、&self、&mut self 等时, // 若使用小数点语法调用成员方法,在函数调用这里不能显式写出借用运算符。 fn test2() { let mut x: String = "hello".into(); // len(&self) -> usize // 完整调用形式:String::len(&x) println!("length of String {}", x.len()); // push(&mut self, ch: char) // 完整调用形式:String::push(&mut x, '!') x.push('!'); println!("length of String {}", x.len()); // into_bytes(self) -> Vec<u8> // 注意 self 的类型,此处发生了所有权转移 // 完整调用形式:String::into_bytes(x) let v = x.into_bytes(); // 再次调用 len(),编译失败,因为此处已经超过了 x 的生命周期 // println!("length of String {}", x.len()); } test2(); // 任何借用指针的存在,都会导致原来的变量被“冻结”(Frozen)。 /* fn test3() { let mut x = 1; let p = &mut x; // 因为 p 的存在,此时对 x 的改变被认为是非法的。 x = 2; println!("value of pointed: {}", p); } test3(); */ } // 生命周期标记 // 对一个函数内部的生命周期进行分析,Rust 编译器可以很好地解决。 // 但是,当生命周期跨函数的时候,就需要一种特殊的生命周期标记符号了。 pub fn fourth() { // 函数的生命周期标记 fn test1() { struct T { member: i32, } // 生命周期符号使用单引号开头,后面跟一个合法的名字。 // 生命周期标记和泛型类型参数是一样的,都需要先声明后使用。 // 在上面这段代码中,尖括号里面的 'a 是声明一个生命周期参数, // 它在后面的参数和返回值中被使用。 // 在做局部变量的时候,生命周期参数是可以省略的。 // 生命周期之间有重要的包含关系。如果生命周期 'a 比 'b 更长或相等,则记为 'a : 'b, // 对于借用指针类型来说, // 如果 &'a 是合法的,那么 'b 作为 'a 的一部分, &'b 也一定是合法的。 // 'static 是一个特殊的生命周期,它代表的是这个程序从开始到结束的整个阶段, // 所以它比其他任何生命周期都长。任意一个生命周期 'a 都满足 'static : 'a。 fn test<'a>(arg: &'a T) -> &'a i32 { &arg.member } let t = T { member: 0 }; // 't 开始 // 这条语句实际上是把 &'t i32 类型的变量赋值给 &'x i32 类型的变量。 // 这个赋值是合理的。因为这两个生命周期的关系是 't: 'x。 // test 返回的那个指针在 't 这个生命周期范围内都是合法的, // 在一个被 't 包围的更小范围的生命周期内,它当然也是合法的。 let x = test(&t); // 'x 开始 println!("{:?}", x); } // 先 'x 结束,后 't 结束 // 对于上面的代码,'x 在一个被 't 包围的更小范围的生命周期内,它当然也是合法的。可以编译通过。 test1(); // 函数的生命周期标记,示例2 fn test2() { struct T { member: i32, } // 'a: 'b 指定了 'a 的生命周期 >= 'b 的生命周期 // 如果不指定,'a 和 'b 没有任何关系,编译器会觉得这个赋值是错误的。 fn test<'a, 'b>(arg: &'a T) -> &'b i32 where 'a: 'b { // 'a 比 'b “活”得长,自然,&'a i32 类型赋值给 &'b i32 类型是没问题的 &arg.member } let t = T { member: 0 }; // 't 开始 // 在 test 函数被调用的时候,生命周期参数 'a 和 'b 被分别实例化为了 't 和 'x。 // 它们刚好满足了 where 条件中的 'a: 'b 约束('t: 'x)。 // 而 &arg.member 这条表达式的类型是 &'t i32,返回值要求的是 &'x i32 类型,这也是合法的。 // 所以 test 函数的生命周期检查可以通过。 let x = test(&t); // 'x 开始 println!("{:?}", x); } // 先 'x 结束,后 't 结束 test2(); // 综上 // fn test<'a>(arg: &'a T) -> &'a i32 // fn test<'a, 'b>(arg: &'a T) -> &'b i32 where 'a: 'b // 这两种写法都是合法的。 // Rust 的引用类型是支持“协变”的。在编译器看来,生命周期就是一个区间, // 生命周期参数就是一个普通的泛型参数,它可以被特化为某个具体的生命周期。 fn test3() { fn select<'a>(arg1: &'a i32, arg2: &'a i32) -> &'a i32 { if *arg1 > *arg2 { arg1 } else { arg2 } } let x = 1; // 'x 开始 let y = 2; // 'y 开始 // 分析 // select 这个函数引入了一个生命周期标记,两个参数以及返回值都是用的这个生命周期标记。 // 在调用的时候,传递的实参是具备不同的生命周期的。 // x 的生命周期明显大于 y 的生命周期,&x 可存活的范围要大于 &y 可存活的范围, // 把它们的实际生命周期分别记录为 'x 和 'y。 // select 函数的形式参数要求的是同样的生命周期,而实际参数是两个不同生命周期的引用, // 这个类型之所以可以匹配成功,是因为生命周期的协变特性。 // 编译器可以把 &x 和 &y 的生命周期都缩小到某个生命周期 'a 以内,且满足 'x: 'a, 'y: 'a 。 // 返回的 selected 变量具备 'a 生命周期,也并没有超过 'x 和 'y 的范围。 // 所以,最终的生命周期检查可以通过。 let selected = select(&x, &y); println!("{}", selected); } // 先 'y 结束,后 'x 结束. 'x: 'y test3(); // 类型的生命周期标记 // 如果自定义类型中有成员包含生命周期参数,那么这个自定义类型也必须有生命周期参数。 fn test4() { struct T<'a> { member: &'a str } // 在使用 impl 的时候,也需要先声明再使用 impl<'t> T<'t> { fn test<'a>(&self, s: &'a str) {} } // 若是有 where T: 'static 的约束,意思则是,类型 T 里面不包含任何指向 // 短生命周期的借用指针,意思是要么完全不包含任何借用,要么可以有指向 // 'static 的借用指针。 } test4(); // 省略生命周期标记 // 在某些情况下,Rust 允许在写函数的时候省略掉显式生命周期标记。在这种时候,编译器会 // 通过一定的固定规则为参数和返回值指定合适的生命周期,从而省略一些显而易见的生命周期标记。 fn test5() { fn get_str(s: &String) -> &str { s.as_ref() } // 等价于 fn get_str_x<'a>(s: &'a String) -> &'a str { s.as_ref() } // 这个函数返回的指针将并不指向参数传人的数据,而是指向一个静态常量 // fn get_str_y(s: &String) -> &str // 期望返回的指针是 &'static str 类型, // 实际上返回值的生命周期被编译器指定为和输入参数一致 // 所以这时,不能省略生命周期标记 // fn get_str_y<'a>(s: &'a String) -> &'static str { // 只写返回值的生命周期标记也可 fn get_str_y(s: &String) -> &'static str { println!("call fn {}", s); "hello world" } let c = String::from("hello"); // error[E0597]: `c` does not live long enough let x: &'static str = get_str_y(&c); // 按照分析,变量 x 理应指向一个 'static 生命周期的变量,根本不是指向 c 变量, // 它的存活时间足够长,为什么编译器没发现这一点呢? // 这是因为,编译器对于省略掉的生命周期,不是用的“自动推理“策略,而是用的几个非常简单的 // “固定规则”策略。这跟类型自动推导不一样,当省略变量的类型时,编译器会试图通过变量的 // 使用方式推导出变量的类型,这个过程叫 “type inference”。 // 对于省略掉的生命周期参数,编译器的处理方式就简单粗暴得多,它完全不管函数内部的实现, // 并不尝试找到最合适的推理方案,只是应用几个固定的规则, // 这些规则被称为 “lifetime elision rules”。 // 省略的生命周期被自动补全的规则: // 1. 每个带生命周期参数的输入参数,每个对应不同的生命周期参数; // 2. 如果只有一个输入参数带生命周期参数,那么返回值的生命周期被指定为这个参数; // 3. 如果有多个输入参数带生命周期参数,但其中有 &self、&mut self, // 那么返回值的生命周期被指定为这个参数; // 4. 以上都不满足,就不能自动补全返回值的生命周期参数。 println!("{}", x); } test5(); // 总结,elision != inference,省略 != 推导 // 省略生命周期参数和类型自动推导的原理是完全不同的。 }
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::{self, Read, Write}; use crate::errors::{message::ErrorKind::*, ErrorKind, Result, ResultExt}; #[derive(Clone, Debug)] pub struct MessageHeader { command: [u8; 12], payload_size: u32, checksum: [u8; 4], } pub const MESSAGE_MAGIC: &[u8; 4] = b"\xe3\xe1\xf3\xe8"; pub const HEADER_SIZE: usize = 4 + 12 + 4 + 4; impl MessageHeader { pub fn new(command: [u8; 12], payload_size: u32, checksum: [u8; 4]) -> Self { MessageHeader { command, payload_size, checksum, } } pub fn from_slice(bytes: &[u8]) -> Result<Self> { let mut magic = [0; 4]; let mut command = [0; 12]; let mut checksum = [0; 4]; let mut cur = io::Cursor::new(bytes); cur.read_exact(&mut magic).chain_err(|| IoError)?; if &magic[..] != MESSAGE_MAGIC { return Err(ErrorKind::Message(WrongMagic(magic.to_vec())).into()); } cur.read_exact(&mut command).chain_err(|| IoError)?; let payload_size = cur.read_u32::<LittleEndian>().chain_err(|| IoError)?; cur.read_exact(&mut checksum).chain_err(|| IoError)?; Ok(MessageHeader { command, payload_size, checksum, }) } pub fn bytes(&self) -> [u8; HEADER_SIZE] { let mut header = [0u8; HEADER_SIZE]; let mut cur = io::Cursor::new(&mut header[..]); cur.write_all(MESSAGE_MAGIC).unwrap(); cur.write_all(&self.command).unwrap(); cur.write_u32::<LittleEndian>(self.payload_size).unwrap(); cur.write_all(&self.checksum).unwrap(); header } pub fn payload_size(&self) -> u32 { self.payload_size } pub fn checksum(&self) -> [u8; 4] { self.checksum } pub fn command_name(&self) -> &[u8] { let len = self .command .iter() .position(|b| *b == 0) .unwrap_or_else(|| self.command.len()); &self.command[..len] } } impl std::fmt::Display for MessageHeader { fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::result::Result<(), std::fmt::Error> { writeln!(f, "command: {}", String::from_utf8_lossy(&self.command))?; writeln!(f, "payload size: {}", self.payload_size)?; writeln!(f, "checksum: {}", hex::encode(&self.checksum))?; Ok(()) } }
/*! # Davidson Diagonalization The Davidson method is suitable for diagonal-dominant symmetric matrices, that are quite common in certain scientific problems like [electronic structure](https://en.wikipedia.org/wiki/Electronic_structure). The Davidson method could be not practical for other kind of symmetric matrices. The current implementation uses a general davidson algorithm, meaning that it compute all the requested eigenvalues simultaneusly using a variable size block approach. The family of Davidson algorithm only differ in the way that the correction vector is computed. Available correction methods are: * **DPR**: Diagonal-Preconditioned-Residue * **GJD**: Generalized Jacobi Davidson */ extern crate nalgebra as na; use crate::utils; use na::linalg::SymmetricEigen; use na::{DMatrix, DVector, Dynamic}; use std::f64; /// Structure containing the initial configuration data struct Config { method: String, tolerance: f64, max_iters: usize, max_dim_sub: usize, init_dim: usize, } impl Config { /// Choose sensible default values for the davidson algorithm, where: /// * `nvalues` - Number of eigenvalue/eigenvector pairs to compute /// * `dim` - dimension of the matrix to diagonalize fn new(nvalues: usize, dim: usize) -> Self { let max_dim_sub = if nvalues * 10 < dim { nvalues * 10 } else { dim }; Config { method: String::from("DPR"), tolerance: 1e-8, max_iters: 100, max_dim_sub: max_dim_sub, init_dim: nvalues * 2, } } } /// Structure with the configuration data pub struct EigenDavidson { pub eigenvalues: DVector<f64>, pub eigenvectors: DMatrix<f64>, } impl EigenDavidson { /// The new static method takes the following arguments: /// * `h` - A highly diagonal symmetric matrix /// * `nvalues` - the number of eigenvalues/eigenvectors pair to compute pub fn new(h: DMatrix<f64>, nvalues: usize) -> Result<Self, &'static str> { // Initial configuration let conf = Config::new(nvalues, h.nrows()); // Initial subpace let mut dim_sub = conf.init_dim; // 1. Select the initial ortogonal subspace based on lowest elements let mut basis = generate_subspace(&h.diagonal(), conf.max_dim_sub); // Outer loop block Davidson schema let mut result = Err("Algorithm didn't converge!"); for i in 0..conf.max_iters { // 2. Generate subpace matrix problem by projecting into the basis let subspace = basis.columns(0, dim_sub); let matrix_proj = subspace.transpose() * (&h * subspace); // 3. compute the eigenvalues and their corresponding ritz_vectors let eig = utils::sort_eigenpairs(SymmetricEigen::new(matrix_proj)); // 4. Check for convergence // 4.1 Compute the residues let ritz_vectors = subspace * eig.eigenvectors.columns(0, dim_sub); let residues = compute_residues(&h, &eig.eigenvalues, &ritz_vectors); // 4.2 Check Converge for each pair eigenvalue/eigenvector let errors = DVector::<f64>::from_iterator( nvalues, residues .columns(0, nvalues) .column_iter() .map(|col| col.norm()), ); // 4.3 Check if all eigenvalues/eigenvectors have converged if errors.iter().all(|&x| x < conf.tolerance) { result = Ok(create_results(&eig.eigenvalues, &ritz_vectors, nvalues)); break; } // 5. Update subspace basis set // 5.1 Add the correction vectors to the current basis if 2 * dim_sub <= conf.max_dim_sub { let correction = compute_correction(&h, residues, eig, &conf.method); update_subspace(&mut basis, correction, dim_sub, dim_sub * 2); // 6. Orthogonalize the subspace basis = orthogonalize_subspace(basis); // update counter dim_sub *= 2; // 5.2 Otherwise reduce the basis of the subspace to the current correction } else { dim_sub = conf.init_dim; basis.fill(0.0); update_subspace(&mut basis, ritz_vectors, 0, dim_sub); } // Check number of iterations if i > conf.max_iters { break; } } result } } /// Extract the requested eigenvalues/eigenvectors pairs fn create_results( subspace_eigenvalues: &DVector<f64>, ritz_vectors: &DMatrix<f64>, nvalues: usize, ) -> EigenDavidson { let eigenvectors = DMatrix::<f64>::from_iterator( ritz_vectors.nrows(), nvalues, ritz_vectors.columns(0, nvalues).iter().cloned(), ); let eigenvalues = DVector::<f64>::from_iterator( nvalues, subspace_eigenvalues.rows(0, nvalues).iter().cloned(), ); EigenDavidson { eigenvalues, eigenvectors, } } /// Update the subpace with new vectors fn update_subspace(basis: &mut DMatrix<f64>, vectors: DMatrix<f64>, start: usize, end: usize) { let mut i = 0; // indices for the new vector to add for k in start..end { basis.set_column(k, &vectors.column(i)); i += 1; } } /// Orthogonalize the subpsace using the QR method fn orthogonalize_subspace(basis: DMatrix<f64>) -> DMatrix<f64> { let qr = na::linalg::QR::new(basis); qr.q() } /// Residue vectors fn compute_residues( h: &DMatrix<f64>, eigenvalues: &DVector<f64>, ritz_vectors: &DMatrix<f64>, ) -> DMatrix<f64> { let dim_sub = eigenvalues.nrows(); let mut residues = DMatrix::<f64>::zeros(h.nrows(), dim_sub); for k in 0..dim_sub { let guess = eigenvalues[k] * ritz_vectors.column(k); let vs = h * ritz_vectors.column(k); residues.set_column(k, &(vs - guess)); } residues } /// compute the correction vectors using either DPR or GJD fn compute_correction( h: &DMatrix<f64>, residues: DMatrix<f64>, eigenpairs: SymmetricEigen<f64, Dynamic>, method: &str, ) -> DMatrix<f64> { match method.to_uppercase().as_ref() { "DPR" => compute_dpr_correction(&h, residues, &eigenpairs.eigenvalues), "GJD" => compute_gjd_correction(&h, residues, &eigenpairs), _ => panic!("Method {} has not been implemented", method), } } /// Use the Diagonal-Preconditioned-Residue (DPR) method to compute the correction fn compute_dpr_correction( h: &DMatrix<f64>, residues: DMatrix<f64>, eigenvalues: &DVector<f64>, ) -> DMatrix<f64> { let d = h.diagonal(); let mut correction = DMatrix::<f64>::zeros(h.nrows(), residues.ncols()); for (k, r) in eigenvalues.iter().enumerate() { let rs = DVector::<f64>::repeat(h.nrows(), *r); let x = residues.column(k).component_mul(&(rs - &d)); correction.set_column(k, &x); } correction } /// Use the Generalized Jacobi Davidson (GJD) to compute the correction fn compute_gjd_correction( h: &DMatrix<f64>, residues: DMatrix<f64>, eigenpairs: &SymmetricEigen<f64, Dynamic>, ) -> DMatrix<f64> { let dimx = h.nrows(); let dimy = eigenpairs.eigenvalues.nrows(); let id = DMatrix::<f64>::identity(dimx, dimx); let ones = DVector::<f64>::repeat(dimx, 1.0); let mut correction = DMatrix::<f64>::zeros(dimx, dimy); for (k, r) in eigenpairs.eigenvalues.iter().enumerate() { // Create the components of the linear system let x = eigenpairs.eigenvectors.column(k); let t1 = &id - x * x.transpose(); let mut t2 = h.clone(); t2.set_diagonal(&(*r * &ones)); let arr = &t1 * t2 * &t1; // Solve the linear system let decomp = arr.lu(); let mut b = -residues.column(k); decomp.solve_mut(&mut b); correction.set_column(k, &b); } correction } /// Generate initial orthonormal subspace fn generate_subspace(diag: &DVector<f64>, max_dim_sub: usize) -> DMatrix<f64> { if is_sorted(diag) { DMatrix::<f64>::identity(diag.nrows(), max_dim_sub) } else { // TODO implement the case when the diagonal is not sorted panic!("Matrix diagonal elements are not sorted") } } /// Check if a vector is sorted in ascending order fn is_sorted(xs: &DVector<f64>) -> bool { let mut d: Vec<f64> = xs.iter().cloned().collect(); d.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); let vs: DVector<f64> = DVector::<f64>::from_vec(d); let r = xs - vs; r.norm() < f64::EPSILON } #[cfg(test)] mod test { extern crate nalgebra as na; use na::{DMatrix, DVector}; #[test] fn test_update_subspace() { let mut arr = DMatrix::<f64>::repeat(3, 3, 1.); let brr = DMatrix::<f64>::zeros(3, 2); super::update_subspace(&mut arr, brr, 0, 2); assert_eq!(arr.column(1).sum(), 0.); assert_eq!(arr.column(2).sum(), 3.); } }
use crate::animals::Animal; use crate::species::default::Canine; use crate::species::Species; use std::fmt; /// Dog pub struct Dog { name: Option<String>, species: Canine, } impl Dog { pub fn new(name: Option<String>) -> Self { Dog { name, species: Canine {}, } } } impl fmt::Display for Dog { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.name { Some(name) => write!(f, "Name: {}, Species: {}", name, self.species), None => write!(f, "Name: Unnamed, Species: {}", self.species), } } } impl Default for Dog { fn default() -> Self { Dog { name: None, species: Canine {}, } } } impl Animal for Dog { fn name(&self) -> Option<String> { self.name.clone() } fn species(&self) -> Box<dyn Species> { Box::new(self.species.clone()) } fn set_name(&mut self, new_name: Option<String>) { self.name = new_name; } } #[cfg(test)] mod tests { use super::*; #[test] fn default_correct() { let test_dog = Dog::default(); assert_eq!(test_dog.name, None); assert_eq!(test_dog.species, Canine {}); } #[test] fn new_no_name() { let test_dog = Dog::new(None); assert_eq!(test_dog.name, None); assert_eq!(test_dog.species, Canine {}); } #[test] fn new_with_name() { let test_dog = Dog::new(Some("Rover".to_string())); assert_eq!(test_dog.name, Some("Rover".to_string())); assert_eq!(test_dog.species, Canine {}); } #[test] fn canine_species_string() { let test_species = Canine {}; assert_eq!(test_species.to_string(), "Canine"); } }
// Copyright 2018 The Exonum Team // // 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. //! Cryptocurrency implementation example using [exonum](http://exonum.com/). #![deny( missing_debug_implementations, // missing_docs, unsafe_code, bare_trait_objects )] #[macro_use] extern crate exonum_derive; #[macro_use] extern crate failure; #[macro_use] extern crate serde_derive; extern crate rlua; extern crate hex; pub mod proto; pub mod currency; pub mod lvm;
use std::collections::{HashMap, HashSet}; use std::io::{self, BufRead}; use std::iter::once; type Rule = [(usize, usize); 2]; type Rules = HashMap<String, Rule>; type Ticket = Vec<usize>; fn parse_rule(line: &str) -> Option<(String, Rule)> { let mut it1 = line.split(": "); let name = it1.next()?.to_string(); let mut it2 = it1.next()?.split(" or "); let mut itr1 = it2.next()?.split('-'); let mut itr2 = it2.next()?.split('-'); let a = itr1.next()?.parse().ok()?; let b = itr1.next()?.parse().ok()?; let c = itr2.next()?.parse().ok()?; let d = itr2.next()?.parse().ok()?; Some((name, [(a, b), (c, d)])) } fn parse_ticket(s: &str) -> Ticket { s.split(',').filter_map(|x| x.parse().ok()).collect() } fn parse(lines: &[String]) -> Option<(Rules, Ticket, Vec<Ticket>)> { let mut it = lines.split(|x| x.is_empty()); let rules = it.next()?.iter().filter_map(|x| parse_rule(x)).collect(); let ticket = parse_ticket(it.next()?.get(1)?); let tickets = it .next()? .get(1..)? .iter() .map(|x| parse_ticket(&x)) .collect(); Some((rules, ticket, tickets)) } fn is_valid(value: usize, rules: &Rules) -> bool { rules .values() .flatten() .any(|&(a, b)| a <= value && value <= b) } fn part1(rules: &Rules, tickets: &[Ticket]) -> usize { tickets .iter() .flatten() .filter(|&x| !is_valid(*x, rules)) .sum() } fn part2(rules: &Rules, ticket: Ticket, tickets: &[Ticket]) -> usize { let valid_tickets: Vec<&Ticket> = tickets .iter() .filter(|&x| x.iter().all(|&y| is_valid(y, rules))) .chain(once(&ticket)) .collect(); // Loop over column index let mut matching = (0..ticket.len()) // Produce a vector of (index, name) tuples .map(|i| { // Keep the index because of the upcoming sort ( i, // Loop over rules rules .iter() // Filter rules that are inconsistent with the column i .filter(|(_, &[(a, b), (c, d)])| { // Loop over valid tickets valid_tickets .iter() // Check the ith value of the ticket against the current rule .all(|x| (a <= x[i] && x[i] <= b) || (c <= x[i] && x[i] <= d)) }) // Keep the name .map(|(name, _)| name) // Collect as a vector of names .collect::<Vec<_>>(), ) }) // Collect as a vector of vector .collect::<Vec<_>>(); matching.sort_by_key(|(_, x)| x.len()); let mut seen = HashSet::<&&String>::new(); let mut solved = HashMap::new(); for (i, x) in matching.iter() { let mut current = x.iter().collect::<HashSet<_>>(); current.retain(|x| !seen.contains(x)); seen.extend(current.iter()); assert!(current.len() == 1); solved.insert(current.iter().cloned().next().unwrap(), i); } solved .iter() .filter(|(name, _)| name.starts_with("departure")) .map(|(_, &i)| ticket[*i]) .product() } fn main() { let lines: Vec<_> = io::stdin().lock().lines().filter_map(|x| x.ok()).collect(); let (rules, ticket, tickets) = parse(&lines).unwrap(); let result = part1(&rules, &tickets); println!("Part 1: {}", result); let result = part2(&rules, ticket, &tickets); println!("Part 2: {}", result); }
#![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(debug_assertions, warn(missing_docs))] #![cfg_attr(not(debug_assertions), deny(missing_docs))] #![deny(unconditional_recursion)] use core::{ fmt::{ Debug, Display, }, num::{ FpCategory, ParseIntError, }, str::FromStr, }; #[macro_use] mod macros; pub mod num; pub mod ptr; pub use crate::{ num::{ Floating, Integral, Numeric, Signed, Unsigned, }, ptr::{ Permission, Pointer, Reference, Shared, Unique, }, }; /// Declares that a type is one of the language fundamental types. pub trait Fundamental: 'static + Sized + Send + Sync + Unpin + Clone + Copy + Default + FromStr // cmp + PartialEq<Self> + PartialOrd<Self> // fmt + Debug + Display { /// Tests `self != 0`. fn as_bool(self) -> bool; /// Represents `self` as a Unicode Scalar Value, if possible. fn as_char(self) -> Option<char>; /// Performs `self as i8`. fn as_i8(self) -> i8; /// Performs `self as i16`. fn as_i16(self) -> i16; /// Performs `self as i32`. fn as_i32(self) -> i32; /// Performs `self as i64`. fn as_i64(self) -> i64; /// Performs `self as i128`. fn as_i128(self) -> i128; /// Performs `self as isize`. fn as_isize(self) -> isize; /// Performs `self as u8`. fn as_u8(self) -> u8; /// Performs `self as u16`. fn as_u16(self) -> u16; /// Performs `self as u32`. fn as_u32(self) -> u32; /// Performs `self as u64`. fn as_u64(self) -> u64; /// Performs `self as u128`. fn as_u128(self) -> u128; /// Performs `self as usize`. fn as_usize(self) -> usize; /// Performs `self as f32`. fn as_f32(self) -> f32; /// Performs `self as f64`. fn as_f64(self) -> f64; } /// Declares that a type is exactly eight bits wide. pub trait Is8: Fundamental {} /// Declares that a type is exactly sixteen bits wide. pub trait Is16: Fundamental {} /// Declares that a type is exactly thirty-two bits wide. pub trait Is32: Fundamental {} /// Declares that a type is exactly sixty-four bits wide. pub trait Is64: Fundamental {} /// Declares that a type is exactly one hundred twenty-eight bits wide. pub trait Is128: Fundamental {} /// Declares that a type is eight or more bits wide. pub trait AtLeast8: Fundamental {} /// Declares that a type is sixteen or more bits wide. pub trait AtLeast16: Fundamental {} /// Declares that a type is thirty-two or more bits wide. pub trait AtLeast32: Fundamental {} /// Declares that a type is sixty-four or more bits wide. pub trait AtLeast64: Fundamental {} /// Declares that a type is one hundred twenty-eight or more bits wide. pub trait AtLeast128: Fundamental {} /// Declares that a type is eight or fewer bits wide. pub trait AtMost8: Fundamental {} /// Declares that a type is sixteen or fewer bits wide. pub trait AtMost16: Fundamental {} /// Declares that a type is thirty-two or fewer bits wide. pub trait AtMost32: Fundamental {} /// Declares that a type is sixty-four or fewer bits wide. pub trait AtMost64: Fundamental {} /// Declares that a type is one hundred twenty-eight or fewer bits wide. pub trait AtMost128: Fundamental {} macro_rules! impl_for { (Fundamental => $($t:ty => $is_zero:expr),+ $(,)?) => { $( impl Fundamental for $t { #[inline(always)] #[allow(clippy::redundant_closure_call)] fn as_bool(self) -> bool { ($is_zero)(self) } #[inline(always)] fn as_char(self) -> Option<char> { core::char::from_u32(self as u32) } #[inline(always)] fn as_i8(self) -> i8 { self as i8 } #[inline(always)] fn as_i16(self) -> i16 { self as i16 } #[inline(always)] fn as_i32(self) -> i32 { self as i32 } #[inline(always)] fn as_i64(self) -> i64 { self as i64 } #[inline(always)] fn as_i128(self) -> i128 { self as i128 } #[inline(always)] fn as_isize(self) -> isize { self as isize } #[inline(always)] fn as_u8(self) -> u8 { self as u8 } #[inline(always)] fn as_u16(self) -> u16 { self as u16 } #[inline(always)] fn as_u32(self) -> u32 { self as u32 } #[inline(always)] fn as_u64(self) -> u64 { self as u64 } #[inline(always)] fn as_u128(self) ->u128 { self as u128 } #[inline(always)] fn as_usize(self) -> usize { self as usize } #[inline(always)] fn as_f32(self) -> f32 { self as f32 } #[inline(always)] fn as_f64(self) -> f64 { self as f64 } } )+ }; (Numeric => $($t:ty),+ $(,)?) => { $( impl Numeric for $t { type Bytes = [u8; core::mem::size_of::<Self>()]; items! { $t => fn to_be_bytes(self) -> Self::Bytes; fn to_le_bytes(self) -> Self::Bytes; fn to_ne_bytes(self) -> Self::Bytes; } items! { $t => fn from_be_bytes(bytes: Self::Bytes) -> Self; fn from_le_bytes(bytes: Self::Bytes) -> Self; fn from_ne_bytes(bytes: Self::Bytes) -> Self; } } )+ }; (Integral => { $($t:ty, $s:ty, $u:ty);+ $(;)? }) => { $( impl Integral for $t { type Signed = $s; type Unsigned = $u; const ZERO: Self = 0; const ONE: Self = 1; items! { $t => const MIN: Self; const MAX: Self; const BITS: u32; } items! { $t => fn min_value() -> Self; fn max_value() -> Self; fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>; } items! { $t => fn count_ones(self) -> u32; fn count_zeros(self) -> u32; fn leading_zeros(self) -> u32; fn trailing_zeros(self) -> u32; fn leading_ones(self) -> u32; fn trailing_ones(self) -> u32; fn rotate_left(self, n: u32) -> Self; fn rotate_right(self, n: u32) -> Self; fn swap_bytes(self) -> Self; fn reverse_bits(self) -> Self; fn from_be(self) -> Self; fn from_le(self) -> Self; fn to_be(self) -> Self; fn to_le(self) -> Self; fn checked_add(self, rhs: Self) -> Option<Self>; fn checked_sub(self, rhs: Self) -> Option<Self>; fn checked_mul(self, rhs: Self) -> Option<Self>; fn checked_div(self, rhs: Self) -> Option<Self>; fn checked_div_euclid(self, rhs: Self) -> Option<Self>; fn checked_rem(self, rhs: Self) -> Option<Self>; fn checked_rem_euclid(self, rhs: Self) -> Option<Self>; fn checked_neg(self) -> Option<Self>; fn checked_shl(self, rhs: u32) -> Option<Self>; fn checked_shr(self, rhs: u32) -> Option<Self>; fn checked_pow(self, rhs: u32) -> Option<Self>; fn saturating_add(self, rhs: Self) -> Self; fn saturating_sub(self, rhs: Self) -> Self; fn saturating_mul(self, rhs: Self) -> Self; fn saturating_div(self, rhs: Self) -> Self; fn saturating_pow(self, rhs: u32) -> Self; fn wrapping_add(self, rhs: Self) -> Self; fn wrapping_sub(self, rhs: Self) -> Self; fn wrapping_mul(self, rhs: Self) -> Self; fn wrapping_div(self, rhs: Self) -> Self; fn wrapping_div_euclid(self, rhs: Self) -> Self; fn wrapping_rem(self, rhs: Self) -> Self; fn wrapping_rem_euclid(self, rhs: Self) -> Self; fn wrapping_neg(self) -> Self; fn wrapping_shl(self, rhs: u32) -> Self; fn wrapping_shr(self, rhs: u32) -> Self; fn wrapping_pow(self, rhs: u32) -> Self; fn overflowing_add(self, rhs: Self) -> (Self, bool); fn overflowing_sub(self, rhs: Self) -> (Self, bool); fn abs_diff(self, rhs: Self) -> Self::Unsigned; fn overflowing_mul(self, rhs: Self) -> (Self, bool); fn overflowing_div(self, rhs: Self) -> (Self, bool); fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool); fn overflowing_rem(self, rhs: Self) -> (Self, bool); fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool); fn overflowing_neg(self) -> (Self, bool); fn overflowing_shl(self, rhs: u32) -> (Self, bool); fn overflowing_shr(self, rhs: u32) -> (Self, bool); fn overflowing_pow(self, rhs: u32) -> (Self, bool); fn pow(self, rhs: u32) -> Self; fn div_euclid(self, rhs: Self) -> Self; fn rem_euclid(self, rhs: Self) -> Self; } } )+ }; (Signed => $($t:ty),+ $(,)?) => { $( impl Signed for $t { items! { $t => fn checked_abs(self) -> Option<Self>; fn wrapping_abs(self) -> Self; fn overflowing_abs(self) -> (Self, bool); fn abs(self) -> Self; fn signum(self) -> Self; fn is_positive(self) -> bool; fn is_negative(self) -> bool; } } )+ }; (Unsigned => $($t:ty),+ $(,)?) => { $( impl Unsigned for $t { items! { $t => fn is_power_of_two(self) -> bool; fn next_power_of_two(self) -> Self; fn checked_next_power_of_two(self) -> Option<Self>; } } )+ }; (Floating => $($t:ident | $u:ty),+ $(,)?) => { $( impl Floating for $t { type Raw = $u; items! { $t => const RADIX: u32; const MANTISSA_DIGITS: u32; const DIGITS: u32; const EPSILON: Self; const MIN: Self; const MIN_POSITIVE: Self; const MAX: Self; const MIN_EXP: i32; const MAX_EXP: i32; const MIN_10_EXP: i32; const MAX_10_EXP: i32; const NAN: Self; const INFINITY: Self; const NEG_INFINITY: Self; } items! { $t => mod const PI: Self; mod const FRAC_PI_2: Self; mod const FRAC_PI_3: Self; mod const FRAC_PI_4: Self; mod const FRAC_PI_6: Self; mod const FRAC_PI_8: Self; mod const FRAC_1_PI: Self; mod const FRAC_2_PI: Self; mod const FRAC_2_SQRT_PI: Self; mod const SQRT_2: Self; mod const FRAC_1_SQRT_2: Self; mod const E: Self; mod const LOG2_E: Self; mod const LOG10_E: Self; mod const LN_2: Self; mod const LN_10: Self; } items! { $t => #[cfg(feature = "std")] fn floor(self) -> Self; #[cfg(feature = "std")] fn ceil(self) -> Self; #[cfg(feature = "std")] fn round(self) -> Self; #[cfg(feature = "std")] fn trunc(self) -> Self; #[cfg(feature = "std")] fn fract(self) -> Self; #[cfg(feature = "std")] fn abs(self) -> Self; #[cfg(feature = "std")] fn signum(self) -> Self; #[cfg(feature = "std")] fn copysign(self, sign: Self) -> Self; #[cfg(feature = "std")] fn mul_add(self, a: Self, b: Self) -> Self; #[cfg(feature = "std")] fn div_euclid(self, rhs: Self) -> Self; #[cfg(feature = "std")] fn rem_euclid(self, rhs: Self) -> Self; #[cfg(feature = "std")] fn powi(self, n: i32) -> Self; #[cfg(feature = "std")] fn powf(self, n: Self) -> Self; #[cfg(feature = "std")] fn sqrt(self) -> Self; #[cfg(feature = "std")] fn exp(self) -> Self; #[cfg(feature = "std")] fn exp2(self) -> Self; #[cfg(feature = "std")] fn ln(self) -> Self; #[cfg(feature = "std")] fn log(self, base: Self) -> Self; #[cfg(feature = "std")] fn log2(self) -> Self; #[cfg(feature = "std")] fn log10(self) -> Self; #[cfg(feature = "std")] fn cbrt(self) -> Self; #[cfg(feature = "std")] fn hypot(self, other: Self) -> Self; #[cfg(feature = "std")] fn sin(self) -> Self; #[cfg(feature = "std")] fn cos(self) -> Self; #[cfg(feature = "std")] fn tan(self) -> Self; #[cfg(feature = "std")] fn asin(self) -> Self; #[cfg(feature = "std")] fn acos(self) -> Self; #[cfg(feature = "std")] fn atan(self) -> Self; #[cfg(feature = "std")] fn atan2(self, other: Self) -> Self; #[cfg(feature = "std")] fn sin_cos(self) -> (Self, Self); #[cfg(feature = "std")] fn exp_m1(self) -> Self; #[cfg(feature = "std")] fn ln_1p(self) -> Self; #[cfg(feature = "std")] fn sinh(self) -> Self; #[cfg(feature = "std")] fn cosh(self) -> Self; #[cfg(feature = "std")] fn tanh(self) -> Self; #[cfg(feature = "std")] fn asinh(self) -> Self; #[cfg(feature = "std")] fn acosh(self) -> Self; #[cfg(feature = "std")] fn atanh(self) -> Self; fn is_nan(self) -> bool; fn is_infinite(self) -> bool; fn is_finite(self) -> bool; fn is_normal(self) -> bool; fn classify(self) -> FpCategory; fn is_sign_positive(self) -> bool; fn is_sign_negative(self) -> bool; fn recip(self) -> Self; fn to_degrees(self) -> Self; fn to_radians(self) -> Self; fn max(self, other: Self) -> Self; fn min(self, other: Self) -> Self; fn to_bits(self) -> Self::Raw; } items! { $t => fn from_bits(bits: Self::Raw) -> Self; } } )+ }; ($which:ty => $($t:ty),+ $(,)?) => { $( impl $which for $t {} )+ }; } impl Fundamental for bool { #[inline(always)] fn as_bool(self) -> bool { self } #[inline(always)] fn as_char(self) -> Option<char> { Some(self as u8 as char) } #[inline(always)] fn as_i8(self) -> i8 { self as i8 } #[inline(always)] fn as_i16(self) -> i16 { self as i16 } #[inline(always)] fn as_i32(self) -> i32 { self as i32 } #[inline(always)] fn as_i64(self) -> i64 { self as i64 } #[inline(always)] fn as_i128(self) -> i128 { self as i128 } #[inline(always)] fn as_isize(self) -> isize { self as isize } #[inline(always)] fn as_u8(self) -> u8 { self as u8 } #[inline(always)] fn as_u16(self) -> u16 { self as u16 } #[inline(always)] fn as_u32(self) -> u32 { self as u32 } #[inline(always)] fn as_u64(self) -> u64 { self as u64 } #[inline(always)] fn as_u128(self) -> u128 { self as u128 } #[inline(always)] fn as_usize(self) -> usize { self as usize } #[inline(always)] fn as_f32(self) -> f32 { self as u8 as f32 } #[inline(always)] fn as_f64(self) -> f64 { self as u8 as f64 } } impl Fundamental for char { #[inline(always)] fn as_bool(self) -> bool { self != '\0' } #[inline(always)] fn as_char(self) -> Option<char> { Some(self) } #[inline(always)] fn as_i8(self) -> i8 { self as i8 } #[inline(always)] fn as_i16(self) -> i16 { self as i16 } #[inline(always)] fn as_i32(self) -> i32 { self as i32 } #[inline(always)] fn as_i64(self) -> i64 { self as i64 } #[inline(always)] fn as_i128(self) -> i128 { self as i128 } #[inline(always)] fn as_isize(self) -> isize { self as isize } #[inline(always)] fn as_u8(self) -> u8 { self as u8 } #[inline(always)] fn as_u16(self) -> u16 { self as u16 } #[inline(always)] fn as_u32(self) -> u32 { self as u32 } #[inline(always)] fn as_u64(self) -> u64 { self as u64 } #[inline(always)] fn as_u128(self) -> u128 { self as u128 } #[inline(always)] fn as_usize(self) -> usize { self as usize } #[inline(always)] fn as_f32(self) -> f32 { self as u32 as f32 } #[inline(always)] fn as_f64(self) -> f64 { self as u32 as f64 } } impl_for!(Fundamental => i8 => |this| this != 0, i16 => |this| this != 0, i32 => |this| this != 0, i64 => |this| this != 0, i128 => |this| this != 0, isize => |this| this != 0, u8 => |this| this != 0, u16 => |this| this != 0, u32 => |this| this != 0, u64 => |this| this != 0, u128 => |this| this != 0, usize => |this| this != 0, f32 => |this: f32| (-Self::EPSILON ..= Self::EPSILON).contains(&this), f64 => |this: f64| (-Self::EPSILON ..= Self::EPSILON).contains(&this), ); impl_for!(Numeric => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, ); impl_for!(Integral => { i8, i8, u8; i16, i16, u16; i32, i32, u32; i64, i64, u64; i128, i128, u128; isize, isize, usize; u8, i8, u8; u16, i16, u16; u32, i32, u32; u64, i64, u64; u128, i128, u128; usize, isize, usize; }); impl_for!(Signed => i8, i16, i32, i64, i128, isize); impl_for!(Unsigned => u8, u16, u32, u64, u128, usize); impl_for!(Floating => f32 | u32, f64 | u64); impl_for!(Is8 => i8, u8); impl_for!(Is16 => i16, u16); impl_for!(Is32 => i32, u32, f32); impl_for!(Is64 => i64, u64, f64); impl_for!(Is128 => i128, u128); #[cfg(target_pointer_width = "16")] impl_for!(Is16 => isize, usize); #[cfg(target_pointer_width = "32")] impl_for!(Is32 => isize, usize); #[cfg(target_pointer_width = "64")] impl_for!(Is64 => isize, usize); impl_for!(AtLeast8 => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, ); impl_for!(AtLeast16 => i16, i32, i64, i128, u16, u32, u64, u128, f32, f64); impl_for!(AtLeast32 => i32, i64, i128, u32, u64, u128, f32, f64); impl_for!(AtLeast64 => i64, i128, u64, u128, f64); impl_for!(AtLeast128 => i128, u128); #[cfg(any( target_pointer_width = "16", target_pointer_width = "32", target_pointer_width = "64" ))] impl_for!(AtLeast16 => isize, usize); #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] impl_for!(AtLeast32 => isize, usize); #[cfg(target_pointer_width = "64")] impl_for!(AtLeast64 => isize, usize); impl_for!(AtMost8 => i8, u8); impl_for!(AtMost16 => i8, i16, u8, u16); impl_for!(AtMost32 => i8, i16, i32, u8, u16, u32, f32); impl_for!(AtMost64 => i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64, ); impl_for!(AtMost128 => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, ); #[cfg(target_pointer_width = "16")] impl_for!(AtMost16 => isize, usize); #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] impl_for!(AtMost32 => isize, usize); #[cfg(test)] mod tests { use super::*; use static_assertions::*; assert_impl_all!(bool: Fundamental); assert_impl_all!(char: Fundamental); assert_impl_all!(i8: Integral, Signed, Is8); assert_impl_all!(i16: Integral, Signed, Is16); assert_impl_all!(i32: Integral, Signed, Is32); assert_impl_all!(i64: Integral, Signed, Is64); assert_impl_all!(i128: Integral, Signed, Is128); assert_impl_all!(isize: Integral, Signed); assert_impl_all!(u8: Integral, Unsigned, Is8); assert_impl_all!(u16: Integral, Unsigned, Is16); assert_impl_all!(u32: Integral, Unsigned, Is32); assert_impl_all!(u64: Integral, Unsigned, Is64); assert_impl_all!(u128: Integral, Unsigned, Is128); assert_impl_all!(usize: Integral, Unsigned); assert_impl_all!(f32: Floating, Is32); assert_impl_all!(f64: Floating, Is64); }
#![crate_type="lib"] #![crate_name="wasmlib"] #[macro_use] extern crate lazy_static; pub mod host_api; pub use host_api::*; pub mod resource; pub use resource::*;
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let value = &numbers[0]; println!("value: {}", value); }
use hilbert_qexp::eisenstein::eisenstein_series_from_lvals; use hilbert_qexp::elements::{square_root_mut, HmfGen}; use flint::fmpq::Fmpq; use flint::fmpz::Fmpz; pub fn eisensten_series(k: u64, prec: usize) -> HmfGen<Fmpq> { assert!(2 <= k && k <= 10); let l_vals = [ ("48", "1"), ("480", "11"), ("1008", "361"), ("960", "24611"), ("528", "2873041"), ]; let (num_s, den_s) = l_vals[((k - 2) >> 1) as usize]; let num = &Fmpz::from_str(&num_s, 10).unwrap(); let den = &Fmpz::from_str(&den_s, 10).unwrap(); eisenstein_series_from_lvals(k, 2, num, den, prec) } pub fn s2_form(prec: usize) -> HmfGen<Fmpq> { eisensten_series(2, prec) } pub fn s4_form(prec: usize) -> HmfGen<Fmpq> { let g2 = eisensten_series(2, prec); let g4 = eisensten_series(4, prec); let mut res = &g2 * &g2; res -= &g4; res *= 11; res /= &Into::<Fmpq>::into((192 * 3, 1)); res } pub fn s6_form(prec: usize) -> HmfGen<Fmpq> { let g2 = eisensten_series(2, prec); let g4 = eisensten_series(4, prec); let g6 = eisensten_series(6, prec); let mut res = g2.pow(3); res *= -25 * 49; res += &(&(&g2 * &g4) * (3 * 11 * 59)); res -= &(&g6 * (2 * 19 * 19)); res /= &From::from(449280); res } fn s5_squared(prec: usize) -> HmfGen<Fmpq> { let s4 = s4_form(prec); let s6 = s6_form(prec); let g2 = eisensten_series(2, prec); (&s6 * 4 + &s4 * &g2) * &s4 } pub fn s5_form(prec: usize) -> HmfGen<Fmpq> { let mut res = HmfGen::<Fmpq>::new(2, prec + 1); let bd = res.u_bds.vec[1] as i64; res.fcvec.fc_ref_mut(1, 1, bd).set_si(1, 1); res.fcvec.fc_ref_mut(1, -1, bd).set_si(-1, 1); square_root_mut(&mut res, 1, &s5_squared(prec + 1)); res } fn s9_squared(prec: usize) -> HmfGen<Fmpq> { let g2 = eisensten_series(2, prec); let s4 = s4_form(prec); let s6 = s6_form(prec); let mut res = &g2.pow(3) * &s6; res += &(&(&g2.pow(2) * &s4.pow(2)) * 4); res -= &(&(&g2 * &(&s4 * &s6)) * (32 * 9)); res -= &(&s4.pow(3) * 1024); res -= &(&s6.pow(2) * (64 * 27)); res * &s6 } pub fn s9_form(prec: usize) -> HmfGen<Fmpq> { let f = s9_squared(prec + 1); let mut res = HmfGen::<Fmpq>::new(2, prec + 1); let bd = res.u_bds.vec[1] as i64; res.fcvec.fc_ref_mut(1, 0, bd).set_si(1, 1); square_root_mut(&mut res, 1, &f); res } #[cfg(test)] mod tests { use super::*; #[test] fn test_s5_squared() { let prec = 5; let f = s5_squared(prec); let s5 = s5_form(prec); assert_eq!(f, &s5 * &s5); } #[test] fn test_s9_squared() { let prec = 5; let f = s9_squared(prec); println!("{}", f); assert_eq!( f.diagonal_restriction(), vec![0, 0, 1, -1056, 270216, 4819328] .into_iter() .map(|x| Into::<Fmpq>::into((x, 1))) .collect::<Vec<_>>() ); } }
fn profile_for<T: AsRef<[u8]>>(email: T) -> Vec<u8> { let mut output = "email=".as_bytes().to_vec(); let cleaned: Vec<&u8> = email .as_ref() .into_iter() .filter(|c| !(**c == b'&' || **c == b'=')) .collect(); output.extend(cleaned); output.extend_from_slice("&uid=10&role=user".as_bytes()); output } #[cfg(test)] mod test { use crate::set1::aes; use crate::set2::cut_and_paste::profile_for; use crate::set2::{kv, pkcs7}; static KEY: [u8; 16] = [ 162, 16, 247, 214, 196, 106, 167, 142, 100, 136, 17, 82, 127, 118, 107, 212, ]; fn oracle<T: AsRef<[u8]>>(input: T) -> Vec<u8> { aes::ecb::encrypt(&KEY.to_vec(), profile_for(input)) } fn decrypt<T: AsRef<[u8]>>(input: T) -> Vec<u8> { pkcs7::unpad(aes::ecb::decrypt(&KEY, input)).unwrap() } #[test] fn break_oracle() { // Push "user" off the end so we can remove the block let input1 = oracle("a".repeat(13)).into_iter().take(2 * 16); // Create ciphertext including a padded block that starts with "admin" let email = b"a" .repeat(10) .into_iter() .chain(pkcs7::pad("admin", 16)) .collect::<Vec<u8>>(); let input2 = oracle(email); // Stitch the blocks together let mut synthesised = Vec::new(); synthesised.extend(input1.clone()); synthesised.extend(&input2[16..=31]); let output = String::from_utf8(decrypt(synthesised)).unwrap(); assert_eq!(*kv::parse(&output).get("role").unwrap(), "admin"); } #[test] fn profile_for_email() { let output = profile_for("foo@bar.com"); assert_eq!( output, "email=foo@bar.com&uid=10&role=user".as_bytes().to_vec() ); } #[test] fn profile_for_email_remove_special_chars() { let output = profile_for("foo@bar.com&role=admin"); assert_eq!( output, "email=foo@bar.comroleadmin&uid=10&role=user" .as_bytes() .to_vec() ); } }
use option_lock::*; use std::sync::Arc; #[test] fn option_lock_guard() { let a = OptionLock::from(1); assert!(!a.is_locked()); let mut guard = a.try_lock().unwrap(); assert!(a.is_locked()); assert_eq!(a.try_lock().unwrap_err(), OptionLockError::Unavailable); assert_eq!(a.try_take(), Err(OptionLockError::Unavailable)); assert_eq!(guard.as_ref(), Some(&1)); guard.replace(2); drop(guard); assert_eq!(a.try_lock().unwrap().as_ref(), Some(&2)); assert!(!a.is_locked()); } #[test] fn option_lock_take() { let a = OptionLock::<u32>::empty(); assert_eq!(a.try_take(), Err(OptionLockError::FillState)); drop(a); let b = OptionLock::from(101); assert_eq!(b.try_take(), Ok(101)); drop(b); } #[test] fn option_lock_debug() { assert_eq!( format!("{:?}", &OptionLock::<i32>::empty()), "OptionLock(None)" ); assert_eq!(format!("{:?}", &OptionLock::from(1)), "OptionLock(Some)"); let lock = OptionLock::from(1); let guard = lock.try_lock().unwrap(); assert_eq!(format!("{:?}", &guard), "OptionGuard(Some(1))"); assert_eq!(format!("{:?}", &lock), "OptionLock(Locked)"); } #[test] fn option_lock_drop() { use std::sync::atomic::{AtomicUsize, Ordering}; static DROPPED: AtomicUsize = AtomicUsize::new(0); struct DropCheck; impl DropCheck { fn count() -> usize { DROPPED.load(Ordering::Relaxed) } } impl Drop for DropCheck { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::Release); } } let lock = OptionLock::<DropCheck>::empty(); drop(lock); assert_eq!(DropCheck::count(), 0); let lock = OptionLock::from(DropCheck); drop(lock); assert_eq!(DropCheck::count(), 1); let lock = OptionLock::empty(); let mut guard = lock.try_lock().unwrap(); assert_eq!(DropCheck::count(), 1); guard.replace(DropCheck); drop(guard); assert_eq!(DropCheck::count(), 1); drop(lock); assert_eq!(DropCheck::count(), 2); } #[test] fn option_lock_try_get() { let a = OptionLock::from(1); assert!(!a.is_locked()); let mut guard = a.try_get().unwrap(); assert!(a.is_locked()); assert_eq!(a.try_lock().unwrap_err(), OptionLockError::Unavailable); assert_eq!(a.try_take(), Err(OptionLockError::Unavailable)); assert_eq!(*guard, 1); *guard += 1; drop(guard); assert_eq!(*a.try_get().unwrap(), 2); assert!(!a.is_locked()); } #[test] fn option_lock_try_clone() { let a = OptionLock::from(1); assert_eq!(a.try_clone(), Ok(1)); assert_eq!(a.try_take(), Ok(1)); assert_eq!(a.try_clone(), Err(OptionLockError::FillState)); } #[test] fn option_lock_try_copy() { let a = OptionLock::from(1); assert_eq!(a.try_copy(), Ok(1)); assert_eq!(a.try_take(), Ok(1)); assert_eq!(a.try_copy(), Err(OptionLockError::FillState)); } #[test] fn owned_take() { let mut lock1 = OptionLock::<()>::empty(); assert_eq!(lock1.take(), None); let mut lock2 = OptionLock::new(98u32); assert_eq!(lock2.take(), Some(98u32)); let lock3 = OptionLock::new(99u32); let val: Option<u32> = lock3.into(); assert_eq!(val, Some(99u32)); } #[test] fn owned_replace() { let mut lock1 = OptionLock::<()>::empty(); assert_eq!(lock1.replace(()), None); assert_eq!(lock1.replace(()), Some(())); let mut lock2 = OptionLock::new(18); assert_eq!(lock2.replace(19), Some(18)); assert_eq!(lock2.replace(20), Some(19)); } #[test] fn arc_lock_guard() { let a = Arc::new(OptionLock::from(1)); assert!(!a.is_locked()); let mut guard = a.try_lock_arc().unwrap(); assert!(a.is_locked()); assert_eq!(a.try_lock().unwrap_err(), OptionLockError::Unavailable); assert_eq!(a.try_take(), Err(OptionLockError::Unavailable)); assert_eq!(guard.as_ref(), Some(&1)); guard.replace(2); drop(guard); assert_eq!(a.try_lock().unwrap().as_ref(), Some(&2)); assert!(!a.is_locked()); } #[test] fn arc_lock_try_get() { let a = Arc::new(OptionLock::from(1)); assert!(!a.is_locked()); let mut guard = a.try_get_arc().unwrap(); assert!(a.is_locked()); assert_eq!(a.try_lock().unwrap_err(), OptionLockError::Unavailable); assert_eq!(a.try_take(), Err(OptionLockError::Unavailable)); assert_eq!(*guard, 1); guard.replace(2); drop(guard); assert_eq!(a.try_lock().unwrap().as_ref(), Some(&2)); assert!(!a.is_locked()); } #[test] fn arc_lock_debug() { let lock = Arc::new(OptionLock::from(1)); let guard = lock.try_lock_arc().unwrap(); assert_eq!(format!("{:?}", &guard), "OptionGuardArc(Some(1))"); assert_eq!(format!("{:?}", &lock), "OptionLock(Locked)"); drop(guard); let guard = lock.try_get_arc().unwrap(); assert_eq!(format!("{:?}", &guard), "MutexGuardArc(1)"); } #[test] fn arc_lock_drop() { use std::sync::atomic::{AtomicUsize, Ordering}; static DROPPED: AtomicUsize = AtomicUsize::new(0); struct DropCheck; impl DropCheck { fn count() -> usize { DROPPED.load(Ordering::Relaxed) } } impl Drop for DropCheck { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::Release); } } let lock = Arc::new(OptionLock::empty()); let mut guard = lock.try_lock_arc().unwrap(); assert_eq!(DropCheck::count(), 0); guard.replace(DropCheck); drop(guard); assert_eq!(DropCheck::count(), 0); drop(lock); assert_eq!(DropCheck::count(), 1); } #[test] fn once_cell_set_struct_member() { struct MyStruct { param: OnceCell<i32>, } impl MyStruct { pub fn new(value: i32) -> Self { let slf = Self { param: Default::default(), }; slf.param.set(value).unwrap(); slf } pub fn get(&self) -> &i32 { self.param.get().unwrap() } } let s = MyStruct::new(156); assert_eq!(*s.get(), 156); assert_eq!(format!("{:?}", &s.param), "OnceCell(Some(156))"); } #[test] fn once_cell_get_or_init() { let cell = OnceCell::empty(); assert_eq!(*cell.get_or_init(|| 10), 10); assert_eq!(*cell.get_or_init(|| 11), 10); } #[test] fn lazy_static() { static CELL: Lazy<i32> = Lazy::new(|| 99); assert_eq!(*CELL, 99); }
use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; pub struct State<T>(Rc<RefCell<T>>); impl<T> Clone for State<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<T> State<T> { pub fn new(x: T) -> Self { Self(Rc::new(RefCell::new(x))) } pub fn get_mut(&self) -> RefMut<T> { self.0.borrow_mut() } pub fn get(&self) -> Ref<T> { self.0.borrow() } }
#[derive(Debug)] pub enum Task { //RunDnsResolver, }
use std::io::{stdout, Write}; fn main() { let args = std::env::args(); let argc = args.len(); // compute the width to print numbers in the range `0..argc` let width: usize = if argc <= 10 { 1 } else if argc <= 100 { 2 } else if argc <= 1_000 { 3 } else if argc <= 10_000 { 4 } else if argc <= 100_000 { 5 } else if argc <= 1_000_000 { 6 } else { 0 }; let mut stdout_lock = stdout().lock(); for (i, arg) in args.enumerate() { writeln!(stdout_lock, "{:width$}: `{}`", i, arg).unwrap(); } }
/* TODO setup external file for testing - examples? multiple targets? why is this so complex see if &self can be named anything else - is it like python classes? */ use std::ops::{Mul,Div,Add,Sub}; // allows println to show struct - https://doc.rust-lang.org/book/ch05-02-example-structs.html #[derive(Debug)] #[derive(Copy, Clone)] pub struct Vec3{ pub x: f64, pub y: f64, pub z: f64, } impl Mul<f64> for Vec3 { type Output = Vec3; // maybe should be references to prevent copying?: // fn mul(&self, other: &f64) fn mul(self, other: f64) -> Vec3 { Vec3 { x: self.x * other, y: self.y * other, z: self.z * other, } } } impl Mul<Vec3> for f64 { type Output = Vec3; fn mul(self, other: Vec3) -> Vec3 { Vec3 { x: other.x * self, y: other.y * self, z: other.z * self, } } } impl Div<f64> for Vec3 { type Output = Vec3; fn div(self, other: f64) -> Vec3 { Vec3 { x: self.x / other, y: self.y / other, z: self.z / other, } } } impl Add<Vec3> for Vec3 { type Output = Vec3; fn add(self, other: Vec3) -> Vec3 { Vec3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } } impl Sub<Vec3> for Vec3 { type Output = Vec3; fn sub(self, other: Vec3) -> Vec3 { Vec3 { x: self.x - other.x, y: self.y - other.y, z: self.z - other.z, } } } impl Vec3 { pub fn new(sx: f64, sy: f64, sz: f64) -> Vec3 { Vec3 {x: sx, y: sy, z: sz} } pub fn zero() -> Vec3 { Vec3 { x: 0.0, y: 0.0, z: 0.0, } } // borrows the vector to return another value pub fn length(&self) -> f64 { let val = self.x*self.x + self.y*self.y + self.z*self.z; val.sqrt() } pub fn length2(&self) -> f64 { self.x*self.x + self.y*self.y + self.z*self.z } pub fn dot(&self, other: &Vec3) -> f64 { self.x*other.x + self.y*other.y + self.z*other.z } pub fn normalized(self) -> Vec3 { //Vec3::new(self.x, self.y, self.z) / self.length() self / self.length() } //we need to read and write - mutable reference borrow // pub fn normalize(&mut self) -> () { // let length = self.length(); // self.x /= length; // self.y /= length; // self.z /= length; // } } #[cfg(test)] mod tests{ use super::*; #[test] fn test_add(){ let v: Vec3 = Vec3::new(1.0, 2.0, 3.0); let result: Vec3 = v + Vec3::new(0.1,0.2,0.3); assert!(result.x == 1.1); assert!(result.y == 2.2); assert!(result.z == 3.3); } #[test] fn test_sub(){ let v: Vec3 = Vec3::new(1.0, 2.0, 3.0); let result: Vec3 = v - Vec3::new(0.1,0.2,0.3); assert!(result.x == 0.9); assert!(result.y == 1.8); assert!(result.z == 2.7); } #[test] fn test_mul(){ let v: Vec3 = Vec3::new(1.0, 2.0, 3.0); let s: f64 = 3.0; let left: Vec3 = v * s; let right: Vec3 = s * v; // check side equality assert!(left.x == right.x); assert!(left.y == right.y); assert!(left.z == right.z); assert!(left.x == 3.0); assert!(left.y == 6.0); assert!(left.z == 9.0); } #[test] fn test_difficult(){ let t: f64 = 0.5; let o: Vec3 = (1.0-t)*Vec3::new(1.0,1.0,1.0) + t*Vec3::new(0.5,0.7,1.0); assert!(o.x == 0.75);//0.5+0.5*0.5); assert!(o.y == 0.85);//0.5+0.5*0.7); assert!(o.z == 1.0);//0.5+0.5*1.0); } #[test] fn test_length(){ let vector: Vec3 = Vec3::new(1.0, 4.0, 8.0); let length = vector.length(); assert!(length == 9.0); } #[test] fn test_normalize(){ let vector: Vec3 = Vec3::new(3.0, 0.0, 4.0); let n: Vec3 = vector.normalized(); assert!(n.x == 3.0/5.0); assert!(n.y == 0.0); assert!(n.z == 4.0/5.0); assert!(n.length() == 1.0); } }
use amethyst::{ assets::AssetStorage, core::ecs::{Join, Read, ReadStorage, SystemData, World}, error::Error, renderer::{ bundle::{RenderOrder, RenderPlan, RenderPlugin, Target}, pipeline::{PipelineDescBuilder, PipelinesBuilder}, pod::ViewArgs, rendy::{ command::{QueueId, RenderPassEncoder}, factory::Factory, graph::{ render::{PrepareResult, RenderGroup, RenderGroupDesc}, GraphContext, NodeBuffer, NodeImage, }, hal::{self, device::Device, pso}, mesh::{AsVertex, Position, TexCoord, VertexFormat}, shader::{PathBufShaderInfo, Shader, ShaderKind, SourceLanguage, SpirvShader}, }, submodules::{gather::CameraGatherer, DynamicUniform}, types::Backend, util, Mesh, }, }; use std::path::PathBuf; use gv_client_shared::ecs::{components::HealthUiGraphics, resources::HealthUiMesh}; use gv_core::math::Vector2; #[derive(Default, Debug)] pub struct HealthUiPlugin { target: Target, } impl<B: Backend> RenderPlugin<B> for HealthUiPlugin { fn on_plan( &mut self, plan: &mut RenderPlan<B>, _factory: &mut Factory<B>, _world: &World, ) -> Result<(), Error> { plan.extend_target(self.target, |ctx| { ctx.add(RenderOrder::Overlay, DrawHealthUiDesc::new().builder())?; Ok(()) }); Ok(()) } } lazy_static::lazy_static! { static ref VERTEX_SRC: SpirvShader = PathBufShaderInfo::new( PathBuf::from("resources/shaders/health_ui.vert"), ShaderKind::Vertex, SourceLanguage::GLSL, "main", ).precompile().unwrap(); static ref VERTEX: SpirvShader = SpirvShader::new( (*VERTEX_SRC).spirv().unwrap().to_vec(), (*VERTEX_SRC).stage(), "main", ); static ref FRAGMENT_SRC: SpirvShader = PathBufShaderInfo::new( PathBuf::from("resources/shaders/health_ui.frag"), ShaderKind::Fragment, SourceLanguage::GLSL, "main", ).precompile().unwrap(); static ref FRAGMENT: SpirvShader = SpirvShader::new( (*FRAGMENT_SRC).spirv().unwrap().to_vec(), (*FRAGMENT_SRC).stage(), "main", ); } // TODO: hey mate, you don't use it. #[repr(C)] #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub struct HealthUiArgs; impl HealthUiArgs { fn vertex_formats() -> Vec<VertexFormat> { vec![TexCoord::vertex(), Position::vertex()] } } impl AsVertex for HealthUiArgs { fn vertex() -> VertexFormat { VertexFormat::new((Position::vertex(), TexCoord::vertex())) } } #[derive(Debug)] pub struct DrawHealthUiDesc; impl DrawHealthUiDesc { pub fn new() -> Self { Self } } impl<B: Backend> RenderGroupDesc<B, World> for DrawHealthUiDesc { fn build( self, _ctx: &GraphContext<B>, factory: &mut Factory<B>, _queue: QueueId, _world: &World, framebuffer_width: u32, framebuffer_height: u32, subpass: hal::pass::Subpass<'_, B>, _buffers: Vec<NodeBuffer>, _images: Vec<NodeImage>, ) -> Result<Box<dyn RenderGroup<B, World>>, failure::Error> { let env = DynamicUniform::new(factory, pso::ShaderStageFlags::VERTEX)?; let (pipeline, pipeline_layout) = build_pipeline( factory, subpass, framebuffer_width, framebuffer_height, vec![env.raw_layout()], )?; Ok(Box::new(DrawHealthUi::<B> { pipeline, pipeline_layout, env, })) } } #[derive(Debug)] pub struct DrawHealthUi<B: Backend> { pipeline: B::GraphicsPipeline, pipeline_layout: B::PipelineLayout, env: DynamicUniform<B, ViewArgs>, } impl<B: Backend> RenderGroup<B, World> for DrawHealthUi<B> { fn prepare( &mut self, factory: &Factory<B>, _queue: QueueId, index: usize, _subpass: hal::pass::Subpass<'_, B>, world: &World, ) -> PrepareResult { let camera = CameraGatherer::gather(world); self.env.write(factory, index, camera.projview); PrepareResult::DrawRecord } fn draw_inline( &mut self, mut encoder: RenderPassEncoder<'_, B>, index: usize, _: hal::pass::Subpass<'_, B>, world: &World, ) { let (mesh_storage, health_ui_mesh_handle, health_ui_graphics) = <( Read<'_, AssetStorage<Mesh>>, Option<Read<'_, HealthUiMesh>>, ReadStorage<'_, HealthUiGraphics>, )>::fetch(world); if health_ui_mesh_handle.is_none() { return; } let layout = &self.pipeline_layout; encoder.bind_graphics_pipeline(&self.pipeline); self.env.bind(index, layout, 0, &mut encoder); let mesh_id = health_ui_mesh_handle.as_ref().unwrap().0.id(); if let Some(mesh) = B::unwrap_mesh(unsafe { mesh_storage.get_by_id_unchecked(mesh_id) }) { mesh.bind(0, &HealthUiArgs::vertex_formats(), &mut encoder) .expect("Expected to bind a Mesh"); for health_ui_graphics in (health_ui_graphics).join() { let constant = HealthUiVertPushConstant { translation: health_ui_graphics.screen_position, scale: health_ui_graphics.scale_ratio, }; let push_constants: [u32; 3] = unsafe { std::mem::transmute(constant) }; unsafe { encoder.push_constants( layout, pso::ShaderStageFlags::VERTEX, 0, &push_constants, ); } let constant = HealthUiFragPushConstant { health: health_ui_graphics.health, }; let push_constants: [u32; 1] = unsafe { std::mem::transmute(constant) }; unsafe { encoder.push_constants( layout, pso::ShaderStageFlags::FRAGMENT, std::mem::size_of::<HealthUiVertPushConstant>() as u32, &push_constants, ); } unsafe { encoder.draw_indexed(0..mesh.len(), 0, 0..1); } } } } fn dispose(self: Box<Self>, factory: &mut Factory<B>, _aux: &World) { unsafe { factory.device().destroy_graphics_pipeline(self.pipeline); factory .device() .destroy_pipeline_layout(self.pipeline_layout); } } } fn build_pipeline<B: Backend>( factory: &Factory<B>, subpass: hal::pass::Subpass<'_, B>, framebuffer_width: u32, framebuffer_height: u32, layouts: Vec<&B::DescriptorSetLayout>, ) -> Result<(B::GraphicsPipeline, B::PipelineLayout), failure::Error> { let push_constants = vec![ (pso::ShaderStageFlags::VERTEX, 0..4), (pso::ShaderStageFlags::FRAGMENT, 0..4), ]; let pipeline_layout = unsafe { factory .device() .create_pipeline_layout(layouts, push_constants) }?; let shader_vertex = unsafe { VERTEX.module(factory).unwrap() }; let shader_fragment = unsafe { FRAGMENT.module(factory).unwrap() }; let vertex_desc = HealthUiArgs::vertex_formats() .iter() .map(|f| (f.clone(), pso::VertexInputRate::Vertex)) .collect::<Vec<_>>(); let pipes = PipelinesBuilder::new() .with_pipeline( PipelineDescBuilder::new() .with_vertex_desc(&vertex_desc) .with_input_assembler(pso::InputAssemblerDesc::new(hal::Primitive::TriangleList)) .with_rasterizer(hal::pso::Rasterizer { polygon_mode: hal::pso::PolygonMode::Fill, cull_face: hal::pso::Face::NONE, front_face: hal::pso::FrontFace::Clockwise, depth_clamping: false, depth_bias: None, conservative: false, }) .with_shaders(util::simple_shader_set( &shader_vertex, Some(&shader_fragment), )) .with_layout(&pipeline_layout) .with_subpass(subpass) .with_baked_states(hal::pso::BakedStates { viewport: Some(hal::pso::Viewport { rect: hal::pso::Rect { x: 0, y: 0, w: framebuffer_width as i16, h: framebuffer_height as i16, }, depth: 0.0..1.0, }), scissor: None, ..Default::default() }) .with_blend_targets(vec![pso::ColorBlendDesc { mask: pso::ColorMask::ALL, blend: Some(pso::BlendState::ALPHA), }]) .with_depth_test(pso::DepthTest { fun: pso::Comparison::Less, write: false, }), ) .build(factory, None); unsafe { factory.destroy_shader_module(shader_vertex); factory.destroy_shader_module(shader_fragment); } match pipes { Err(e) => { unsafe { factory.device().destroy_pipeline_layout(pipeline_layout); } Err(e) } Ok(mut pipes) => Ok((pipes.remove(0), pipeline_layout)), } } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct HealthUiVertPushConstant { translation: Vector2, scale: f32, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct HealthUiFragPushConstant { health: f32, }
pub fn large_group_positions(s: String) -> Vec<Vec<i32>> { if s.len() < 3 { return vec![]; } let bytes = s.as_bytes(); let mut ans = vec![]; ans.push(vec![0, 1]); let mut pre_c = bytes[0]; let mut start = 0; let mut end = 0; for i in 1..bytes.len() { if bytes[i] == pre_c { end = i; } else { if (end - start + 1) >= 3 { ans.push(vec![start as i32, end as i32]); } start = i; end = i; pre_c = bytes[i]; } } if (end - start + 1) >= 3 { ans.push(vec![start as i32, end as i32]); } ans } fn main() { println!( "{:?}", split_array_into_fibonacci_sequence::Solution::split_into_fibonacci("0123".into()) ); println!("Hello, world!"); }
const INF: i64 = 1 << 61; use std::cmp::min; struct Graph { edges: Vec<Vec<(usize, i64, i64, i64)>>, // adjacent list n: usize } impl Graph { fn new(n: usize) -> Self { Graph { edges: vec![Vec::new(); n], n, } } fn add(&mut self, from: usize, to: usize, cap: i64, cost: i64, directed: bool) { // edge[from]: to, cap, cost, rev(逆辺) if directed { let rev_from: i64 = self.edges[to].len() as i64; self.edges[from].push((to, cap, cost, rev_from)); let rev_to: i64 = self.edges[from].len() as i64; self.edges[to].push((from, 0, -cost, rev_to-1)); } else { // TODO: must be verified let rev_from: i64 = self.edges[to].len() as i64; self.edges[from].push((to, cap, cost, rev_from)); let rev_to: i64 = self.edges[from].len() as i64; self.edges[to].push((from, 0, -cost, rev_to-1)); self.edges[to].push((from, cap, cost, rev_to)); let rev_from: i64 = self.edges[to].len() as i64; self.edges[from].push((to, 0, -cost, rev_from-1)); } } fn min_cost_flow_bellmanford(&mut self, start: usize, goal: usize, mut flow: i64) -> i64 { let mut res: i64 = 0; let mut prev_vertex: Vec<usize> = vec![0; self.n]; let mut prev_edge: Vec<usize> = vec![0; self.n]; while flow > 0 { let mut dist: Vec<i64> = vec![INF; self.n]; dist[start] = 0; let mut update = true; while update { update = false; for v in 0..self.n { if dist[v] == INF {continue} for (i, edge) in self.edges[v].iter().enumerate() { let (to, cap, cost, _) = *edge; if (cap > 0) & (dist[to] > dist[v] + cost) { dist[to] = dist[v] + cost; prev_vertex[to] = v; prev_edge[to] = i; update = true; } } } } if dist[goal] == INF { return -1 } let mut d = flow; let mut v = goal; while v != start { d = min(d, self.edges[prev_vertex[v]][prev_edge[v]].1); v = prev_vertex[v]; } flow -= d; res += d * dist[goal]; let mut v = goal; while v != start { self.edges[prev_vertex[v]][prev_edge[v]].1 -= d; let e = self.edges[prev_vertex[v]][prev_edge[v]]; self.edges[v][e.3 as usize].1 += d; v = prev_vertex[v]; } } return res } }
use std::ffi::CStr; use std::mem; use std::slice; use vkr::{vk, Builder, Loader}; fn get_memory_type_index( memory_properties: &vk::PhysicalDeviceMemoryProperties, memory_type_bits: u32, property_flags: vk::MemoryPropertyFlags, ) -> Option<u32> { for i in 0..memory_properties.memory_type_count { let mt = &memory_properties.memory_types[i as usize]; if (memory_type_bits & (1 << i)) != 0 && mt.property_flags.contains(property_flags) { return Some(i); } } None } fn main() -> Result<(), vkr::LoaderError> { // this example only requires Vulkan 1.0.0 let version = Default::default(); // load the Vulkan lib let instance = { let loader = Loader::new()?; let layer_names_raw = [unsafe { CStr::from_bytes_with_nul_unchecked(b"VK_LAYER_LUNARG_standard_validation\0") }.as_ptr()]; let app_info = vk::ApplicationInfo::builder() .p_application_name(CStr::from_bytes_with_nul(b"compute\0").unwrap()) .api_version(version); let instance_create_info = vk::InstanceCreateInfo::builder() .p_application_info(Some(&app_info)) .pp_enabled_layer_names(&layer_names_raw); unsafe { loader.create_instance(&instance_create_info, None) }? }; // find the first physical device let physical_device = { let physical_devices = unsafe { instance.enumerate_physical_devices_to_vec() }?; for physical_device in &physical_devices { let props = unsafe { instance.get_physical_device_properties(*physical_device) }; println!("physical device ({}): {:?}", props.device_type, unsafe { CStr::from_ptr(props.device_name.as_ptr()) }); } physical_devices.first().cloned().expect("no physical device found") }; // find the first queue family that supports compute let queue_family_properties = unsafe { instance.get_physical_device_queue_family_properties_to_vec(physical_device) }; let queue_family_index = queue_family_properties .iter() .enumerate() .filter_map(|(index, &info)| { if info.queue_flags.contains(vk::QueueFlags::COMPUTE) { Some(index as u32) } else { None } }) .next() .expect("no queue family supports compute"); // create a device for this queue family let device = { let queue_priority = 1.0; let device_queue_create_info = vk::DeviceQueueCreateInfo::builder() .queue_family_index(queue_family_index) .p_queue_priorities(slice::from_ref(&queue_priority)); let device_create_info = vk::DeviceCreateInfo::builder().p_queue_create_infos(slice::from_ref(&device_queue_create_info)); unsafe { instance.create_device(physical_device, &device_create_info, None, version) }? }; // load the compute shader let shader_module = { let shader_bytes = include_bytes!("compute_fill.comp.spv"); let shader_module_create_info = vk::ShaderModuleCreateInfo { code_size: shader_bytes.len(), p_code: shader_bytes.as_ptr() as _, ..Default::default() }; unsafe { device.create_shader_module(&shader_module_create_info, None) }? }; // create a buffer for outputs let dispatch_size = 256; let buffer_size = dispatch_size * mem::size_of::<f32>(); let buffer = { let buffer_create_info = vk::BufferCreateInfo { size: buffer_size as vk::DeviceSize, usage: vk::BufferUsageFlags::STORAGE_BUFFER, ..Default::default() }; unsafe { device.create_buffer(&buffer_create_info, None) }? }; let mem_req = unsafe { device.get_buffer_memory_requirements(buffer) }; // allocate memory for the buffer let mem = { let memory_properties = unsafe { instance.get_physical_device_memory_properties(physical_device) }; let memory_type_index = get_memory_type_index( &memory_properties, mem_req.memory_type_bits, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, ) .expect("no suitable memory type found"); let memory_allocate_info = vk::MemoryAllocateInfo { allocation_size: mem_req.size, memory_type_index, ..Default::default() }; unsafe { device.allocate_memory(&memory_allocate_info, None) }? }; unsafe { device.bind_buffer_memory(buffer, mem, 0) }?; // make the pipeline layout let descriptor_set_layout = { let descriptor_set_layout_bindings = [vk::DescriptorSetLayoutBinding { binding: 0, descriptor_type: vk::DescriptorType::STORAGE_BUFFER, descriptor_count: 1, stage_flags: vk::ShaderStageFlags::COMPUTE, ..Default::default() }]; let descriptor_set_layout_create_info = vk::DescriptorSetLayoutCreateInfo::builder().p_bindings(&descriptor_set_layout_bindings); unsafe { device.create_descriptor_set_layout(&descriptor_set_layout_create_info, None) }? }; let pipeline_layout = { let pipeline_layout_create_info = vk::PipelineLayoutCreateInfo::builder().p_set_layouts(slice::from_ref(&descriptor_set_layout)); unsafe { device.create_pipeline_layout(&pipeline_layout_create_info, None) }? }; // create the pipeline let pipeline_create_info = vk::ComputePipelineCreateInfo { stage: vk::PipelineShaderStageCreateInfo { stage: vk::ShaderStageFlags::COMPUTE, module: Some(shader_module), p_name: unsafe { CStr::from_bytes_with_nul_unchecked(b"main\0") }.as_ptr(), ..Default::default() }, layout: Some(pipeline_layout), ..Default::default() }; let pipeline = unsafe { device.create_compute_pipelines_single(None, slice::from_ref(&pipeline_create_info), None) }?; // create a pool for the descriptor we need let descriptor_pool = { let descriptor_pool_sizes = [vk::DescriptorPoolSize { ty: vk::DescriptorType::STORAGE_BUFFER, descriptor_count: 1, }]; let descriptor_pool_create_info = vk::DescriptorPoolCreateInfo::builder() .max_sets(1) .p_pool_sizes(&descriptor_pool_sizes); unsafe { device.create_descriptor_pool(&descriptor_pool_create_info, None) }? }; // allocate and write the descriptor set let descriptor_set_allocate_info = vk::DescriptorSetAllocateInfo::builder() .descriptor_pool(descriptor_pool) .p_set_layouts(slice::from_ref(&descriptor_set_layout)); let descriptor_set = unsafe { device.allocate_descriptor_sets_single(&descriptor_set_allocate_info) }?; let descriptor_buffer_info = [vk::DescriptorBufferInfo { buffer: Some(buffer), offset: 0, range: vk::WHOLE_SIZE, }]; let write_descriptor_set = vk::WriteDescriptorSet::builder() .dst_set(descriptor_set) .dst_binding(0) .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) .p_buffer_info(&descriptor_buffer_info); unsafe { device.update_descriptor_sets(slice::from_ref(&write_descriptor_set), &[]) }; // run a command buffer to run the shader let command_pool_create_info = vk::CommandPoolCreateInfo { queue_family_index, ..Default::default() }; let command_pool = unsafe { device.create_command_pool(&command_pool_create_info, None) }?; let command_buffer_allocate_info = vk::CommandBufferAllocateInfo { command_pool: Some(command_pool), level: vk::CommandBufferLevel::PRIMARY, command_buffer_count: 1, ..Default::default() }; let command_buffer = unsafe { device.allocate_command_buffers_single(&command_buffer_allocate_info) }?; // make a command buffer that runs the ceompute shader let command_buffer_begin_info = vk::CommandBufferBeginInfo { flags: vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT, ..Default::default() }; unsafe { device.begin_command_buffer(command_buffer, &command_buffer_begin_info) }?; unsafe { device.cmd_bind_pipeline(command_buffer, vk::PipelineBindPoint::COMPUTE, pipeline) }; unsafe { device.cmd_bind_descriptor_sets( command_buffer, vk::PipelineBindPoint::COMPUTE, pipeline_layout, 0, slice::from_ref(&descriptor_set), &[], ) }; unsafe { device.cmd_dispatch(command_buffer, (dispatch_size as u32) / 16, 1, 1) }; unsafe { device.end_command_buffer(command_buffer) }?; // run it and wait until it is completed let queue = unsafe { device.get_device_queue(queue_family_index, 0) }; let submit_info = vk::SubmitInfo::builder().p_command_buffers(slice::from_ref(&command_buffer)); unsafe { device.queue_submit(queue, slice::from_ref(&submit_info), None) }?; unsafe { device.device_wait_idle() }?; // check results let mapping = unsafe { device.map_memory(mem, 0, vk::WHOLE_SIZE, Default::default()) }?; let check = unsafe { slice::from_raw_parts(mapping as *const f32, dispatch_size) }; for (i, v) in check.iter().cloned().enumerate() { assert_eq!(i as f32, v); } println!("compute shader run successfully!"); // let the driver clean up Ok(()) }
// Ennen makrojen ajamista macro_rules! impl_from { ($Small: ty, $Large: ty) => { impl From<$Small> for $Large { #[inline] fn from(small: $Small) -> $Large { small as $Large } } } } impl_from!(u16, u32); impl_from!(u16, u64); // Makrojen ajamisen jälkeen impl From<u16> for u32 { #[inline] fn from(small: u16) -> u32 { small as u32 } } impl From<u16> for u64 { #[inline] fn from(small: u16) -> u64 { small as u64 } }
use actix_web::{web, Responder}; use chrono::NaiveDateTime; use rbatis::core::value::DateTimeNow; use crate::domain::domain::SysRes; use crate::domain::dto::{EmptyDTO, IdDTO, ResAddDTO, ResEditDTO, ResPageDTO}; use crate::domain::vo::RespVO; use crate::service::CONTEXT; use rbatis::plugin::snowflake::new_snowflake_id; /// 资源分页(json请求) pub async fn page(page: web::Json<ResPageDTO>) -> impl Responder { let data = CONTEXT.sys_res_service.page(&page.0).await; RespVO::from_result(&data).resp_json() } /// 资源全部(json请求) pub async fn all(page: web::Json<EmptyDTO>) -> impl Responder { let data = CONTEXT.sys_res_service.finds_all().await; RespVO::from_result(&data).resp_json() } /// 顶层权限 pub async fn layer_top(page: web::Json<EmptyDTO>) -> impl Responder { let data = CONTEXT.sys_res_service.finds_layer_top().await; RespVO::from_result(&data).resp_json() } ///资源添加 pub async fn add(mut arg: web::Json<ResAddDTO>) -> impl Responder { if arg.name.is_none() { return RespVO::<u64>::from_error_info("", "资源名字不能为空!").resp_json(); } if arg.permission.is_none() { return RespVO::<u64>::from_error_info("", "资源permission不能为空!").resp_json(); } if arg.path.is_none() { arg.path = Some("".to_string()); } let res = SysRes { id: new_snowflake_id().to_string().into(), parent_id: arg.parent_id.clone(), name: arg.name.clone(), permission: arg.permission.clone(), path: arg.path.clone(), del: 0.into(), create_date: NaiveDateTime::now().into(), }; let data = CONTEXT.sys_res_service.add(&res).await; CONTEXT.sys_res_service.update_cache().await; RespVO::from_result(&data).resp_json() } ///资源修改 pub async fn update(arg: web::Json<ResEditDTO>) -> impl Responder { let data = CONTEXT.sys_res_service.edit(&arg.0).await; CONTEXT.sys_res_service.update_cache().await; RespVO::from_result(&data).resp_json() } ///资源删除 pub async fn remove(arg: web::Json<IdDTO>) -> impl Responder { let data = CONTEXT .sys_res_service .remove(&arg.0.id.unwrap_or_default()) .await; CONTEXT.sys_res_service.update_cache().await; RespVO::from_result(&data).resp_json() }
#![feature(proc_macro_non_items)] #![feature(use_extern_macros)] extern crate procmacro2; fn main() { procmacro2::misc_syntax!( where while abcd : u64 >> 1 + 2 * 3; where T: 'x + A<B='y+C+D>;[M];A::f ); }
/// Used to verify the server's authenticity to the client. pub fn stupid_hash(mut value: crate::data::EOThree) -> crate::data::EOThree { value += 1; 110905 + (value % 9 + 1) * ((11092004 - value) % ((value % 11 + 1) * 119)) * 119 + value % 2004 } mod packet_processor; pub use packet_processor::PacketProcessor; mod client_sequencer; pub use client_sequencer::ClientSequencer; mod server_sequencer; pub use server_sequencer::ServerSequencer;
use std::ops::{Add}; trait Animal { fn create(name: &'static str) -> Self; fn name(&self) -> &'static str; fn talk(&self) { println!("{} cannot talk", self.name()); } } struct Human { name: &'static str } struct Cat { name: &'static str } impl Animal for Human { fn create(name:&'static str) -> Human { Human{name: name} } fn name(&self) -> &'static str { self.name } fn talk(&self) { println!("{} says hello", self.name()); } } impl Animal for Cat { fn create(name:&'static str) -> Cat { Cat{name: name} } fn name(&self) -> &'static str { self.name } fn talk(&self) { println!("{} says meow", self.name()); } } trait Summable<T> { fn sum(&self) -> T; } impl Summable<i32> for Vec<i32> { fn sum(&self) -> i32 { let mut result:i32 = 0; for x in self { result += *x } return result; } } fn traits() { // let h = Human{name:"Landon"}; let h:Human = Animal::create("John"); h.talk(); let c = Cat{name:"Bear"}; c.talk(); let a = vec![1,2,3]; println!("sum = {}", a.sum()); } // Operator Overloading #[derive(Debug)] struct Complex<T> { re: T, im: T } impl<T> Complex<T> { fn new(re: T, im: T) -> Complex<T> { Complex::<T> { re, im } } } impl Add for Complex<i32> { type Output = Complex<i32>; fn add(self, rhs: Self) -> Self::Output { Complex { re: self.re + rhs.re, im: self.im + rhs.im } } } fn operator_overloading() { let mut a = Complex::new(1, 2); let mut b = Complex:: new(3, 4); println!("{:?}", a + b); } fn main() { //traits(); operator_overloading(); }
// #![feature(trait_alias)] use async_std::io; use tide_validator::{HttpField, ValidatorMiddleware}; #[async_std::main] async fn main() -> io::Result<()> { let mut app = tide::new(); let mut validator_middleware = ValidatorMiddleware::new(); let is_number = |_field_name: &str, field_value: Option<&str>| { field_value .unwrap() .parse::<i64>() .map(|_| ()) .map_err(|_| "invalid number") }; validator_middleware.add_validator(HttpField::Param("age"), is_number); app.at("/test/:age") .middleware(validator_middleware) .get(|_: tide::Request<()>| async move { Ok("Hello World") }); app.listen("127.0.0.1:8080").await?; Ok(()) }
mod filterload; mod getdata; pub mod inv; mod message_trait; mod ping; mod version; pub use filterload::*; pub use getdata::*; pub use inv::InvMessage; pub use message_trait::*; pub use ping::*; pub use version::*;
mod db; pub use db::Rocksdb;
pub fn hamming_distance(strand1: &str, strand2: &str) -> Result<u32, &'static str> { if strand1.len() != strand2.len() { return Result::Err("Lenth of strands not equal!") } let strand1_bases = strand1.chars(); let strand2_bases = strand2.chars(); let base_pairs = strand1_bases.zip(strand2_bases); let hamming_distance = base_pairs.filter(|&(x, y)| x != y).count() as u32; Result::Ok(hamming_distance) }
// Copyright (c) 2019 Alain Brenzikofer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use rstd::prelude::*; // Encoding library use parity_codec::Encode; // Enables access to the runtime storage use support::{decl_module, decl_storage, decl_event, StorageValue, StorageMap, Parameter, dispatch::Result}; // Enables us to do hashing use runtime_primitives::traits::{Zero, Hash, As, Member, SimpleArithmetic}; // Enables access to account balances and interacting with signed messages use {balances, system::{self, ensure_signed}}; use parity_codec::Codec; use timestamp::OnTimestampSet; use runtime_io; // list all traits that define types we will need pub trait Trait: balances::Trait + timestamp::Trait { type Event: From<Event> + Into<<Self as system::Trait>::Event>; } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { fn deposit_event() = default; // entry points fn register(origin) -> Result { let sender = ensure_signed(origin)?; Self::register_account_id(&sender); // debug only: reward for registration Self::reward_registrant(&sender); //println!("[ceremonies] register was called."); Ok(()) } fn witness(_origin) -> Result { Ok(()) } fn on_finalize(n: T::BlockNumber) { runtime_io::print("ceremonies: on_finalize was called"); let p = Self::ceremony_period(); if (n % p).is_zero() { runtime_io::print("blocknumber is divisible by CeremonyPeriod"); Self::deposit_event(Event::TimeToRegister()); //<CeremonyRegistry<T>>::for_each_tuple( // runtime_io::print // ) } } } } decl_storage! { trait Store for Module<T: Trait> as Ceremonies { pub LastCeremony get(last_ceremony) config(): Option<T::BlockNumber>; CeremonyPeriod get(ceremony_period) config(): T::BlockNumber = runtime_primitives::traits::One::one(); pub WitnessingPeriod get(witnessing_period) config(): Option<T::BlockNumber>; //FIXME: should be simple u32 pub CeremonyRegistry get(ceremony_registry): map T::AccountId => i32; pub Witnesses get(witnesses): map T::AccountId => T::AccountId; pub LuckyOne get(luckyone): T::AccountId; } } decl_event!( pub enum Event { Registered(u32), TimeToRegister(), } ); impl<T: Trait> Module<T> { // PUBLIC IMMUTABLES // PUBLIC MUTABLES (DANGEROUS) pub fn register_account_id(who: &T::AccountId) -> Result { <CeremonyRegistry<T>>::insert(who,1); Ok(()) } // PRIVATE // fn on_timestamp_set<H: HandleReport>(now: T::Moment, slot_duration: T::Moment) { // //println!("[ceremonies] on_timestamp_set was called.") // Ok(()) // } fn reward_registrant(who: &T::AccountId) -> Result { let value = T::Balance::sa(100); //TODO <balances::Module<T>>::reward(who, value); Ok(()) } } impl<T: Trait> OnTimestampSet<T::Moment> for Module<T> { fn on_timestamp_set(moment: T::Moment) { runtime_io::print("ceremonies::on_timestamp_set was called!"); // doesnt compile // let luckyone = <LuckyOne<T>>::AccountId; // Self::reward_registrant(&luckyone); } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
mod test; const fn roman_lut(numeral: &char) -> Option<usize> { match numeral { 'I' => Some(1), 'V' => Some(5), 'X' => Some(10), 'L' => Some(50), 'C' => Some(100), 'D' => Some(500), 'M' => Some(1000), _ => None, } } const fn arabic_lut(digit: &usize) -> Option<&str> { match digit { 1 => Some("I"), 4 => Some("IV"), 5 => Some("V"), 9 => Some("IX"), 10 => Some("X"), 40 => Some("XL"), 50 => Some("L"), 90 => Some("XC"), 100 => Some("C"), 400 => Some("CD"), 500 => Some("D"), 900 => Some("DM"), 1000 => Some("M"), _ => None, } } static DIGITS_DESC: [usize; 13] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; struct Tally { total: usize, max: usize, } // Impure function as it prints to stdout immediately. pub fn convert_and_print_numerals(list_of_numerals: &[String]) { for number_str in list_of_numerals { let result = match number_str.chars().next() { Some(c) => match c { c if c.is_ascii_alphabetic() => roman_to_arabic(&number_str.to_ascii_uppercase()), c if c.is_ascii_digit() => arabic_to_roman(number_str), _ => None, }, _ => unreachable!(), }; match result { Some(s) => println!("{}", s), None => println!("Invalid numerals!"), }; } } fn arabic_to_roman(arabic_numerals: &str) -> Option<String> { let mut num = match arabic_numerals.parse::<usize>() { Ok(n) => n, Err(_) => return None, }; let result = DIGITS_DESC .iter() .fold(String::new(), |mut state: String, digit| { let quot = num / *digit; num = num % *digit; let numeral = match arabic_lut(digit) { Some(s) => s, None => unreachable!(), }; state.push_str(&numeral.repeat(quot)); state }); Some(result) } fn roman_to_arabic(roman_numerals: &str) -> Option<String> { let result = roman_numerals.chars().rfold( Some(Tally { total: 0, max: 0 }), |tally: Option<Tally>, c| { let current_value = match roman_lut(&c) { Some(val) => val, None => return None, }; let (total, mut max) = match tally { Some(Tally { total, max }) => (total, max), None => return None, }; max = current_value.max(max); if current_value >= max { Some(Tally { total: total + current_value, max, }) } else { Some(Tally { total: total - current_value, max, }) } }, ); match result { Some(Tally { total, .. }) => Some(total.to_string()), None => None, } }
// use anyhow::Result; // pub fn find_matches(reader: impl std::io::BufRead, pattern: &str, mut writer: impl std::io::Write) -> Result<()> { // for line in reader.lines() { // if let Ok(l) = line { // if l.contains(pattern) { // writeln!(writer, "{}", l)?; // } // } // } // Ok(()) // } // #[test] // fn find_a_match() { // let mut result = vec![]; // find_matches("In principio erat Verbum,\net Verbum erat apud Deum,\net Deus erat Verbum.".as_bytes(), "Deum", &mut result); // assert_eq!(result, b"et Verbum erat apud Deum,\n"); // }
#[cfg(test)] mod tests { use super::*; #[test] fn example() { assert_eq!("-6,-3-1,3-5,7-11,14,15,17-20", solution::range_extraction(&[-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20])); assert_eq!("-3--1,2,10,15,16,18-20", solution::range_extraction(&[-3,-2,-1,2,10,15,16,18,19,20])); } } mod solution { pub fn range_extraction(a: &[i32]) -> String { // Your solution here let mut a = a.to_owned(); a.sort(); let mut range_result : Vec<Vec<i32>> = Vec::new(); let mut old = 0; let mut temp:Vec<i32> = Vec::new(); // can use iter().enumerate() here. for index in 0..a.len() { if index != 0 { if a[index] == old + 1 { temp.push(a[index]); }else{ range_result.push(temp.to_owned()); temp.clear(); temp.push(a[index]); } old = a[index]; }else{ temp.push(a[index]); old = a[index]; } } if temp.len() != 0 { range_result.push(temp.to_owned()); } range_result.iter().map(|v| { if v.len() <= 2 { v.iter().map(|i| { i.to_string() }).collect::<Vec<String>>().join(",") }else{ format!("{}-{}",v[0],v[v.len()-1]) } }).collect::<Vec<String>>().join(",") } ////////// Other Examples // Remember to use unwrap when Option<T> // use itertools::Itertools; // // https://stackoverflow.com/a/50392400 // fn consecutive_slices(data: &[i32]) -> Vec<Vec<i32>> { // (&(0..data.len()).group_by(|&i| (data[i] as usize).wrapping_sub(i))) // .into_iter() // .map(|(_, group)| group.map(|i| data[i]).collect()) // .collect() // } // fn vec_to_string(vec: &Vec<i32>) -> String { // match &vec[..] { // &[] => "".to_string(), // &[a] => a.to_string(), // &[a, b] => format!("{},{}", a, b), // _ => format!("{}-{}", vec[0], vec.iter().last().unwrap()) // } // } // pub fn range_extraction(a: &[i32]) -> String { // consecutive_slices(a).iter().map(vec_to_string).collect::<Vec<_>>().join(",") // } ////////// Other Example [Best Practice] // pub fn range_extraction(a: &[i32]) -> String { // let mut ans = vec![]; // let mut start = a[0]; // let mut current = a[0]; // // use skip to skip items // // and skip more if-else branch, there is [no need to memo every value]. // // we only need the edge value. // for i in a.iter().skip(1) { // if *i != current + 1 { // ans.push((start, current)); // start = *i; // } // current = *i; // } // ans.push((start, current)); // ans.iter() // .map(|(start, end)| { // if end == start { // end.to_string() // } else if *end == start + 1 { // format!("{},{}", start, end) // } else { // format!("{}-{}", start, end) // } // }) // .collect::<Vec<_>>() // .join(",") // } }
use oxygengine::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone)] pub enum LevelError { /// (provided, expected) CellsStringSizeDoesNotMatchSize(usize, usize), UnsupportedObjectCharacter(char), UnsupportedTileCharacter(char), } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct LevelAsset { pub cols: usize, pub rows: usize, pub cells: String, } impl LevelAsset { pub fn build_data(&self) -> Result<LevelData, LevelError> { let cells = self .cells .chars() .filter(|c| !c.is_whitespace()) .collect::<Vec<_>>(); let provided = cells.len(); let expected = self.cols * self.rows * 2; if provided != expected { return Err(LevelError::CellsStringSizeDoesNotMatchSize( provided, expected, )); } Ok(LevelData { cols: self.cols, rows: self.rows, cells: cells .chunks(2) .map(|c| { let object = match c[0] { '.' => LevelObject::None, '*' => LevelObject::Star, '$' => LevelObject::Shield, '@' => LevelObject::PlayerStart, c => return Err(LevelError::UnsupportedObjectCharacter(c)), }; let tile = match c[1] { 'o' => LevelTile::Ocean, 'g' => LevelTile::Grass, 'p' => LevelTile::Pond, 'l' => LevelTile::Lava, c => return Err(LevelError::UnsupportedTileCharacter(c)), }; Ok(LevelCell { tile, object }) }) .collect::<Result<_, _>>()?, }) } } #[derive(Debug, Default, Clone)] pub struct LevelData { pub cols: usize, pub rows: usize, pub cells: Vec<LevelCell>, } impl LevelData { pub fn build_render_commands(&self, cell_size: Scalar) -> Vec<Command<'static>> { self.cells .iter() .enumerate() .map(|(index, cell)| { let col = index % self.cols; let row = index / self.cols; Command::Draw(cell.tile.build_image(col, row, cell_size).into()) }) .collect::<Vec<_>>() } } #[derive(Debug, Clone)] pub struct LevelCell { pub tile: LevelTile, pub object: LevelObject, } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum LevelTile { Ocean, Grass, Pond, Lava, } impl LevelTile { pub fn build_image(self, col: usize, row: usize, size: Scalar) -> Image<'static> { let image = match self { Self::Ocean => "images/tile-ocean.svg", Self::Grass => "images/tile-grass.svg", Self::Pond => "images/tile-pond.svg", Self::Lava => "images/tile-lava.svg", }; Image::new(image).destination(Some( [size * col as Scalar, size * row as Scalar, size, size].into(), )) } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum LevelObject { None, Star, Shield, PlayerStart, }
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #![deny(warnings)] #![deny(unused)] #![deny(unsafe_code)] use std::env; use std::fs; use std::path::Path; use rom_ext_config::parser::ParsedConfig; use rom_ext_image::image::RawImage; use mundane::hash::Sha256; use mundane::public::rsa::RsaPkcs1v15; use mundane::public::rsa::RsaPrivKey; use mundane::public::rsa::RsaSignature; use mundane::public::rsa::B3072; use mundane::public::DerPrivateKey; use mundane::public::Signature; fn main() { let arg: String = env::args().nth(1).expect("Config path is missing"); let config_path = Path::new(&arg); // Parse the config. let config = ParsedConfig::new(&config_path); // Read raw binary. let mut image = RawImage::new(&config.input_files.image_path); // Get the private key used for signature generation. It is also used to // extract key public exponent and modulus. let private_key_der = fs::read(&config.input_files.private_key_der_path).expect("Failed to read the image!"); // Update "signed" manifest fields. image.update_static_fields(&config); // Convert ASN.1 DER private key into Mundane RsaPrivKey. let private_key = RsaPrivKey::parse_from_der(&private_key_der).expect("Failed to parse private key!"); let mut exponent = private_key.public_exponent_be(); // Encode public key components in little-endian byte order. exponent.reverse(); image.update_exponent_field(&exponent); let mut modulus = private_key.public_modulus_be(); // Encode public key components in little-endian byte order. modulus.reverse(); image.update_modulus_field(&modulus); // Produce the signature from concatenated system_state_value, // device_usage_value and the portion of the "signed" portion of the image. let image_sign_data = image.data_to_sign(); let device_usage_value = &device_usage_value(&config.input_files.usage_constraints_path); let system_state_value = &system_state_value(&config.input_files.system_state_value_path); let mut message_to_sign = Vec::<u8>::new(); message_to_sign.extend_from_slice(system_state_value); message_to_sign.extend_from_slice(device_usage_value); message_to_sign.extend_from_slice(image_sign_data); let signature = RsaSignature::<B3072, RsaPkcs1v15, Sha256>::sign(&private_key, &message_to_sign) .expect("Failed to sign!"); image.update_signature_field(&signature.bytes()); // The whole image has been updated and signed, write the result to disk. image.write_file(); } /// Generates the device usage value. /// /// This value is extrapolated from the ROM_EXT manifest usage_constraints /// field, and does not reside in the ROM_EXT manifest directly. pub fn device_usage_value(path: &Path) -> Vec<u8> { let _usage_constraints = fs::read(path).expect("Failed to read usage constraints!"); // TODO: generate the device_usage_value from usage_constraints. // meanwhile use a "dummy" hard-coded vector. vec![0xA5; 1024] } /// Obtains the system state value from the binary on disk. pub fn system_state_value(path: &Path) -> Vec<u8> { fs::read(path).expect("Failed to read system state value!") }
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use uvll; use raw::{Loop, Handle, Allocated, Raw}; use UvResult; pub struct Idle { handle: *mut uvll::uv_idle_t, } impl Idle { /// Create a new uv_idle_t handle. /// /// This function is unsafe as a successful return value is not /// automatically deallocated. pub unsafe fn new(uv_loop: &Loop) -> UvResult<Idle> { let raw = Raw::new(); try!(call!(uvll::uv_idle_init(uv_loop.raw(), raw.get()))); Ok(Idle { handle: raw.unwrap() }) } pub fn start(&mut self, f: uvll::uv_idle_cb) -> UvResult<()> { unsafe { try!(call!(uvll::uv_idle_start(self.handle, f))); } Ok(()) } pub fn stop(&mut self) -> UvResult<()> { unsafe { try!(call!(uvll::uv_idle_stop(self.handle))); } Ok(()) } } impl Allocated for uvll::uv_idle_t { fn size(_self: Option<uvll::uv_idle_t>) -> uint { unsafe { uvll::uv_handle_size(uvll::UV_IDLE) as uint } } } impl Handle<uvll::uv_idle_t> for Idle { fn raw(&self) -> *mut uvll::uv_idle_t { self.handle } fn from_raw(t: *mut uvll::uv_idle_t) -> Idle { Idle { handle: t } } }
extern crate nom; #[macro_use] extern crate enum_display_derive; pub mod ir; pub mod parser;
use expectest::prelude::be_equal_to; use sql::data_manager::DataManager; #[test] fn saves_to_one_row_table() { let data_manger = DataManager::default(); drop(data_manger.save_to("table_name", vec!["1".to_owned()])); expect!(data_manger.get_range_till_end("table_name", 0)) .to(be_equal_to(vec![vec!["1"]])); } #[test] fn retrievs_data_from_table() { let data_manager = DataManager::default(); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned()])); drop(data_manager.save_to("table_name", vec!["3".to_owned(), "4".to_owned()])); expect!(data_manager.get_row_from("table_name", 0)) .to(be_equal_to(vec!["1", "2"])); expect!(data_manager.get_row_from("table_name", 1)) .to(be_equal_to(vec!["3", "4"])); } #[test] fn retrievs_range_of_rows_from_table() { let data_manager = DataManager::default(); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned(), "3".to_owned()])); drop(data_manager.save_to("table_name", vec!["4".to_owned(), "5".to_owned(), "6".to_owned()])); drop(data_manager.save_to("table_name", vec!["7".to_owned(), "8".to_owned(), "9".to_owned()])); drop(data_manager.save_to("table_name", vec!["10".to_owned(), "11".to_owned(), "12".to_owned()])); drop(data_manager.save_to("table_name", vec!["13".to_owned(), "14".to_owned(), "15".to_owned()])); expect!(data_manager.get_range("table_name", 1, 3)) .to(be_equal_to( vec![ vec!["4", "5", "6"], vec!["7", "8", "9"], vec!["10", "11", "12"] ] )); expect!(data_manager.get_range("table_name", 2, 2)) .to(be_equal_to( vec![ vec!["7", "8", "9"], vec!["10", "11", "12"] ] )); } #[test] fn retrievs_range_from_index_till_end() { let data_manager = DataManager::default(); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned(), "3".to_owned()])); drop(data_manager.save_to("table_name", vec!["4".to_owned(), "5".to_owned(), "6".to_owned()])); drop(data_manager.save_to("table_name", vec!["7".to_owned(), "8".to_owned(), "9".to_owned()])); drop(data_manager.save_to("table_name", vec!["10".to_owned(), "11".to_owned(), "12".to_owned()])); drop(data_manager.save_to("table_name", vec!["13".to_owned(), "14".to_owned(), "15".to_owned()])); expect!(data_manager.get_range_till_end("table_name", 2)) .to(be_equal_to( vec![ vec!["7", "8", "9"], vec!["10", "11", "12"], vec!["13", "14", "15"] ] )); } #[test] fn retrievs_by_not_equal_predicate_on_column() { let data_manager = DataManager::default(); drop(data_manager.save_to("table_name", vec!["10".to_owned(), "11".to_owned(), "12".to_owned()])); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned(), "3".to_owned()])); drop(data_manager.save_to("table_name", vec!["7".to_owned(), "8".to_owned(), "9".to_owned()])); expect!(data_manager.get_not_equal("table_name", 0, &("1".to_owned()))) .to(be_equal_to( vec![ vec!["10", "11", "12"], vec!["7", "8", "9"] ] )); } #[test] fn retrives_by_column_index() { let data_manager = DataManager::default(); drop(data_manager.save_to("table_name", vec!["10".to_owned(), "11".to_owned(), "12".to_owned()])); drop(data_manager.save_to("table_name", vec!["1".to_owned(), "2".to_owned(), "3".to_owned()])); drop(data_manager.save_to("table_name", vec!["7".to_owned(), "8".to_owned(), "9".to_owned()])); expect!(data_manager.get_range_till_end_for_column("table_name", 0, 1)) .to(be_equal_to( vec![ vec!["10"], vec!["1"], vec!["7"] ] )); }
/// An enum to represent all characters in the TaiTham block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum TaiTham { /// \u{1a20}: 'ᨠ' LetterHighKa, /// \u{1a21}: 'ᨡ' LetterHighKha, /// \u{1a22}: 'ᨢ' LetterHighKxa, /// \u{1a23}: 'ᨣ' LetterLowKa, /// \u{1a24}: 'ᨤ' LetterLowKxa, /// \u{1a25}: 'ᨥ' LetterLowKha, /// \u{1a26}: 'ᨦ' LetterNga, /// \u{1a27}: 'ᨧ' LetterHighCa, /// \u{1a28}: 'ᨨ' LetterHighCha, /// \u{1a29}: 'ᨩ' LetterLowCa, /// \u{1a2a}: 'ᨪ' LetterLowSa, /// \u{1a2b}: 'ᨫ' LetterLowCha, /// \u{1a2c}: 'ᨬ' LetterNya, /// \u{1a2d}: 'ᨭ' LetterRata, /// \u{1a2e}: 'ᨮ' LetterHighRatha, /// \u{1a2f}: 'ᨯ' LetterDa, /// \u{1a30}: 'ᨰ' LetterLowRatha, /// \u{1a31}: 'ᨱ' LetterRana, /// \u{1a32}: 'ᨲ' LetterHighTa, /// \u{1a33}: 'ᨳ' LetterHighTha, /// \u{1a34}: 'ᨴ' LetterLowTa, /// \u{1a35}: 'ᨵ' LetterLowTha, /// \u{1a36}: 'ᨶ' LetterNa, /// \u{1a37}: 'ᨷ' LetterBa, /// \u{1a38}: 'ᨸ' LetterHighPa, /// \u{1a39}: 'ᨹ' LetterHighPha, /// \u{1a3a}: 'ᨺ' LetterHighFa, /// \u{1a3b}: 'ᨻ' LetterLowPa, /// \u{1a3c}: 'ᨼ' LetterLowFa, /// \u{1a3d}: 'ᨽ' LetterLowPha, /// \u{1a3e}: 'ᨾ' LetterMa, /// \u{1a3f}: 'ᨿ' LetterLowYa, /// \u{1a40}: 'ᩀ' LetterHighYa, /// \u{1a41}: 'ᩁ' LetterRa, /// \u{1a42}: 'ᩂ' LetterRue, /// \u{1a43}: 'ᩃ' LetterLa, /// \u{1a44}: 'ᩄ' LetterLue, /// \u{1a45}: 'ᩅ' LetterWa, /// \u{1a46}: 'ᩆ' LetterHighSha, /// \u{1a47}: 'ᩇ' LetterHighSsa, /// \u{1a48}: 'ᩈ' LetterHighSa, /// \u{1a49}: 'ᩉ' LetterHighHa, /// \u{1a4a}: 'ᩊ' LetterLla, /// \u{1a4b}: 'ᩋ' LetterA, /// \u{1a4c}: 'ᩌ' LetterLowHa, /// \u{1a4d}: 'ᩍ' LetterI, /// \u{1a4e}: 'ᩎ' LetterIi, /// \u{1a4f}: 'ᩏ' LetterU, /// \u{1a50}: 'ᩐ' LetterUu, /// \u{1a51}: 'ᩑ' LetterEe, /// \u{1a52}: 'ᩒ' LetterOo, /// \u{1a53}: 'ᩓ' LetterLae, /// \u{1a54}: 'ᩔ' LetterGreatSa, /// \u{1a55}: 'ᩕ' ConsonantSignMedialRa, /// \u{1a56}: 'ᩖ' ConsonantSignMedialLa, /// \u{1a57}: 'ᩗ' ConsonantSignLaTangLai, /// \u{1a58}: 'ᩘ' SignMaiKangLai, /// \u{1a59}: 'ᩙ' ConsonantSignFinalNga, /// \u{1a5a}: 'ᩚ' ConsonantSignLowPa, /// \u{1a5b}: 'ᩛ' ConsonantSignHighRathaOrLowPa, /// \u{1a5c}: 'ᩜ' ConsonantSignMa, /// \u{1a5d}: 'ᩝ' ConsonantSignBa, /// \u{1a5e}: 'ᩞ' ConsonantSignSa, /// \u{1a60}: '᩠' SignSakot, /// \u{1a61}: 'ᩡ' VowelSignA, /// \u{1a62}: 'ᩢ' VowelSignMaiSat, /// \u{1a63}: 'ᩣ' VowelSignAa, /// \u{1a64}: 'ᩤ' VowelSignTallAa, /// \u{1a65}: 'ᩥ' VowelSignI, /// \u{1a66}: 'ᩦ' VowelSignIi, /// \u{1a67}: 'ᩧ' VowelSignUe, /// \u{1a68}: 'ᩨ' VowelSignUue, /// \u{1a69}: 'ᩩ' VowelSignU, /// \u{1a6a}: 'ᩪ' VowelSignUu, /// \u{1a6b}: 'ᩫ' VowelSignO, /// \u{1a6c}: 'ᩬ' VowelSignOaBelow, /// \u{1a6d}: 'ᩭ' VowelSignOy, /// \u{1a6e}: 'ᩮ' VowelSignE, /// \u{1a6f}: 'ᩯ' VowelSignAe, /// \u{1a70}: 'ᩰ' VowelSignOo, /// \u{1a71}: 'ᩱ' VowelSignAi, /// \u{1a72}: 'ᩲ' VowelSignThamAi, /// \u{1a73}: 'ᩳ' VowelSignOaAbove, /// \u{1a74}: 'ᩴ' SignMaiKang, /// \u{1a75}: '᩵' SignToneDash1, /// \u{1a76}: '᩶' SignToneDash2, /// \u{1a77}: '᩷' SignKhuenToneDash3, /// \u{1a78}: '᩸' SignKhuenToneDash4, /// \u{1a79}: '᩹' SignKhuenToneDash5, /// \u{1a7a}: '᩺' SignRaHaam, /// \u{1a7b}: '᩻' SignMaiSam, /// \u{1a7c}: '᩼' SignKhuenDashLueKaran, /// \u{1a7f}: '᩿' CombiningCryptogrammicDot, /// \u{1a80}: '᪀' HoraDigitZero, /// \u{1a81}: '᪁' HoraDigitOne, /// \u{1a82}: '᪂' HoraDigitTwo, /// \u{1a83}: '᪃' HoraDigitThree, /// \u{1a84}: '᪄' HoraDigitFour, /// \u{1a85}: '᪅' HoraDigitFive, /// \u{1a86}: '᪆' HoraDigitSix, /// \u{1a87}: '᪇' HoraDigitSeven, /// \u{1a88}: '᪈' HoraDigitEight, /// \u{1a89}: '᪉' HoraDigitNine, /// \u{1a90}: '᪐' ThamDigitZero, /// \u{1a91}: '᪑' ThamDigitOne, /// \u{1a92}: '᪒' ThamDigitTwo, /// \u{1a93}: '᪓' ThamDigitThree, /// \u{1a94}: '᪔' ThamDigitFour, /// \u{1a95}: '᪕' ThamDigitFive, /// \u{1a96}: '᪖' ThamDigitSix, /// \u{1a97}: '᪗' ThamDigitSeven, /// \u{1a98}: '᪘' ThamDigitEight, /// \u{1a99}: '᪙' ThamDigitNine, /// \u{1aa0}: '᪠' SignWiang, /// \u{1aa1}: '᪡' SignWiangwaak, /// \u{1aa2}: '᪢' SignSawan, /// \u{1aa3}: '᪣' SignKeow, /// \u{1aa4}: '᪤' SignHoy, /// \u{1aa5}: '᪥' SignDokmai, /// \u{1aa6}: '᪦' SignReversedRotatedRana, /// \u{1aa7}: 'ᪧ' SignMaiYamok, /// \u{1aa8}: '᪨' SignKaan, /// \u{1aa9}: '᪩' SignKaankuu, /// \u{1aaa}: '᪪' SignSatkaan, /// \u{1aab}: '᪫' SignSatkaankuu, /// \u{1aac}: '᪬' SignHang, /// \u{1aad}: '᪭' SignCaang, } impl Into<char> for TaiTham { fn into(self) -> char { match self { TaiTham::LetterHighKa => 'ᨠ', TaiTham::LetterHighKha => 'ᨡ', TaiTham::LetterHighKxa => 'ᨢ', TaiTham::LetterLowKa => 'ᨣ', TaiTham::LetterLowKxa => 'ᨤ', TaiTham::LetterLowKha => 'ᨥ', TaiTham::LetterNga => 'ᨦ', TaiTham::LetterHighCa => 'ᨧ', TaiTham::LetterHighCha => 'ᨨ', TaiTham::LetterLowCa => 'ᨩ', TaiTham::LetterLowSa => 'ᨪ', TaiTham::LetterLowCha => 'ᨫ', TaiTham::LetterNya => 'ᨬ', TaiTham::LetterRata => 'ᨭ', TaiTham::LetterHighRatha => 'ᨮ', TaiTham::LetterDa => 'ᨯ', TaiTham::LetterLowRatha => 'ᨰ', TaiTham::LetterRana => 'ᨱ', TaiTham::LetterHighTa => 'ᨲ', TaiTham::LetterHighTha => 'ᨳ', TaiTham::LetterLowTa => 'ᨴ', TaiTham::LetterLowTha => 'ᨵ', TaiTham::LetterNa => 'ᨶ', TaiTham::LetterBa => 'ᨷ', TaiTham::LetterHighPa => 'ᨸ', TaiTham::LetterHighPha => 'ᨹ', TaiTham::LetterHighFa => 'ᨺ', TaiTham::LetterLowPa => 'ᨻ', TaiTham::LetterLowFa => 'ᨼ', TaiTham::LetterLowPha => 'ᨽ', TaiTham::LetterMa => 'ᨾ', TaiTham::LetterLowYa => 'ᨿ', TaiTham::LetterHighYa => 'ᩀ', TaiTham::LetterRa => 'ᩁ', TaiTham::LetterRue => 'ᩂ', TaiTham::LetterLa => 'ᩃ', TaiTham::LetterLue => 'ᩄ', TaiTham::LetterWa => 'ᩅ', TaiTham::LetterHighSha => 'ᩆ', TaiTham::LetterHighSsa => 'ᩇ', TaiTham::LetterHighSa => 'ᩈ', TaiTham::LetterHighHa => 'ᩉ', TaiTham::LetterLla => 'ᩊ', TaiTham::LetterA => 'ᩋ', TaiTham::LetterLowHa => 'ᩌ', TaiTham::LetterI => 'ᩍ', TaiTham::LetterIi => 'ᩎ', TaiTham::LetterU => 'ᩏ', TaiTham::LetterUu => 'ᩐ', TaiTham::LetterEe => 'ᩑ', TaiTham::LetterOo => 'ᩒ', TaiTham::LetterLae => 'ᩓ', TaiTham::LetterGreatSa => 'ᩔ', TaiTham::ConsonantSignMedialRa => 'ᩕ', TaiTham::ConsonantSignMedialLa => 'ᩖ', TaiTham::ConsonantSignLaTangLai => 'ᩗ', TaiTham::SignMaiKangLai => 'ᩘ', TaiTham::ConsonantSignFinalNga => 'ᩙ', TaiTham::ConsonantSignLowPa => 'ᩚ', TaiTham::ConsonantSignHighRathaOrLowPa => 'ᩛ', TaiTham::ConsonantSignMa => 'ᩜ', TaiTham::ConsonantSignBa => 'ᩝ', TaiTham::ConsonantSignSa => 'ᩞ', TaiTham::SignSakot => '᩠', TaiTham::VowelSignA => 'ᩡ', TaiTham::VowelSignMaiSat => 'ᩢ', TaiTham::VowelSignAa => 'ᩣ', TaiTham::VowelSignTallAa => 'ᩤ', TaiTham::VowelSignI => 'ᩥ', TaiTham::VowelSignIi => 'ᩦ', TaiTham::VowelSignUe => 'ᩧ', TaiTham::VowelSignUue => 'ᩨ', TaiTham::VowelSignU => 'ᩩ', TaiTham::VowelSignUu => 'ᩪ', TaiTham::VowelSignO => 'ᩫ', TaiTham::VowelSignOaBelow => 'ᩬ', TaiTham::VowelSignOy => 'ᩭ', TaiTham::VowelSignE => 'ᩮ', TaiTham::VowelSignAe => 'ᩯ', TaiTham::VowelSignOo => 'ᩰ', TaiTham::VowelSignAi => 'ᩱ', TaiTham::VowelSignThamAi => 'ᩲ', TaiTham::VowelSignOaAbove => 'ᩳ', TaiTham::SignMaiKang => 'ᩴ', TaiTham::SignToneDash1 => '᩵', TaiTham::SignToneDash2 => '᩶', TaiTham::SignKhuenToneDash3 => '᩷', TaiTham::SignKhuenToneDash4 => '᩸', TaiTham::SignKhuenToneDash5 => '᩹', TaiTham::SignRaHaam => '᩺', TaiTham::SignMaiSam => '᩻', TaiTham::SignKhuenDashLueKaran => '᩼', TaiTham::CombiningCryptogrammicDot => '᩿', TaiTham::HoraDigitZero => '᪀', TaiTham::HoraDigitOne => '᪁', TaiTham::HoraDigitTwo => '᪂', TaiTham::HoraDigitThree => '᪃', TaiTham::HoraDigitFour => '᪄', TaiTham::HoraDigitFive => '᪅', TaiTham::HoraDigitSix => '᪆', TaiTham::HoraDigitSeven => '᪇', TaiTham::HoraDigitEight => '᪈', TaiTham::HoraDigitNine => '᪉', TaiTham::ThamDigitZero => '᪐', TaiTham::ThamDigitOne => '᪑', TaiTham::ThamDigitTwo => '᪒', TaiTham::ThamDigitThree => '᪓', TaiTham::ThamDigitFour => '᪔', TaiTham::ThamDigitFive => '᪕', TaiTham::ThamDigitSix => '᪖', TaiTham::ThamDigitSeven => '᪗', TaiTham::ThamDigitEight => '᪘', TaiTham::ThamDigitNine => '᪙', TaiTham::SignWiang => '᪠', TaiTham::SignWiangwaak => '᪡', TaiTham::SignSawan => '᪢', TaiTham::SignKeow => '᪣', TaiTham::SignHoy => '᪤', TaiTham::SignDokmai => '᪥', TaiTham::SignReversedRotatedRana => '᪦', TaiTham::SignMaiYamok => 'ᪧ', TaiTham::SignKaan => '᪨', TaiTham::SignKaankuu => '᪩', TaiTham::SignSatkaan => '᪪', TaiTham::SignSatkaankuu => '᪫', TaiTham::SignHang => '᪬', TaiTham::SignCaang => '᪭', } } } impl std::convert::TryFrom<char> for TaiTham { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { 'ᨠ' => Ok(TaiTham::LetterHighKa), 'ᨡ' => Ok(TaiTham::LetterHighKha), 'ᨢ' => Ok(TaiTham::LetterHighKxa), 'ᨣ' => Ok(TaiTham::LetterLowKa), 'ᨤ' => Ok(TaiTham::LetterLowKxa), 'ᨥ' => Ok(TaiTham::LetterLowKha), 'ᨦ' => Ok(TaiTham::LetterNga), 'ᨧ' => Ok(TaiTham::LetterHighCa), 'ᨨ' => Ok(TaiTham::LetterHighCha), 'ᨩ' => Ok(TaiTham::LetterLowCa), 'ᨪ' => Ok(TaiTham::LetterLowSa), 'ᨫ' => Ok(TaiTham::LetterLowCha), 'ᨬ' => Ok(TaiTham::LetterNya), 'ᨭ' => Ok(TaiTham::LetterRata), 'ᨮ' => Ok(TaiTham::LetterHighRatha), 'ᨯ' => Ok(TaiTham::LetterDa), 'ᨰ' => Ok(TaiTham::LetterLowRatha), 'ᨱ' => Ok(TaiTham::LetterRana), 'ᨲ' => Ok(TaiTham::LetterHighTa), 'ᨳ' => Ok(TaiTham::LetterHighTha), 'ᨴ' => Ok(TaiTham::LetterLowTa), 'ᨵ' => Ok(TaiTham::LetterLowTha), 'ᨶ' => Ok(TaiTham::LetterNa), 'ᨷ' => Ok(TaiTham::LetterBa), 'ᨸ' => Ok(TaiTham::LetterHighPa), 'ᨹ' => Ok(TaiTham::LetterHighPha), 'ᨺ' => Ok(TaiTham::LetterHighFa), 'ᨻ' => Ok(TaiTham::LetterLowPa), 'ᨼ' => Ok(TaiTham::LetterLowFa), 'ᨽ' => Ok(TaiTham::LetterLowPha), 'ᨾ' => Ok(TaiTham::LetterMa), 'ᨿ' => Ok(TaiTham::LetterLowYa), 'ᩀ' => Ok(TaiTham::LetterHighYa), 'ᩁ' => Ok(TaiTham::LetterRa), 'ᩂ' => Ok(TaiTham::LetterRue), 'ᩃ' => Ok(TaiTham::LetterLa), 'ᩄ' => Ok(TaiTham::LetterLue), 'ᩅ' => Ok(TaiTham::LetterWa), 'ᩆ' => Ok(TaiTham::LetterHighSha), 'ᩇ' => Ok(TaiTham::LetterHighSsa), 'ᩈ' => Ok(TaiTham::LetterHighSa), 'ᩉ' => Ok(TaiTham::LetterHighHa), 'ᩊ' => Ok(TaiTham::LetterLla), 'ᩋ' => Ok(TaiTham::LetterA), 'ᩌ' => Ok(TaiTham::LetterLowHa), 'ᩍ' => Ok(TaiTham::LetterI), 'ᩎ' => Ok(TaiTham::LetterIi), 'ᩏ' => Ok(TaiTham::LetterU), 'ᩐ' => Ok(TaiTham::LetterUu), 'ᩑ' => Ok(TaiTham::LetterEe), 'ᩒ' => Ok(TaiTham::LetterOo), 'ᩓ' => Ok(TaiTham::LetterLae), 'ᩔ' => Ok(TaiTham::LetterGreatSa), 'ᩕ' => Ok(TaiTham::ConsonantSignMedialRa), 'ᩖ' => Ok(TaiTham::ConsonantSignMedialLa), 'ᩗ' => Ok(TaiTham::ConsonantSignLaTangLai), 'ᩘ' => Ok(TaiTham::SignMaiKangLai), 'ᩙ' => Ok(TaiTham::ConsonantSignFinalNga), 'ᩚ' => Ok(TaiTham::ConsonantSignLowPa), 'ᩛ' => Ok(TaiTham::ConsonantSignHighRathaOrLowPa), 'ᩜ' => Ok(TaiTham::ConsonantSignMa), 'ᩝ' => Ok(TaiTham::ConsonantSignBa), 'ᩞ' => Ok(TaiTham::ConsonantSignSa), '᩠' => Ok(TaiTham::SignSakot), 'ᩡ' => Ok(TaiTham::VowelSignA), 'ᩢ' => Ok(TaiTham::VowelSignMaiSat), 'ᩣ' => Ok(TaiTham::VowelSignAa), 'ᩤ' => Ok(TaiTham::VowelSignTallAa), 'ᩥ' => Ok(TaiTham::VowelSignI), 'ᩦ' => Ok(TaiTham::VowelSignIi), 'ᩧ' => Ok(TaiTham::VowelSignUe), 'ᩨ' => Ok(TaiTham::VowelSignUue), 'ᩩ' => Ok(TaiTham::VowelSignU), 'ᩪ' => Ok(TaiTham::VowelSignUu), 'ᩫ' => Ok(TaiTham::VowelSignO), 'ᩬ' => Ok(TaiTham::VowelSignOaBelow), 'ᩭ' => Ok(TaiTham::VowelSignOy), 'ᩮ' => Ok(TaiTham::VowelSignE), 'ᩯ' => Ok(TaiTham::VowelSignAe), 'ᩰ' => Ok(TaiTham::VowelSignOo), 'ᩱ' => Ok(TaiTham::VowelSignAi), 'ᩲ' => Ok(TaiTham::VowelSignThamAi), 'ᩳ' => Ok(TaiTham::VowelSignOaAbove), 'ᩴ' => Ok(TaiTham::SignMaiKang), '᩵' => Ok(TaiTham::SignToneDash1), '᩶' => Ok(TaiTham::SignToneDash2), '᩷' => Ok(TaiTham::SignKhuenToneDash3), '᩸' => Ok(TaiTham::SignKhuenToneDash4), '᩹' => Ok(TaiTham::SignKhuenToneDash5), '᩺' => Ok(TaiTham::SignRaHaam), '᩻' => Ok(TaiTham::SignMaiSam), '᩼' => Ok(TaiTham::SignKhuenDashLueKaran), '᩿' => Ok(TaiTham::CombiningCryptogrammicDot), '᪀' => Ok(TaiTham::HoraDigitZero), '᪁' => Ok(TaiTham::HoraDigitOne), '᪂' => Ok(TaiTham::HoraDigitTwo), '᪃' => Ok(TaiTham::HoraDigitThree), '᪄' => Ok(TaiTham::HoraDigitFour), '᪅' => Ok(TaiTham::HoraDigitFive), '᪆' => Ok(TaiTham::HoraDigitSix), '᪇' => Ok(TaiTham::HoraDigitSeven), '᪈' => Ok(TaiTham::HoraDigitEight), '᪉' => Ok(TaiTham::HoraDigitNine), '᪐' => Ok(TaiTham::ThamDigitZero), '᪑' => Ok(TaiTham::ThamDigitOne), '᪒' => Ok(TaiTham::ThamDigitTwo), '᪓' => Ok(TaiTham::ThamDigitThree), '᪔' => Ok(TaiTham::ThamDigitFour), '᪕' => Ok(TaiTham::ThamDigitFive), '᪖' => Ok(TaiTham::ThamDigitSix), '᪗' => Ok(TaiTham::ThamDigitSeven), '᪘' => Ok(TaiTham::ThamDigitEight), '᪙' => Ok(TaiTham::ThamDigitNine), '᪠' => Ok(TaiTham::SignWiang), '᪡' => Ok(TaiTham::SignWiangwaak), '᪢' => Ok(TaiTham::SignSawan), '᪣' => Ok(TaiTham::SignKeow), '᪤' => Ok(TaiTham::SignHoy), '᪥' => Ok(TaiTham::SignDokmai), '᪦' => Ok(TaiTham::SignReversedRotatedRana), 'ᪧ' => Ok(TaiTham::SignMaiYamok), '᪨' => Ok(TaiTham::SignKaan), '᪩' => Ok(TaiTham::SignKaankuu), '᪪' => Ok(TaiTham::SignSatkaan), '᪫' => Ok(TaiTham::SignSatkaankuu), '᪬' => Ok(TaiTham::SignHang), '᪭' => Ok(TaiTham::SignCaang), _ => Err(()), } } } impl Into<u32> for TaiTham { 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 TaiTham { 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 TaiTham { 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 TaiTham { /// The character with the lowest index in this unicode block pub fn new() -> Self { TaiTham::LetterHighKa } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("TaiTham{:#?}", self); string_morph::to_sentence_case(&s) } }
pub use num::rational::Ratio; use conv::{ValueFrom, ApproxFrom, ValueInto, ApproxInto}; use num::integer::Integer; /// A trait defining how an integer can be scaled by ratios of various types. /// `T` is the type of the ratio, `I` is the intermediate promotion type. /// E.g., to correctly scale i8 by Ratio<u32>, we would want both self and /// the scale ratio to be converted to i64, then down to i8 for the final /// result: /// ``` /// impl Scalable<u32, i64> for u8 {} /// ``` /// Standard warnings about integer overflow apply. /// pub trait Scalable<T, I>: Clone + Integer + ApproxFrom<I> where T: Clone + Integer, I: Clone + Integer + ValueFrom<T> + ValueFrom<Self>{ fn scale(&self, scale: Ratio<T>) -> Self { // Promote all values to intermediate type let n: I = scale.numer().clone().value_into().unwrap(); let d: I = scale.denom().clone().value_into().unwrap(); let x: I = self.clone().value_into().unwrap(); // Apply rational multiplication and convert back to integer (Ratio::from_integer(x) * Ratio::new(n, d)) .to_integer() .approx_into() .unwrap() } } impl Scalable<u32, u32> for u32 {} impl Scalable<i32, i32> for i32 {} // Scaling an i32 by Ratio<u32> involves first converting to i64. impl Scalable<u32, i64> for i32 {} impl Scalable<u32, u32> for u8 {} impl Scalable<u32, u32> for u16 {} impl Scalable<u32, i64> for i8 {} impl Scalable<u32, i64> for i16 {} // Note that there is no implementation of Scalable<i32, X> for u32; scaling // an unsigned integer by a signed ratio makes no sense since the desired // result type (the same as the source integer's type) can never be negative. #[test] fn scale_u32() { let r = Ratio::new(1, 2); assert_eq!(4u32.scale(r), 2); } #[test] fn scale_i32() { let r = Ratio::new(1, 2); assert_eq!(4i32.scale(r), 2); } #[test] fn scale_i32_by_u32_ratio() { let r = Ratio::new(1u32, 2u32); assert_eq!(-4.scale(r), -2); } #[test] fn scale_u8_by_u32_ratio() { let r = Ratio::new(1523u32, 1546u32); assert_eq!(232u8.scale(r), 228); } #[test] fn scale_u16_by_u32_ratio() { let r = Ratio::new(7251u32, 492124u32); assert_eq!(51221u16.scale(r), 754); } #[test] fn scale_i8_by_u32_ratio() { let r = Ratio::new(5u32, 25u32); assert_eq!(-100.scale(r), -20); } #[test] fn scale_i16_by_u32_ratio() { let r = Ratio::new(5u32, 20u32); assert_eq!(-12.scale(r), -3); }
extern crate nix; #[cfg(feature = "signalfd")] use nix::sys::signalfd::SignalFd; #[cfg(feature = "signalfd")] use nix::sys::signal; #[cfg(feature = "signalfd")] use nix::unistd; #[cfg(feature = "signalfd")] fn main() { print!("test test_signalfd ... "); let mut mask = signal::SigSet::empty(); mask.add(signal::SIGUSR1).unwrap(); mask.thread_block().unwrap(); let mut fd = SignalFd::new(&mask).unwrap(); let pid = unistd::getpid(); signal::kill(pid, signal::SIGUSR1).unwrap(); let res = fd.read_signal(); assert_eq!(res.unwrap().unwrap().ssi_signo as i32, signal::SIGUSR1); println!("ok"); } #[cfg(not(feature = "signalfd"))] fn main() {}
pub fn lsp(series: &str, num: usize) -> Result<u32, &str> { if num > series.len() { return Result::Err("Span longer than length of digit series") } if num == 0 { return Result::Ok(1); } if !series.chars().all(|ch| ch.is_digit(10)) { return Result::Err("Non-digit character provided") } let digits = series.chars() .map(|ch| ch.to_digit(10).unwrap()) .collect::<Vec<u32>>(); let products = digits.windows(num).map(|win| win.iter().product()); Result::Ok(products.max().unwrap()) }
use tendermint::abci; use tendermint::rpc::endpoint::abci_query::AbciQuery; use relayer_modules::Height; use crate::chain::Chain; use crate::error; pub mod client_consensus_state; /// The type of IBC response sent back for a given IBC `Query`. pub trait IbcResponse<Query>: Sized { /// The type of the raw response returned by the interface used to query the chain /// /// TODO: Uncomment once we abstract over the IBC client // type RawType; /// Build a response of this type from the initial `query` and the IBC `response`. /// /// TODO: Replace `AbciQuery` with `Self::RawType` fn from_abci_response(query: Query, response: AbciQuery) -> Result<Self, error::Error>; } /// Defines an IBC query pub trait IbcQuery: Sized { type Response: IbcResponse<Self>; fn path(&self) -> abci::Path; fn height(&self) -> Height; fn prove(&self) -> bool; fn data(&self) -> Vec<u8>; /// Build a `Response` from a raw `AbciQuery` response /// /// TODO: Replace `AbciQuery` with `<Self::Response as IbcResponse<Self>>::RawType` fn build_response(self, response: AbciQuery) -> Result<Self::Response, error::Error> { Self::Response::from_abci_response(self, response) } } /// Perform an IBC `query` on the given `chain`, and return the corresponding IBC response. pub async fn ibc_query<C, Q>(chain: &C, query: Q) -> Result<Q::Response, error::Error> where C: Chain, Q: IbcQuery, { let abci_response = chain .rpc_client() .abci_query( Some(query.path()), query.data(), Some(query.height().into()), query.prove(), ) .await .map_err(|e| error::Kind::Rpc.context(e))?; if !abci_response.code.is_ok() { todo!() // TODO: Fail with response log } // Data that is not from trusted node or subspace query needs verification if is_query_store_with_proof(&query.path()) { todo!() // TODO: Verify proof } query.build_response(abci_response) } /// Whether or not this path requires proof verification. /// /// is_query_store_with_proofxpects a format like /<queryType>/<storeName>/<subpath>, /// where queryType must be "store" and subpath must be "key" to require a proof. fn is_query_store_with_proof(_path: &abci::Path) -> bool { todo!() }
use preexplorer::prelude::*; fn main() -> anyhow::Result<()> { let domain = (1..15).map(|i| (i as f64).sqrt()); let image: Vec<Vec<f64>> = (1..15) .map(|i| { (0..10) .map(|j| { let j = j as f64; let i = i as f64; // Some computation i + j / i }) .collect() }) .collect(); pre::ProcessViolin::new(domain, image) .set_title("Numerical results through histograms") .set_xlabel("index") .set_ylabel("value") .plot("my_identifier")?; Ok(()) }
#[doc = "Register `FMC_SR` reader"] pub type R = crate::R<FMC_SR_SPEC>; #[doc = "Field `ISOST` reader - ISOST"] pub type ISOST_R = crate::FieldReader; #[doc = "Field `PEF` reader - PEF"] pub type PEF_R = crate::BitReader; #[doc = "Field `NWRF` reader - NWRF"] pub type NWRF_R = crate::BitReader; impl R { #[doc = "Bits 0:1 - ISOST"] #[inline(always)] pub fn isost(&self) -> ISOST_R { ISOST_R::new((self.bits & 3) as u8) } #[doc = "Bit 4 - PEF"] #[inline(always)] pub fn pef(&self) -> PEF_R { PEF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 6 - NWRF"] #[inline(always)] pub fn nwrf(&self) -> NWRF_R { NWRF_R::new(((self.bits >> 6) & 1) != 0) } } #[doc = "This register contains information about the AXI interface isolation status and the NAND write requests status. The FMC has to be disabled before modifying some registers. As requests might be pending, it is necessary to wait till the AXI interface is stable and the core of the block is totally isolated from its AXI interface before reconfiguring the registers. The PEF and PNWEF bits indicate the status of the pipe. If Hamming algorithm is used, the ECC is calculated while data are written to the memory. To read the correct ECC, the software must consequently wait untill no write request to the NAND controller are pending, by polling PEF and NWRF bits.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FMC_SR_SPEC; impl crate::RegisterSpec for FMC_SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fmc_sr::R`](R) reader structure"] impl crate::Readable for FMC_SR_SPEC {} #[doc = "`reset()` method sets FMC_SR to value 0x40"] impl crate::Resettable for FMC_SR_SPEC { const RESET_VALUE: Self::Ux = 0x40; }
#[macro_use] extern crate clap; use bellman::groth16; use bls12_381::{Bls12, Scalar}; use std::collections::{HashMap, HashSet}; pub mod async_serial; pub mod bls_extensions; pub mod circuit; pub mod crypto; pub mod endian; pub mod error; pub mod gfx; pub mod gui; pub mod net; pub mod rpc; pub mod serial; pub mod service; pub mod system; pub mod tx; pub mod vm; pub mod vm_serial; pub use crate::bls_extensions::BlsStringConversion; pub use crate::error::{Error, Result}; pub use crate::net::p2p::P2p; pub use crate::serial::{Decodable, Encodable}; pub use crate::vm::{ AllocType, ConstraintInstruction, CryptoOperation, VariableIndex, VariableRef, ZKVMCircuit, ZKVirtualMachine, }; pub type Bytes = Vec<u8>; pub struct ZKContract { pub name: String, pub vm: ZKVirtualMachine, params_map: HashMap<String, VariableIndex>, pub params: HashMap<VariableIndex, Scalar>, public_map: bimap::BiMap<String, VariableIndex>, } pub struct ZKProof { pub public: HashMap<String, Scalar>, pub proof: groth16::Proof<Bls12>, } impl ZKContract { // Just have a load() and save() // Load the contract, do the setup, save it... pub fn setup(&mut self, filename: &str) -> Result<()> { self.vm.setup()?; let buffer = std::fs::File::create(filename)?; self.vm.params.as_ref().unwrap().write(buffer)?; Ok(()) } pub fn load_setup(&mut self, filename: &str) -> Result<()> { let buffer = std::fs::File::open(filename)?; let setup = groth16::Parameters::<Bls12>::read(buffer, false)?; let vk = groth16::prepare_verifying_key(&setup.vk); self.vm.params = Some(setup); self.vm.verifying_key = Some(vk); Ok(()) } pub fn param_names(&self) -> Vec<String> { self.params_map.keys().cloned().collect() } pub fn set_param(&mut self, name: &str, value: Scalar) -> Result<()> { match self.params_map.get(name) { Some(index) => { self.params.insert(*index, value); Ok(()) } None => Err(Error::InvalidParamName), } } pub fn prove(&mut self) -> Result<ZKProof> { // Error if params not all set let user_params: HashSet<_> = self.params.keys().collect(); let req_params: HashSet<_> = self.params_map.values().collect(); if user_params != req_params { return Err(Error::MissingParams); } // execute let params = std::mem::replace(&mut self.params, HashMap::default()); self.vm.initialize(&params.into_iter().collect())?; // prove let proof = self.vm.prove(); let mut public = HashMap::new(); for (index, value) in self.vm.public() { match self.public_map.get_by_right(&index) { Some(name) => { public.insert(name.clone(), value); } None => return Err(Error::BadContract), } } // return proof and public values (Hashmap string -> scalars) Ok(ZKProof { public, proof }) } pub fn verify(&self, proof: &ZKProof) -> bool { let mut public = vec![]; for (name, value) in &proof.public { match self.public_map.get_by_left(name) { Some(index) => { public.push((index, value.clone())); } None => return false, } } public.sort_by(|a, b| a.0.partial_cmp(b.0).unwrap()); let (_, public): (Vec<VariableIndex>, Vec<Scalar>) = public.into_iter().unzip(); // Takes proof and public values self.vm.verify(&proof.proof, &public) } }
use std::ops::{Deref, DerefMut}; use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; // Lock Shenanigans pub struct RwLockOption<T> { lock: RwLock<Option<T>> } impl<T> RwLockOption<T> { pub fn new() -> Self { RwLockOption{lock: RwLock::new(None)} } pub fn read<'a>(&'a self) -> InnerRwReadLock<'a, T> { let guard = self.lock.read().unwrap(); InnerRwReadLock{guard} } pub fn write(&self, val: T) { let mut opt = self.lock.write().unwrap(); *opt = Some(val); } pub fn get_mut<'a>(&'a self) -> InnerRwWriteLock<'a, T> { let guard = self.lock.write().unwrap(); InnerRwWriteLock{guard} } } pub struct InnerRwReadLock<'a, T> { guard: RwLockReadGuard<'a, Option<T>> } pub struct InnerRwWriteLock<'a, T> { guard: RwLockWriteGuard<'a, Option<T>> } impl<'a, T> Deref for InnerRwReadLock<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.guard.as_ref().unwrap() } } impl<'a, T> Deref for InnerRwWriteLock<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.guard.as_ref().unwrap() } } impl<'a, T> DerefMut for InnerRwWriteLock<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.guard.as_mut().unwrap() } } pub struct MutexOption<T> { lock: Mutex<Option<T>> } impl<T> MutexOption<T> { pub fn new() -> Self { MutexOption{lock: Mutex::new(None)} } pub fn read<'a>(&'a self) -> InnerMutex<'a, T> { let guard = self.lock.lock().unwrap(); InnerMutex{guard} } pub fn write(&self, val: T) { let mut opt = self.lock.lock().unwrap(); *opt = Some(val); } } pub struct InnerMutex<'a, T> { guard: MutexGuard<'a, Option<T>> } impl<'a, T> Deref for InnerMutex<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.guard.as_ref().unwrap() } } impl<'a, T> DerefMut for InnerMutex<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.guard.as_mut().unwrap() } }
use std::cmp::min; use std::io::{BufWriter, stdin, stdout, Write}; #[derive(Default)] struct Scanner { buffer: Vec<String> } impl Scanner { fn next<T: std::str::FromStr>(&mut self) -> T { loop { if let Some(token) = self.buffer.pop() { return token.parse().ok().expect("Failed parse"); } let mut input = String::new(); stdin().read_line(&mut input).expect("Faild read"); self.buffer = input.split_whitespace().rev().map(String::from).collect(); } } } fn gao(n: i32, l1: i32, r1: i32, l2: i32, r2: i32) -> i32 { if l1 + l2 > n || r1 + r2 < n { return 0; } let d = n - l1; let l; let r; if d <= r2 { l = l1; r = min(l1 + d - l2, r1); } else { l = l1 + d - r2; r = min(l + r2 - l2, r1); } return r - l + 1; } fn main() { let mut scan = Scanner::default(); let out = &mut BufWriter::new(stdout()); for _ in 0..scan.next::<usize>() { let n = scan.next::<i32>(); let l1 = scan.next::<i32>(); let r1 = scan.next::<i32>(); let l2 = scan.next::<i32>(); let r2 = scan.next::<i32>(); writeln!(out, "{}", gao(n, l1, r1, l2, r2)).ok(); } }
#[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] #[macro_use] extern crate log; #[cfg(any(target_os = "ios", target_os = "android", target_os = "emscripten"))] extern crate android_log; pub use common; use noise::{NoiseFn, Perlin, Seedable}; pub use rand; use rand::prelude::*; use specs::prelude::*; use specs_derive::Component; use std::io::{BufReader, Error as IOError, Read}; use nalgebra::geometry::Orthographic3; use common::*; use image; use red; use red::glow; use red::glow::Context; use red::VertexAttribPointers; use glyph_brush::{ rusttype::{point, Rect}, BrushAction, BrushError, DefaultSectionHasher, GlyphBrush, }; use packer::SerializedSpriteSheet; use red::data::*; use red::shader::Texture; use red::{DrawParams, DrawType, Operation, Stencil, StencilTest}; use sdl2::rwops::RWops; use std::path::Path; pub mod effects; pub use effects::*; pub mod animation; pub use animation::*; const Z_CANVAS: f32 = 0f32; const Z_FAR: f32 = 15f32; const MAX_ADD_SPEED_Z: f32 = 10f32; const SPEED_EMA: f32 = 0.04f32; // new value will be taken with with that coef pub const _BACKGROUND_SIZE: f32 = 20f32; pub fn iso3_iso2(iso3: &Isometry3) -> Isometry2 { Isometry2::new( Vector2::new(iso3.translation.vector.x, iso3.translation.vector.y), iso3.rotation.euler_angles().2, ) } pub fn get_view(observer: Point3) -> Isometry3 { let mut target = observer.clone(); target.z = Z_CANVAS; Isometry3::look_at_rh(&observer, &target, &Vector3::y()) } pub fn perspective(width: u32, height: u32) -> Perspective3 { let aspect_ratio = width as f32 / height as f32; Perspective3::new(aspect_ratio, 3.14 / 3.0, 0.1, 1000.0) } fn gl_assert_ok(gl_context: &red::GL) { let err = unsafe { gl_context.get_error() }; // assert_eq!(err, glow::NO_ERROR, "{}", gl_err_to_str(err)); } fn gl_err_to_str(err: u32) -> &'static str { match err { glow::INVALID_ENUM => "INVALID_ENUM", glow::INVALID_VALUE => "INVALID_VALUE", glow::INVALID_OPERATION => "INVALID_OPERATION", glow::INVALID_FRAMEBUFFER_OPERATION => "INVALID_FRAMEBUFFER_OPERATION", glow::OUT_OF_MEMORY => "OUT_OF_MEMORY", glow::STACK_UNDERFLOW => "STACK_UNDERFLOW", glow::STACK_OVERFLOW => "STACK_OVERFLOW", _ => "Unknown error", } } // #[derive(Debug, Component, Clone, Copy)] // pub struct Image(pub specs::Entity); #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct GeometryVertex { pub position: red::data::f32_f32, } #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct TextVertex { #[divisor = "1"] left_top: f32_f32_f32, #[divisor = "1"] right_bottom: f32_f32, #[divisor = "1"] tex_left_top: f32_f32, #[divisor = "1"] tex_right_bottom: f32_f32, #[divisor = "1"] color: f32_f32_f32_f32, } pub type GlyphVertex = [std::os::raw::c_float; 13]; pub struct GeometryData { positions: GeometryVertexBuffer<GeometryVertex>, index_buffer: red::buffer::IndexBuffer, } impl GeometryData { pub fn new( gl: &red::GL, positions: &[Point2], indices: &[u16], ) -> Result<Self, String> { let shape: Vec<GeometryVertex> = positions .iter() .map(|pos| GeometryVertex { position: red::data::f32_f32::new(pos.x, pos.y), }) .collect(); let vertex_buffer = GeometryVertexBuffer::new(gl, &shape)?; let index_buffer = red::buffer::IndexBuffer::new(gl, &indices)?; Ok(GeometryData { positions: vertex_buffer, index_buffer, }) } } #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct Vertex { pub position: red::data::f32_f32, pub tex_coords: red::data::f32_f32, } #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct WorldVertex { #[divisor = "1"] pub world_position: red::data::f32_f32_f32, } #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct WorldIsometry { #[divisor = "1"] pub world_position: red::data::f32_f32_f32, #[divisor = "1"] pub angle: red::data::f32_, #[divisor = "1"] pub scale: red::data::f32_, } // we will pass it to shader for each image via instancing #[derive(Copy, Clone, Debug)] #[repr(C, packed)] #[derive(VertexAttribPointers)] pub struct AtlasRegion { #[divisor = "1"] pub offset: red::data::f32_f32, #[divisor = "1"] pub fraction_wh: red::data::f32_f32, #[divisor = "1"] pub dim_scales: red::data::f32_f32, #[divisor = "1"] pub transparency: red::data::f32_, // r, g, b, intensity #[divisor = "1"] pub color: red::data::f32_f32_f32_f32, } pub struct ImageInstancingData { pub image_model: ImageModel, pub regions: AtlasRegionBuffer<AtlasRegion>, pub isometries: WorldIsometryBuffer<WorldIsometry>, } pub struct InstancingData { pub vertex_buffer: GeometryVertexBuffer<GeometryVertex>, pub indices: red::buffer::IndexBuffer, pub per_instance: WorldVertexBuffer<WorldVertex>, } pub struct TextData<'a> { pub vertex_buffer: TextVertexBuffer<TextVertex>, pub vertex_num: i32, pub glyph_texture: red::Texture, pub glyph_brush: GlyphBrush<'a, GlyphVertex, DefaultSectionHasher>, } pub struct WorldTextData<'a> { pub vertex_buffer: TextVertexBuffer<TextVertex>, pub vertex_num: i32, pub glyph_texture: red::Texture, pub glyph_brush: GlyphBrush<'a, GlyphVertex, DefaultSectionHasher>, } pub struct ImageModel { pub positions: VertexBuffer<Vertex>, pub indices: red::buffer::IndexBuffer, } #[derive(Debug, Component, Clone, Copy)] pub struct AtlasImage { offset: (f32, f32), fraction_wh: (f32, f32), dim_scales: (f32, f32), pub transparency: f32, // r, g, b, intensity pub color: (f32, f32, f32, f32), } pub fn load_atlas_image( image_name: &str, atlas: &SerializedSpriteSheet, transparency: f32, ) -> Option<AtlasImage> { if let Some(sprite) = atlas.sprites.get(image_name) { let offset = ( sprite.x / atlas.texture_width, sprite.y / atlas.texture_height, ); let fraction_wh = ( sprite.width / atlas.texture_width, sprite.height / atlas.texture_height, ); let dimensions = (sprite.width, sprite.height); let dimensions = (1.0, dimensions.1 as f32 / dimensions.0 as f32); Some(AtlasImage { dim_scales: dimensions, fraction_wh, offset, transparency, color: (0f32, 0f32, 0f32, 0f32), }) } else { None } } impl AtlasImage { pub fn new( image_name: &str, atlas: &SerializedSpriteSheet, transparency: f32, color: (f32, f32, f32, f32), ) -> Self { let sprite = atlas.sprites[image_name].clone(); let offset = ( sprite.x / atlas.texture_width, sprite.y / atlas.texture_height, ); let fraction_wh = ( sprite.width / atlas.texture_width, sprite.height / atlas.texture_height, ); let dimensions = (sprite.width, sprite.height); let dimensions = (1.0, dimensions.1 as f32 / dimensions.0 as f32); Self { dim_scales: dimensions, fraction_wh, offset, transparency, color, } } } impl ImageModel { pub fn new(gl: &red::GL) -> Result<Self, String> { let positions = vec![(-1f32, -1f32), (-1f32, 1f32), (1f32, 1f32), (1f32, -1f32)]; let textures = vec![(0f32, 0f32), (0f32, 1f32), (1f32, 1f32), (1f32, 0f32)]; let shape: Vec<Vertex> = positions .into_iter() .zip(textures) .map(|(pos, tex)| Vertex { position: pos.into(), tex_coords: tex.into(), }) .collect(); let vertex_buffer = VertexBuffer::new(gl, &shape)?; let index_buffer = red::buffer::IndexBuffer::new(gl, &[0u16, 1, 2, 2, 3, 0])?; Ok(ImageModel { positions: vertex_buffer, indices: index_buffer, }) } } pub struct ImageData { positions: VertexBuffer<Vertex>, indices: red::buffer::IndexBuffer, texture: red::shader::Texture, dim_scales: Vector2, } impl ImageData { pub fn new(gl: &red::GL, image_name: &str) -> Result<Self, String> { // let positions = vec![(-1f32, 1f32), (-1f32, -1f32), (1f32, -1f32), (1f32, 1f32)]; let positions = vec![(-1f32, -1f32), (-1f32, 1f32), (1f32, 1f32), (1f32, -1f32)]; let textures = vec![(0f32, 0f32), (0f32, 1f32), (1f32, 1f32), (1f32, 0f32)]; let shape: Vec<Vertex> = positions .into_iter() .zip(textures) .map(|(pos, tex)| Vertex { position: pos.into(), tex_coords: tex.into(), }) .collect(); let vertex_buffer = VertexBuffer::new(gl, &shape)?; let index_buffer = red::buffer::IndexBuffer::new(gl, &[0u16, 1, 2, 2, 3, 0])?; let texture = load_texture(gl, image_name); let dimensions = texture.dimensions(); let dimensions = Vector2::new(1.0, dimensions.1 as f32 / dimensions.0 as f32); Ok(ImageData { positions: vertex_buffer, indices: index_buffer, texture, dim_scales: dimensions, }) } } pub fn read_file(filename: &str) -> Result<String, IOError> { let mut result_str = String::new(); let mut rw = RWops::from_file(Path::new(filename), "r") .expect(&format!("failed to load {}", filename).to_string()); rw.read_to_string(&mut result_str)?; Ok(result_str) } pub fn load_texture(gl: &red::GL, name: &str) -> red::shader::Texture { let path_str = format!("assets/{}.png", name); let texture_file = RWops::from_file(Path::new(&path_str), "r") .expect(&format!("failed to load {}", &path_str).to_string()); let reader = BufReader::new(texture_file); let image = image::load(reader, image::PNG).unwrap().to_rgba(); let image_dimensions = image.dimensions(); red::shader::Texture::from_rgba8( gl, image_dimensions.0, image_dimensions.1, &image.into_raw(), ) } pub fn create_shader_program( gl: &red::GL, pref: &str, name: &str, glsl_version: &str, ) -> Result<red::Program, String> { let vertex = format!("{}gles/v_{}.glsl", pref, name); let fragment = format!("{}gles/f_{}.glsl", pref, name); #[cfg(any(target_os = "android"))] trace!("{:?}, \n {:?}", vertex, fragment); let (vertex_shader, fragment_shader) = ( format!("{}\n{}", glsl_version, read_file(&vertex).unwrap()), format!("{}\n{}", glsl_version, read_file(&fragment).unwrap()), ); #[cfg(any(target_os = "android"))] trace!( "{:?} \n {:?} \n {:?}", vertex_shader, "---", fragment_shader ); let vertex_shader = red::Shader::from_vert_source(&gl, &vertex_shader).unwrap(); let fragment_shader = red::Shader::from_frag_source(&gl, &fragment_shader).unwrap(); let program = red::Program::from_shaders(&gl, &[vertex_shader, fragment_shader])?; Ok(program) } pub enum RenderMode { StencilWrite, StencilCheck, Draw, } impl Into<DrawParams> for RenderMode { fn into(self) -> DrawParams { match self { RenderMode::StencilWrite => red::DrawParams { draw_type: DrawType::Standart, stencil: Some(Stencil { ref_value: 1, mask: 0xFF, test: StencilTest::AlwaysPass, pass_operation: Some(Operation::Replace), }), color_mask: (false, false, false, false), ..Default::default() }, RenderMode::Draw => red::DrawParams { blend: Some(red::Blend), ..Default::default() }, RenderMode::StencilCheck => red::DrawParams { draw_type: DrawType::Standart, stencil: Some(Stencil { ref_value: 1, mask: 0xFF, test: StencilTest::NotEqual, pass_operation: None, }), blend: Some(red::Blend), ..Default::default() }, } } } /// 2D graphics pub struct Canvas { program: red::Program, // @vlad TODO: we want to use many programs program_light: red::Program, // but for now simpler=better program_instancing: red::Program, program_primitive: red::Program, program_primitive_texture: red::Program, program_sprite_batch: red::Program, pub program_glyph: red::Program, program_atlas: red::Program, observer: Point3, perlin_x: Perlin, perlin_y: Perlin, perlin_time: f32, camera_wobble: f32, direction: Vector2, direction_offset: Vector2, pub z_far: f32, atlas: red::shader::Texture, image_model: ImageModel, // default_params: glium::DrawParameters<'a>, // stencil_check_params: glium::DrawParameters<'a>, // stencil_write_params: glium::DrawParameters<'a>, } impl Canvas { pub fn new( gl: &red::GL, pref: &str, atlas: &str, glsl_version: &str, ) -> Result<Self, String> { let program = create_shader_program(gl, pref, "", glsl_version)?; let program_primitive = create_shader_program(gl, pref, "primitive", glsl_version)?; let program_primitive_texture = create_shader_program(gl, pref, "primitive_texture", glsl_version)?; let program_light = create_shader_program(gl, pref, "light", glsl_version)?; let program_instancing = create_shader_program(gl, pref, "instancing", glsl_version)?; let program_glyph = create_shader_program(gl, pref, "text", &glsl_version)?; let program_atlas = create_shader_program(gl, pref, "atlas", &glsl_version)?; let program_sprite_batch = create_shader_program(gl, pref, "spritebatch", &glsl_version)?; let z_far = Z_FAR; let atlas = load_texture(gl, atlas); let image_model = ImageModel::new(gl).expect("failed image model"); Ok(Canvas { program, program_primitive, program_primitive_texture, program_light, program_instancing, program_atlas, program_sprite_batch, observer: Point3::new(0f32, 0f32, z_far), program_glyph, perlin_x: Perlin::new().set_seed(0), perlin_y: Perlin::new().set_seed(1), perlin_time: 0.1f32, camera_wobble: 0f32, direction: Vector2::new(0f32, 0f32), direction_offset: Vector2::new(0f32, 0f32), z_far, atlas, image_model, }) } /// draw lines with only one draw call pub fn draw_lines( &self, lines: &[(Point2, Point2)], context: &red::GL, frame: &mut red::Frame, viewport: &red::Viewport, color: Point3, line_width: f32, ) { let mut positions = vec![]; let mut indices = vec![]; let mut cur_id = 0u16; for (a, b) in lines.iter() { let line_length = (b.coords - a.coords).norm(); let current_positions = vec![ Point2::new(-line_width / 2.0, 0f32), Point2::new(line_width / 2.0, 0f32), Point2::new(-line_width / 2.0, -line_length), Point2::new(line_width / 2.0, -line_length), ]; let up = Vector2::new(0.0, -line_length); let rotation = Rotation2::rotation_between(&up, &(&b.coords - a.coords)); let iso = Isometry3::new( Vector3::new(a.x, a.y, 0f32), Vector3::new(0f32, 0f32, rotation.angle()), ); let current_indices = [0u16, 1, 2, 1, 3, 2]; positions .extend(current_positions.iter().map(|x| iso3_iso2(&iso) * x)); indices.extend(current_indices.iter().map(|x| cur_id + x)); cur_id += current_indices.len() as u16; } let geometry_data = GeometryData::new(&context, &positions, &indices).unwrap(); self.render_geometry( &context, &viewport, frame, &geometry_data, &Isometry3::new( Vector3::new(0.0, 0.0, 0.0), Vector3::new(0f32, 0f32, 0f32), ), RenderMode::Draw, color, ); } pub fn draw_line( &self, a: Point2, b: Point2, context: &red::GL, frame: &mut red::Frame, viewport: &red::Viewport, color: Point3, line_width: f32, ) { let line_length = (b.coords - a.coords).norm(); let positions = vec![ Point2::new(-line_width / 2.0, 0f32), Point2::new(line_width / 2.0, 0f32), Point2::new(-line_width / 2.0, -line_length), Point2::new(line_width / 2.0, -line_length), ]; let up = Vector2::new(0.0, -line_length); let rotation = Rotation2::rotation_between(&up, &(&b.coords - a.coords)); let iso = Isometry3::new( Vector3::new(a.x, a.y, 0f32), Vector3::new(0f32, 0f32, rotation.angle()), ); let indices = [0u16, 1, 2, 1, 3, 2]; let geometry_data = GeometryData::new(&context, &positions, &indices).unwrap(); self.render_geometry( &context, &viewport, frame, &geometry_data, &iso, RenderMode::Draw, color, ); } pub fn observer(&self) -> Point3 { // let mut rng = rand::thread_rng(); // let noise: Vector3 = 0.1 * Vector3::new(rng.gen(), rng.gen(), 0f32).normalize(); let time = self.perlin_time as f64; let x = self.perlin_x.get([time, time]); let y = self.perlin_y.get([time, time]); let noise: Vector3 = self.camera_wobble * Vector3::new(x as f32, y as f32, 0f32); self.observer + noise + 2f32 * Vector3::new( self.direction_offset.x, self.direction_offset.y, 0f32, ) } pub fn add_wobble(&mut self, wobble: f32) { self.camera_wobble += wobble; } pub fn update_observer( &mut self, pos: Point2, speed_ratio: f32, direction: Vector2, ) { self.observer.x = pos.x; self.observer.y = pos.y; self.observer.z = (1.0 - SPEED_EMA) * self.observer.z + SPEED_EMA * (self.z_far + MAX_ADD_SPEED_Z * speed_ratio); self.perlin_time += 0.1; self.camera_wobble /= 2.0; self.direction = direction; self.direction_offset = self.direction_offset * 0.99 + 0.01 * direction; } pub fn get_z_shift(&self) -> f32 { self.observer.z - self.z_far } pub fn render_text( &self, text_data: &mut TextData, viewport: &red::Viewport, frame: &mut red::Frame, persp: bool, ) { let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let program = &self.program_glyph; let transform: [[f32; 4]; 4] = if persp { perspective(dims.0, dims.1).to_homogeneous().into() } else { orthographic(dims.0, dims.1).to_homogeneous().into() }; let view: [[f32; 4]; 4] = if persp { get_view(self.observer()).to_homogeneous().into() } else { Matrix4::identity().into() }; // TODO move to resource let max_image_dimension = { let value = unsafe { frame.gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) }; value as u32 }; let mut brush_action; loop { let current_texture = text_data.glyph_texture.texture.clone(); brush_action = text_data.glyph_brush.process_queued( |rect, tex_data| unsafe { // eprintln!("{:?}, {:?}", rect, tex_data); // Update part of gpu texture with new glyph alpha values frame .gl .bind_texture(glow::TEXTURE_2D, Some(current_texture)); frame.gl.tex_sub_image_2d_u8_slice( glow::TEXTURE_2D, -0, rect.min.x as _, rect.min.y as _, rect.width() as _, rect.height() as _, glow::RED, glow::UNSIGNED_BYTE, Some(tex_data), ); gl_assert_ok(&frame.gl) }, to_vertex, ); match brush_action { Ok(_) => break, Err(BrushError::TextureTooSmall { suggested, .. }) => { let (new_width, new_height) = if (suggested.0 > max_image_dimension || suggested.1 > max_image_dimension) && (text_data.glyph_brush.texture_dimensions().0 < max_image_dimension || text_data.glyph_brush.texture_dimensions().1 < max_image_dimension) { (max_image_dimension, max_image_dimension) } else { suggested }; // Recreate texture as a larger size to fit more text_data.glyph_texture = Texture::new(&frame.gl, (new_width, new_height)); //GlGlyphTexture::new((new_width, new_height)); text_data.glyph_brush.resize_texture(new_width, new_height); } } } match brush_action.unwrap() { BrushAction::Draw(vertices) => { text_data.vertex_num = vertices.len() as i32; unsafe { text_data.vertex_buffer.dynamic_draw_data( std::slice::from_raw_parts( vertices.as_ptr() as *const TextVertex, vertices.len(), ), ); } } // vertex_max = vertex_max.max(vertex_count); // } BrushAction::ReDraw => {} } program.set_uniform("transform", transform); program.set_uniform("font_tex", text_data.glyph_texture.clone()); program.set_uniform("view", view); let text_vb: &TextVertexBuffer<TextVertex> = &text_data.vertex_buffer; program.set_layout(&frame.gl, &text_vb.vao, &[text_vb]); let vao = &text_vb.vao; unsafe { vao.bind(); program.set_used(); frame.gl.draw_arrays_instanced( glow::TRIANGLE_STRIP, 0, 4, text_data.vertex_num, ); vao.unbind() } } // copy paste (TODO. trait for text data...) pub fn render_world_text( &self, text_data: &mut WorldTextData, viewport: &red::Viewport, frame: &mut red::Frame, persp: bool, ) { let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let program = &self.program_glyph; let view: [[f32; 4]; 4] = if persp { get_view(self.observer()).to_homogeneous().into() } else { Matrix4::identity().into() }; let transform: [[f32; 4]; 4] = if persp { perspective(dims.0, dims.1).to_homogeneous().into() // _orthographic_from_zero(dims.0, dims.1).to_homogeneous().into() } else { orthographic(dims.0, dims.1).to_homogeneous().into() }; // TODO move to resource let max_image_dimension = { let value = unsafe { frame.gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) }; value as u32 }; let mut brush_action; loop { let current_texture = text_data.glyph_texture.texture.clone(); brush_action = text_data.glyph_brush.process_queued( |rect, tex_data| unsafe { // eprintln!("{:?}, {:?}", rect, tex_data); // Update part of gpu texture with new glyph alpha values frame .gl .bind_texture(glow::TEXTURE_2D, Some(current_texture)); frame.gl.tex_sub_image_2d_u8_slice( glow::TEXTURE_2D, -0, rect.min.x as _, rect.min.y as _, rect.width() as _, rect.height() as _, glow::RED, glow::UNSIGNED_BYTE, Some(tex_data), ); gl_assert_ok(&frame.gl) }, to_vertex, ); match brush_action { Ok(_) => break, Err(BrushError::TextureTooSmall { suggested, .. }) => { let (new_width, new_height) = if (suggested.0 > max_image_dimension || suggested.1 > max_image_dimension) && (text_data.glyph_brush.texture_dimensions().0 < max_image_dimension || text_data.glyph_brush.texture_dimensions().1 < max_image_dimension) { (max_image_dimension, max_image_dimension) } else { suggested }; // let (new_width, new_height) = (new_width / 50, new_height / 50); // Recreate texture as a larger size to fit more text_data.glyph_texture = Texture::new(&frame.gl, (new_width, new_height)); //GlGlyphTexture::new((new_width, new_height)); text_data.glyph_brush.resize_texture(new_width, new_height); } } } match brush_action.unwrap() { BrushAction::Draw(vertices) => { text_data.vertex_num = vertices.len() as i32; unsafe { text_data.vertex_buffer.dynamic_draw_data( std::slice::from_raw_parts( vertices.as_ptr() as *const TextVertex, vertices.len(), ), ); } } // vertex_max = vertex_max.max(vertex_count); // } BrushAction::ReDraw => {} } program.set_uniform("transform", transform); program.set_uniform("view", view); program.set_uniform("font_tex", text_data.glyph_texture.clone()); let text_vb: &TextVertexBuffer<TextVertex> = &text_data.vertex_buffer; program.set_layout(&frame.gl, &text_vb.vao, &[text_vb]); let vao = &text_vb.vao; unsafe { vao.bind(); program.set_used(); frame.gl.draw_arrays_instanced( glow::TRIANGLE_STRIP, 0, 4, text_data.vertex_num, ); vao.unbind() } } pub fn render_geometry( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, geometry_data: &GeometryData, model: &Isometry3, render_mode: RenderMode, color: Point3, ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); let vao = &geometry_data.positions.vao; let program = &self.program_light; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("perspective", perspective); program.set_uniform("color", (color.x, color.y, color.z)); program.set_layout(&gl, vao, &[&geometry_data.positions]); let draw_params = render_mode.into(); frame.draw( vao, Some(&geometry_data.index_buffer), &program, &draw_params, ); } pub fn render_primitive( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, geometry_data: &GeometryData, model: &Isometry3, fill_color: (f32, f32, f32), with_projection: bool, render_mode: RenderMode, ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let (projection, view) = if with_projection { let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); (perspective, view) } else { let orthographic: [[f32; 4]; 4] = orthographic(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = Matrix4::identity().into(); (orthographic, view) }; let vao = &geometry_data.positions.vao; let program = &self.program_primitive; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("projection", projection); program.set_uniform("fill_color", fill_color); program.set_layout(&gl, vao, &[&geometry_data.positions]); let draw_params = render_mode.into(); frame.draw( vao, Some(&geometry_data.index_buffer), program, &draw_params, ); } pub fn render_atlas( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, atlas_image: &AtlasImage, model: &Isometry3, scale: f32, with_lights: bool, blend: Option<red::Blend>, ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); // let draw_params = if with_lights { // &self.stencil_check_params // } else { // &self.default_params // }; let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); let vao = &self.image_model.positions.vao; let program = &self.program_atlas; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("perspective", perspective); program.set_uniform("dim_scales", atlas_image.dim_scales); program.set_uniform("tex", self.atlas.clone()); // this is just shallow copy if idx program.set_uniform("scale", scale); program.set_uniform("offset", atlas_image.offset); program.set_uniform("fraction_wh", atlas_image.fraction_wh); program.set_layout(&gl, vao, &[&self.image_model.positions]); let draw_params = if with_lights { red::DrawParams { draw_type: DrawType::Standart, stencil: Some(Stencil { ref_value: 1, mask: 0xFF, test: StencilTest::NotEqual, pass_operation: None, }), blend, ..Default::default() } } else { DrawParams { blend, ..Default::default() } }; frame.draw( vao, Some(&self.image_model.indices), &program, &draw_params, ); } pub fn render( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, image_data: &ImageData, model: &Isometry3, scale: f32, with_lights: bool, blend: Option<red::Blend>, ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let texture = &image_data.texture; // let draw_params = if with_lights { // &self.stencil_check_params // } else { // &self.default_params // }; let scales = image_data.dim_scales; let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); let vao = &image_data.positions.vao; let program = &self.program; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("perspective", perspective); program.set_uniform("dim_scales", (scales.x, scales.y)); program.set_uniform("tex", texture.clone()); program.set_uniform("scale", scale); program.set_layout(&gl, vao, &[&image_data.positions]); let draw_params = if with_lights { red::DrawParams { draw_type: DrawType::Standart, stencil: Some(Stencil { ref_value: 1, mask: 0xFF, test: StencilTest::NotEqual, pass_operation: None, }), blend, ..Default::default() } } else { DrawParams { blend, ..Default::default() } }; frame.draw(vao, Some(&image_data.indices), &program, &draw_params); } pub fn render_sprite_batch( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, sprite_batch: &SpriteBatch, with_lights: bool, blend: Option<red::Blend>, ) { let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); let vao = &sprite_batch.instancing_data.image_model.positions.vao; let program = &self.program_sprite_batch; program.set_uniform("view", view); program.set_uniform("perspective", perspective); // program.set_uniform("dim_scales", atlas_image.dim_scales); program.set_uniform("tex", self.atlas.clone()); // this is just shallow copy if idx // program.set_uniform("scale", 1.0); program.set_layout( &gl, vao, &[ &sprite_batch.instancing_data.image_model.positions, &sprite_batch.instancing_data.regions, &sprite_batch.instancing_data.isometries, ], ); let draw_type = red::DrawType::Instancing(sprite_batch.len); let draw_params = if with_lights { red::DrawParams { draw_type, stencil: Some(Stencil { ref_value: 1, mask: 0xFF, test: StencilTest::NotEqual, pass_operation: None, }), blend, ..Default::default() } } else { DrawParams { draw_type, blend, ..Default::default() } }; frame.draw( vao, Some(&sprite_batch.instancing_data.image_model.indices), &program, &draw_params, ); } pub fn render_instancing( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, instancing_data: &InstancingData, model: &Isometry3, // transparency: f32, ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); let vao = &instancing_data.vertex_buffer.vao; let program = &self.program_instancing; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("perspective", perspective); program.set_uniform("transparency", 1f32); program.set_layout( &gl, vao, &[ &instancing_data.vertex_buffer, &instancing_data.per_instance, ], ); let draw_type = red::DrawType::Instancing( instancing_data.per_instance.len.unwrap(), ); let draw_params = red::DrawParams { stencil: None, draw_type, ..Default::default() }; frame.draw(vao, Some(&instancing_data.indices), &program, &draw_params); } pub fn render_primitive_texture( &self, gl: &red::GL, viewport: &red::Viewport, frame: &mut red::Frame, atlas_image: &AtlasImage, model: &Isometry3, with_projection: bool, dim_scales: (f32, f32), ) { let model: [[f32; 4]; 4] = model.to_homogeneous().into(); let dims = viewport.dimensions(); let dims = (dims.0 as u32, dims.1 as u32); let vao = &self.image_model.positions.vao; let program = &self.program_primitive_texture; let (projection, view) = if with_projection { let perspective: [[f32; 4]; 4] = perspective(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = get_view(self.observer()).to_homogeneous().into(); (perspective, view) } else { let orthographic: [[f32; 4]; 4] = orthographic(dims.0, dims.1).to_homogeneous().into(); let view: [[f32; 4]; 4] = Matrix4::identity().into(); (orthographic, view) }; // let scales = image_data.dim_scales; program.set_uniform("model", model); program.set_uniform("view", view); program.set_uniform("projection", projection); program.set_uniform("tex", self.atlas.clone()); program.set_uniform("dim_scales", dim_scales); // program.set_uniform("size", size); // program.set_uniform("dim_scales", atlas_image.dim_scales); program.set_uniform("offset", atlas_image.offset); program.set_uniform("fraction_wh", atlas_image.fraction_wh); program.set_layout(&gl, vao, &[&self.image_model.positions]); let draw_params = DrawParams::default(); frame.draw( vao, Some(&self.image_model.indices), &program, &draw_params, ); } } pub fn _orthographic_from_zero(width: u32, height: u32) -> Orthographic3<f32> { Orthographic3::new(0f32, width as f32, 0f32, height as f32, -0.9, 0.0) } // creates ortograohic projection left=bot=0 z_near=0.1 far=1.0 pub fn orthographic(width: u32, height: u32) -> Orthographic3<f32> { Orthographic3::new(0f32, width as f32, 0f32, height as f32, -1f32, 1f32) } // it's from 2d not real pub fn ortho_unproject(width: u32, height: u32, point: Point2) -> Point2 { let ortho: Matrix4 = orthographic(width, height).into(); let unortho = ortho.try_inverse().unwrap(); let res = unortho * Point4::new(point.x, point.y, 1f32, 1f32); Point2::new(res.x, res.y) } // wow such a name (REAL) pub fn ortho_unproject_real(width: u32, height: u32, point: Point4) -> Point2 { let ortho: Matrix4 = orthographic(width, height).into(); let unortho = ortho.try_inverse().unwrap(); let res = unortho * point; Point2::new(res.x / res.w, res.y / res.w) } pub fn unproject( observer: Point3, window_coord: &Point2, width: u32, height: u32, z_far: f32, ) -> (Point3, Vector3) { let begin_ray = Point4::new(window_coord.x, window_coord.y, 0f32, 1f32); let ingame_window_coord = Point4::new(window_coord.x, window_coord.y, z_far, 1f32); let perspective: Matrix4 = perspective(width, height).into(); let view: Matrix4 = get_view(observer).to_homogeneous().into(); let inverse_transform = (perspective * view).try_inverse().unwrap(); let unprojected_begin = inverse_transform * begin_ray; let unprojected_end = inverse_transform * ingame_window_coord; let unprojected_begin = Point3::from_homogeneous(unprojected_begin.coords).unwrap(); let unprojected_end = Point3::from_homogeneous(unprojected_end.coords).unwrap(); // * Why (perspective * view)^-1 // * Exlanation: // * * this coords then passed to the Isometry and then as model to shader // * * the order is: // * * perspective * view * model ( unprojected_begin, (unprojected_end - unprojected_begin).normalize(), ) } pub fn unproject_with_z( observer: Point3, window_coord: &Point2, z_coord: f32, width: u32, height: u32, z_far: f32, ) -> Point3 { let (pos, dir) = unproject(observer, window_coord, width, height, z_far); let z_safe_scaler = (-pos.z + z_coord) / dir.z; pos + dir * z_safe_scaler } // text #[inline] pub fn to_vertex( glyph_brush::GlyphVertex { mut tex_coords, pixel_coords, bounds, color, z, }: glyph_brush::GlyphVertex, ) -> GlyphVertex { let gl_bounds = bounds; let mut gl_rect = Rect { min: point(pixel_coords.min.x as f32, pixel_coords.min.y as f32), max: point(pixel_coords.max.x as f32, pixel_coords.max.y as f32), }; // handle overlapping bounds, modify uv_rect to preserve texture aspect if gl_rect.max.x > gl_bounds.max.x { let old_width = gl_rect.width(); gl_rect.max.x = gl_bounds.max.x; tex_coords.max.x = tex_coords.min.x + tex_coords.width() * gl_rect.width() / old_width; } if gl_rect.min.x < gl_bounds.min.x { let old_width = gl_rect.width(); gl_rect.min.x = gl_bounds.min.x; tex_coords.min.x = tex_coords.max.x - tex_coords.width() * gl_rect.width() / old_width; } if gl_rect.max.y > gl_bounds.max.y { let old_height = gl_rect.height(); gl_rect.max.y = gl_bounds.max.y; tex_coords.max.y = tex_coords.min.y + tex_coords.height() * gl_rect.height() / old_height; } if gl_rect.min.y < gl_bounds.min.y { let old_height = gl_rect.height(); gl_rect.min.y = gl_bounds.min.y; tex_coords.min.y = tex_coords.max.y - tex_coords.height() * gl_rect.height() / old_height; } [ gl_rect.min.x, gl_rect.max.y, z, gl_rect.max.x, gl_rect.min.y, tex_coords.min.x, tex_coords.max.y, tex_coords.max.x, tex_coords.min.y, color[0], color[1], color[2], color[3], ] } pub struct SpriteBatch { pub instancing_data: ImageInstancingData, pub len: usize, } impl SpriteBatch { pub fn new( gl: &red::GL, images: &[AtlasImage], isometries: &[Isometry3], sizes: &[f32], ) -> Self { let image_model = ImageModel::new(gl).expect("failed image model"); let regions: Vec<AtlasRegion> = images .iter() .map(|image| AtlasRegion { offset: red::data::f32_f32 { d0: image.offset.0, d1: image.offset.1, }, fraction_wh: red::data::f32_f32::new( image.fraction_wh.0, image.fraction_wh.1, ), dim_scales: red::data::f32_f32::new( image.dim_scales.0, image.dim_scales.1, ), transparency: red::data::f32_::new(image.transparency), color: red::data::f32_f32_f32_f32( image.color.0, image.color.1, image.color.2, image.color.3, ), }) .collect(); let isometries: Vec<WorldIsometry> = isometries .iter() .zip(sizes.iter()) .map(|(iso, size)| { let pos = iso.translation.vector; let angle = iso.rotation.euler_angles().2; WorldIsometry { world_position: red::data::f32_f32_f32::new( pos.x, pos.y, pos.z, ), angle: red::data::f32_::new(angle), scale: red::data::f32_::new(*size), } }) .collect(); let regions = AtlasRegionBuffer::new(gl, &regions) .expect("failed to create regions buffer"); let isometries = WorldIsometryBuffer::new(gl, &isometries) .expect("failed to create isometries buffer"); let instancing_data = ImageInstancingData { image_model, regions, isometries, }; SpriteBatch { instancing_data, len: images.len(), } } }
pub mod colag; extern crate rand; use std::time::{SystemTime, Duration}; use std::mem; use std::fmt; use std::collections::{HashSet}; use std::thread; use std::sync::Arc; use rand::Rng; use rand::distributions::{Range, Sample}; use colag::{Domain, NUM_PARAMS}; const COLAG_TSV: &'static str = "./COLAG_2011_ids.txt"; const NUM_SENTENCES: u32 = 2_000_000; const RUNS_PER_LANGUAGE: u8 = 100; const LEARNING_RATE: f64 = 0.001; const THRESHOLD: f64 = 0.02; type Grammar = u16; type Sentence = u32; type ParamWeights = [f64; NUM_PARAMS]; enum Hypothesis { Trigger ( Grammar ), Genetic ( HashSet<Grammar> ), RewardOnlyVL ( ParamWeights ), RewardOnlyRelevantVL ( ParamWeights ), } impl fmt::Display for Hypothesis { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Hypothesis::RewardOnlyRelevantVL(weights) | &Hypothesis::RewardOnlyVL(weights) => { write!(f, "VL( [{}] ", random_weighted_grammar(&weights))?; for w in weights.iter(){ write!(f, "{:.2} ", w)?; } write!(f, ")") } _ => write!(f, "---") } } } fn init_weights() -> ParamWeights { unsafe { let mut array: ParamWeights = mem::uninitialized(); for param in 0..NUM_PARAMS { array[param] = 0.5; } array } } impl Hypothesis { fn new_trigger() -> Hypothesis { Hypothesis::Trigger(0) } fn new_reward_only() -> Hypothesis { Hypothesis::RewardOnlyVL(init_weights()) } fn new_reward_only_relevant() -> Hypothesis { Hypothesis::RewardOnlyRelevantVL(init_weights()) } fn new_genetic() -> Hypothesis { Hypothesis::Genetic(HashSet::new()) } fn converged(&self) -> bool { match *self { Hypothesis::RewardOnlyVL(weights) | Hypothesis::RewardOnlyRelevantVL(weights) => { for weight in weights.iter() { if (weight > &THRESHOLD) & (weight < &(1.0 - THRESHOLD)) { return false; } } true } Hypothesis::Genetic(ref set) => { set.len() == 1 } Hypothesis::Trigger(_) => false } } fn update(&mut self, domain: &Domain, sentence: &Sentence) { match self { &mut Hypothesis::RewardOnlyVL(ref mut weights) => { loop { let ref grammar = random_weighted_grammar(&weights); // only returns ok if grammar exists in colag if let Ok(parses) = sentence_parses(domain, grammar, sentence) { if parses { *weights = reward_weights(*weights, grammar, sentence); } break; } } }, &mut Hypothesis::RewardOnlyRelevantVL(ref mut weights) => { loop { let ref grammar = random_weighted_grammar(&weights); if let Ok(parses) = sentence_parses(domain, grammar, sentence) { if parses { } break; } } }, _ => panic!("not implemented") } } } struct IllegalGrammar ( Grammar ); fn random_weighted_grammar(weights: &ParamWeights) -> Grammar { let mut grammar = 0; for param in 0..NUM_PARAMS { if weighted_coin_flip(weights[param]) { grammar = set_param(grammar, param); } } grammar } fn sentence_parses(domain: &Domain, grammar: &Grammar, sentence: &Sentence) -> Result<bool, IllegalGrammar> { if let Some(sentences) = domain.language.get(grammar) { Ok(sentences.contains(sentence)) } else { Err(IllegalGrammar(*grammar)) } } pub fn reward_weights(mut weights: ParamWeights, grammar: &Grammar, _: &Sentence) -> ParamWeights { for param in 0..NUM_PARAMS { let weight = weights[param]; if get_param(grammar, param) == 0 { weights[param] -= LEARNING_RATE * weight } else { weights[param] += LEARNING_RATE * (1. - weight) } } weights } pub fn reward_relevant_weights(mut weights: ParamWeights, grammar: &Grammar, sentence: &Sentence, _triggers: ()) -> ParamWeights { for param in 0..NUM_PARAMS { let weight = weights[param]; if get_param(grammar, param) == 0 { weights[param] -= LEARNING_RATE * weight } else { weights[param] += LEARNING_RATE * (1. - weight) } } weights } /// Returns paramter # `param_num` from `grammar`. fn get_param(grammar: &Grammar, param_num: usize) -> Grammar { (grammar >> (NUM_PARAMS - param_num - 1)) & 1 } /// Returns `grammar` with `param_num` turned on. fn set_param(grammar: Grammar, param_num: usize) -> Grammar { grammar + (1 << (NUM_PARAMS - param_num - 1)) } /// Returns true `weight` percent of the time fn weighted_coin_flip(weight: f64) -> bool { debug_assert!((weight >= 0.) & (weight <= 1.)); let mut rng = rand::thread_rng(); let mut range = Range::new(0., 1.); range.sample(&mut rng) < weight } struct Report { hypothesis: Hypothesis, target: Grammar, converged: bool, consumed: u32, runtime: Duration } fn learn_language(colag: &Domain, target: &Grammar, mut hypothesis: Hypothesis) -> Report { let start = SystemTime::now(); let mut rng = rand::thread_rng(); let sentences: Vec<&u32> = colag.language .get(&target) .expect(&format!("language {} does not exist", target)) .iter().collect(); let mut converged = false; let mut consumed = NUM_SENTENCES; for i in 1..NUM_SENTENCES { let sentence = rng.choose(&sentences).unwrap(); hypothesis.update(colag, &sentence); converged = hypothesis.converged(); if converged { consumed = i; break; } } let time = SystemTime::now().duration_since(start).unwrap(); Report { hypothesis: hypothesis, target: *target, consumed: consumed, converged: converged, runtime: time } } trait AsMs { fn to_ms(&self) -> u64; } impl AsMs for Duration { fn to_ms(&self) -> u64 { self.as_secs() * 1000 + self.subsec_nanos() as u64 / 1_000_000 } } fn main() { let colag = Arc::new(Domain::from_file(&String::from(COLAG_TSV)).unwrap()); let languages = vec![611, 584, 2253, 3856]; let mut handles = Vec::new(); let start = SystemTime::now(); for target in languages { let colag = colag.clone(); handles.push(thread::spawn(move || { for _ in 0..100 { let mut hypothesis = Hypothesis::new_reward_only(); let report = learn_language(&colag, &target, hypothesis); println!("{} {} {} {} {:?}", report.converged, report.consumed, report.target, report.hypothesis, report.runtime.to_ms()) } })) } for handle in handles { handle.join().unwrap(); } println!("total runtime: {:?}", SystemTime::now().duration_since(start).unwrap()); } enum Parameter { SP, HIP, HCP, OPT, NS, NT, WHM, PI, TM, VtoI, ItoC, AH, QInv }
use super::TemplateProviderError; use crate::service::template::manager::{TemplateManager, TemplateManagerError}; use crate::service::template::template::Template; use async_trait::async_trait; use serde::Deserialize; use serde_json::Value as JsonValue; use std::fs::{read_to_string, File}; use std::io::BufReader; use std::path::Path; pub const CONFIG_PROVIDER_LOCAL_ROOT: &'static str = "TEMPLATE_ROOT"; fn default_mjml_path() -> String { "template.mjml".into() } #[derive(Debug, Deserialize)] pub struct LocalMetadata { name: String, description: String, #[serde(default = "default_mjml_path")] mjml: String, attributes: JsonValue, } #[derive(Clone, Debug)] pub struct LocalTemplateProvider { root: String, } impl LocalTemplateProvider { pub fn from_env() -> Result<Self, TemplateProviderError> { match std::env::var(CONFIG_PROVIDER_LOCAL_ROOT) { Ok(value) => Ok(Self::new(value.as_str())), Err(_) => Err(TemplateProviderError::ConfigurationInvalid( "variable TEMPLATE_ROOT not found".into(), )), } } pub fn new(root: &str) -> Self { Self { root: root.into() } } } #[async_trait] impl TemplateManager for LocalTemplateProvider { async fn find_by_name(&self, name: &str) -> Result<Template, TemplateManagerError> { info!("find_by_name: {}", name); let path = Path::new(self.root.as_str()) .join(name) .join("metadata.json"); let metadata_file = File::open(path)?; let metadata_reader = BufReader::new(metadata_file); let metadata: LocalMetadata = serde_json::from_reader(metadata_reader)?; let mjml_path = Path::new(self.root.as_str()).join(name).join(metadata.mjml); let content = read_to_string(mjml_path)?; Ok(Template { name: metadata.name, description: metadata.description, content, attributes: metadata.attributes, }) } } // LCOV_EXCL_START #[cfg(test)] mod tests { use super::*; use crate::test_util::TempEnvVar; fn get_root() -> String { match std::env::var(CONFIG_PROVIDER_LOCAL_ROOT) { Ok(value) => value, Err(_) => String::from("template"), } } #[test] #[serial] fn without_template_root() { let _env_base_url = TempEnvVar::new(CONFIG_PROVIDER_LOCAL_ROOT); let result = LocalTemplateProvider::from_env(); assert!(result.is_err()); } #[test] #[serial] fn with_template_root() { let _env_base_url = TempEnvVar::new(CONFIG_PROVIDER_LOCAL_ROOT).with("./template"); let result = LocalTemplateProvider::from_env(); assert!(result.is_ok()); } #[actix_rt::test] #[serial] async fn local_find_by_name_not_found() { let manager = LocalTemplateProvider::new(get_root().as_str()); assert!(match manager.find_by_name("not_found").await.unwrap_err() { TemplateManagerError::TemplateNotFound => true, _ => false, }); } #[actix_rt::test] #[serial] async fn local_find_by_name_success() { let manager = LocalTemplateProvider::new(get_root().as_str()); let result = manager.find_by_name("user-login").await.unwrap(); assert_eq!(result.name, "user-login"); assert_eq!(result.description, "Template for login with magic link"); } } // LCOV_EXCL_END
use std::path; use friday_error::{FridayError, frierr}; use friday_logging; use wav; use std::fs::File; use std::fs; #[derive(Clone)] pub struct Files { root: path::PathBuf } impl Files { pub fn new(root: path::PathBuf) -> Result<Files, FridayError> { if root.is_dir() { Ok(Files { root }) } else { frierr!("Failed to create 'Files' storage, Reason: {:?} is not a directory", root) } } /// Stores the audio data as a file named 'name' /// If successful returns Ok('name'.wav) pub fn store_audio<S: AsRef<str>>(&self, name: S, data: Vec<i16>, sample_rate: u32) -> Result<String, FridayError> { let file_name = name.as_ref().to_owned() + ".wav"; let mut file_path = self.root.clone(); file_path.push(file_name.clone()); match File::create(file_path.clone()) { Err(err) => frierr!("Failed to create file {:?} for storing audio, Reason: {:?}", file_path, err), Ok(mut file) => match wav::write(wav::Header::new(1, 1, sample_rate, 16), wav::BitDepth::Sixteen(data), &mut file) { Err(err) => frierr!("Failed to write data to wav file, Reason: {:?}", err), Ok(_) => Ok(file_name) } } } /// Reads an audio file stored with 'store_audio' and returns the PCM data and sample_rate pub fn read_audio<S: AsRef<str>>(&self, name: S) -> Result<(Vec<i16>, u32), FridayError> { let mut file_path = self.root.clone(); file_path.push(name.as_ref().clone()); match File::open(file_path) { Err(err) => frierr!("Failed to open audio file {:?}", err), Ok(mut file) => match wav::read(&mut file){ Err(err) => frierr!("Failed to read wav file {:?}", err), Ok((header, data)) => match header.sampling_rate == 16000 && header.bits_per_sample == 16 && header.channel_count == 1 { false => frierr!("Audio file {} contains unexpected header fields \ got bits per sample {} - sample rate {} - channel count {} - Audio Format {} \ expect bits per sample 16 - sample rate 16000 - channel count 1 - Audio Format 1", name.as_ref(), header.bits_per_sample, header.sampling_rate, header.channel_count, header.audio_format), true => match data { wav::BitDepth::Sixteen(audio) => Ok((audio, header.sampling_rate)), // This error should not occur, since we validate bitdepth in the // parent match _ => frierr!("Wav data contained an unexpected bitdepth, expected 16") } } } } } /// Tries to remove the file identified by 'name' pub fn remove_file<S: AsRef<str>>(&self, name: S) -> Result<(), FridayError> { let mut file_path = self.root.clone(); file_path.push(name.as_ref()); match fs::remove_file(file_path.clone()) { Err(err) => frierr!("Failed to remove file {:?}, Reason: {:?}", file_path, err), Ok(_) => Ok(()) } } /// Opens and returns handle to a file read-only file pub fn get_file<S: AsRef<str>>(&self, name: S) -> Result<File, FridayError> { let mut file_path = self.root.clone(); file_path.push(name.as_ref()); match File::open(file_path.clone()) { Err(err) => frierr!("Failed to open file {:?}, Reason: {:?}", file_path, err), Ok(handle) => Ok(handle) } } /// Tries to rename the node identified by 'old_name' to 'new_name' pub fn rename<S: AsRef<str>>(&self, old_name: S, new_name: S) -> Result<(), FridayError> { let mut old_path = self.root.clone(); old_path.push(old_name.as_ref()); let mut new_path = self.root.clone(); new_path.push(new_name.as_ref()); match fs::rename(old_path.clone(), new_path.clone()) { Err(err) => frierr!("Failed to move node {:?} to {:?}, Reason: {:?}", old_path, new_path, err), Ok(_) => Ok(()) } } /// Checks that a file or directory exists pub fn exists<S: AsRef<str>>(&self, name: S) -> bool { let mut path = self.root.clone(); path.push(name.as_ref()); path.exists() } /// Gets full path of a file pub fn full_path_of<S: AsRef<str>>(&self, name: S) -> Result<String, FridayError> { let mut root = self.root.clone(); root.push(name.as_ref()); match root.to_str() { Some(s) => Ok(s.to_owned()), None => frierr!("Failed to convert {:?} to String", root) } } /// Lists all files under "namespace" pub fn list_files_under<S: AsRef<str>>(&self, namespace: S) -> Result<Vec<String>, FridayError> { let mut namespace_path = self.root.clone(); namespace_path.push(namespace.as_ref()); match namespace_path.read_dir() { Err(err) => frierr!("Failed to read directory {:?}, Reason {:?}", namespace_path, err), Ok(it) => { let mut names = Vec::new(); for entry in it { // As soon as one error occurs we fail match entry { Err(err) => friday_logging::error!( "Failed to read directory entry Reason: {:?}", err), Ok(e) => match e.metadata() { Err(err) => friday_logging::error!( "Failed to get metadata for {:?}, Reason: {:?}", e, err), Ok(meta) => { // list only files not directories if meta.is_file() { match e.file_name().into_string() { Err(osstr) => return frierr!("Failed to convert {:?} into String", osstr), Ok(r) => names.push(r) } } } } }; } Ok(names) } } } } #[cfg(test)] mod tests { use super::*; use std::env; use crate::config; #[test] fn test_file_exists() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); assert!(files.exists("test_file")); assert!(!files.exists("doo")); } #[test] fn test_file_rename() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); files.rename("test_file", "some_file").expect("Failed to rename file"); assert!(!files.exists("test_file")); assert!(files.exists("some_file")); files.rename("some_file", "test_file").expect("Failed to rename file"); assert!(files.exists("test_file")); assert!(!files.exists("some_file")); } #[test] fn test_file_remove() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); File::create("./test-resources/tmp_file").expect("Failed to create file"); assert!(files.exists("tmp_file")); files.remove_file("tmp_file").expect("Failed to remove tmp_file"); assert!(!files.exists("tmp_file")); } #[test] fn test_file_store_audio() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); let mut data: Vec<i16> = vec![0; 16000]; for i in 0..16000 { data[i] = (((i as f32) / 1.0).sin() * 1000.0) as i16; } files.store_audio("audio_test", data, 8000).expect("Failed to store audio"); assert!(files.exists("audio_test.wav")); files.remove_file("audio_test.wav").expect("Failed to remove audio_test.wav"); assert!(!files.exists("audio_test.wav")); } #[test] fn test_file_list_namespace() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); assert_eq!(files.list_files_under("").expect("Failed to list files"), vec!["test_config.json", "test_file"]); } #[test] fn test_file_full_path() { env::set_var("FRIDAY_CONFIG", "./test-resources"); let config_dir = config::get_config_directory().expect("failed to get config directory"); let files = Files::new(config_dir).expect("Failed to create 'Files' storage"); assert_eq!(files.full_path_of("test_config.json").expect("Failed to list files"), "./test-resources/test_config.json"); } }
pub(crate) mod generate; #[proc_macro] pub fn rspg(input: proc_macro::TokenStream) -> proc_macro::TokenStream { generate::generate(input.into()) .unwrap_or_else(|err| err.to_compile_error()) .into() }
use std::cell::Cell; fn main() { let c=Cell::new(10); c=4; //c.set(20); println!("{}",c.get()); }
use std::collections::HashMap; use super::super::gc::GcObject; use super::value::{Value, Object}; pub struct Scope { parent: Option<GcObject<Scope>>, defines: HashMap<String, Box<Object>>, } impl Scope { #[inline(always)] pub fn new(parent: Option<GcObject<Scope>>) -> Self { Scope { parent: parent, defines: HashMap::new(), } } #[inline] pub fn parent(&self) -> Option<&GcObject<Scope>> { match self.parent { Some(ref parent) => Some(parent), None => None, } } #[inline] pub fn contains(&self, ident: &str) -> bool { if self.defines.contains_key(ident) { true } else if let Some(ref parent) = self.parent { parent.contains(ident) } else { false } } #[inline] pub fn get(&self, ident: &str) -> Option<&Box<Object>> { if let Some(ref value) = self.defines.get(ident) { Some(value) } else if let Some(ref parent) = self.parent { parent.get(ident) } else { None } } #[inline] fn get_defined_scope_mut(&mut self, ident: &str) -> Option<&mut GcObject<Scope>> { if let Some(ref mut parent) = self.parent { if parent.defines.contains_key(ident) { Some(parent) } else { parent.get_defined_scope_mut(ident) } } else { None } } #[inline] pub fn define<T: 'static + Sync + Send>(&mut self, ident: String, value: Value<T>) { if let Some(ref mut scope) = self.get_defined_scope_mut(&ident) { scope.defines.insert(ident, Box::new(value)); return; } self.defines.insert(ident, Box::new(value)); } }
use std::iter; use syn::{Ident, DeriveInput, Data, DataStruct, Fields}; use quote::Tokens; use accepts; use composites::Field; use enums::Variant; use overrides::Overrides; pub fn expand_derive_tosql(input: DeriveInput) -> Result<Tokens, String> { let overrides = Overrides::extract(&input.attrs)?; let name = overrides.name.unwrap_or_else(|| input.ident.to_string()); let (accepts_body, to_sql_body) = match input.data { Data::Enum(ref data) => { let variants = data.variants.iter().map(Variant::parse).collect::<Result<Vec<_>, _>>()?; (accepts::enum_body(&name, &variants), enum_body(&input.ident, &variants)) } Data::Struct(DataStruct { fields: Fields::Unnamed(ref fields), .. }) if fields.unnamed.len() == 1 => { let field = fields.unnamed.first().unwrap().into_value(); (accepts::domain_body(&name, &field), domain_body()) } Data::Struct(DataStruct { fields: Fields::Named(ref fields), .. }) => { let fields = fields.named.iter().map(Field::parse).collect::<Result<Vec<_>, _>>()?; (accepts::composite_body(&name, "ToSql", &fields), composite_body(&fields)) } _ => { return Err("#[derive(ToSql)] may only be applied to structs, single field tuple \ structs, and enums".to_owned()) } }; let ident = &input.ident; let out = quote! { impl ::postgres::types::ToSql for #ident { fn to_sql(&self, _type: &::postgres::types::Type, buf: &mut ::std::vec::Vec<u8>) -> ::std::result::Result<::postgres::types::IsNull, ::std::boxed::Box<::std::error::Error + ::std::marker::Sync + ::std::marker::Send>> { #to_sql_body } fn accepts(type_: &::postgres::types::Type) -> bool { #accepts_body } to_sql_checked!(); } }; Ok(out) } fn enum_body(ident: &Ident, variants: &[Variant]) -> Tokens { let idents = iter::repeat(ident); let variant_idents = variants.iter().map(|v| &v.ident); let variant_names = variants.iter().map(|v| &v.name); quote! { let s = match *self { #( #idents::#variant_idents => #variant_names, )* }; buf.extend_from_slice(s.as_bytes()); ::std::result::Result::Ok(::postgres::types::IsNull::No) } } fn domain_body() -> Tokens { quote! { let type_ = match *_type.kind() { ::postgres::types::Kind::Domain(ref type_) => type_, _ => unreachable!(), }; ::postgres::types::ToSql::to_sql(&self.0, type_, buf) } } fn composite_body(fields: &[Field]) -> Tokens { let field_names = fields.iter().map(|f| &f.name); let field_idents = fields.iter().map(|f| &f.ident); quote! { fn write_be_i32<W>(buf: &mut W, n: i32) -> ::std::io::Result<()> where W: ::std::io::Write { let be = [(n >> 24) as u8, (n >> 16) as u8, (n >> 8) as u8, n as u8]; buf.write_all(&be) } let fields = match *_type.kind() { ::postgres::types::Kind::Composite(ref fields) => fields, _ => unreachable!(), }; write_be_i32(buf, fields.len() as i32)?; for field in fields { write_be_i32(buf, field.type_().oid() as i32)?; let base = buf.len(); write_be_i32(buf, 0)?; let r = match field.name() { #( #field_names => { ::postgres::types::ToSql::to_sql(&self.#field_idents, field.type_(), buf) } )* _ => unreachable!(), }; let count = match r? { ::postgres::types::IsNull::Yes => -1, ::postgres::types::IsNull::No => { let len = buf.len() - base - 4; if len > i32::max_value() as usize { return ::std::result::Result::Err( ::std::convert::Into::into("value too large to transmit")); } len as i32 } }; write_be_i32(&mut &mut buf[base..base + 4], count)?; } ::std::result::Result::Ok(::postgres::types::IsNull::No) } }
#[cfg(feature = "windows")] macro_rules! target { () => { "windows" }; } #[cfg(feature = "macos")] macro_rules! target { () => { "macos" }; } #[cfg(feature = "prefix")] macro_rules! target { () => { "prefix" }; } macro_rules! title { () => { concat!( "pahkat v", env!("CARGO_PKG_VERSION"), " (", target!(), ") <https://github.com/divvun/pahkat>" ) }; } pub(crate) const VERSION: &str = concat!( "v", env!("CARGO_PKG_VERSION"), " (", target!(), ")", " <https://github.com/divvun/pahkat>\n\n", "Authors: ", structopt::clap::crate_authors!(), "\n", "License: GPL-3.0 <https://github.com/divvun/pahkat/blob/master/pahkat-cli/LICENSE>", ); pub(crate) const MAIN_TEMPLATE: &str = concat!( title!(), " Usage: {usage} Commands: {subcommands} Options: {unified} " ); pub(crate) const SUB_TEMPLATE: &str = concat!( title!(), " Usage: {usage} Arguments: {positionals} Options: {unified} " ); pub(crate) const SUBN_TEMPLATE: &str = concat!( title!(), " Usage: {usage} Options: {unified} " ); pub(crate) const SUBC_TEMPLATE: &str = concat!( title!(), " Usage: {usage} Commands: {subcommands} Options: {unified} " );
use proconio::input; fn main() { input! { n: i64, k: i64, } let mut a = n; for _ in 1..=k { a = f(a); } println!("{}", a); } fn f(x: i64) -> i64 { g1(x) - g2(x) } fn g1(x: i64) -> i64 { let mut s: Vec<_> = format!("{}", x).chars().collect(); s.sort(); let s: String = s.into_iter().rev().collect(); s.parse().unwrap() } fn g2(x: i64) -> i64 { let mut s: Vec<_> = format!("{}", x).chars().collect(); s.sort(); let s: String = s.into_iter().collect(); s.parse().unwrap() }
use super::component::*; use crate::system::WriteComp; pub trait EntityCommon: PartialEq + Eq{ fn add<'e, 'd: 'e, T: Component>(&'e self, storage: &'e mut WriteComp<'d, T>, comp: T) -> &'e Self; fn remove<'e, 'd: 'e, T: Component>(&'e self, storage: &'e mut WriteComp<'d, T>) -> &'e Self; }
//! copyright (c) 2020 by shaipe //! mod timer; use timer::Timer; fn main() { let mut t = Timer::new(); t.start(|x, interval|{ println!("{:?} -- {:?}", x, interval); }); }
extern crate slack; use date; use reply::CHANNEL; static mut day: &'static str = ""; pub fn send_mention(cli: &mut slack::RtmClient) { let today_string = date::get_day_of_week(); let today = match today_string.as_str() { "Mon" => "月", "Tue" => "火", "Wed" => "水", "Thu" => "木", "Fri" => "金", "Sun" => "土", "Sat" => "日", _ => "", }; unsafe { if day != today { if today == "火" || today == "金" { cli.send_message(CHANNEL, "今日は燃えるゴミの日です!"); } if today == "月" { cli.send_message(CHANNEL, "今日は燃えるゴミ以外の日です!"); } day = today; } } }
#![recursion_limit="1024"] extern crate common; extern crate proc_macro; extern crate proc_macro2; extern crate syn; extern crate quote; use common::{StorageType}; use proc_macro::{TokenStream}; use proc_macro2::{Span}; use syn::{Data, DeriveInput, Ident, Meta, parse_macro_input}; use quote::quote; #[allow(non_snake_case)] #[proc_macro_attribute] pub fn TorchStorage(args : TokenStream, item : TokenStream) -> TokenStream { if args.is_empty() { panic!(" Need exactly one of variant name defined in StorageType enum. For example: #[TensorStorage(THFloatStorage)] struct FloatStorage {} ") } let ty = match parse_macro_input!(args) { Meta::Word(ident) => { StorageType::from_str(&ident.to_string()) }, _ => { panic!(" Need exactly one of variant name defined in StorageType enum. For example: #[TensorStorage(THFloatStorage)] struct FloatStorage {} ") } // Meta::List(idents) => { // print!("Got list=["); // idents.nested.iter().for_each(|meta| { // if let NestedMeta::Meta(Meta::Word(id)) = meta { // print!("{}, ", id); // } else if let NestedMeta::Literal(Lit::Str(id)) = meta { // print!("\"{}\", ", id.value()); // } else { // print!("UNDEFINED"); // } // }); // println!("]") // }, // Meta::NameValue(pairs) => { // if let Lit::Str(v) = pairs.lit { // println!("Got {}={}", pairs.ident, v.value()); // } else { // println!("Got unsupported pair"); // } // } }; let c_ty = ty.to_string(); let c_ty_id = Ident::new(&c_ty, Span::call_site()); let ast = parse_macro_input!(item as DeriveInput); match ast.data { Data::Struct(_) => (), _ => panic!(" This procedural macro support only struct. For example: #[TorchStorage(i8)] struct ByteStorage; ") } let ident = ast.ident; let t = Ident::new(ty.to_ty(), Span::call_site()); let new_fn = Ident::new(&(c_ty.to_owned() + "_new"), Span::call_site()); let new_with_size_fn = Ident::new(&(c_ty.to_owned() + "_newWithSize"), Span::call_site()); let data_fn = Ident::new(&(c_ty.to_owned() + "_data"), Span::call_site()); let fill_fn = Ident::new(&(c_ty.to_owned() + "_fill"), Span::call_site()); let resize_fn = Ident::new(&(c_ty.to_owned() + "_resize"), Span::call_site()); let retain_fn = Ident::new(&(c_ty.to_owned() + "_retain"), Span::call_site()); let size_fn = Ident::new(&(c_ty.to_owned() + "_size"), Span::call_site()); let swap_fn = Ident::new(&(c_ty.to_owned() + "_swap"), Span::call_site()); let free_fn = Ident::new(&(c_ty.to_owned() + "_free"), Span::call_site()); let expanded = quote! { #[repr(C)] pub struct #c_ty_id; #[link(name="caffe2")] extern { fn #new_fn() -> *mut #c_ty_id; fn #new_with_size_fn(size: usize) -> *mut #c_ty_id; fn #data_fn(storage: *mut #c_ty_id) -> *mut #t; fn #fill_fn(storage: *mut #c_ty_id, scalar: #t); fn #resize_fn(storage: *mut #c_ty_id, size: usize); fn #retain_fn(storage: *mut #c_ty_id); fn #size_fn(storage: *const #c_ty_id) -> usize; fn #swap_fn(storage_1: *mut #c_ty_id, storage_2: *mut #c_ty_id); fn #free_fn(storage: *mut #c_ty_id); } pub struct #ident { _data: *mut [#t], forget : bool, storage : *mut #c_ty_id, n : usize } impl #ident { /// Get short description of storage. /// This includes name of storage, size, and /// sample data if it has more than 20 elements. /// If it has less than 20 elements, it'll display /// every elements. fn short_desc(&mut self) -> String { unsafe { let size = self.n; let data = &*self._data; let name = stringify!(#ident); if size > 20 { format!("{}:size={}:first(10)={:?}:last(10)={:?}", name, size, &data[0..10], &data[(data.len() - 10)..data.len()] ) } else { format!("{}:size={}:data={:?}", name, size, data ) } } } /// Unsafe function to retrieve underlying pointer to actual storage. pub unsafe fn storage(&self) -> *mut #c_ty_id { self.storage } /// Alias for short_desc #[inline(always)] fn to_string(&mut self) -> String { self.short_desc() } } impl TensorStorage for #ident { type Datum = #t; fn new() -> Self { unsafe { let storage = #new_fn(); let size = #size_fn(storage); #ident { _data: std::slice::from_raw_parts_mut(#data_fn(storage), size) as *mut [#t], forget: false, storage: storage, n: size } } } fn new_with_size(size: usize) -> Self { unsafe { let storage = #new_with_size_fn(size); #ident { _data: std::slice::from_raw_parts_mut(#data_fn(storage), size) as *mut [#t], forget: false, storage: storage, n: size } } } fn data(&self) -> &[#t] { unsafe { &*self._data } } fn data_mut(&mut self) -> &mut [#t] { unsafe { &mut *self._data } } unsafe fn forget(mut self) -> Self { self.forget = true; self } fn fill(&mut self, value: #t) { self.data_mut().iter_mut().for_each(|v| *v = value); } fn resize(&mut self, size: usize) { self.n = size; unsafe { #resize_fn(self.storage, size); self._data = std::slice::from_raw_parts_mut(#data_fn(self.storage), size) as *mut [#t]; } } fn retain(&mut self) { unsafe { #retain_fn(self.storage); self.n = #size_fn(self.storage); self._data = std::slice::from_raw_parts_mut(#data_fn(self.storage), self.n) as *mut [#t]; } } fn size(&self) -> usize { self.n } fn swap(&mut self, with : Self) { unsafe { // need to call to Caffe2 to ensure that their storage got swap as well #swap_fn(self.storage, with.storage); self.n = with.n; self._data = std::slice::from_raw_parts_mut(#data_fn(self.storage), self.n) as *mut [#t]; } } } /// For each of usage, it return a slice of actual data /// of this struct. For higher throughput, consider using /// [data function](trait.TensorStorage.html#tymethod.data) instead. impl Deref for #ident { type Target = [#t]; fn deref(&self) -> &[#t] { unsafe { &*self._data } } } /// For each of usage, it return mutable slice of actual data /// of this struct. For higher throughput, consider using /// [data function](trait.TensorStorage.html#tymethod.data) instead. impl DerefMut for #ident { fn deref_mut(&mut self) -> &mut [#t] { unsafe { &mut *self._data } } } /// Clean up memory allocated outside of Rust. /// Unless [forget function](trait.TensorStorage.html#tymethod.forget) is called, /// it'll leave underlying storage untouch. impl Drop for #ident { fn drop(&mut self) { unsafe { if !self.forget { #free_fn(self.storage); } } } } impl From<*mut #c_ty_id> for #ident { fn from(c_storage: *mut #c_ty_id) -> #ident { unsafe { let size = #size_fn(c_storage); let data = #data_fn(c_storage); #ident { _data: std::slice::from_raw_parts_mut(data, size) as *mut [#t], forget: false, storage: c_storage, n: size } } } } #[cfg(feature = "serde")] impl Serialize for #ident { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { unsafe { let data = &*self._data; let mut state = serializer.serialize_seq(Some(data.len()))?; for v in data { state.serialize_element(v)?; }; state.end() } } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for #ident { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { struct ElemVisitor; impl<'de> Visitor<'de> for ElemVisitor { type Value = Vec<#t>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "Expecting a sequence of type {}", stringify!(#t)) } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> where A: SeqAccess<'de> { let mut v = match seq.size_hint() { Some(size) => Vec::with_capacity(size), None => Vec::new() }; while let Some(s) = seq.next_element()? { v.push(s); } Ok(v) } } let elems = deserializer.deserialize_seq(ElemVisitor)?; let mut store = #ident::new_with_size(elems.len()); store.iter_mut().zip(elems.iter()).for_each(|(s, e)| *s = *e); Ok(store) } } }; TokenStream::from(expanded) }