text
stringlengths
8
4.13M
use crate::vec3::Vec3; use crate::ray::Ray; pub struct Camera { pub vfov: f64, pub aspect: f64, pub look_from: Vec3, pub look_at: Vec3, pub look_up: Vec3 } impl Camera { pub fn new( look_from: Vec3, look_at: Vec3, look_up: Vec3, vfov: f64, aspect: f64) -> Camera { Camera { look_from, look_at, look_up, vfov, aspect } } pub fn origin(&self) -> Vec3 { self.look_from } pub fn upper_left_corner(&self) -> Vec3 { let half_height = (self.vfov/2.0).tan(); let half_width = half_height * self.aspect; let w = (self.look_from-self.look_at).unit_vector(); let u = Vec3::cross(self.look_up,w).unit_vector(); let v = Vec3::cross(w,u); self.look_from - u*half_width + v*half_height - w } pub fn horizontal(&self) -> Vec3 { let half_width = (self.vfov/2.0).tan() * self.aspect; let w = (self.look_from-self.look_at).unit_vector(); let u = Vec3::cross(self.look_up,w).unit_vector(); u*(2.0*half_width) } pub fn vertical(&self) -> Vec3 { let half_height = (self.vfov/2.0).tan(); let w = (self.look_from-self.look_at).unit_vector(); let u = Vec3::cross(self.look_up,w).unit_vector(); let v = Vec3::cross(w,u); v*(2.0*half_height) } pub fn get_ray( &self, u: f64, v: f64) -> Ray { Ray::new(self.origin() , self.upper_left_corner() + self.horizontal()*u + self.vertical()*(-v)) } }
use wasm_bindgen::prelude::*; use crate::game::*; use crate::ai; use crate::ai::types::*; #[wasm_bindgen] pub struct GameJs { game: Game } #[wasm_bindgen] impl GameJs { pub fn new(random_first_move: bool) -> GameJs { GameJs { game: Game::new(random_first_move) } } pub fn skip_turn(&mut self) { self.game.skip_turn() } pub fn turn(&mut self, relative_hole: usize) -> Option<TurnResult> { self.game.turn(relative_hole) } pub fn game_over(&self) -> bool { self.game.game_over() } pub fn current_player(&self) -> Player { self.game.current_player() } pub fn winner(&self) -> Option<Player> { self.game.winner() } pub fn should_skip_next_move(&self) -> bool { self.game.should_skip_next_move() } pub fn board(&self) -> JsValue { JsValue::from_serde(&self.game.board()).unwrap() } pub fn p1_score(&self) -> usize { self.game.p1_score() } pub fn p2_score(&self) -> usize { self.game.p2_score() } pub fn ai_move(&self, algorithm: Algorithm, tree_depth: usize, heuristics: &JsValue) -> AITurnRes { ai::turn::next_turn(&self.game, &AIConfig { algorithm, tree_depth, heuristics: heuristics.into_serde().unwrap() }) } }
#![recursion_limit = "1000"] extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; use proc_macro::TokenStream; use syn::Ident; use quote::Tokens; #[proc_macro_derive(IntoHeap)] pub fn derive_into_heap(input: TokenStream) -> TokenStream { let source = input.to_string(); let ast = syn::parse_derive_input(&source).unwrap(); let expanded = impl_into_heap(&ast); // Uncomment to debug the generated code... // println!("{:?}", expanded); expanded.parse().unwrap() } fn impl_into_heap(ast: &syn::DeriveInput) -> Tokens { match ast.body { syn::Body::Struct(ref data) => impl_into_heap_for_struct(ast, data), syn::Body::Enum(ref variants) => impl_into_heap_for_enum(ast, variants), } } fn impl_into_heap_for_struct(ast: &syn::DeriveInput, data: &syn::VariantData) -> Tokens { let name = &ast.ident; let name_str: &str = name.as_ref(); let storage_type_name: Ident = Ident::from(name_str.to_string() + "Storage"); let vis = &ast.vis; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let heap_lifetime = &ast.generics .lifetimes .first() .expect("lifetime parameter required") .lifetime; match *data { syn::VariantData::Struct(ref fields) => { let field_vis: &Vec<_> = &fields.iter().map(|f| &f.vis).collect(); let field_names: &Vec<_> = &fields.iter().map(|f| &f.ident).collect(); let field_types: &Vec<_> = &fields.iter().map(|f| &f.ty).collect(); let field_storage_types: Vec<_> = fields .iter() .map(|f| { let field_ty = &f.ty; quote! { <#field_ty as ::cell_gc::traits::IntoHeap<#heap_lifetime>>::In } }) .collect(); // 1. The in-heap representation of the struct. let storage_struct = quote! { #vis struct #storage_type_name #impl_generics #where_clause { #( #field_vis #field_names: #field_storage_types ),* } }; // 2. IntoHeap implementation. // Body of the trace() method. let trace_fields: Vec<Tokens> = fields .iter() .map(|f| { let name = &f.ident; let ty = &f.ty; quote! { <#ty as ::cell_gc::traits::IntoHeap<#heap_lifetime>> ::trace(&storage.#name, tracer); } }) .collect(); // Oddly you can't use the same identifier more than once in the // same loop. So create an alias. let field_names_1 = field_names; let into_heap = quote! { unsafe impl #impl_generics ::cell_gc::traits::IntoHeap<#heap_lifetime> for #name #ty_generics #where_clause { type In = #storage_type_name #ty_generics; fn into_heap(self) -> Self::In { #storage_type_name { #( #field_names: ::cell_gc::traits::IntoHeap::into_heap( self.#field_names_1) ),* } } unsafe fn trace<R>(storage: &Self::In, tracer: &mut R) where R: ::cell_gc::traits::Tracer { #( #trace_fields )* // Quiet unused variable warnings when `$(...)*` expands // to nothing. let _ = tracer; } unsafe fn from_heap(storage: &Self::In) -> Self { #name { #( #field_names: ::cell_gc::traits::IntoHeap::from_heap( &storage.#field_names_1) ),* } } } }; // 3. IntoHeapAllocation implementation. let ref_type_name: Ident = Ident::from(name_str.to_string() + "Ref"); let into_heap_allocation = quote! { impl #impl_generics ::cell_gc::traits::IntoHeapAllocation<#heap_lifetime> for #name #ty_generics #where_clause { type Ref = #ref_type_name #ty_generics; fn wrap_gcref(gcref: ::cell_gc::GcRef<#heap_lifetime, #name #ty_generics>) -> #ref_type_name #ty_generics { #ref_type_name(gcref) } } }; // 4. #ref_type_name: A safe reference to the struct let ref_type = quote! { #[derive(Clone, Debug, PartialEq, Eq)] #vis struct #ref_type_name #impl_generics (::cell_gc::GcRef<#heap_lifetime, #name #ty_generics>) #where_clause; }; // 5. The ref type also gets an IntoHeap impl... let ref_type_into_heap = quote! { unsafe impl #impl_generics ::cell_gc::traits::IntoHeap<#heap_lifetime> for #ref_type_name #ty_generics #where_clause { type In = ::cell_gc::ptr::Pointer<#storage_type_name #ty_generics>; fn into_heap(self) -> Self::In { self.0.ptr() } unsafe fn trace<R>(storage: &Self::In, tracer: &mut R) where R: ::cell_gc::traits::Tracer { if !storage.is_null() { tracer.visit::<#name #ty_generics>(*storage); } } unsafe fn from_heap(storage: &Self::In) -> #ref_type_name #ty_generics { #ref_type_name(::cell_gc::GcRef::<#name #ty_generics>::new(*storage)) } } }; // 6. Getters and setters. let field_setter_names: Vec<_> = fields .iter() .map(|f| { let field_str: &str = f.ident.as_ref().unwrap().as_ref(); Ident::from(format!("set_{}", field_str)) }) .collect(); let accessors = quote! { impl #impl_generics #ref_type_name #ty_generics #where_clause { #( #[allow(dead_code)] #field_vis fn #field_names(&self) -> #field_types { let ptr = self.0.as_ptr(); unsafe { ::cell_gc::traits::IntoHeap::from_heap( &(*ptr).#field_names_1) } } )* #( #[allow(dead_code)] #field_vis fn #field_setter_names(&self, v: #field_types) { let ptr = self.0.as_mut_ptr(); let u = ::cell_gc::traits::IntoHeap::into_heap(v); unsafe { (*ptr).#field_names = u; } } )* ///// Get all fields at once. //pub fn get(&self) -> #name { // ::cell_gc::traits::IntoHeap::from_heap(ptr) //} #[allow(dead_code)] pub fn as_mut_ptr(&self) -> *mut #storage_type_name #ty_generics { self.0.as_mut_ptr() } } }; quote! { #storage_struct #into_heap #into_heap_allocation #ref_type #ref_type_into_heap #accessors } } syn::VariantData::Tuple(ref _fields) => { panic!("#[derive(IntoHeap)] does not support tuple structs"); } syn::VariantData::Unit => { panic!("#[derive(IntoHeap)] does not support unit structs"); } } } fn impl_into_heap_for_enum(ast: &syn::DeriveInput, variants: &[syn::Variant]) -> Tokens { let attrs = &ast.attrs; let name = &ast.ident; let name_str: &str = name.as_ref(); let storage_type_name: Ident = Ident::from(name_str.to_string() + "Storage"); let vis = &ast.vis; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let heap_lifetime = &ast.generics .lifetimes .first() .expect("lifetime parameter required") .lifetime; let variant_storage = variants.iter().map(|v| { let attrs = &v.attrs; let ident = &v.ident; if v.discriminant.is_some() { panic!("#[derive(IntoHeap)] does not support enum variants with discriminants"); } match v.data { syn::VariantData::Struct(ref fields) => { let field_decls = fields.iter().map(|f| { let field_attrs = &f.attrs; let field_name = &f.ident; let field_ty = &f.ty; quote! { #( #field_attrs )* #field_name: <#field_ty as ::cell_gc::traits::IntoHeap<#heap_lifetime>>::In } }); quote! { #( #attrs )* #ident { #( #field_decls ),* } } } syn::VariantData::Tuple(ref fields) => { let field_decls = fields.iter().map(|f| { let field_ty = &f.ty; let field_attrs = &f.attrs; quote! { #( #field_attrs )* <#field_ty as ::cell_gc::traits::IntoHeap<#heap_lifetime>>::In } }); quote! { #( #attrs )* #ident( #( #field_decls ),* ) } } syn::VariantData::Unit => { quote! { #( #attrs )* #ident } } } }); let storage_enum = quote! { #( #attrs )* #vis enum #storage_type_name #impl_generics #where_clause { #( #variant_storage ),* } }; let into_heap_arms = variants.iter().map(|v| { let ident = &v.ident; match v.data { syn::VariantData::Struct(ref fields) => { let field_names: &Vec<_> = &fields.iter().map(|f| &f.ident).collect(); let field_names_1 = field_names; let field_types = fields.iter().map(|f| &f.ty); quote! { #name::#ident { #(#field_names),* } => { #storage_type_name::#ident { #( #field_names: <#field_types as ::cell_gc::traits::IntoHeap> ::into_heap(#field_names_1) ),* } } } } syn::VariantData::Tuple(ref fields) => { let field_types = fields.iter().map(|f| &f.ty); let bindings: &Vec<Ident> = &(0..fields.len()) .map(|n| Ident::from(format!("x{}", n))) .collect(); quote! { #name::#ident( #(#bindings),* ) => { #storage_type_name::#ident( #( <#field_types as ::cell_gc::traits::IntoHeap> ::into_heap(#bindings) ),* ) } } } syn::VariantData::Unit => { quote! { #name::#ident => #storage_type_name::#ident } } } }); let from_heap_arms = variants.iter().map(|v| { let ident = &v.ident; match v.data { syn::VariantData::Struct(ref fields) => { let field_names: &Vec<_> = &fields.iter().map(|f| &f.ident).collect(); let field_names_1 = field_names; let field_types = fields.iter().map(|f| &f.ty); quote! { #storage_type_name::#ident { #(ref #field_names),* } => { #name::#ident { #( #field_names: <#field_types as ::cell_gc::traits::IntoHeap> ::from_heap(#field_names_1) ),* } } } } syn::VariantData::Tuple(ref fields) => { let field_types = fields.iter().map(|f| &f.ty); let bindings: &Vec<Ident> = &(0..fields.len()) .map(|n| Ident::from(format!("x{}", n))) .collect(); quote! { #storage_type_name::#ident( #(ref #bindings),* ) => { #name::#ident( #( <#field_types as ::cell_gc::traits::IntoHeap> ::from_heap(#bindings) ),* ) } } } syn::VariantData::Unit => { quote! { #storage_type_name::#ident => #name::#ident } } } }); let trace_arms = variants.iter().map(|v| { let ident = &v.ident; match v.data { syn::VariantData::Struct(ref fields) => { let field_names: &Vec<_> = &fields.iter().map(|f| &f.ident).collect(); let field_types = fields.iter().map(|f| &f.ty); quote! { #storage_type_name::#ident { #(ref #field_names),* } => { #( <#field_types as ::cell_gc::traits::IntoHeap> ::trace(#field_names, tracer); )* } } } syn::VariantData::Tuple(ref fields) => { let field_types = fields.iter().map(|f| &f.ty); let bindings: &Vec<Ident> = &(0..fields.len()) .map(|n| Ident::from(format!("x{}", n))) .collect(); quote! { #storage_type_name::#ident( #(ref #bindings),* ) => { #( <#field_types as ::cell_gc::traits::IntoHeap> ::trace(#bindings, tracer); )* } } } syn::VariantData::Unit => { quote! { #storage_type_name::#ident => () } } } }); let into_heap = quote! { unsafe impl #impl_generics ::cell_gc::traits::IntoHeap<#heap_lifetime> for #name #ty_generics #where_clause { type In = #storage_type_name #ty_generics; fn into_heap(self) -> Self::In { match self { #( #into_heap_arms ),* } } unsafe fn from_heap(storage: &Self::In) -> Self { match *storage { #( #from_heap_arms ),* } } unsafe fn trace<R>(storage: &Self::In, tracer: &mut R) where R: ::cell_gc::traits::Tracer { match *storage { #( #trace_arms ),* } // Quiet unused variable warnings when `$(...)*` expands to // nothing. let _ = tracer; } } }; quote! { #storage_enum #into_heap } }
use crate::*; extern "C" { type MlirSymbolTable; } /// This enum represents the visibility of a symbol in a symbol table #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[repr(u32)] pub enum Visibility { /// The symbol is public and may be referenced anywhere internal or external /// to the visible references in the IR. Public = 0, /// The symbol is private and may only be referenced by SymbolRefAttrs local /// to the operations within the current symbol table. Private, /// The symbol is visible to the current IR, which may include operations in /// symbol tables above the one that owns the current symbol. `Nested` /// visibility allows for referencing a symbol outside of its current symbol /// table, while retaining the ability to observe all uses. Nested, } /// The `SymbolTable` API provides facilities for looking up symbols in the current /// symbol table, or in other symbol tables, and setting symbol names and visibility. #[repr(transparent)] #[derive(Copy, Clone)] pub struct SymbolTable(*const MlirSymbolTable); impl SymbolTable { #[inline] pub fn is_null(&self) -> bool { self.0.is_null() } /// Creates a symbol table for the given operation. /// /// If the operation does not have the C++ SymbolTable trait, returns None pub fn create<O: Operation>(op: O) -> Option<Self> { let this = unsafe { mlir_symbol_table_create(op.base()) }; if this.is_null() { None } else { Some(this) } } /// Destroys this symbol table /// /// NOTE: This does not affect operations in the table pub fn destroy(self) { unsafe { mlir_symbol_table_destroy(self) } } /// Looks up a symbol with the given name in this symbol table and /// returns the operation that corresponds to it. /// /// If the symbol cannot be found, returns None pub fn lookup<S: Into<StringRef>>(&self, name: S) -> Option<OperationBase> { let name = name.into(); let op = unsafe { mlir_symbol_table_lookup(*self, name) }; if op.is_null() { None } else { Some(op) } } /// Inserts the given operation in this symbol table. /// /// The operation must have the C++ Symbol trait. /// /// If the symbol table already has a symbol with the same name, renames /// the symbol being inserted to ensure uniqueness. NOTE: This does not move /// the operation itself into the block of the operation holding the symbol table, /// this should be done separately. /// /// Returns the name of the symbol after insertion. pub fn insert<O: Operation>(&self, op: O) -> StringAttr { unsafe { mlir_symbol_table_insert(*self, op.base()) } } /// Removes the given operation from this symbol table pub fn erase<O: Operation>(&self, op: O) { unsafe { mlir_symbol_table_erase(*self, op.base()) } } /// Returns the nearest Operation that is a symbol table, if one exists pub fn get_nearest<O: Operation>(from: O) -> Option<OperationBase> { let op = unsafe { mlir_symbol_table_get_nearest_symbol_table(from.base()) }; if op.is_null() { None } else { Some(op) } } /// Returns the nearest Operation that has the given symbol name, if it exists pub fn lookup_nearest_symbol_from<O: Operation, S: Into<StringRef>>( from: O, symbol: S, ) -> Option<OperationBase> { let op = unsafe { mlir_symbol_table_lookup_nearest_symbol_from(from.base(), symbol.into()) }; if op.is_null() { None } else { Some(op) } } /// Returns the symbol with the given name, in the symbol table of the provided Operation, if it /// exists pub fn lookup_symbol_in<O: Operation, S: Into<StringRef>>( op: O, symbol: S, ) -> Option<OperationBase> { let op = unsafe { mlir_symbol_table_lookup_in(op.base(), symbol.into()) }; if op.is_null() { None } else { Some(op) } } /// Return whether the given symbol is known to have no uses that are nested /// within the given operation 'from'. This does not traverse into any nested /// symbol tables. This function will also return false if there are any /// unknown operations that may potentially be symbol tables. This doesn't /// necessarily mean that there are no uses, we just can't conservatively /// prove it. pub fn has_uses_from<O: Operation, S: Into<StringRef>>(from: O, symbol: S) -> bool { unsafe { mlir_symbol_table_known_use_empty(symbol.into(), from.base()) } } /// Attempt to replace all uses that are nested within the given operation with symbol `old`, /// with symbol `new`. /// /// This does not traverse into nested symbol tables. /// /// Will fail atomically if there are any unknown operations that may be potential symbol tables. pub fn replace_all_uses<O: Operation, S: Into<StringRef>>(from: O, old: S, new: S) -> bool { let result = unsafe { mlir_symbol_table_replace_all_symbol_uses(old.into(), new.into(), from.base()) }; result.into() } /// Get the symbol name for the given Operation pub fn get_symbol_name<O: Operation>(op: O) -> StringRef { unsafe { mlir_symbol_table_get_symbol_name(op.base()) } } /// Set the symbol name for the given Operation pub fn set_symbol_name<O: Operation, S: Into<StringRef>>(op: O, name: S) { unsafe { mlir_symbol_table_set_symbol_name(op.base(), name.into()); } } /// Get the symbol visibility for the given Operation pub fn get_symbol_visibility<O: Operation>(op: O) -> Visibility { unsafe { mlir_symbol_table_get_symbol_visibility(op.base()) } } /// Set the symbol visibility for the given Operation pub fn set_symbol_visibility<O: Operation>(op: O, visibility: Visibility) { unsafe { mlir_symbol_table_set_symbol_visibility(op.base(), visibility); } } /// Get the attribute name used to store symbol names on an Operation pub fn get_symbol_attr_name() -> &'static str { // The string reference returned here is known to be utf-8, and have static lifetime let sr = unsafe { mlir_symbol_table_get_symbol_attr_name() }; let s = sr.try_into().unwrap(); unsafe { core::mem::transmute::<&str, &'static str>(s) } } /// Get the attribute name used to store symbol visibility on an Operation pub fn get_symbol_visibility_name() -> &'static str { // The string reference returned here is known to be utf-8, and have static lifetime let sr = unsafe { mlir_symbol_table_get_visibility_attr_name() }; let s = sr.try_into().unwrap(); unsafe { core::mem::transmute::<&str, &'static str>(s) } } } extern "C" { #[link_name = "mlirSymbolTableCreate"] fn mlir_symbol_table_create(op: OperationBase) -> SymbolTable; #[link_name = "mlirSymbolTableDestroy"] fn mlir_symbol_table_destroy(table: SymbolTable); #[link_name = "mlirSymbolTableLookup"] fn mlir_symbol_table_lookup(table: SymbolTable, name: StringRef) -> OperationBase; #[link_name = "mlirSymbolTableInsert"] fn mlir_symbol_table_insert(table: SymbolTable, op: OperationBase) -> StringAttr; #[link_name = "mlirSymbolTableErase"] fn mlir_symbol_table_erase(table: SymbolTable, op: OperationBase); #[link_name = "mlirSymbolTableGetNearestSymbolTable"] fn mlir_symbol_table_get_nearest_symbol_table(from: OperationBase) -> OperationBase; #[link_name = "mlirSymbolTableLookupNearestSymbolFrom"] fn mlir_symbol_table_lookup_nearest_symbol_from( from: OperationBase, symbol: StringRef, ) -> OperationBase; #[link_name = "mlirSymbolTableLookupIn"] fn mlir_symbol_table_lookup_in(op: OperationBase, symbol: StringRef) -> OperationBase; #[link_name = "mlirSymbolTableSymbolKnownUseEmpty"] fn mlir_symbol_table_known_use_empty(symbol: StringRef, from: OperationBase) -> bool; #[link_name = "mlirSymbolTableReplaceAllSymbolUses"] fn mlir_symbol_table_replace_all_symbol_uses( old: StringRef, new: StringRef, from: OperationBase, ) -> LogicalResult; #[link_name = "mlirSymbolTableGetSymbolVisibility"] fn mlir_symbol_table_get_symbol_visibility(symbol: OperationBase) -> Visibility; #[link_name = "mlirSymbolTableSetSymbolVisibility"] fn mlir_symbol_table_set_symbol_visibility(symbol: OperationBase, visibility: Visibility); #[link_name = "mlirSymbolTableGetSymbolName"] fn mlir_symbol_table_get_symbol_name(symbol: OperationBase) -> StringRef; #[link_name = "mlirSymbolTableSetSymbolName"] fn mlir_symbol_table_set_symbol_name(symbol: OperationBase, name: StringRef); #[link_name = "mlirSymbolTableGetSymbolAttributeName"] fn mlir_symbol_table_get_symbol_attr_name() -> StringRef; #[link_name = "mlirSymbolTableGetVisibilityAttributeName"] fn mlir_symbol_table_get_visibility_attr_name() -> StringRef; }
#[macro_use] extern crate actix_web; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; mod chunker; mod db; mod external_id; mod graphql_schema; mod graphql_service; mod mk_certs; mod models; mod playlists_service; mod prng; mod schema; mod tracks_service; use std::sync::Arc; use actix_files::Files; use actix_web::{ dev::ServiceRequest, error, web::{self, Data}, App, Error, HttpResponse, HttpServer, }; use actix_web_httpauth::{extractors::basic::BasicAuth, middleware::HttpAuthentication}; use actix_web_middleware_redirect_scheme::RedirectSchemeBuilder; use actix_web_static_files; use clap::{self, value_t}; use diesel::prelude::*; use graphql_schema::{create_schema, RequestContext}; use mk_certs::{mk_ca_cert, mk_ca_signed_cert}; use models::User; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use schema::users; use sha2::{Digest, Sha256}; async fn validator(req: ServiceRequest, credentials: BasicAuth) -> Result<ServiceRequest, Error> { let valid = { let mut valid = false; if let Some(context) = req.app_data::<Data<RequestContext>>() { let conn = context.pool.get().unwrap(); if let Ok(user) = users::table .find(credentials.user_id()) .get_result::<User>(&conn) { let hash = Sha256::digest( credentials .password() .map(|password| password.as_bytes()) .unwrap_or_default(), ); valid = user.password == hash.as_slice(); } } valid }; if valid { Ok(req) } else { Err(error::ErrorUnauthorized("")) } } #[actix_rt::main] async fn main() -> std::io::Result<()> { let matches = clap::App::new("pitunes") .version("0.1.0") .about("A Raspberry Pi compatible tool to manage and stream your personal music collection remotely.") .author("Bernhard Fritz <bernhard.e.fritz@gmail.com>") .arg( clap::Arg::with_name("http-port") .short("p") .long("http-port") .value_name("HTTP PORT") .help("HTTP port to use (defaults to 8080)") .takes_value(true), ) .arg( clap::Arg::with_name("https-port") .short("s") .long("https-port") .value_name("HTTPS PORT") .help("HTTPS port to use (defaults to 8443)") .takes_value(true), ) .arg( clap::Arg::with_name("cert") .short("c") .long("cert") .value_name("FILE") .help("Certificate to use (defaults to self-signed)") ) .arg( clap::Arg::with_name("key") .short("k") .long("key") .value_name("FILE") .help("Private key to use (defaults to self-signed)") ) .arg( clap::Arg::with_name("redirect-http-to-https") .short("r") .long("redirect-http-to-https") .value_name("BOOL") .help("Redirect HTTP to HTTPS (defaults to true)") ) .get_matches(); let http_port = value_t!(matches, "http-port", u16).unwrap_or(8080); let https_port = value_t!(matches, "https-port", u16).unwrap_or(8443); let cert = value_t!(matches, "cert", String); let key = value_t!(matches, "key", String); let redirect_http_to_https = value_t!(matches, "redirect-http-to-https", bool).unwrap_or(true); let config_dir = { let mut config_dir = dirs::config_dir().unwrap(); config_dir.push("pitunes"); config_dir }; let tracks_dir = { let mut tracks_dir = config_dir.clone(); tracks_dir.push("tracks"); std::fs::create_dir_all(tracks_dir.as_path())?; tracks_dir }; // r2d2 pool let pool = { let pitunes_db = { let mut pitunes_db = config_dir.clone(); pitunes_db.push("pitunes"); pitunes_db.set_extension("db"); pitunes_db.into_os_string().into_string().unwrap() }; db::establish_connection(&pitunes_db[..]) }; let st = Arc::new(create_schema()); // load ssl keys let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); if let (Ok(cert), Ok(key)) = (cert, key) { builder.set_private_key_file(key, SslFiletype::PEM).unwrap(); builder.set_certificate_chain_file(cert).unwrap(); } else { let (ca_cert, ca_privkey) = mk_ca_cert().unwrap(); let (cert, _privkey) = mk_ca_signed_cert(&ca_cert, &ca_privkey).unwrap(); builder.set_private_key(&_privkey).unwrap(); builder.set_certificate(&cert).unwrap(); } let http_server = HttpServer::new(move || { let ctx = RequestContext::new(pool.clone(), tracks_dir.clone()); let auth = HttpAuthentication::basic(validator); let pitunes_frontend = pitunes_frontend::generate(); App::new() .wrap(auth) .wrap(RedirectSchemeBuilder::new().replacements(&[(format!(":{}", http_port), format!(":{}", https_port))]).enable(redirect_http_to_https).build()) .data(st.clone()) .data(ctx) .service( web::scope("/api") .service(graphql_service::graphql) .service(tracks_service::post_tracks) .service(playlists_service::get_playlist) .service(Files::new("/tracks", tracks_dir.clone())) .service( web::resource("/tracks/{id}.mp3") .name("get_track") .to(|| HttpResponse::NotFound()), ), // only used for resource url generation ) .service( actix_web_static_files::ResourceFiles::new("/", pitunes_frontend) .resolve_not_found_to_root(), ) }) .bind(format!("0.0.0.0:{}", http_port))? .bind_openssl(format!("0.0.0.0:{}", https_port), builder)?; println!( r#" _ _____ _ __ (_)_ _| _ _ __ ___ ___ | '_ \| | | || | | | '_ \ / _ \/ __| | |_) | | | || |_| | | | | __/\__ \ | .__/|_| |_| \__,_|_| |_|\___||___/ v{} |_| "#, env!("CARGO_PKG_VERSION") ); for (addrs, scheme) in http_server.addrs_with_scheme() { println!("Listening on {}://{}", scheme, addrs); } http_server.run().await }
use crate::hal::time::Hertz; use crate::hal::time::U32Ext; use alloc::string::String; use alloc::vec::Vec; use embedded_hal::timer::CountDown; pub type Result<T> = core::result::Result<T, crate::io::Error>; #[derive(Debug)] pub enum Error { Timeout, EOF, WriteError, ReadError, Other(String), BufferFull, NoIoDevice, NoNetwork, DeviceBusy, } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { match self { Error::Timeout => write!(f, "timeout"), Error::EOF => write!(f, "end of file"), Error::WriteError => write!(f, "write error"), Error::ReadError => write!(f, "read error"), Error::Other(detail) => write!(f, "error {}", detail), Error::BufferFull => write!(f, "buffer full"), Error::NoIoDevice => write!(f, "no io device"), Error::NoNetwork => write!(f, "no network"), Error::DeviceBusy => write!(f, "device is busy"), } } } pub struct TimeoutReader<'a, R, TIM>(pub &'a mut R, pub &'a mut TIM); impl<'a, R, TIM> TimeoutReader<'a, R, TIM> where R: embedded_hal::serial::Read<u8>, TIM: CountDown<Time = Hertz>, { pub fn read_line(&mut self, milliseconds: u32) -> Result<String> { let mut str = String::new(); let buf = unsafe { str.as_mut_vec() }; self.read_until('\n' as u8, buf, milliseconds)?; Ok(str) } pub fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>, milliseconds: u32) -> Result<usize> { let mut read = 0; self.1.start(1.khz()); let mut timeout = 0; loop { match self.0.read() { Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(_e)) => { return Err(Error::ReadError); } Ok(b) => { buf.push(b); read += 1; if byte == b { return Ok(read); } } } nb::block!(self.1.wait()).ok(); timeout += 1; if timeout >= milliseconds { return Err(Error::Timeout); } } } pub fn read_exact(&mut self, buf: &mut [u8], milliseconds: u32) -> Result<()> { self.1.start(1.khz()); let len = buf.len(); let mut i = 0; let mut timeout = 0; loop { match self.0.read() { Ok(r) => { buf[i] = r; i += 1; if i == len { return Ok(()); } } Err(nb::Error::WouldBlock) => { timeout += 1; } Err(_err) => return Err(Error::ReadError), } match self.1.wait() { Err(nb::Error::Other(_e)) => { unreachable!() } Err(nb::Error::WouldBlock) => continue, Ok(()) => { if timeout == milliseconds { return Err(Error::Timeout); } self.1.start(1.khz()); } } } } } pub trait BufRead: embedded_hal::serial::Read<u8> { fn read_line(&mut self) -> Result<String> { let mut str = String::new(); let buf = unsafe { str.as_mut_vec() }; self.read_until('\n' as u8, buf)?; Ok(str) } fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> { let mut read = 0; loop { match nb::block!(self.read()) { Ok(b) => { buf.push(b); read += 1; if b == byte { break; } } Err(_err) => return Err(Error::ReadError), } } Ok(read) } fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> { buf.iter_mut() .try_for_each(|b| match nb::block!(self.read()) { Ok(r) => { *b = r; Ok(()) } Err(_err) => return Err(Error::ReadError), }) } }
mod term; use std::io; use std::str::FromStr; fn main() { let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(_) => { match term::Term::from_str(&input) { Ok(t) => { println!("{}", term::normal_form(&t, term::Strategy::Normal)); } Err(error) => { println!("error: {:?}", error); } } } Err(error) => { println!("error: {}", error); } } }
extern crate math; use math::round; use std::cmp::Ordering; use std::mem; // courtesy of https://stackoverflow.com/a/28294764 fn swap<T>(x: &mut Vec<T>, i: usize, j: usize) { let (lo, hi) = match i.cmp(&j) { // no swapping necessary Ordering::Equal => return, // get the smallest and largest of the two indices Ordering::Less => (i, j), Ordering::Greater => (j ,i), }; let (init, tail) = x.split_at_mut(hi); mem::swap(&mut init[lo], &mut tail[0]); } // Constructs a heap from elements of a given array by the bottom-up algorithm // Input: An array h[1..n] of orderable items // Output: A heap h[1..n] fn heap_bottom_up(h: &mut Vec<u8>) { let n = h.len(); let nh = round::floor(n as f64 / 2.0, 0) as usize; for i in 1..(nh + 1) { let mut k = nh - i + 1; let v = h[k - 1]; let mut heap = false; while !heap && (2 * k) <= n { let mut j = 2 * k; if j < n { // there are two children if h[j - 1] < h[j] { j = j + 1; } } if v >= h[j - 1] { heap = true; } else { h[k - 1] = h[j - 1]; k = j; } } h[k - 1] = v; } } fn heapsort(h: &mut Vec<u8>) { // construct a heap for a given array heap_bottom_up(h); // apply the root-deletion operation n-1 times to the remaining heap let n = h.len(); for i in 0..(n-1) { // exchange the root's key with the last key k of the heap swap::<u8>(h, 0, n - 1 - i); // verify the parental dominance for k let mut hn = Vec::<u8>::from(&h[0..(n - 1 - i)]); heap_bottom_up(&mut hn); for j in 0..(n-1-i) { h[j] = hn[j]; } } } fn main() { // sort example array from book let mut h = vec![2, 9, 7, 6, 5, 8]; println!("Array before heapsort: {:?}", h); heapsort(&mut h); println!("Array after heapsort: {:?}", h); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationActivation(pub ::windows::core::IUnknown); impl IWebApplicationActivation { pub unsafe fn CancelPendingActivation(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationActivation { type Vtable = IWebApplicationActivation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbcdcd0de_330e_481b_b843_4898a6a8ebac); } impl ::core::convert::From<IWebApplicationActivation> for ::windows::core::IUnknown { fn from(value: IWebApplicationActivation) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationActivation> for ::windows::core::IUnknown { fn from(value: &IWebApplicationActivation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationActivation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationActivation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationActivation_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationAuthoringMode(pub ::windows::core::IUnknown); impl IWebApplicationAuthoringMode { pub unsafe fn QueryService(&self, guidservice: *const ::windows::core::GUID, riid: *const ::windows::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(guidservice), ::core::mem::transmute(riid), ::core::mem::transmute(ppvobject)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn AuthoringClientBinary(&self) -> ::windows::core::Result<super::super::super::super::Foundation::BSTR> { let mut result__: <super::super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::super::Foundation::BSTR>(result__) } } unsafe impl ::windows::core::Interface for IWebApplicationAuthoringMode { type Vtable = IWebApplicationAuthoringMode_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x720aea93_1964_4db0_b005_29eb9e2b18a9); } impl ::core::convert::From<IWebApplicationAuthoringMode> for ::windows::core::IUnknown { fn from(value: IWebApplicationAuthoringMode) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationAuthoringMode> for ::windows::core::IUnknown { fn from(value: &IWebApplicationAuthoringMode) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationAuthoringMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationAuthoringMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<IWebApplicationAuthoringMode> for super::super::super::Com::IServiceProvider { fn from(value: IWebApplicationAuthoringMode) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<&IWebApplicationAuthoringMode> for super::super::super::Com::IServiceProvider { fn from(value: &IWebApplicationAuthoringMode) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Com::IServiceProvider> for IWebApplicationAuthoringMode { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Com::IServiceProvider> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::super::Com::IServiceProvider> for &IWebApplicationAuthoringMode { fn into_param(self) -> ::windows::core::Param<'a, super::super::super::Com::IServiceProvider> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationAuthoringMode_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, guidservice: *const ::windows::core::GUID, riid: *const ::windows::core::GUID, ppvobject: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, designmodedllpath: *mut ::core::mem::ManuallyDrop<super::super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationHost(pub ::windows::core::IUnknown); impl IWebApplicationHost { #[cfg(feature = "Win32_Foundation")] pub unsafe fn HWND(&self, hwnd: *mut super::super::super::super::Foundation::HWND) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(hwnd)).ok() } #[cfg(feature = "Win32_Web_MsHtml")] pub unsafe fn Document(&self) -> ::windows::core::Result<super::super::super::super::Web::MsHtml::IHTMLDocument2> { let mut result__: <super::super::super::super::Web::MsHtml::IHTMLDocument2 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::super::Web::MsHtml::IHTMLDocument2>(result__) } pub unsafe fn Refresh(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Advise<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, interfaceid: *const ::windows::core::GUID, callback: Param1, cookie: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(interfaceid), callback.into_param().abi(), ::core::mem::transmute(cookie)).ok() } pub unsafe fn Unadvise(&self, cookie: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(cookie)).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationHost { type Vtable = IWebApplicationHost_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcecbd2c3_a3a5_4749_9681_20e9161c6794); } impl ::core::convert::From<IWebApplicationHost> for ::windows::core::IUnknown { fn from(value: IWebApplicationHost) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationHost> for ::windows::core::IUnknown { fn from(value: &IWebApplicationHost) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationHost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationHost { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationHost_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hwnd: *mut super::super::super::super::Foundation::HWND) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Web_MsHtml")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmldocument: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Web_MsHtml"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, interfaceid: *const ::windows::core::GUID, callback: ::windows::core::RawPtr, cookie: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationNavigationEvents(pub ::windows::core::IUnknown); impl IWebApplicationNavigationEvents { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe fn BeforeNavigate<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>>(&self, htmlwindow: Param0, url: Param1, navigationflags: u32, targetframename: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi(), url.into_param().abi(), ::core::mem::transmute(navigationflags), targetframename.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe fn NavigateComplete<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>>(&self, htmlwindow: Param0, url: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi(), url.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe fn NavigateError<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>>(&self, htmlwindow: Param0, url: Param1, targetframename: Param2, statuscode: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi(), url.into_param().abi(), targetframename.into_param().abi(), ::core::mem::transmute(statuscode)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe fn DocumentComplete<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>>(&self, htmlwindow: Param0, url: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi(), url.into_param().abi()).ok() } pub unsafe fn DownloadBegin(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn DownloadComplete(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationNavigationEvents { type Vtable = IWebApplicationNavigationEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc22615d2_d318_4da2_8422_1fcaf77b10e4); } impl ::core::convert::From<IWebApplicationNavigationEvents> for ::windows::core::IUnknown { fn from(value: IWebApplicationNavigationEvents) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationNavigationEvents> for ::windows::core::IUnknown { fn from(value: &IWebApplicationNavigationEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationNavigationEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationNavigationEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationNavigationEvents_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr, url: super::super::super::super::Foundation::PWSTR, navigationflags: u32, targetframename: super::super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr, url: super::super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr, url: super::super::super::super::Foundation::PWSTR, targetframename: super::super::super::super::Foundation::PWSTR, statuscode: u32) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr, url: super::super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationScriptEvents(pub ::windows::core::IUnknown); impl IWebApplicationScriptEvents { #[cfg(feature = "Win32_Web_MsHtml")] pub unsafe fn BeforeScriptExecute<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>>(&self, htmlwindow: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe fn ScriptError<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Web::MsHtml::IHTMLWindow2>, Param1: ::windows::core::IntoParam<'a, super::IActiveScriptError>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::BOOL>>(&self, htmlwindow: Param0, scripterror: Param1, url: Param2, errorhandled: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), htmlwindow.into_param().abi(), scripterror.into_param().abi(), url.into_param().abi(), errorhandled.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationScriptEvents { type Vtable = IWebApplicationScriptEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7c3f6998_1567_4bba_b52b_48d32141d613); } impl ::core::convert::From<IWebApplicationScriptEvents> for ::windows::core::IUnknown { fn from(value: IWebApplicationScriptEvents) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationScriptEvents> for ::windows::core::IUnknown { fn from(value: &IWebApplicationScriptEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationScriptEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationScriptEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationScriptEvents_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Web_MsHtml")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Web_MsHtml"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, htmlwindow: ::windows::core::RawPtr, scripterror: ::windows::core::RawPtr, url: super::super::super::super::Foundation::PWSTR, errorhandled: super::super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Web_MsHtml")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationUIEvents(pub ::windows::core::IUnknown); impl IWebApplicationUIEvents { pub unsafe fn SecurityProblem(&self, securityproblem: u32, result: *mut ::windows::core::HRESULT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(securityproblem), ::core::mem::transmute(result)).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationUIEvents { type Vtable = IWebApplicationUIEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5b2b3f99_328c_41d5_a6f7_7483ed8e71dd); } impl ::core::convert::From<IWebApplicationUIEvents> for ::windows::core::IUnknown { fn from(value: IWebApplicationUIEvents) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationUIEvents> for ::windows::core::IUnknown { fn from(value: &IWebApplicationUIEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationUIEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationUIEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationUIEvents_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, securityproblem: u32, result: *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWebApplicationUpdateEvents(pub ::windows::core::IUnknown); impl IWebApplicationUpdateEvents { pub unsafe fn OnPaint(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn OnCssChanged(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IWebApplicationUpdateEvents { type Vtable = IWebApplicationUpdateEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e59e6b7_c652_4daf_ad5e_16feb350cde3); } impl ::core::convert::From<IWebApplicationUpdateEvents> for ::windows::core::IUnknown { fn from(value: IWebApplicationUpdateEvents) -> Self { value.0 } } impl ::core::convert::From<&IWebApplicationUpdateEvents> for ::windows::core::IUnknown { fn from(value: &IWebApplicationUpdateEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWebApplicationUpdateEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWebApplicationUpdateEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWebApplicationUpdateEvents_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); pub type RegisterAuthoringClientFunctionType = unsafe extern "system" fn(authoringmodeobject: ::windows::core::RawPtr, host: ::windows::core::RawPtr) -> ::windows::core::HRESULT; pub type UnregisterAuthoringClientFunctionType = unsafe extern "system" fn(host: ::windows::core::RawPtr) -> ::windows::core::HRESULT;
use std::collections::HashSet; fn part_1_solve(input_str: &str) -> i32 { input_str.lines().map(|x| x.parse::<i32>().unwrap()).sum() } fn part_2_solve(input_str: &str) -> i32 { let mut frequencies = HashSet::new(); let mut frequency = 0; let _ = input_str.lines().cycle().map(|x| x.parse::<i32>().unwrap()).take_while(|x| { frequency += x; frequencies.insert(frequency) }).count(); frequency } fn main() { println!("Part 1: {}", part_1_solve(include_str!("../input/input.txt"))); println!("Part 2: {}", part_2_solve(include_str!("../input/input.txt"))); } #[test] fn part_2_test() { let mut test_str = "+3\n+3\n+4\n-2\n-4"; assert_eq!(part_2_solve(test_str), 10); test_str = "-6\n+3\n+8\n+5\n-6"; assert_eq!(part_2_solve(test_str), 5); test_str = "+7\n+7\n-2\n-7\n-4"; assert_eq!(part_2_solve(test_str), 14); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CallEnclave<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(lproutine: isize, lpparameter: *const ::core::ffi::c_void, fwaitforthread: Param2, lpreturnvalue: *mut *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CallEnclave(lproutine: isize, lpparameter: *const ::core::ffi::c_void, fwaitforthread: super::super::Foundation::BOOL, lpreturnvalue: *mut *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL; } ::core::mem::transmute(CallEnclave(::core::mem::transmute(lproutine), ::core::mem::transmute(lpparameter), fwaitforthread.into_param().abi(), ::core::mem::transmute(lpreturnvalue))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CreateEnclave<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0, lpaddress: *const ::core::ffi::c_void, dwsize: usize, dwinitialcommitment: usize, flenclavetype: u32, lpenclaveinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpenclaveerror: *mut u32) -> *mut ::core::ffi::c_void { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateEnclave(hprocess: super::super::Foundation::HANDLE, lpaddress: *const ::core::ffi::c_void, dwsize: usize, dwinitialcommitment: usize, flenclavetype: u32, lpenclaveinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpenclaveerror: *mut u32) -> *mut ::core::ffi::c_void; } ::core::mem::transmute(CreateEnclave( hprocess.into_param().abi(), ::core::mem::transmute(lpaddress), ::core::mem::transmute(dwsize), ::core::mem::transmute(dwinitialcommitment), ::core::mem::transmute(flenclavetype), ::core::mem::transmute(lpenclaveinformation), ::core::mem::transmute(dwinfolength), ::core::mem::transmute(lpenclaveerror), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CreateEnvironmentBlock<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(lpenvironment: *mut *mut ::core::ffi::c_void, htoken: Param1, binherit: Param2) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CreateEnvironmentBlock(lpenvironment: *mut *mut ::core::ffi::c_void, htoken: super::super::Foundation::HANDLE, binherit: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL; } ::core::mem::transmute(CreateEnvironmentBlock(::core::mem::transmute(lpenvironment), htoken.into_param().abi(), binherit.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DeleteEnclave(lpaddress: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DeleteEnclave(lpaddress: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL; } ::core::mem::transmute(DeleteEnclave(::core::mem::transmute(lpaddress))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn DestroyEnvironmentBlock(lpenvironment: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn DestroyEnvironmentBlock(lpenvironment: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL; } ::core::mem::transmute(DestroyEnvironmentBlock(::core::mem::transmute(lpenvironment))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const ENCLAVE_FLAG_DYNAMIC_DEBUG_ACTIVE: u32 = 4u32; pub const ENCLAVE_FLAG_DYNAMIC_DEBUG_ENABLED: u32 = 2u32; pub const ENCLAVE_FLAG_FULL_DEBUG_ENABLED: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct ENCLAVE_IDENTITY { pub OwnerId: [u8; 32], pub UniqueId: [u8; 32], pub AuthorId: [u8; 32], pub FamilyId: [u8; 16], pub ImageId: [u8; 16], pub EnclaveSvn: u32, pub SecureKernelSvn: u32, pub PlatformSvn: u32, pub Flags: u32, pub SigningLevel: u32, pub EnclaveType: u32, } impl ENCLAVE_IDENTITY {} impl ::core::default::Default for ENCLAVE_IDENTITY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for ENCLAVE_IDENTITY { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for ENCLAVE_IDENTITY {} unsafe impl ::windows::core::Abi for ENCLAVE_IDENTITY { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ENCLAVE_INFORMATION { pub EnclaveType: u32, pub Reserved: u32, pub BaseAddress: *mut ::core::ffi::c_void, pub Size: usize, pub Identity: ENCLAVE_IDENTITY, } impl ENCLAVE_INFORMATION {} impl ::core::default::Default for ENCLAVE_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for ENCLAVE_INFORMATION { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for ENCLAVE_INFORMATION {} unsafe impl ::windows::core::Abi for ENCLAVE_INFORMATION { type Abi = Self; } pub const ENCLAVE_REPORT_DATA_LENGTH: u32 = 64u32; pub const ENCLAVE_RUNTIME_POLICY_ALLOW_DYNAMIC_DEBUG: u32 = 2u32; pub const ENCLAVE_RUNTIME_POLICY_ALLOW_FULL_DEBUG: u32 = 1u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ENCLAVE_SEALING_IDENTITY_POLICY(pub i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_INVALID: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(0i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_EXACT_CODE: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(1i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_PRIMARY_CODE: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(2i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_IMAGE: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(3i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_FAMILY: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(4i32); pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_AUTHOR: ENCLAVE_SEALING_IDENTITY_POLICY = ENCLAVE_SEALING_IDENTITY_POLICY(5i32); impl ::core::convert::From<i32> for ENCLAVE_SEALING_IDENTITY_POLICY { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ENCLAVE_SEALING_IDENTITY_POLICY { type Abi = Self; } pub const ENCLAVE_UNSEAL_FLAG_STALE_KEY: u32 = 1u32; pub const ENCLAVE_VBS_BASIC_KEY_FLAG_DEBUG_KEY: u32 = 8u32; pub const ENCLAVE_VBS_BASIC_KEY_FLAG_FAMILY_ID: u32 = 2u32; pub const ENCLAVE_VBS_BASIC_KEY_FLAG_IMAGE_ID: u32 = 4u32; pub const ENCLAVE_VBS_BASIC_KEY_FLAG_MEASUREMENT: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ENCLAVE_VBS_BASIC_KEY_REQUEST { pub RequestSize: u32, pub Flags: u32, pub EnclaveSVN: u32, pub SystemKeyID: u32, pub CurrentSystemKeyID: u32, } impl ENCLAVE_VBS_BASIC_KEY_REQUEST {} impl ::core::default::Default for ENCLAVE_VBS_BASIC_KEY_REQUEST { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ENCLAVE_VBS_BASIC_KEY_REQUEST { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ENCLAVE_VBS_BASIC_KEY_REQUEST").field("RequestSize", &self.RequestSize).field("Flags", &self.Flags).field("EnclaveSVN", &self.EnclaveSVN).field("SystemKeyID", &self.SystemKeyID).field("CurrentSystemKeyID", &self.CurrentSystemKeyID).finish() } } impl ::core::cmp::PartialEq for ENCLAVE_VBS_BASIC_KEY_REQUEST { fn eq(&self, other: &Self) -> bool { self.RequestSize == other.RequestSize && self.Flags == other.Flags && self.EnclaveSVN == other.EnclaveSVN && self.SystemKeyID == other.SystemKeyID && self.CurrentSystemKeyID == other.CurrentSystemKeyID } } impl ::core::cmp::Eq for ENCLAVE_VBS_BASIC_KEY_REQUEST {} unsafe impl ::windows::core::Abi for ENCLAVE_VBS_BASIC_KEY_REQUEST { type Abi = Self; } #[inline] pub unsafe fn EnclaveGetAttestationReport(enclavedata: *const u8, report: *mut ::core::ffi::c_void, buffersize: u32, outputsize: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnclaveGetAttestationReport(enclavedata: *const u8, report: *mut ::core::ffi::c_void, buffersize: u32, outputsize: *mut u32) -> ::windows::core::HRESULT; } EnclaveGetAttestationReport(::core::mem::transmute(enclavedata), ::core::mem::transmute(report), ::core::mem::transmute(buffersize), ::core::mem::transmute(outputsize)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EnclaveGetEnclaveInformation(informationsize: u32) -> ::windows::core::Result<ENCLAVE_INFORMATION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnclaveGetEnclaveInformation(informationsize: u32, enclaveinformation: *mut ENCLAVE_INFORMATION) -> ::windows::core::HRESULT; } let mut result__: <ENCLAVE_INFORMATION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); EnclaveGetEnclaveInformation(::core::mem::transmute(informationsize), &mut result__).from_abi::<ENCLAVE_INFORMATION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EnclaveSealData(datatoencrypt: *const ::core::ffi::c_void, datatoencryptsize: u32, identitypolicy: ENCLAVE_SEALING_IDENTITY_POLICY, runtimepolicy: u32, protectedblob: *mut ::core::ffi::c_void, buffersize: u32, protectedblobsize: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnclaveSealData(datatoencrypt: *const ::core::ffi::c_void, datatoencryptsize: u32, identitypolicy: ENCLAVE_SEALING_IDENTITY_POLICY, runtimepolicy: u32, protectedblob: *mut ::core::ffi::c_void, buffersize: u32, protectedblobsize: *mut u32) -> ::windows::core::HRESULT; } EnclaveSealData(::core::mem::transmute(datatoencrypt), ::core::mem::transmute(datatoencryptsize), ::core::mem::transmute(identitypolicy), ::core::mem::transmute(runtimepolicy), ::core::mem::transmute(protectedblob), ::core::mem::transmute(buffersize), ::core::mem::transmute(protectedblobsize)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EnclaveUnsealData(protectedblob: *const ::core::ffi::c_void, protectedblobsize: u32, decrypteddata: *mut ::core::ffi::c_void, buffersize: u32, decrypteddatasize: *mut u32, sealingidentity: *mut ENCLAVE_IDENTITY, unsealingflags: *mut u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnclaveUnsealData(protectedblob: *const ::core::ffi::c_void, protectedblobsize: u32, decrypteddata: *mut ::core::ffi::c_void, buffersize: u32, decrypteddatasize: *mut u32, sealingidentity: *mut ENCLAVE_IDENTITY, unsealingflags: *mut u32) -> ::windows::core::HRESULT; } EnclaveUnsealData(::core::mem::transmute(protectedblob), ::core::mem::transmute(protectedblobsize), ::core::mem::transmute(decrypteddata), ::core::mem::transmute(buffersize), ::core::mem::transmute(decrypteddatasize), ::core::mem::transmute(sealingidentity), ::core::mem::transmute(unsealingflags)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn EnclaveVerifyAttestationReport(enclavetype: u32, report: *const ::core::ffi::c_void, reportsize: u32) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn EnclaveVerifyAttestationReport(enclavetype: u32, report: *const ::core::ffi::c_void, reportsize: u32) -> ::windows::core::HRESULT; } EnclaveVerifyAttestationReport(::core::mem::transmute(enclavetype), ::core::mem::transmute(report), ::core::mem::transmute(reportsize)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ExpandEnvironmentStringsA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpsrc: Param0, lpdst: super::super::Foundation::PSTR, nsize: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ExpandEnvironmentStringsA(lpsrc: super::super::Foundation::PSTR, lpdst: super::super::Foundation::PSTR, nsize: u32) -> u32; } ::core::mem::transmute(ExpandEnvironmentStringsA(lpsrc.into_param().abi(), ::core::mem::transmute(lpdst), ::core::mem::transmute(nsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ExpandEnvironmentStringsForUserA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(htoken: Param0, lpsrc: Param1, lpdest: super::super::Foundation::PSTR, dwsize: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ExpandEnvironmentStringsForUserA(htoken: super::super::Foundation::HANDLE, lpsrc: super::super::Foundation::PSTR, lpdest: super::super::Foundation::PSTR, dwsize: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ExpandEnvironmentStringsForUserA(htoken.into_param().abi(), lpsrc.into_param().abi(), ::core::mem::transmute(lpdest), ::core::mem::transmute(dwsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ExpandEnvironmentStringsForUserW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(htoken: Param0, lpsrc: Param1, lpdest: super::super::Foundation::PWSTR, dwsize: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ExpandEnvironmentStringsForUserW(htoken: super::super::Foundation::HANDLE, lpsrc: super::super::Foundation::PWSTR, lpdest: super::super::Foundation::PWSTR, dwsize: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(ExpandEnvironmentStringsForUserW(htoken.into_param().abi(), lpsrc.into_param().abi(), ::core::mem::transmute(lpdest), ::core::mem::transmute(dwsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ExpandEnvironmentStringsW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpsrc: Param0, lpdst: super::super::Foundation::PWSTR, nsize: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ExpandEnvironmentStringsW(lpsrc: super::super::Foundation::PWSTR, lpdst: super::super::Foundation::PWSTR, nsize: u32) -> u32; } ::core::mem::transmute(ExpandEnvironmentStringsW(lpsrc.into_param().abi(), ::core::mem::transmute(lpdst), ::core::mem::transmute(nsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FreeEnvironmentStringsA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(penv: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FreeEnvironmentStringsA(penv: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FreeEnvironmentStringsA(penv.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn FreeEnvironmentStringsW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(penv: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn FreeEnvironmentStringsW(penv: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(FreeEnvironmentStringsW(penv.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetCommandLineA() -> super::super::Foundation::PSTR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetCommandLineA() -> super::super::Foundation::PSTR; } ::core::mem::transmute(GetCommandLineA()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetCommandLineW() -> super::super::Foundation::PWSTR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetCommandLineW() -> super::super::Foundation::PWSTR; } ::core::mem::transmute(GetCommandLineW()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetCurrentDirectoryA(nbufferlength: u32, lpbuffer: super::super::Foundation::PSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetCurrentDirectoryA(nbufferlength: u32, lpbuffer: super::super::Foundation::PSTR) -> u32; } ::core::mem::transmute(GetCurrentDirectoryA(::core::mem::transmute(nbufferlength), ::core::mem::transmute(lpbuffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetCurrentDirectoryW(nbufferlength: u32, lpbuffer: super::super::Foundation::PWSTR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetCurrentDirectoryW(nbufferlength: u32, lpbuffer: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(GetCurrentDirectoryW(::core::mem::transmute(nbufferlength), ::core::mem::transmute(lpbuffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetEnvironmentStrings() -> super::super::Foundation::PSTR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetEnvironmentStrings() -> super::super::Foundation::PSTR; } ::core::mem::transmute(GetEnvironmentStrings()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetEnvironmentStringsW() -> super::super::Foundation::PWSTR { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetEnvironmentStringsW() -> super::super::Foundation::PWSTR; } ::core::mem::transmute(GetEnvironmentStringsW()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetEnvironmentVariableA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpname: Param0, lpbuffer: super::super::Foundation::PSTR, nsize: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetEnvironmentVariableA(lpname: super::super::Foundation::PSTR, lpbuffer: super::super::Foundation::PSTR, nsize: u32) -> u32; } ::core::mem::transmute(GetEnvironmentVariableA(lpname.into_param().abi(), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(nsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn GetEnvironmentVariableW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpname: Param0, lpbuffer: super::super::Foundation::PWSTR, nsize: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetEnvironmentVariableW(lpname: super::super::Foundation::PWSTR, lpbuffer: super::super::Foundation::PWSTR, nsize: u32) -> u32; } ::core::mem::transmute(GetEnvironmentVariableW(lpname.into_param().abi(), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(nsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn InitializeEnclave<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0, lpaddress: *const ::core::ffi::c_void, lpenclaveinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpenclaveerror: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn InitializeEnclave(hprocess: super::super::Foundation::HANDLE, lpaddress: *const ::core::ffi::c_void, lpenclaveinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpenclaveerror: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(InitializeEnclave(hprocess.into_param().abi(), ::core::mem::transmute(lpaddress), ::core::mem::transmute(lpenclaveinformation), ::core::mem::transmute(dwinfolength), ::core::mem::transmute(lpenclaveerror))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn IsEnclaveTypeSupported(flenclavetype: u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn IsEnclaveTypeSupported(flenclavetype: u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(IsEnclaveTypeSupported(::core::mem::transmute(flenclavetype))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoadEnclaveData<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::HANDLE>>(hprocess: Param0, lpaddress: *const ::core::ffi::c_void, lpbuffer: *const ::core::ffi::c_void, nsize: usize, flprotect: u32, lppageinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpnumberofbyteswritten: *mut usize, lpenclaveerror: *mut u32) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoadEnclaveData(hprocess: super::super::Foundation::HANDLE, lpaddress: *const ::core::ffi::c_void, lpbuffer: *const ::core::ffi::c_void, nsize: usize, flprotect: u32, lppageinformation: *const ::core::ffi::c_void, dwinfolength: u32, lpnumberofbyteswritten: *mut usize, lpenclaveerror: *mut u32) -> super::super::Foundation::BOOL; } ::core::mem::transmute(LoadEnclaveData( hprocess.into_param().abi(), ::core::mem::transmute(lpaddress), ::core::mem::transmute(lpbuffer), ::core::mem::transmute(nsize), ::core::mem::transmute(flprotect), ::core::mem::transmute(lppageinformation), ::core::mem::transmute(dwinfolength), ::core::mem::transmute(lpnumberofbyteswritten), ::core::mem::transmute(lpenclaveerror), )) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoadEnclaveImageA<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpenclaveaddress: *const ::core::ffi::c_void, lpimagename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoadEnclaveImageA(lpenclaveaddress: *const ::core::ffi::c_void, lpimagename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(LoadEnclaveImageA(::core::mem::transmute(lpenclaveaddress), lpimagename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoadEnclaveImageW<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpenclaveaddress: *const ::core::ffi::c_void, lpimagename: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoadEnclaveImageW(lpenclaveaddress: *const ::core::ffi::c_void, lpimagename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(LoadEnclaveImageW(::core::mem::transmute(lpenclaveaddress), lpimagename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NeedCurrentDirectoryForExePathA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(exename: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NeedCurrentDirectoryForExePathA(exename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(NeedCurrentDirectoryForExePathA(exename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NeedCurrentDirectoryForExePathW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(exename: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NeedCurrentDirectoryForExePathW(exename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(NeedCurrentDirectoryForExePathW(exename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetCurrentDirectoryA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lppathname: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetCurrentDirectoryA(lppathname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetCurrentDirectoryA(lppathname.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetCurrentDirectoryW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lppathname: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetCurrentDirectoryW(lppathname: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetCurrentDirectoryW(lppathname.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetEnvironmentStringsW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(newenvironment: Param0) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetEnvironmentStringsW(newenvironment: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetEnvironmentStringsW(newenvironment.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetEnvironmentVariableA<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PSTR>>(lpname: Param0, lpvalue: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetEnvironmentVariableA(lpname: super::super::Foundation::PSTR, lpvalue: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetEnvironmentVariableA(lpname.into_param().abi(), lpvalue.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn SetEnvironmentVariableW<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(lpname: Param0, lpvalue: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn SetEnvironmentVariableW(lpname: super::super::Foundation::PWSTR, lpvalue: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL; } ::core::mem::transmute(SetEnvironmentVariableW(lpname.into_param().abi(), lpvalue.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn TerminateEnclave<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(lpaddress: *const ::core::ffi::c_void, fwait: Param1) -> super::super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn TerminateEnclave(lpaddress: *const ::core::ffi::c_void, fwait: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL; } ::core::mem::transmute(TerminateEnclave(::core::mem::transmute(lpaddress), fwait.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub type VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES = unsafe extern "system" fn(enclaveaddress: *const ::core::ffi::c_void, numberofbytes: usize, sourceaddress: *const ::core::ffi::c_void, pageprotection: u32) -> i32; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64) -> i32; #[cfg(any(target_arch = "x86",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES = unsafe extern "system" fn(enclaveaddress: *const ::core::ffi::c_void, numberofbytes: usize) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY = unsafe extern "system" fn(keyrequest: *mut ENCLAVE_VBS_BASIC_KEY_REQUEST, requestedkeysize: u32, returnedkey: *mut u8) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA = unsafe extern "system" fn(buffer: *mut u8, numberofbytes: u32, generation: *mut u64) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT = unsafe extern "system" fn(enclavedata: *const u8, report: *mut ::core::ffi::c_void, buffersize: u32, outputsize: *mut u32) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION = unsafe extern "system" fn(enclaveinfo: *mut ENCLAVE_INFORMATION) -> i32; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64) -> i32; #[cfg(any(target_arch = "x86",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES = unsafe extern "system" fn(enclaveaddress: *const ::core::ffi::c_void, numberofytes: usize, pageprotection: u32) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE = unsafe extern "system" fn(returnvalue: usize); #[cfg(any(target_arch = "x86_64",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION = unsafe extern "system" fn(exceptionrecord: *const VBS_BASIC_ENCLAVE_EXCEPTION_AMD64) -> i32; #[cfg(any(target_arch = "x86", target_arch = "aarch64",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION = unsafe extern "system" fn(exceptionrecord: *const ::core::ffi::c_void) -> i32; #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64) -> i32; #[cfg(any(target_arch = "x86",))] pub type VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD = unsafe extern "system" fn(threaddescriptor: *const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32) -> i32; pub type VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT = unsafe extern "system" fn(report: *const ::core::ffi::c_void, reportsize: u32) -> i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 { pub ExceptionCode: u32, pub NumberParameters: u32, pub ExceptionInformation: [usize; 3], pub ExceptionRAX: usize, pub ExceptionRCX: usize, pub ExceptionRIP: usize, pub ExceptionRFLAGS: usize, pub ExceptionRSP: usize, } impl VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 {} impl ::core::default::Default for VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VBS_BASIC_ENCLAVE_EXCEPTION_AMD64") .field("ExceptionCode", &self.ExceptionCode) .field("NumberParameters", &self.NumberParameters) .field("ExceptionInformation", &self.ExceptionInformation) .field("ExceptionRAX", &self.ExceptionRAX) .field("ExceptionRCX", &self.ExceptionRCX) .field("ExceptionRIP", &self.ExceptionRIP) .field("ExceptionRFLAGS", &self.ExceptionRFLAGS) .field("ExceptionRSP", &self.ExceptionRSP) .finish() } } impl ::core::cmp::PartialEq for VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 { fn eq(&self, other: &Self) -> bool { self.ExceptionCode == other.ExceptionCode && self.NumberParameters == other.NumberParameters && self.ExceptionInformation == other.ExceptionInformation && self.ExceptionRAX == other.ExceptionRAX && self.ExceptionRCX == other.ExceptionRCX && self.ExceptionRIP == other.ExceptionRIP && self.ExceptionRFLAGS == other.ExceptionRFLAGS && self.ExceptionRSP == other.ExceptionRSP } } impl ::core::cmp::Eq for VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 {} unsafe impl ::windows::core::Abi for VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] pub struct VBS_BASIC_ENCLAVE_SYSCALL_PAGE { pub ReturnFromEnclave: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE>, pub ReturnFromException: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION>, pub TerminateThread: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD>, pub InterruptThread: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD>, pub CommitPages: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES>, pub DecommitPages: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES>, pub ProtectPages: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES>, pub CreateThread: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD>, pub GetEnclaveInformation: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION>, pub GenerateKey: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY>, pub GenerateReport: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT>, pub VerifyReport: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT>, pub GenerateRandomData: ::core::option::Option<VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA>, } impl VBS_BASIC_ENCLAVE_SYSCALL_PAGE {} impl ::core::default::Default for VBS_BASIC_ENCLAVE_SYSCALL_PAGE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VBS_BASIC_ENCLAVE_SYSCALL_PAGE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VBS_BASIC_ENCLAVE_SYSCALL_PAGE").finish() } } impl ::core::cmp::PartialEq for VBS_BASIC_ENCLAVE_SYSCALL_PAGE { fn eq(&self, other: &Self) -> bool { self.ReturnFromEnclave.map(|f| f as usize) == other.ReturnFromEnclave.map(|f| f as usize) && self.ReturnFromException.map(|f| f as usize) == other.ReturnFromException.map(|f| f as usize) && self.TerminateThread.map(|f| f as usize) == other.TerminateThread.map(|f| f as usize) && self.InterruptThread.map(|f| f as usize) == other.InterruptThread.map(|f| f as usize) && self.CommitPages.map(|f| f as usize) == other.CommitPages.map(|f| f as usize) && self.DecommitPages.map(|f| f as usize) == other.DecommitPages.map(|f| f as usize) && self.ProtectPages.map(|f| f as usize) == other.ProtectPages.map(|f| f as usize) && self.CreateThread.map(|f| f as usize) == other.CreateThread.map(|f| f as usize) && self.GetEnclaveInformation.map(|f| f as usize) == other.GetEnclaveInformation.map(|f| f as usize) && self.GenerateKey.map(|f| f as usize) == other.GenerateKey.map(|f| f as usize) && self.GenerateReport.map(|f| f as usize) == other.GenerateReport.map(|f| f as usize) && self.VerifyReport.map(|f| f as usize) == other.VerifyReport.map(|f| f as usize) && self.GenerateRandomData.map(|f| f as usize) == other.GenerateRandomData.map(|f| f as usize) } } impl ::core::cmp::Eq for VBS_BASIC_ENCLAVE_SYSCALL_PAGE {} unsafe impl ::windows::core::Abi for VBS_BASIC_ENCLAVE_SYSCALL_PAGE { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 { pub ThreadContext: [u32; 4], pub EntryPoint: u32, pub StackPointer: u32, pub ExceptionEntryPoint: u32, pub ExceptionStack: u32, pub ExceptionActive: u32, } impl VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 {} impl ::core::default::Default for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32") .field("ThreadContext", &self.ThreadContext) .field("EntryPoint", &self.EntryPoint) .field("StackPointer", &self.StackPointer) .field("ExceptionEntryPoint", &self.ExceptionEntryPoint) .field("ExceptionStack", &self.ExceptionStack) .field("ExceptionActive", &self.ExceptionActive) .finish() } } impl ::core::cmp::PartialEq for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 { fn eq(&self, other: &Self) -> bool { self.ThreadContext == other.ThreadContext && self.EntryPoint == other.EntryPoint && self.StackPointer == other.StackPointer && self.ExceptionEntryPoint == other.ExceptionEntryPoint && self.ExceptionStack == other.ExceptionStack && self.ExceptionActive == other.ExceptionActive } } impl ::core::cmp::Eq for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 {} unsafe impl ::windows::core::Abi for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 { pub ThreadContext: [u64; 4], pub EntryPoint: u64, pub StackPointer: u64, pub ExceptionEntryPoint: u64, pub ExceptionStack: u64, pub ExceptionActive: u32, } impl VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 {} impl ::core::default::Default for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64") .field("ThreadContext", &self.ThreadContext) .field("EntryPoint", &self.EntryPoint) .field("StackPointer", &self.StackPointer) .field("ExceptionEntryPoint", &self.ExceptionEntryPoint) .field("ExceptionStack", &self.ExceptionStack) .field("ExceptionActive", &self.ExceptionActive) .finish() } } impl ::core::cmp::PartialEq for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 { fn eq(&self, other: &Self) -> bool { self.ThreadContext == other.ThreadContext && self.EntryPoint == other.EntryPoint && self.StackPointer == other.StackPointer && self.ExceptionEntryPoint == other.ExceptionEntryPoint && self.ExceptionStack == other.ExceptionStack && self.ExceptionActive == other.ExceptionActive } } impl ::core::cmp::Eq for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 {} unsafe impl ::windows::core::Abi for VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct VBS_ENCLAVE_REPORT { pub ReportSize: u32, pub ReportVersion: u32, pub EnclaveData: [u8; 64], pub EnclaveIdentity: ENCLAVE_IDENTITY, } impl VBS_ENCLAVE_REPORT {} impl ::core::default::Default for VBS_ENCLAVE_REPORT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VBS_ENCLAVE_REPORT { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VBS_ENCLAVE_REPORT {} unsafe impl ::windows::core::Abi for VBS_ENCLAVE_REPORT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct VBS_ENCLAVE_REPORT_MODULE { pub Header: VBS_ENCLAVE_REPORT_VARDATA_HEADER, pub UniqueId: [u8; 32], pub AuthorId: [u8; 32], pub FamilyId: [u8; 16], pub ImageId: [u8; 16], pub Svn: u32, pub ModuleName: [u16; 1], } impl VBS_ENCLAVE_REPORT_MODULE {} impl ::core::default::Default for VBS_ENCLAVE_REPORT_MODULE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VBS_ENCLAVE_REPORT_MODULE { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VBS_ENCLAVE_REPORT_MODULE {} unsafe impl ::windows::core::Abi for VBS_ENCLAVE_REPORT_MODULE { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct VBS_ENCLAVE_REPORT_PKG_HEADER { pub PackageSize: u32, pub Version: u32, pub SignatureScheme: u32, pub SignedStatementSize: u32, pub SignatureSize: u32, pub Reserved: u32, } impl VBS_ENCLAVE_REPORT_PKG_HEADER {} impl ::core::default::Default for VBS_ENCLAVE_REPORT_PKG_HEADER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VBS_ENCLAVE_REPORT_PKG_HEADER { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VBS_ENCLAVE_REPORT_PKG_HEADER {} unsafe impl ::windows::core::Abi for VBS_ENCLAVE_REPORT_PKG_HEADER { type Abi = Self; } pub const VBS_ENCLAVE_REPORT_PKG_HEADER_VERSION_CURRENT: u32 = 1u32; pub const VBS_ENCLAVE_REPORT_SIGNATURE_SCHEME_SHA256_RSA_PSS_SHA256: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct VBS_ENCLAVE_REPORT_VARDATA_HEADER { pub DataType: u32, pub Size: u32, } impl VBS_ENCLAVE_REPORT_VARDATA_HEADER {} impl ::core::default::Default for VBS_ENCLAVE_REPORT_VARDATA_HEADER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for VBS_ENCLAVE_REPORT_VARDATA_HEADER { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for VBS_ENCLAVE_REPORT_VARDATA_HEADER {} unsafe impl ::windows::core::Abi for VBS_ENCLAVE_REPORT_VARDATA_HEADER { type Abi = Self; } pub const VBS_ENCLAVE_REPORT_VERSION_CURRENT: u32 = 1u32; pub const VBS_ENCLAVE_VARDATA_INVALID: u32 = 0u32; pub const VBS_ENCLAVE_VARDATA_MODULE: u32 = 1u32;
use alloc::vec::Vec; /// Trait to be implemented by a collection that can be extended from a slice /// /// ## Example /// /// ```rust /// use smallvec::{ExtendFromSlice, SmallVec}; /// /// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) { /// v.extend_from_slice(b"Test!"); /// } /// /// let mut vec = Vec::new(); /// initialize(&mut vec); /// assert_eq!(&vec, b"Test!"); /// /// let mut small_vec = SmallVec::<[u8; 8]>::new(); /// initialize(&mut small_vec); /// assert_eq!(&small_vec as &[_], b"Test!"); /// ``` pub trait ExtendFromSlice<T> { /// Extends a collection from a slice of its element type fn extend_from_slice(&mut self, other: &[T]); } impl<T: Clone> ExtendFromSlice<T> for Vec<T> { fn extend_from_slice(&mut self, other: &[T]) { Vec::extend_from_slice(self, other) } }
use std::thread; use tokio::sync::{broadcast, mpsc, watch}; pub mod consumer_state; mod tokio_server; pub fn start(port: u32) -> Result<(), ()> { // Server thread-alive channel. let (ser_thread_alive_tokio_tx, ser_alive_consumer_rx) = { watch::channel::<bool>(false) }; // Client connection event channel. let (cli_conn_tokio_tx, cli_conn_consumer_rx) = { mpsc::channel::<String>(16) }; // Server message broadcast channel (consumer -> server -> client(s)). let (ser_msg_tokio_tx, _) = { broadcast::channel::<Vec<tokio_tungstenite::tungstenite::Message>>(16) }; // Both the consumer thread(s) and the tokio thread(s) will have their own copies of the transmitter. The consumer thread uses its copy to send() messages. The tokio thread uses its copy to create per-connection receivers. let ser_msg_consumer_tx = ser_msg_tokio_tx.clone(); // Client message channel. let (cli_msg_store_tokio_tx, cli_msg_store_consumer_rx) = { mpsc::channel::<tokio_tungstenite::tungstenite::Message>(16) }; // Shutdown channel. let (ser_req_shutdown_consumer_tx, ser_req_shutdown_tokio_rx) = { watch::channel::<bool>(false) }; // Set the consumer thread statics with all its relevant comms channels. use consumer_state as cs; cs::set_value(&cs::CS_SER_ALIVE_RX, ser_alive_consumer_rx) .expect("Failed to set consumer state channel!"); cs::set_value(&cs::CS_CLI_CONN_RX, cli_conn_consumer_rx) .expect("Failed to set consumer state channel!"); cs::set_value(&cs::CS_SER_MSG_TX, ser_msg_consumer_tx) .expect("Failed to set consumer state channel!"); cs::set_value(&cs::CS_CLI_MSG_RX, cli_msg_store_consumer_rx) .expect("Failed to set consumer state channel!"); cs::set_value(&cs::CS_SER_REQ_SHUTDOWN_TX, ser_req_shutdown_consumer_tx) .expect("Failed to set consumer state channel!"); // Launch the tokio thread, passing ownership of all the tokio-side channels. // Launch the tokio thread. let _thread_handle = thread::spawn(move || tokio_server::main( port, ser_thread_alive_tokio_tx, cli_conn_tokio_tx, ser_msg_tokio_tx, cli_msg_store_tokio_tx, ser_req_shutdown_tokio_rx )); Ok(()) }
use std::collections::{HashMap, HashSet}; use std::io::{Write, stdin}; #[macro_use] mod error; mod client; mod cost; mod index; use crate::client::{Client, ItemId, Recipe, RecipeId}; use crate::cost::{Cost, Source}; use crate::error::Result; use crate::index::{Index, RecipeSource}; #[derive(Debug, Clone)] struct Profit { id: RecipeId, days: i32, sale: i32, value: i32, daily: HashSet<ItemId>, cost: Cost, mats_profit: Option<i32>, } impl Profit { fn per_day(&self) -> i32 { let d = std::cmp::max(1, self.days) as f32; ((self.value as f32) / d).floor() as i32 } } const MIN_PROFIT: i32 = 5000; enum Command { Done, Continue, Print { min_profit: i32 }, RefreshMats, Profit { id: ItemId }, Cost { id: ItemId, count: i32 }, } fn main() -> Result<()> { let mut client = Client::new(); let mut index = Index::new(&mut client, RecipeSource::Characters)?; let (flip_profits, bank_profits) = find_profits(&index); println!("flip profits: {}", flip_profits.len()); println!("bank profits: {}", bank_profits.len()); let mut command = Command::Print { min_profit: MIN_PROFIT }; loop { use Command::*; let mut print = None; match command { Done => break, Continue => (), Print { min_profit } => print = Some(min_profit), RefreshMats => { index.refresh_materials(&mut client)?; print = Some(MIN_PROFIT); } Profit { id } => { for p in &flip_profits { let r = index.recipes.get(&p.id).unwrap(); if r.output_item_id == id { print_profit(&index, p)?; } } } Cost { id, count } => print_cost(&index, &cost::Cost::new(&index, &id, count), 0), }; if let Some(min_profit) = print { println!(""); println!("=== Flip Profits ==="); println!(""); print_profits_min(&index, &flip_profits, min_profit)?; println!("=== Bank Profits ==="); println!(""); print_profits_min(&index, &bank_profits, min_profit)?; } command = match get_command() { Ok(c) => c, Err(e) => { println!("Error: {}", e); Continue } } } Ok(()) } fn find_profits(index: &Index) -> (Vec<Profit>, Vec<Profit>) { let mut flip_profits = vec![]; let mut bank_profits = vec![]; for r in index.recipes.values() { let item = if let Some(i) = index.items.get(&r.output_item_id) { i } else { continue }; if item.description.as_ref().map_or(false, |d| d.contains("used to craft the legendary")) { continue } if item.name == "Guild Catapult" { continue } let sale = { let listings = if let Some(ls) = index.listings.get(&r.output_item_id) { ls } else { continue }; let gross_sale = if let Ok(s) = listings.sale(r.output_item_count) { s } else { continue }; gross_sale - ((0.15 * (gross_sale as f32)).ceil()) as i32 }; if let Some(p) = flip_profit(index, r, sale) { flip_profits.push(p); } if let Some(p) = bank_profit(index, r, sale) { bank_profits.push(p); } } flip_profits.sort_by(|b, a| { a.per_day().cmp(&b.per_day()) }); bank_profits.sort_by(|b, a| { a.per_day().cmp(&b.per_day()) }); (flip_profits, bank_profits) } fn flip_profit(index: &Index, r: &Recipe, sale: i32) -> Option<Profit> { let cost = Cost::new(&index, &r.output_item_id, 1); if let Source::Auction = cost.source { return None } let daily = days(&cost); let mut days = 0; for d in daily.values() { days = std::cmp::max(days, *d); } if sale > cost.total { return Some(Profit { id: r.id, days, sale, value: sale - cost.total, daily: daily.keys().cloned().collect(), cost, mats_profit: None, }); } None } fn bank_profit(index: &Index, r: &Recipe, sale: i32) -> Option<Profit> { let mut bank = index.materials.clone(); let cost = Cost::new_with_bank(&index, &r.output_item_id, 1, &mut bank); if let Source::Auction = cost.source { return None } let daily = days(&cost); let mut days = 0; for d in daily.values() { days = std::cmp::max(days, *d); } let used = bank_used(&cost); let mut used_profit = 0; for (id, count) in &used { if let Some(s) = index.listings.get(id).and_then(|l| l.sale(*count).ok()) { used_profit += s; }/* else if let Some(sc) = cost::special(index, id) { used_profit += sc*count; }*/ } if sale > cost.total + used_profit { return Some(Profit { id: r.id, days, sale, value: sale - (cost.total + used_profit), daily: daily.keys().cloned().collect(), cost, mats_profit: Some(used_profit), }); } None } fn bank_used(c: &Cost) -> HashMap<ItemId, i32> { let mut out = HashMap::new(); bank_used_aux(&c.id, &c.source, &mut out); out } fn bank_used_aux(id: &ItemId, s: &Source, out: &mut HashMap<ItemId, i32>) { match s { Source::Bank { used, rest } => { *out.entry(*id).or_insert(0) += used; if let Some(r) = rest { bank_used_aux(id, r, out); } }, Source::Recipe { ingredients, .. } => { for (id, c) in ingredients { bank_used_aux(id, &c.source, out); } }, _ => () } } fn print_profits_min(index: &Index, profits: &[Profit], min: i32) -> Result<()> { let mut daily_used = HashSet::new(); 'profits: for p in profits { if p.per_day() < min { break } let recipe = index.recipes.get(&p.id).unwrap(); let item = index.items.get(&recipe.output_item_id).unwrap(); if p.days > 1 { println!("(skip: {} : {} [{} days])\n", item.name, money(p.per_day()), p.days); continue } for d in &p.daily { if !daily_used.insert(d) { let used = index.items.get(d).unwrap(); println!("(skip: {} : {} [{}])\n", item.name, money(p.per_day()), used.name); continue 'profits } } print_profit(&index, &p)?; println!(""); } Ok(()) } fn print_profit(index: &Index, p: &Profit) -> Result<()> { let recipe = index.recipes.get(&p.id).unwrap(); let item = index.items.get(&recipe.output_item_id).unwrap(); let cost = &p.cost; println!("{} : {} ({} over {} days)", item.name, money(p.per_day()), money(p.value), p.days); let output_price = index.listings.get(&item.id).unwrap().sale(1).unwrap(); println!("\tSale: {} = {} @ {}", money(p.sale), recipe.output_item_count, money(output_price)); println!("\tCost: {}", money(cost.total)); if let Some(mp) = p.mats_profit { println!("\tMats: {}", money(mp)); } print_cost(&index, &cost, 1); let ingredients = shopping_ingredients(&index, &cost); let mut shop_cost = 0; println!("\tShopping:"); for (id, count) in &ingredients { let cost = Cost::new(&index, id, *count); let item = index.items.get(id).unwrap(); println!("\t\t{} : {} = {}{}", item.name, count, money(cost.total), cost.source.to_str()); shop_cost += cost.total; } println!("\tTotal: {}", money(shop_cost)); Ok(()) } fn print_cost(index: &Index, cost: &Cost, indent: usize) { let ii = index.items.get(&cost.id).unwrap(); let tabs: Vec<_> = std::iter::repeat("\t").take(indent).collect(); let tabs = tabs.join(""); let (quantity, total) = if let Source::Bank { used, .. } = cost.source { (used, 0) } else { (cost.quantity, cost.total) }; println!("{}{} : {} = {}{}", tabs, ii.name, quantity, money(total), cost.source.to_str()); match &cost.source { Source::Recipe { ingredients, .. } => { for ing in ingredients.values() { print_cost(index, ing, indent+1); } } Source::Bank { used, rest: Some(r) } => { let subcost = Cost { source: (**r).clone(), quantity: cost.quantity - used, ..*cost }; print_cost(index, &subcost, indent); } _ => () } } fn shopping_ingredients(index: &Index, cost: &Cost) -> HashMap<ItemId, i32> { let mut out = HashMap::new(); for (id, count) in cost.base_ingredients() { let has = index.materials.get(&id).cloned().unwrap_or(0); if has < count { out.insert(id, count - has); } } out } fn money(amount: i32) -> String { let mut out = String::new(); if amount >= 10000 { out.push_str(&format!("{}g ", amount / 10000)); } if amount >= 100 { out.push_str(&format!("{}s ", (amount / 100) % 100)); } out.push_str(&format!("{}c", amount % 100)); out } fn is_daily(id: &ItemId) -> bool { match id.0 { // Charged Quartz Crystal 43772 => true, // Glob of Elder Spirit Residue 46744 => true, // Lump of Mithrillium 46742 => true, // Spool of Silk Weaving Thread 46740 => true, // Spool of Thick Elonian Cord 46745 => true, _ => false, } } fn days(cost: &Cost) -> HashMap<ItemId, i32> { if is_daily(&cost.id) { let mut out = HashMap::new(); out.insert(cost.id, cost.quantity); return out; } let ingredients = if let Source::Recipe { ingredients, .. } = &cost.source { ingredients } else { return HashMap::new() }; let mut out = HashMap::new(); for ing in ingredients.values() { for (id, count) in days(ing) { *out.entry(id).or_insert(0) += count; } } out } fn get_command() -> Result<Command> { use Command::*; let mut line = String::new(); println!("mats | profit <id> | cost <id> [count] | min profit <copper>"); print!("> "); std::io::stdout().flush()?; line.clear(); stdin().read_line(&mut line)?; let line = line.trim(); if line == "exit" { return Ok(Done); } if line == "mats" { return Ok(RefreshMats); } if let Some(rest) = line.strip_prefix("profit ") { return Ok(Profit { id: ItemId(rest.parse::<i32>()?) }) } if let Some(rest) = line.strip_prefix("cost ") { let parts: Vec<_> = rest.split(' ').collect(); let id = ItemId(parts[0].parse::<i32>()?); let count = if parts.len() == 2 { parts[1].parse::<i32>()? } else { 1 }; return Ok(Cost { id, count }) } if let Some(rest) = line.strip_prefix("min profit ") { return Ok(Print { min_profit: rest.parse::<i32>()? }) } failed!("unknown command {:?}", line); }
#[cfg(test)] mod tests { use connectfour::*; #[test] fn board_with_one_item() { let mut board = Board::new(); board.drop_into(2, SlotState::Red); assert!(!board.check_for_winner()); } #[test] fn board_with_winning_row() { let mut board = Board::new(); board.drop_into(1, SlotState::Red); board.drop_into(7, SlotState::Blue); board.drop_into(2, SlotState::Red); board.drop_into(6, SlotState::Blue); board.drop_into(3, SlotState::Red); board.drop_into(5, SlotState::Blue); board.drop_into(4, SlotState::Red); assert!(board.check_for_winner()); } #[test] fn board_with_winning_column() { let mut board = Board::new(); board.drop_into(1, SlotState::Red); board.drop_into(2, SlotState::Blue); board.drop_into(2, SlotState::Red); board.drop_into(1, SlotState::Blue); board.drop_into(2, SlotState::Red); board.drop_into(1, SlotState::Blue); board.drop_into(2, SlotState::Red); board.drop_into(1, SlotState::Blue); board.drop_into(2, SlotState::Red); assert!(board.check_for_winner()); } #[test] fn board_with_winning_diagonal_below_mid() { let mut board = Board::new(); board.drop_into(7, SlotState::Red); board.drop_into(7, SlotState::Blue); board.drop_into(7, SlotState::Red); board.drop_into(7, SlotState::Blue); board.drop_into(6, SlotState::Red); board.drop_into(6, SlotState::Blue); board.drop_into(1, SlotState::Red); board.drop_into(6, SlotState::Blue); board.drop_into(5, SlotState::Red); board.drop_into(5, SlotState::Blue); board.drop_into(1, SlotState::Red); board.drop_into(4, SlotState::Blue); assert!(board.check_for_winner()); } #[test] fn board_with_winning_antidiagonal_above_mid() { let mut board = Board::new(); board.drop_into(7, SlotState::Red); board.drop_into(6, SlotState::Blue); board.drop_into(6, SlotState::Red); board.drop_into(1, SlotState::Blue); board.drop_into(5, SlotState::Red); board.drop_into(5, SlotState::Blue); board.drop_into(5, SlotState::Red); board.drop_into(4, SlotState::Blue); board.drop_into(4, SlotState::Red); board.drop_into(4, SlotState::Blue); board.drop_into(4, SlotState::Red); assert!(board.check_for_winner()); } #[test] fn board_with_gap_in_row() { let mut board = Board::new(); board.drop_into(1, SlotState::Red); board.drop_into(4, SlotState::Blue); board.drop_into(2, SlotState::Red); board.drop_into(4, SlotState::Blue); board.drop_into(7, SlotState::Red); board.drop_into(4, SlotState::Blue); board.drop_into(6, SlotState::Red); board.drop_into(7, SlotState::Blue); board.drop_into(5, SlotState::Red); board.drop_into(6, SlotState::Blue); board.drop_into(3, SlotState::Red); assert!(!board.check_for_winner()); } } pub mod connectfour { use std::fmt::{Display, Formatter, Result}; pub struct Board { columns: [Column; 7], // Container, Slot tuple last_insert: (usize, usize), } impl Board { pub fn new() -> Self { Board { columns: [Column::new(), Column::new(), Column::new(), Column::new(), Column::new(), Column::new(), Column::new()], last_insert: (0, 0), } } pub fn drop_into(&mut self, column_number: usize, symbol: SlotState) -> bool { let mut first_available_slot = 0; if self.columns[column_number-1].slots.into_iter().rev().enumerate().any(|(i, s)| {first_available_slot = 5 - i; return s.state == SlotState::Empty;}) { self.columns[column_number-1].slots[first_available_slot].state = symbol; self.last_insert = (column_number-1, first_available_slot); return true; } false } pub fn check_for_winner(&self) -> bool { // Check the columns if self.columns[self.last_insert.0].contains_run_of_four() { return true; } // Check the rows let mut run = 1; let mut last_symbol = &SlotState::Empty; for j in 0..7 { let s = &self.columns[j].slots[self.last_insert.1]; if last_symbol == &s.state && s.state != SlotState::Empty { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { return true; } } // Check possible diagonals // Get bottom of diagonal and then attempt to find a run by going to the top of the diagonal run = 1; if self.last_insert.0 + self.last_insert.1 <= 5 { // Look at diagonals above the mid point of the grid let mut bottom_of_diagonal = (0, self.last_insert.0 + self.last_insert.1); let top_of_diagonal = (bottom_of_diagonal.1, bottom_of_diagonal.0); last_symbol = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1].state; while bottom_of_diagonal != top_of_diagonal { bottom_of_diagonal = (bottom_of_diagonal.0 + 1, bottom_of_diagonal.1 - 1); let s = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1]; if last_symbol == &s.state && s.state != SlotState::Empty { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { return true; } } } else { // Look at diagonals below the mid point of the grid let mut bottom_of_diagonal = (self.last_insert.0 + self.last_insert.1 - 5, 5); let top_of_diagonal = (6, bottom_of_diagonal.0 + bottom_of_diagonal.1 - 6); last_symbol = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1].state; while bottom_of_diagonal != top_of_diagonal { bottom_of_diagonal = (bottom_of_diagonal.0 + 1, bottom_of_diagonal.1 - 1); let s = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1]; if last_symbol == &s.state && s.state != SlotState::Empty { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { return true; } } } // Now, do the same but go from the bottom of the antidiagonal to its top run = 1; if self.last_insert.0 <= self.last_insert.1 { let mut bottom_of_diagonal = (5 - self.last_insert.1 + self.last_insert.0, 5); let top_of_diagonal = (0, self.last_insert.1 - self.last_insert.0); last_symbol = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1].state; while bottom_of_diagonal != top_of_diagonal { bottom_of_diagonal = (bottom_of_diagonal.0 - 1, bottom_of_diagonal.1 - 1); let s = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1]; if last_symbol == &s.state && s.state != SlotState::Empty { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { return true; } } } else { let mut bottom_of_diagonal = (6, 6 - self.last_insert.0 + self.last_insert.1); let top_of_diagonal = (self.last_insert.0 - self.last_insert.1, 0); last_symbol = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1].state; while bottom_of_diagonal != top_of_diagonal { bottom_of_diagonal = (bottom_of_diagonal.0 - 1, bottom_of_diagonal.1 - 1); let s = &self.columns[bottom_of_diagonal.0].slots[bottom_of_diagonal.1]; if last_symbol == &s.state && s.state != SlotState::Empty { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { return true; } } } false } } #[allow(unused_must_use)] impl Display for Board { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[0].display(), self.columns[1].slots[0].display(), self.columns[2].slots[0].display(), self.columns[3].slots[0].display(), self.columns[4].slots[0].display(), self.columns[5].slots[0].display(), self.columns[6].slots[0].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[1].display(), self.columns[1].slots[1].display(), self.columns[2].slots[1].display(), self.columns[3].slots[1].display(), self.columns[4].slots[1].display(), self.columns[5].slots[1].display(), self.columns[6].slots[1].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[2].display(), self.columns[1].slots[2].display(), self.columns[2].slots[2].display(), self.columns[3].slots[2].display(), self.columns[4].slots[2].display(), self.columns[5].slots[2].display(), self.columns[6].slots[2].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[3].display(), self.columns[1].slots[3].display(), self.columns[2].slots[3].display(), self.columns[3].slots[3].display(), self.columns[4].slots[3].display(), self.columns[5].slots[3].display(), self.columns[6].slots[3].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[4].display(), self.columns[1].slots[4].display(), self.columns[2].slots[4].display(), self.columns[3].slots[4].display(), self.columns[4].slots[4].display(), self.columns[5].slots[4].display(), self.columns[6].slots[4].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|{:^width$}|\n", self.columns[0].slots[5].display(), self.columns[1].slots[5].display(), self.columns[2].slots[5].display(), self.columns[3].slots[5].display(), self.columns[4].slots[5].display(), self.columns[5].slots[5].display(), self.columns[6].slots[5].display(), width=5); write!(f, "+-----------------------------------------+\n"); write!(f, "{:^width$}{:^width$}{:^width$}{:^width$}{:^width$}{:^width$}{:^width$}\n", "1", "2", "3", "4", "5", "6", "7", width=6) } } struct Column { slots: [Slot; 6], } impl Column { fn new() -> Self { Column { slots: [Slot::new(), Slot::new(), Slot::new(), Slot::new(), Slot::new(), Slot::new()], } } fn contains_run_of_four(&self) -> bool { let mut run = 0; let mut last_symbol = &self.slots[5].state; self.slots.into_iter().rev() .any(|s| { if s.state == SlotState::Empty { return false; } if last_symbol == &s.state { run += 1; } else { run = 1; } last_symbol = &s.state; if run == 4 { true } else { false } }) } } struct Slot { state: SlotState, } impl Slot { fn new() -> Self { Slot { state: SlotState::Empty, } } fn display(&self) -> &str { match self.state { SlotState::Empty => " ", SlotState::Red => "R", SlotState::Blue => "B", } } } #[derive(PartialEq)] pub enum SlotState { Empty, Red, Blue, } }
mod utils; mod sliding_square; use getrandom; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{console, CanvasRenderingContext2d, OffscreenCanvas, Performance}; use tetris::{Tetris, TetrisBuilder, Randomizer, MoveDirection, RotationDirection, TetrisAction}; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen(start)] pub fn run() { console::log_1(&"[wasm] Initialized".into()); utils::set_panic_hook(); } // TODO: make this customizable const PLAYFIELD_DIM: (usize, usize) = (10, 20); // width, height /** * Input Ids * 0 - Down * 1 - Left * 2 - Right * 3 - Rotate counteclockwise * 4 - Rotate clockwise */ #[wasm_bindgen] pub struct WebTetris { timer: Performance, ctx: CanvasRenderingContext2d, // TODO: must be OffscreenCanvasRenderingContext2d, but it's not added in yet canvas: OffscreenCanvas, square_drawer: SquareDrawer, tetris: Tetris, // tetris logic and state last_update_time: f64, } #[wasm_bindgen] impl WebTetris { #[wasm_bindgen(constructor)] pub fn new(canvas: OffscreenCanvas, options: &JsValue) -> Self { console::log_1(&"[Tetris] Started game".into(),); let ctx = canvas .get_context_with_context_options("2d", options) .expect("Failed to get context") .unwrap() .dyn_into::<CanvasRenderingContext2d>() .unwrap(); canvas.set_width(canvas.height() / 2); let square_drawer = { let square_length = canvas.height() as f64 / PLAYFIELD_DIM.1 as f64; let square_padding = (square_length * 0.1_f64).sqrt(); SquareDrawer::new(square_length, square_padding) }; // get timer from global scope let timer = js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance")) .expect("failed to get performance from global object") .dyn_into::<web_sys::Performance>() .unwrap(); let last_update_time = timer.now(); let randomizer: Box<dyn Randomizer<u32>> = { struct WebRandomizer; impl Randomizer<u32> for WebRandomizer { fn get_random(&mut self) -> u32 { let mut buf = [0u8; 1]; getrandom::getrandom(&mut buf).unwrap(); buf[0] as u32 } } Box::new(WebRandomizer {}) }; let tetris = TetrisBuilder { width: PLAYFIELD_DIM.0, height: PLAYFIELD_DIM.1, randomizer, }.build(); Self { timer, ctx, canvas, square_drawer, tetris, last_update_time, } } pub fn render(&self) { // draw object for col in self.tetris.curr_block.pos.column_iter() { self .square_drawer .draw(&self.ctx, (col[(0, 0)] as f64, col[(1, 0)] as f64), Self::match_color(self.tetris.curr_block.block_type as u32)); } // draw playfield for (i, p) in self.tetris.playfield.borrow().iter().enumerate() { if *p > 0 { self .square_drawer .draw( &self.ctx, ((i % PLAYFIELD_DIM.0) as f64, (i as f64 / PLAYFIELD_DIM.0 as f64).floor()), Self::match_color(*p), ); } } } fn match_color(n: u32) -> &'static str { match n { 1 => "red", 2 => "orange", 3 => "yellow", 4 => "green", 5 => "blue", 6 => "indigo", 7 => "pink", _ => "black", } } pub fn clear(&self) { self.ctx.clear_rect( 0_f64, 0_f64, self.canvas.width() as f64, self.canvas.height() as f64, ); } pub fn update(&mut self) { let now = self.timer.now(); if now > self.last_update_time + 1000_f64 { self.last_update_time = now; self.tetris.update(); } } #[wasm_bindgen(js_name = handleInput)] pub fn handle_input(&mut self, key: u32) { use MoveDirection::*; use RotationDirection::*; use TetrisAction::*; // TODO: create macro/test to ensure all variants of TetrisAction are returned // https://stackoverflow.com/questions/58715081/how-to-ensure-every-enum-variant-can-be-returned-from-a-specific-function-at-com let action = match key { 0 => Some(Move(Down)), 1 => Some(Move(Left)), 2 => Some(Move(Right)), 3 => Some(Rotate(CounterClockwise)), 4 => Some(Rotate(Clockwise)), _ => None, }; if let Some(action) = action { self.tetris.do_action(action); }; } // TODO rename to set_size pub fn resize(&mut self, width: u32, height: u32) { self.canvas.set_width(width); self.canvas.set_height(height); self.square_drawer = { let square_length = self.canvas.height() as f64 / PLAYFIELD_DIM.1 as f64; let square_padding = (square_length * 0.1_f64).sqrt(); SquareDrawer::new(square_length, square_padding) }; self.render(); } } pub struct SquareDrawer { length: f64, padding: f64, } impl SquareDrawer { pub fn new(length: f64, padding: f64) -> Self { Self { length, padding } } pub fn draw(&self, ctx: &CanvasRenderingContext2d, pos: (f64, f64), color: &str) { let (l, p) = (self.length, self.padding); let (x, y) = (pos.0 * l, pos.1 * l); ctx.set_fill_style(&JsValue::from(color)); ctx.fill_rect(x + p, y + p, l - (p * 2_f64), l - (p * 2_f64)); } }
#![no_std] use core::{cmp::min, fmt}; pub use crypto_mac::Mac; use crypto_mac::{InvalidKeyLength, MacResult}; use digest::{ generic_array::sequence::GenericSequence, generic_array::{ArrayLength, GenericArray}, BlockInput, FixedOutput, Input, Reset, }; const IPAD: u8 = 0x36; const OPAD: u8 = 0x5c; /// The HMAC using a hash function `D` pub struct Hmac<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength<u8>, { digest: D, i_key_pad: GenericArray<u8, D::BlockSize>, opad_digest: D, } impl<D> Mac for Hmac<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength<u8>, D::OutputSize: ArrayLength<u8>, { type OutputSize = D::OutputSize; type KeySize = D::BlockSize; fn new(key: &GenericArray<u8, Self::KeySize>) -> Self { Self::new_varkey(key.as_slice()).unwrap() } #[inline] fn new_varkey(key: &[u8]) -> Result<Self, InvalidKeyLength> { let mut hmac = Self { digest: Default::default(), i_key_pad: GenericArray::generate(|_| IPAD), opad_digest: Default::default(), }; let mut opad = GenericArray::<u8, D::BlockSize>::generate(|_| OPAD); debug_assert!(hmac.i_key_pad.len() == opad.len()); // The key that Hmac processes must be the same as the block size of the // underlying Digest. If the provided key is smaller than that, we just // pad it with zeros. If its larger, we hash it and then pad it with // zeros. if key.len() <= hmac.i_key_pad.len() { for (k_idx, k_itm) in key.iter().enumerate() { hmac.i_key_pad[k_idx] ^= *k_itm; opad[k_idx] ^= *k_itm; } } else { let mut digest = D::default(); digest.input(key); let output = digest.fixed_result(); let n = min(output.len(), hmac.i_key_pad.len()); for idx in 0..n { hmac.i_key_pad[idx] ^= output[idx]; opad[idx] ^= output[idx]; } } hmac.digest.input(&hmac.i_key_pad); hmac.opad_digest.input(&opad); Ok(hmac) } #[inline] fn input(&mut self, data: &[u8]) { self.digest.input(data); } #[inline] fn result(self) -> MacResult<D::OutputSize> { let mut opad_digest = self.opad_digest.clone(); let hash = self.digest.fixed_result(); opad_digest.input(&hash); MacResult::new(opad_digest.fixed_result()) } #[inline] fn reset(&mut self) { self.digest.reset(); self.digest.input(&self.i_key_pad); } } impl<D> Clone for Hmac<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength<u8>, { fn clone(&self) -> Hmac<D> { Hmac { digest: self.digest.clone(), i_key_pad: self.i_key_pad.clone(), opad_digest: self.opad_digest.clone(), } } } impl<D> fmt::Debug for Hmac<D> where D: Input + BlockInput + FixedOutput + Reset + Default + Clone + fmt::Debug, D::BlockSize: ArrayLength<u8>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Hmac") .field("digest", &self.digest) .field("i_key_pad", &self.i_key_pad) .field("opad_digest", &self.opad_digest) .finish() } }
use cpu::register::Register; use cpu::CPU; /// Perform and or between accumulator and register and put results into the accumulator /// /// Sets condition flags /// /// # Cycles /// /// * Register M: 7 /// * Other: 4 /// /// # Arguments /// /// * `cpu` - The cpu to perform the or in /// * `register` - The register to perform the or with /// pub fn ora(cpu: &mut CPU, register: Register) -> u8 { let result = cpu.a | match register { Register::A => cpu.a, Register::B => cpu.b, Register::C => cpu.c, Register::D => cpu.d, Register::E => cpu.e, Register::H => cpu.h, Register::L => cpu.l, Register::M => { let offset = (u16::from(cpu.h) << 8) + u16::from(cpu.l); cpu.memory[offset as usize] } unsupported => { panic!("ora doesn't support {:?}", unsupported); } }; cpu.a = result; cpu.flags.set(result, false); match register { Register::M => 7, _ => 4, } } /// Perform and or between accumulator and the next immediate byte and put results into the accumulator /// /// Sets condition flags /// /// # Cycles /// /// 7 /// /// # Arguments /// /// * `cpu` - The cpu to perform the or in /// pub fn ori(cpu: &mut CPU) -> u8 { let byte = cpu.read_byte().unwrap(); let result = cpu.a | byte; cpu.a = result; cpu.flags.set(result, false); 7 } #[cfg(test)] mod test { use super::*; use cpu::flags::Flags; #[test] fn ora_resets_carry_bit() { let mut cpu = CPU { a: 123, b: 123, flags: Flags { carry: true, ..Flags::default() }, ..CPU::default() }; ora(&mut cpu, Register::B); assert_eq!(cpu.flags.carry, false); } #[test] fn ora_b_ors_b_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, b: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::B); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_c_ors_c_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, c: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::C); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_d_ors_d_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, d: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::D); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_e_ors_e_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, e: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::E); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_h_ors_h_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, h: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::H); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_l_ors_l_with_accumulator() { let mut cpu = CPU { a: 0b0101_1100, l: 0b0111_1000, ..CPU::default() }; ora(&mut cpu, Register::L); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ora_a_ors_a_with_accumulator() { let mut cpu = CPU { a: 0b1111_1100, ..CPU::default() }; ora(&mut cpu, Register::A); assert_eq!(cpu.a, 0b1111_1100); } #[test] fn ora_m_ors_byte_at_hl_address_to_accumulator() { let mut cpu = CPU { memory: vec![0x00, 0x00, 0x00, 0x00, 0x00, 0b0111_1000], a: 0b0101_1100, h: 0x00, l: 0x05, ..CPU::default() }; ora(&mut cpu, Register::M); assert_eq!(cpu.a, 0b0111_1100); } #[test] fn ori_ors_immediate_byte_with_accumulator() { let mut cpu = CPU { memory: vec![0b0011_0101, 0b0010_0110], a: 0b0111_0000, flags: Flags { carry: true, ..Flags::default() }, ..CPU::default() }; ori(&mut cpu); assert_eq!(cpu.a, 0b0111_0101); assert_eq!(cpu.flags.carry, false); ori(&mut cpu); assert_eq!(cpu.a, 0b0111_0111); assert_eq!(cpu.flags.carry, false); } }
#[derive(Clone, Debug, PartialEq, Eq)] pub enum TokenKind { Character(char), Number(usize), BraceString(String), } impl TokenKind { pub fn is_character(&self) -> bool { match self { TokenKind::Character(_) => true, _ => false, } } pub fn is_number(&self) -> bool { match self { TokenKind::Number(_) => true, _ => false, } } pub fn is_brace_string(&self) -> bool { match self { TokenKind::BraceString(_) => true, _ => false, } } } use std::fmt; impl fmt::Display for TokenKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TokenKind::Character(x) => write!(f, "{}", x), TokenKind::Number(x) => write!(f, "{}", x), TokenKind::BraceString(x) => write!(f, "{}", x), } } } pub type Token = (usize, TokenKind); pub fn tokenize(mml: &str) -> Result<Vec<Token>, String> { let is_ascii = mml.chars().all(|x| x <= '\u{7f}'); if !is_ascii { return Err("MML must not include any non-ascii characters".to_string()); } let mut chars = mml.chars().enumerate().peekable(); let mut tokens = Vec::new(); while let Some((i, byte)) = chars.next() { let token = if '0' <= byte && byte <= '9' { let mut number = (byte as u8 - b'0') as usize; while let Some(&(_, peeked)) = chars.peek() { if !('0' <= peeked && peeked <= '9') { break; } let (multiplied, mul_overflowed) = number.overflowing_mul(10); let (added, add_overflowed) = multiplied.overflowing_add((peeked as u8 - b'0') as usize); if mul_overflowed || add_overflowed { return Err(format!("Too big number at {}", i + 1)); } number = added; chars.next(); } TokenKind::Number(number) } else if byte == '{' { let mut string = String::new(); loop { let peeked = chars.next(); match peeked { Some((_, '}')) => break TokenKind::BraceString(string), Some((_, x)) if !x.is_whitespace() => { string.push(x) } Some((_, _)) => (), None => return Err("Unexpected EOF".to_string()), } } } else if 'A' <= byte && byte <= 'Z' { TokenKind::Character(byte.to_lowercase().next().unwrap()) } else if byte.is_whitespace() { continue; } else { TokenKind::Character(byte) }; tokens.push((i + 1, token)); } Ok(tokens) }
use std::usize; use winit::event::{DeviceEvent, ElementState, Event, MouseScrollDelta, VirtualKeyCode}; use super::{ engine::Engine, window::{Window, WindowMode}, }; #[derive(Debug, PartialEq, Copy, Clone)] struct InputState { /// Stores whether a mouse button is held down mouse_held: [bool; 16], /// Stores whether a key is held down during key_held: [bool; 255], /// The current mouse position mouse_delta: (f64, f64), /// Amount of scroll scroll_delta: (f32, f32), } impl Default for InputState { fn default() -> Self { InputState { mouse_held: [false; 16], key_held: [false; 255], mouse_delta: (0., 0.), scroll_delta: (0., 0.), } } } impl InputState { // rolling over to the next frame, deciding which values to keep and which not fn rollover(&mut self) { self.mouse_delta = (0., 0.); self.scroll_delta = (0., 0.); } } pub struct Input { /// The current input state state: InputState, /// The input state last frame state_prev: InputState, /// Whether we should keep sending events even when the window is not focused events_during_unfocus: bool, /// Whether the cursor is currently captured cursor_captured: bool, } impl Input { pub(crate) fn new() -> Self { Self { state: InputState::default(), state_prev: InputState::default(), events_during_unfocus: false, cursor_captured: true, } } pub(crate) fn update(&mut self, event: &Event<()>, engine: &Engine) { // match other events only if the window is focused if engine.window.is_focused() || self.events_during_unfocus { self.handle_input(event); } } // handle input events fn handle_input(&mut self, event: &Event<()>) { match event { // mouse button Event::DeviceEvent { event: DeviceEvent::Button { button, state }, .. } => match state { ElementState::Pressed => { self.state.mouse_held[*button as usize] = true; } ElementState::Released => { self.state.mouse_held[*button as usize] = false; } }, // mouse motion Event::DeviceEvent { event: DeviceEvent::MouseMotion { delta }, .. } => { self.state.mouse_delta = *delta; } // mouse wheel Event::DeviceEvent { event: DeviceEvent::MouseWheel { delta }, .. } => match delta { MouseScrollDelta::LineDelta(x, y) => { self.state.scroll_delta = (*x, *y); } // this does not work for some reason MouseScrollDelta::PixelDelta(_pos) => {} }, // key press Event::DeviceEvent { event: DeviceEvent::Key(input), .. } => { if let Some(vcc) = input.virtual_keycode { match input.state { ElementState::Pressed => { self.state.key_held[vcc as usize] = true; } ElementState::Released => { self.state.key_held[vcc as usize] = false; } } } } _ => {} } } // handles built-in key presses pub(crate) fn handle_builtin(&mut self, window: &mut Window) { if self.get_button_down(VirtualKeyCode::LAlt) && self.get_button_was_down(VirtualKeyCode::Return) { if window.get_mode() == WindowMode::Windowed { window.set_mode(WindowMode::Exclusive); } else { window.set_mode(WindowMode::Windowed); } } if self.get_button_was_down(VirtualKeyCode::Escape) { self.cursor_captured = !self.cursor_captured; window.set_capture_cursor(self.cursor_captured); } } // run this right after the gameloop update /// Rolls the input state over to next frame pub(crate) fn rollover_state(&mut self) { // reset state and assign prev self.state_prev = self.state; self.state.rollover(); } /// Returns whether the cursor is currently captured pub fn get_cursor_captured(&self) -> bool { self.cursor_captured } /// Returns whether the button was pressed this frame pub fn get_button_was_down(&self, key: VirtualKeyCode) -> bool { !self.state_prev.key_held[key as usize] && self.state.key_held[key as usize] } /// Returns whether the button is pressed down right now pub fn get_button_down(&self, key: VirtualKeyCode) -> bool { self.state.key_held[key as usize] } /// Returns whether the button is not pressed right now pub fn get_button_up(&self, key: VirtualKeyCode) -> bool { !self.get_button_down(key) } /// Returns the mouse delta pub fn get_mouse_delta(&self) -> (f64, f64) { self.state.mouse_delta } /// Returns the scroll delta pub fn get_scroll_delta(&self) -> (f32, f32) { self.state.scroll_delta } /// Set whether events should be recieved even though the window is not focused pub fn set_recieve_events_during_unfocus(&mut self, events_during_unfocus: bool) { self.events_during_unfocus = events_during_unfocus; } }
use std::path::Path; use sdl2::event::Event; use sdl2::pixels::Color; use sdl2::rect::Rect; use sdl2::render::TextureQuery; use setup; const SCREEN_WIDTH: u32 = 640; const SCREEN_HEIGHT: u32 = 480; // handle the annoying Rect i32 macro_rules! rect( ($x:expr, $y:expr, $w:expr, $h:expr) => ( Rect::new($x as i32, $y as i32, $w as u32, $h as u32) ) ); // SDL_ttf creates a new image from a font and a colour // So, we will be loading our image from text rendered by SDL_ttf instead of a file. pub fn font_rendering() { let basic_window_setup = setup::init("Font Rendering", SCREEN_WIDTH, SCREEN_HEIGHT); let mut events = basic_window_setup.sdl_context.event_pump().unwrap(); let ttf = basic_window_setup.ttf_context; let mut renderer = basic_window_setup.window .renderer() .present_vsync() .accelerated() .build() .unwrap(); // Load a font let path: &Path = Path::new("resources/lazy.ttf"); // let attr = fs::metadata(path).ok().expect("cannot query file"); let font_px_size = 128; let font = ttf.load_font(&path, font_px_size) .ok() .expect("Failed to load font"); let red: Color = Color::RGBA(255, 0, 0, 255); let surface = font.render("Hello Rust!").blended(red).unwrap(); let mut text_texture = renderer.create_texture_from_surface(&surface) .ok() .expect("Failed to create texture from image surface"); let TextureQuery { width, height, .. } = text_texture.query(); // If the example text is too big for the screen, downscale it (and center irregardless) let padding = 64; let target = get_centered_rect(width, height, SCREEN_WIDTH - padding, SCREEN_HEIGHT - padding); 'event: loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, Event::KeyDown{keycode: Some(::sdl2::keyboard::Keycode::Q), ..} => break 'event, _ => continue, } } renderer.set_draw_color(Color::RGB(0xff, 0xff, 0xff)); renderer.clear(); renderer.copy(&mut text_texture, None, Some(target)).expect("Texture copy failed"); renderer.present(); } setup::quit(); } // Scale fonts to a reasonable size when they're too big (though they might look less smooth) fn get_centered_rect(rect_width: u32, rect_height: u32, cons_width: u32, cons_height: u32) -> Rect { let wr = rect_width as f32 / cons_width as f32; let hr = rect_height as f32 / cons_height as f32; let (w, h) = if wr > 1f32 || hr > 1f32 { if wr > hr { println!("Scaling down! The text will look worse!"); let h = (rect_height as f32 / wr) as i32; (cons_width as i32, h) } else { println!("Scaling down! The text will look worse!"); let w = (rect_width as f32 / hr) as i32; (w, cons_height as i32) } } else { (rect_width as i32, rect_height as i32) }; let cx = (SCREEN_WIDTH as i32 - w) / 2; let cy = (SCREEN_HEIGHT as i32 - h) / 2; rect!(cx, cy, w, h) }
use crate::{ nfa, util::{ id::{PatternID, StateID}, start::Start, }, }; /// An error that occurred during the construction of a DFA. /// /// This error does not provide many introspection capabilities. There are /// generally only two things you can do with it: /// /// * Obtain a human readable message via its `std::fmt::Display` impl. /// * Access an underlying [`nfa::thompson::Error`] type from its `source` /// method via the `std::error::Error` trait. This error only occurs when using /// convenience routines for building a DFA directly from a pattern string. /// /// When the `std` feature is enabled, this implements the `std::error::Error` /// trait. #[derive(Clone, Debug)] pub struct Error { kind: ErrorKind, } /// The kind of error that occurred during the construction of a DFA. /// /// Note that this error is non-exhaustive. Adding new variants is not /// considered a breaking change. #[derive(Clone, Debug)] enum ErrorKind { /// An error that occurred while constructing an NFA as a precursor step /// before a DFA is compiled. NFA(nfa::thompson::Error), /// An error that occurred because an unsupported regex feature was used. /// The message string describes which unsupported feature was used. /// /// The primary regex feature that is unsupported by DFAs is the Unicode /// word boundary look-around assertion (`\b`). This can be worked around /// by either using an ASCII word boundary (`(?-u:\b)`) or by enabling the /// [`dense::Builder::allow_unicode_word_boundary`](dense/struct.Builder.html#method.allow_unicode_word_boundary) /// option when building a DFA. Unsupported(&'static str), /// An error that occurs if too many states are produced while building a /// DFA. TooManyStates, /// An error that occurs if too many start states are needed while building /// a DFA. /// /// This is a kind of oddball error that occurs when building a DFA with /// start states enabled for each pattern and enough patterns to cause /// the table of start states to overflow `usize`. TooManyStartStates, /// This is another oddball error that can occur if there are too many /// patterns spread out across too many match states. TooManyMatchPatternIDs, /// An error that occurs if the DFA got too big during determinization. DFAExceededSizeLimit { limit: usize }, /// An error that occurs if auxiliary storage (not the DFA) used during /// determinization got too big. DeterminizeExceededSizeLimit { limit: usize }, } impl Error { /// Return the kind of this error. fn kind(&self) -> &ErrorKind { &self.kind } pub(crate) fn nfa(err: nfa::thompson::Error) -> Error { Error { kind: ErrorKind::NFA(err) } } pub(crate) fn unsupported_dfa_word_boundary_unicode() -> Error { let msg = "cannot build DFAs for regexes with Unicode word \ boundaries; switch to ASCII word boundaries, or \ heuristically enable Unicode word boundaries or use a \ different regex engine"; Error { kind: ErrorKind::Unsupported(msg) } } pub(crate) fn too_many_states() -> Error { Error { kind: ErrorKind::TooManyStates } } pub(crate) fn too_many_start_states() -> Error { Error { kind: ErrorKind::TooManyStartStates } } pub(crate) fn too_many_match_pattern_ids() -> Error { Error { kind: ErrorKind::TooManyMatchPatternIDs } } pub(crate) fn dfa_exceeded_size_limit(limit: usize) -> Error { Error { kind: ErrorKind::DFAExceededSizeLimit { limit } } } pub(crate) fn determinize_exceeded_size_limit(limit: usize) -> Error { Error { kind: ErrorKind::DeterminizeExceededSizeLimit { limit } } } } #[cfg(feature = "std")] impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self.kind() { ErrorKind::NFA(ref err) => Some(err), ErrorKind::Unsupported(_) => None, ErrorKind::TooManyStates => None, ErrorKind::TooManyStartStates => None, ErrorKind::TooManyMatchPatternIDs => None, ErrorKind::DFAExceededSizeLimit { .. } => None, ErrorKind::DeterminizeExceededSizeLimit { .. } => None, } } } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self.kind() { ErrorKind::NFA(_) => write!(f, "error building NFA"), ErrorKind::Unsupported(ref msg) => { write!(f, "unsupported regex feature for DFAs: {}", msg) } ErrorKind::TooManyStates => write!( f, "number of DFA states exceeds limit of {}", StateID::LIMIT, ), ErrorKind::TooManyStartStates => { let stride = Start::count(); // The start table has `stride` entries for starting states for // the entire DFA, and then `stride` entries for each pattern // if start states for each pattern are enabled (which is the // only way this error can occur). Thus, the total number of // patterns that can fit in the table is `stride` less than // what we can allocate. let limit = ((core::isize::MAX as usize) - stride) / stride; write!( f, "compiling DFA with start states exceeds pattern \ pattern limit of {}", limit, ) } ErrorKind::TooManyMatchPatternIDs => write!( f, "compiling DFA with total patterns in all match states \ exceeds limit of {}", PatternID::LIMIT, ), ErrorKind::DFAExceededSizeLimit { limit } => write!( f, "DFA exceeded size limit of {:?} during determinization", limit, ), ErrorKind::DeterminizeExceededSizeLimit { limit } => { write!(f, "determinization exceeded size limit of {:?}", limit) } } } }
//! This module implements the session setup request. //! The SMB2 SESSION_SETUP Request packet is sent by the client to request a new authenticated session //! within a new or existing SMB 2 Protocol transport connection to the server. //! This request is composed of an SMB2 header, followed by this request structure. use rand::{ distributions::{Distribution, Standard}, Rng, }; /// session setup request size of 25 bytes const STRUCTURE_SIZE: &[u8; 2] = b"\x19\x00"; /// The SMB2 SESSION_SETUP Request packet is sent by the client to request a /// new authenticated session within a new or existing /// SMB 2 Protocol transport connection to the server. #[derive(Debug, PartialEq, Eq, Clone)] pub struct SessionSetup { /// StructureSize (2 bytes): The client MUST set this field to 25, /// indicating the size of the request structure, not including the header. /// The client MUST set it to this value regardless of how long Buffer[] /// actually is in the request being sent. pub structure_size: Vec<u8>, /// Flags (1 byte): If the client implements the SMB 3.x dialect family, /// this field MUST be set to combination of zero or more flags. /// Otherwise, it MUST be set to 0. pub flags: Vec<u8>, /// SecurityMode (1 byte): The security mode field specifies whether SMB signing /// is enabled or required at the client. This field MUST be set. pub security_mode: Vec<u8>, /// Capabilities (4 bytes): Specifies protocol capabilities for the client. pub capabilities: Vec<u8>, /// Channel (4 bytes): This field MUST NOT be used and MUST be reserved. /// The client MUST set this to 0, and the server MUST ignore it on receipt. pub channel: Vec<u8>, /// SecurityBufferOffset (2 bytes): The offset, in bytes, from the beginning of the /// SMB 2 Protocol header to the security buffer. pub security_buffer_offset: Vec<u8>, /// SecurityBufferLength (2 bytes): The length, in bytes, of the security buffer. pub security_buffer_length: Vec<u8>, /// PreviousSessionId (8 bytes): A previously established session identifier. /// The server uses this value to identify the client session that was disconnected due to a network error. pub previous_session_id: Vec<u8>, /// Buffer (variable): A variable-length buffer that contains the security buffer for the request, /// as specified by SecurityBufferOffset and SecurityBufferLength. /// If the server initiated authentication using SPNEGO, the buffer MUST contain a token as produced by /// the GSS protocol. If the client initiated authentication, the buffer SHOULD contain a token /// as produced by an authentication protocol of the client's choice. pub buffer: Vec<u8>, } impl SessionSetup { pub fn default() -> Self { SessionSetup { structure_size: STRUCTURE_SIZE.to_vec(), flags: Vec::new(), security_mode: Vec::new(), capabilities: Vec::new(), channel: b"\x00\x00\x00\x00".to_vec(), security_buffer_offset: Vec::new(), security_buffer_length: Vec::new(), previous_session_id: Vec::new(), buffer: Vec::new(), } } } /// *Session Setup Binding*: /// - When set, indicates that the request is to bind an existing session to a new connection. /// /// *Zero*: /// - Introduces an additional zero value if no flags are set. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Flags { SessionSetupBinding, Zero, } impl Flags { pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Flags::SessionSetupBinding => b"\x01".to_vec(), Flags::Zero => b"\x00".to_vec(), } } } impl Distribution<Flags> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Flags { match rng.gen_range(0..=1) { 0 => Flags::SessionSetupBinding, _ => Flags::Zero, } } } /// *Global Cap DFS*: /// - When set, indicates that the client supports the Distributed File System (DFS). /// /// *Global Cap Unused1*: /// - SHOULD be set to zero, and server MUST ignore. /// /// *Global Cap Unused2*: /// - SHOULD be set to zero, and server MUST ignore. /// /// *Global Cap Unused3*: /// - SHOULD be set to zero, and server MUST ignore. /// /// Values other than those that are defined in the negotiation capabilities table /// are unused at present and SHOULD be treated as reserved. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Capabilities { GlobalCapDfs, } impl Capabilities { /// Unpack the byte code of session setup capabilities. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Capabilities::GlobalCapDfs => b"\x00\x00\x00\x01".to_vec(), } } }
//! Tests for `#[derive(GraphQLInputObject)]` macro. pub mod common; use juniper::{ execute, graphql_object, graphql_value, graphql_vars, parser::SourcePosition, GraphQLError, GraphQLInputObject, RuleError, }; use self::common::util::schema; mod trivial { use super::*; #[derive(GraphQLInputObject)] struct Point2D { x: f64, y: f64, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { point.x } } #[tokio::test] async fn resolves() { const DOC: &str = r#"{ x(point: { x: 10, y: 20 }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"x": 10.0}), vec![])), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn uses_type_name() { const DOC: &str = r#"{ __type(name: "Point2D") { name } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Point2D"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Point2D") { description } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, { "name": "y", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, ]}}), vec![], )), ); } } mod default_value { use super::*; #[derive(GraphQLInputObject)] struct Point2D { #[graphql(default = 10.0)] x: f64, #[graphql(default = 10.0)] y: f64, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { point.x } } #[tokio::test] async fn resolves() { const DOC: &str = r#"query q($ve_num: Float!) { literal_implicit_other_number: x(point: { y: 20 }) literal_explicit_number: x(point: { x: 20 }) literal_implicit_all: x(point: {}) variable_explicit_number: x(point: { x: $ve_num }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {"ve_num": 40}, &()).await, Ok(( graphql_value!({ "literal_implicit_other_number": 10.0, "literal_explicit_number": 20.0, "literal_implicit_all": 10.0, "variable_explicit_number": 40.0, }), vec![], )), ); } #[tokio::test] async fn errs_on_explicit_null_literal() { const DOC: &str = r#"{ x(point: { x: 20, y: null }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Err(GraphQLError::ValidationError(vec![RuleError::new( "Invalid value for argument \"point\", expected type \"Point2D!\"", &[SourcePosition::new(11, 0, 11)], )])) ); } #[tokio::test] async fn errs_on_missing_variable() { const DOC: &str = r#"query q($x: Float!){ x(point: { x: $x }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Err(GraphQLError::ValidationError(vec![RuleError::new( "Variable \"$x\" of required type \"Float!\" was not provided.", &[SourcePosition::new(8, 0, 8)], )])) ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [{ "name": "x", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": "10", }, { "name": "y", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": "10", }]}}), vec![], )), ); } } mod default_nullable_value { use super::*; #[derive(GraphQLInputObject)] struct Point2D { #[graphql(default = 10.0)] x: Option<f64>, #[graphql(default = 10.0)] y: Option<f64>, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> Option<f64> { point.x } } #[tokio::test] async fn resolves() { const DOC: &str = r#"query q( $ve_num: Float, $ve_null: Float, $vi: Float, $vde_num: Float = 40, $vde_null: Float = 50, $vdi: Float = 60, ) { literal_implicit_other_number: x(point: { y: 20 }) literal_explicit_number: x(point: { x: 20 }) literal_implicit_all: x(point: {}) literal_explicit_null: x(point: { x: null }) literal_implicit_other_null: x(point: { y: null }) variable_explicit_number: x(point: { x: $ve_num }) variable_explicit_null: x(point: { x: $ve_null }) variable_implicit: x(point: { x: $vi }) variable_default_explicit_number: x(point: { x: $vde_num }) variable_default_explicit_null: x(point: { x: $vde_null }) variable_default_implicit: x(point: { x: $vdi }) }"#; let schema = schema(QueryRoot); assert_eq!( execute( DOC, None, &schema, &graphql_vars! { "ve_num": 30.0, "ve_null": null, "vde_num": 100, "vde_null": null, }, &(), ) .await, Ok(( graphql_value!({ "literal_implicit_other_number": 10.0, "literal_explicit_number": 20.0, "literal_implicit_all": 10.0, "literal_explicit_null": null, "literal_implicit_other_null": 10.0, "variable_explicit_number": 30.0, "variable_explicit_null": null, "variable_implicit": 10.0, "variable_default_explicit_number": 100.0, "variable_default_explicit_null": null, "variable_default_implicit": 60.0, }), vec![], )), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { name ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x", "description": null, "type": {"name": "Float", "ofType": null}, "defaultValue": "10", }, { "name": "y", "description": null, "type": {"name": "Float", "ofType": null}, "defaultValue": "10", }, ]}}), vec![], )), ); } } mod ignored_field { use super::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum System { Cartesian, } #[derive(GraphQLInputObject)] struct Point2D { x: f64, y: f64, #[graphql(ignore)] shift: f64, #[graphql(skip, default = System::Cartesian)] system: System, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { assert_eq!(point.shift, f64::default()); assert_eq!(point.system, System::Cartesian); point.x } } #[tokio::test] async fn resolves() { const DOC: &str = r#"{ x(point: { x: 10, y: 20 }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"x": 10.0}), vec![])), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn uses_type_name() { const DOC: &str = r#"{ __type(name: "Point2D") { name } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Point2D"}}), vec![])), ); } #[tokio::test] async fn has_no_description() { const DOC: &str = r#"{ __type(name: "Point2D") { description } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"description": null}}), vec![])), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, { "name": "y", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, ]}}), vec![], )), ); } } mod description_from_doc_comment { use super::*; /// Point in a Cartesian system. #[derive(GraphQLInputObject)] struct Point2D { /// Abscissa value. x: f64, /// Ordinate value. y_coord: f64, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { point.x } } #[tokio::test] async fn resolves() { const DOC: &str = r#"{ x(point: { x: 10, yCoord: 20 }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"x": 10.0}), vec![])), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn uses_type_name() { const DOC: &str = r#"{ __type(name: "Point2D") { name } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Point2D"}}), vec![])), ); } #[tokio::test] async fn has_description() { const DOC: &str = r#"{ __type(name: "Point2D") { description } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "description": "Point in a Cartesian system.", }}), vec![] )), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x", "description": "Abscissa value.", "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, { "name": "yCoord", "description": "Ordinate value.", "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, ]}}), vec![], )), ); } } mod description_from_graphql_attr { use super::*; /// Ignored doc. #[derive(GraphQLInputObject)] #[graphql(name = "Point", desc = "Point in a Cartesian system.")] struct Point2D { /// Ignored doc. #[graphql(name = "x", description = "Abscissa value.")] x_coord: f64, /// Ordinate value. y: f64, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { point.x_coord } } #[tokio::test] async fn resolves() { const DOC: &str = r#"{ x(point: { x: 10, y: 20 }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"x": 10.0}), vec![])), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn uses_type_name() { const DOC: &str = r#"{ __type(name: "Point") { name } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"name": "Point"}}), vec![])), ); } #[tokio::test] async fn has_description() { const DOC: &str = r#"{ __type(name: "Point") { description } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": { "description": "Point in a Cartesian system.", }}), vec![] )), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x", "description": "Abscissa value.", "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, { "name": "y", "description": "Ordinate value.", "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, ]}}), vec![], )), ); } } mod renamed_all_fields { use super::*; #[derive(GraphQLInputObject)] #[graphql(rename_all = "none")] struct Point2D { x_coord: f64, y: f64, } struct QueryRoot; #[graphql_object] impl QueryRoot { fn x(point: Point2D) -> f64 { point.x_coord } } #[tokio::test] async fn resolves() { const DOC: &str = r#"{ x(point: { x_coord: 10, y: 20 }) }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"x": 10.0}), vec![])), ); } #[tokio::test] async fn is_graphql_input_object() { const DOC: &str = r#"{ __type(name: "Point2D") { kind } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"__type": {"kind": "INPUT_OBJECT"}}), vec![])), ); } #[tokio::test] async fn has_input_fields() { const DOC: &str = r#"{ __type(name: "Point2D") { inputFields { name description type { ofType { name } } defaultValue } } }"#; let schema = schema(QueryRoot); assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"__type": {"inputFields": [ { "name": "x_coord", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, { "name": "y", "description": null, "type": {"ofType": {"name": "Float"}}, "defaultValue": null, }, ]}}), vec![], )), ); } }
use crate::fs::FileTypeTrait; use std::ffi::OsStr; use std::fmt::Debug; use std::fs; use std::io; use std::path::Path; pub trait DirEntryTrait: Debug { /// The full path that this entry represents. /// /// See [`walkdir::DirEntry::path`] for more details fn path(&self) -> &Path; /// Return `true` if and only if this entry was created from a symbolic /// link. This is unaffected by the [`follow_links`] setting. /// /// See [`walkdir::DirEntry::path_is_symlink`] for more details fn path_is_symlink(&self) -> bool; /// Return the metadata for the file that this entry points to. /// /// See [`walkdir::DirEntry::metadata`] for more details fn metadata(&self) -> io::Result<fs::Metadata>; /// Return the file type for the file that this entry points to. /// /// See [`walkdir::DirEntry::file_type`] for more details fn file_type(&self) -> Box<dyn FileTypeTrait>; /// Return the file name of this entry. /// /// See [`walkdir::DirEntry::file_name`] for more details fn file_name(&self) -> &OsStr; } pub mod standalone; pub mod validation_dir_entry; pub mod walkdir_impl; pub type WalkdirDirEntry = walkdir_impl::DirEntry; pub type StandaloneDirEntry = standalone::DirEntry; pub type ValidationDirEntry = validation_dir_entry::DirEntry;
use futures_util::future::BoxFuture; use crate::any::connection::AnyConnectionKind; use crate::any::{Any, AnyConnection}; use crate::database::Database; use crate::error::Error; use crate::transaction::TransactionManager; pub struct AnyTransactionManager; impl TransactionManager for AnyTransactionManager { type Database = Any; fn begin(conn: &mut AnyConnection) -> BoxFuture<'_, Result<(), Error>> { match &mut conn.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => { <crate::postgres::Postgres as Database>::TransactionManager::begin(conn) } #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => { <crate::mysql::MySql as Database>::TransactionManager::begin(conn) } #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => { <crate::sqlite::Sqlite as Database>::TransactionManager::begin(conn) } #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => { <crate::mssql::Mssql as Database>::TransactionManager::begin(conn) } } } fn commit(conn: &mut AnyConnection) -> BoxFuture<'_, Result<(), Error>> { match &mut conn.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => { <crate::postgres::Postgres as Database>::TransactionManager::commit(conn) } #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => { <crate::mysql::MySql as Database>::TransactionManager::commit(conn) } #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => { <crate::sqlite::Sqlite as Database>::TransactionManager::commit(conn) } #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => { <crate::mssql::Mssql as Database>::TransactionManager::commit(conn) } } } fn rollback(conn: &mut AnyConnection) -> BoxFuture<'_, Result<(), Error>> { match &mut conn.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => { <crate::postgres::Postgres as Database>::TransactionManager::rollback(conn) } #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => { <crate::mysql::MySql as Database>::TransactionManager::rollback(conn) } #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => { <crate::sqlite::Sqlite as Database>::TransactionManager::rollback(conn) } #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => { <crate::mssql::Mssql as Database>::TransactionManager::rollback(conn) } } } fn start_rollback(conn: &mut AnyConnection) { match &mut conn.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => { <crate::postgres::Postgres as Database>::TransactionManager::start_rollback(conn) } #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => { <crate::mysql::MySql as Database>::TransactionManager::start_rollback(conn) } #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => { <crate::sqlite::Sqlite as Database>::TransactionManager::start_rollback(conn) } #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => { <crate::mssql::Mssql as Database>::TransactionManager::start_rollback(conn) } } } }
pub use chain::*; pub use chain_btc::*; pub use chain_eee::*; pub use chain_eth::*; pub use error::*; pub use parameters::*; pub use setting::*; pub use traits::*; pub use types::*; pub use wallet::*; mod types; mod wallet; mod parameters; mod chain; mod chain_eth; mod chain_eee; mod chain_btc; mod error; mod traits; mod setting; /// Sample code: deref_type!(Data,MData) /// ```` /// use std::ops::{DerefMut,Deref}; /// struct MData{} /// struct Data{ /// pub m: MData, /// } /// /// impl Deref for Data { /// type Target = MData; /// /// fn deref(&self) -> &Self::Target { /// &self.m /// } /// } /// /// impl DerefMut for Data{ /// fn deref_mut(&mut self) -> &mut Self::Target { /// &mut self.m /// } /// } /// ```` #[macro_export] macro_rules! deref_type { ($t:path,$mt:path) => { impl std::ops::Deref for $t { type Target = $mt; fn deref(&self) -> &Self::Target { &self.m } } impl std::ops::DerefMut for $t{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.m } } }; } #[cfg(test)] pub mod tests { use std::sync::atomic::Ordering; use failure::_core::sync::atomic::AtomicBool; use futures::executor::block_on; use mav::kits::test::{mock_files_db, mock_memory_db}; use mav::ma::{Db, DbName}; use crate::ContextTrait; struct WalletsMock { db: Db, stopped: AtomicBool, } impl ContextTrait for WalletsMock { fn db(&self) -> &Db { &self.db } fn stopped(&self) -> bool { self.stopped.load(Ordering::SeqCst) //todo } fn set_stopped(&mut self, s: bool) { self.stopped.store(s, Ordering::SeqCst);//todo } } pub fn mock_memory_context() -> Box<dyn ContextTrait> { let mut t = WalletsMock { db: mock_memory_db(), stopped: Default::default(), }; Box::new(t) } pub fn mock_files_context() -> Box<dyn ContextTrait> { let mut t = WalletsMock { db: mock_files_db(), stopped: Default::default(), }; Box::new(t) } }
pub mod core; /* */
mod game; mod mastermind; use clap::{App, Arg}; use std::io; const DEFAULT_COLORS_COUNT: u32 = 4; fn main() -> Result<(), io::Error> { let matches = App::new("MasterMind") .args(&[ Arg::new("len") .long("len") .short('l') .about("Sets the length of the hidden composition") .default_value(&DEFAULT_COLORS_COUNT.to_string()) .takes_value(true), Arg::new("ai") .long("ai") .short('i') .about("Let an AI solve the game"), ]) .get_matches(); let len: u32 = matches.value_of_t("len").unwrap(); if matches.is_present("ai") { game::as_ai::run(len); } else { game::as_human::run(len)?; } Ok(()) }
use std::env::args; use std::net::UdpSocket; use std::str::from_utf8; fn main() -> std::io::Result<()> { let arguments: Vec<String> = args().collect(); let addr = &arguments[1]; let socket = UdpSocket::bind(addr)?; let mut buf = [0; 100]; let (amt, src) = socket.recv_from(&mut buf)?; println!("{}:{:?}:{}", amt, src, from_utf8(&buf).unwrap()); Ok(()) }
//! Tmux version checks use std::cmp::Ordering; /// Represents Tmux version. /// /// If for some reason `tmux -V` does not work, or can't parse the output /// Will return [TmuxVersion::Max]. #[derive(Debug, PartialEq)] pub enum TmuxVersion { Max, Version(usize, usize), } impl From<Option<&str>> for TmuxVersion { fn from(value: Option<&str>) -> Self { if value.is_none() { return Self::Max; } let value = value.unwrap(); let re = regex::Regex::new(r"(?P<major>\d+)\.(?P<minor>\d+)").unwrap(); let captures = re.captures(value); if captures.is_none() { return Self::Max; } let captures = captures.unwrap(); let major_match = captures.name("major"); let minor_match = captures.name("minor"); let major: usize = match major_match { None => 0, Some(s) => s.as_str().parse().unwrap_or(0), }; let minor = match minor_match { None => 0, Some(s) => s.as_str().parse().unwrap_or(0), }; Self::Version(major, minor) } } impl PartialOrd for TmuxVersion { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match (self, other) { (TmuxVersion::Max, TmuxVersion::Max) => Some(Ordering::Equal), (TmuxVersion::Max, TmuxVersion::Version(_, _)) => Some(Ordering::Greater), (TmuxVersion::Version(_, _), TmuxVersion::Max) => Some(Ordering::Less), (TmuxVersion::Version(x1, x2), TmuxVersion::Version(y1, y2)) => { if x1 == y1 { return x2.partial_cmp(y2); } return x1.partial_cmp(y1); } } } } #[cfg(test)] mod tests { use super::TmuxVersion; #[test] fn test_version_strings_none() { let version: TmuxVersion = None.into(); assert_eq!(version, TmuxVersion::Max); } #[test] fn test_version_strings() { let empty = Some(""); let some_version = Some("tmux 3.3a"); let next_version = Some("tmux next-3.4"); assert_eq!(TmuxVersion::from(empty), TmuxVersion::Max); assert_eq!(TmuxVersion::from(some_version), TmuxVersion::Version(3, 3)); assert_eq!(TmuxVersion::from(next_version), TmuxVersion::Version(3, 4)); } #[test] fn test_version_compare() { assert!(TmuxVersion::Max > TmuxVersion::Version(2, 0)); assert!(TmuxVersion::Version(3, 0) > TmuxVersion::Version(2, 900)); assert!(TmuxVersion::Version(3, 1) < TmuxVersion::Version(3, 2)); assert!(TmuxVersion::Version(3, 1) >= TmuxVersion::Version(3, 1)); } }
// Copyright 2018 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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. //! A Postgres Allocator use std::alloc::{GlobalAlloc, Layout}; use std::ffi::c_void; use crate::pg_sys; /// An allocattor which uses the palloc and pfree functions available from Postgres. /// /// This is managed by Postgres and guarantees that all memory is freed after a transaction completes. pub struct PgAllocator; unsafe impl GlobalAlloc for PgAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // TODO: is there anything we need to do in terms of layout, etc? pg_sys::palloc(layout.size()) as *mut u8 } unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { pg_sys::pfree(dbg!(ptr) as *mut c_void) } }
#[macro_use] extern crate lazy_static; use clap::Clap; use regex::{Captures, Regex}; use std::fs::read_to_string; #[derive(Clap)] struct Opts { input: String, } fn main() -> Result<(), std::io::Error> { let opts: Opts = Opts::parse(); let input = read_to_string(opts.input)?; let count_valid = input .lines() .map(|l| parse(l)) .filter(|r| test_row(r)) .count(); println!("{}", count_valid); Ok(()) } #[derive(Debug)] struct Row<'t> { letter: &'t str, min_occurances: i32, max_occurances: i32, password: &'t str, } fn unwrap_match<'t>(captures: &Option<Captures<'t>>, name: &str) -> Option<&'t str> { match captures { Some(cap) => cap.name(name).map(|m| m.as_str()), None => None, } } fn parse<'t>(string: &'t str) -> Row { lazy_static! { static ref RE: Regex = Regex::new(r"(?P<min>\d+)-(?P<max>\d+) (?P<letter>[a-z]): (?P<password>[a-z]+)") .unwrap(); } let captures = RE.captures(string); Row { min_occurances: unwrap_match(&captures, "min") .unwrap() .parse::<i32>() .unwrap(), max_occurances: unwrap_match(&captures, "max") .unwrap() .parse::<i32>() .unwrap(), letter: unwrap_match(&captures, "letter").unwrap(), password: unwrap_match(&captures, "password").unwrap(), } } fn test_row(row: &Row) -> bool { let mut occurances = 0; for c in row.password.chars().map(|c| c.to_string()) { if &c == row.letter { occurances += 1; } if occurances > row.max_occurances { return false; } } occurances >= row.min_occurances } #[cfg(test)] mod tests { use super::*; #[test] fn test_test_row() { assert_eq!( test_row(&Row { min_occurances: 1, max_occurances: 3, letter: "a", password: "abcde" }), true ); assert_eq!( test_row(&Row { min_occurances: 1, max_occurances: 3, letter: "b", password: "cdefg" }), false ); assert_eq!( test_row(&Row { min_occurances: 2, max_occurances: 9, letter: "c", password: "ccccccccc" }), true ); } }
use crate::models::User; use crate::errors::ServiceError; use crate::schema::users; use crate::schema::user_tokens; use diesel::prelude::*; use crate::models::*; use diesel::r2d2::Pool; use diesel::r2d2::ConnectionManager; use crate::state::AppState; use crate::repositories::UserRepository; use serde::Deserialize; use serde::Serialize; #[derive(Deserialize)] pub struct LoginUser { pub username: String, pub password: String, } #[derive(Deserialize)] pub struct RegisterUser { pub username: String, pub password: String, } #[derive(Deserialize)] pub struct LogoutUser { pub token: String } #[derive(Serialize)] pub struct SimpleUser { pub username: String, pub id: i64, } #[derive(Serialize)] pub struct AuthResult { pub token: String, pub user: SimpleUser, } pub trait UserService { fn login(&self, login_user: LoginUser) -> Result<AuthResult, ServiceError>; fn logout(&self, logout_user: LogoutUser) -> Result<(), ServiceError>; fn register(&self, register_user: RegisterUser) -> Result<AuthResult, ServiceError>; } pub struct PsqlUserService { pub pool: Box<Pool<ConnectionManager<PgConnection>>>, pub app_state: Box<AppState> } impl UserService for PsqlUserService { fn login(&self, login_user: LoginUser) -> Result<AuthResult, ServiceError> { let connection = match self.pool.get() { Ok(connection) => connection, Err(_) => return Err(ServiceError::Server { message: None }), }; let user = match users::dsl::users.filter(users::username.eq(login_user.username)).first::<User>(&connection) { Ok(user) => user, Err(err) => return Err(ServiceError::from_diesel_result_error(err)) }; if !user.check_password(login_user.password) { return Err( ServiceError::Client { message: String::from("password not missmatch") } ); } let token = NewUserToken::new(user.id); return match diesel::insert_into(user_tokens::table).values(token).get_result::<UserToken>(&connection) { Ok(user_token) => { Ok( AuthResult { token: user_token.token, user: SimpleUser { username: user.username, id: user.id, } } ) } Err(_) => { Err( ServiceError::Server { message: Some(String::from("")) } ) } }; } fn logout(&self, logout_user: LogoutUser) -> Result<(), ServiceError> { if let Ok(connection) = self.pool.get() { return if diesel::delete(user_tokens::dsl::user_tokens.filter(user_tokens::token.eq(logout_user.token))).execute(&connection).is_ok() { Ok(()) } else { Err(ServiceError::Server { message: None }) }; } return Err(ServiceError::NotFound); } fn register(&self, register_user: RegisterUser) -> Result<AuthResult, ServiceError> { let connection = match self.pool.get() { Ok(connection) => connection, Err(_) => return Err(ServiceError::Server { message: Some(String::from("")) }) }; let new_user = match NewUser::new(register_user.username, register_user.password) { Ok(new_user) => new_user, Err(e) => return Err( ServiceError::Server { message: Some(e) } ) }; let repo = &self.app_state.user_repository(); let user = match repo.create(new_user) { Ok(user) => user, Err(e) => { println!("ユーザ作成中にエラー発生 e: {}", e); return Err(ServiceError::from_diesel_result_error(e)) } }; let token = NewUserToken::new(user.id); let user_token = match diesel::insert_into(user_tokens::table).values(token).get_result::<UserToken>(&connection) { Ok(user_token) => user_token, Err(e) => return Err(ServiceError::from_diesel_result_error(e)) }; return Ok(AuthResult { token: user_token.token, user: SimpleUser { username: user.username, id: user.id } }); } }
mod common; use common::{round_beam_intersect, round_cutoff, round_tp}; use crisscross::{BeamIntersect, Crossing, Grid, TilePosition, TileRaycaster}; #[test] fn last_valid() { let tc = TileRaycaster::new(Grid::new(4, 4, 1.0)); assert_eq!( tc.last_valid(&((0, 0.0), (0, 0.0)).into(), 30_f32.to_radians(), |tp| { tp.y < 2 }) .map(round_tp), Some(((3, 0.000), (1, 0.732)).into()), ); } #[test] fn first_invalid() { let tc = TileRaycaster::new(Grid::new(4, 4, 1.0)); assert_eq!( tc.first_invalid(&((0, 0.0), (0, 0.0)).into(), 45_f32.to_radians(), |tp| { tp.x < 2 && tp.y < 2 }) .map(round_tp), Some(TilePosition { x: 2, rel_x: 0.000, y: 2, rel_y: 0.000 }), ); assert_eq!( tc.first_invalid(&((0, 0.0), (0, 0.0)).into(), 45_f32.to_radians(), |tp| { tp.x < 1 && tp.y < 1 }) .map(round_tp), Some(TilePosition { x: 1, rel_x: 0.000, y: 1, rel_y: 0.000 }), ); } #[test] fn beam_last_valid() { let tc = TileRaycaster::new(Grid::new(4, 4, 1.0)); let beam_width = 2.0; assert_eq!( tc.beam_last_valid( &((0, 0.0), (0, 0.0)).into(), beam_width, 30_f32.to_radians(), |BeamIntersect(_, tp)| { tp.y < 2 } ) .map(round_beam_intersect), Some(BeamIntersect(0, ((3, 0.000), (1, 0.732)).into())) ); } #[test] fn cutoff() { let tc = TileRaycaster::new(Grid::new(4, 4, 1.0)); let cutoff = round_cutoff(tc.crossing( &((0, 0.0), (0, 0.0)).into(), 30_f32.to_radians(), |tp| tp.y < 2, )); assert_eq!( cutoff, Crossing { valid: Some(((3, 0.000), (1, 0.732)).into(),), invalid: Some(((3, 0.464), (2, 0.000)).into()), } ); let tp_0_0: TilePosition = ((0, 0.0), (0, 0.0)).into(); assert_eq!( round_cutoff(tc.crossing(&tp_0_0, 0_f32.to_radians(), |tp| tp.x <= 0)), Crossing::default(), ); assert_eq!( round_cutoff(tc.crossing(&tp_0_0, 0_f32.to_radians(), |tp| tp.x <= 1)), Crossing { valid: Some(((1, 0.000), (0, 0.000)).into()), invalid: Some(((2, 0.000), (0, 0.000)).into()) } ); assert_eq!( round_cutoff(tc.crossing(&tp_0_0, 0_f32.to_radians(), |tp| tp.x <= 2)), Crossing { valid: Some(((2, 0.000), (0, 0.000)).into()), invalid: Some(((3, 0.000), (0, 0.000)).into()) } ); assert_eq!( round_cutoff(tc.crossing(&tp_0_0, 0_f32.to_radians(), |tp| tp.x <= 3)), Crossing { valid: Some(((3, 0.000), (0, 0.000)).into()), invalid: None, } ); assert_eq!( round_cutoff(tc.crossing(&tp_0_0, 0_f32.to_radians(), |tp| tp.x <= 4)), Crossing { valid: Some(((3, 0.000), (0, 0.000)).into()), invalid: None, } ); }
// 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 fidl_fuchsia_net_ext as fidl_net_ext; use fuchsia_async; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use crate::tests::{assert_ping, TestSetup}; trait TestAddr { const ALICE_IP: fidl_net_ext::IpAddress; const BOB_IP: fidl_net_ext::IpAddress; const SUBNET_ADDR: fidl_net_ext::IpAddress; const SUBNET_PREFIX: u8; } struct TestIpv4Addr; impl TestAddr for TestIpv4Addr { const ALICE_IP: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1))); const BOB_IP: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2))); const SUBNET_ADDR: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 0))); const SUBNET_PREFIX: u8 = 24; } struct TestIpv6Addr; impl TestAddr for TestIpv6Addr { const ALICE_IP: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V6(Ipv6Addr::new(2, 0, 0, 0, 0, 0, 0, 1))); const BOB_IP: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V6(Ipv6Addr::new(2, 0, 0, 0, 0, 0, 0, 2))); const SUBNET_ADDR: fidl_net_ext::IpAddress = fidl_net_ext::IpAddress(IpAddr::V6(Ipv6Addr::new(2, 0, 0, 0, 0, 0, 0, 0))); const SUBNET_PREFIX: u8 = 64; } async fn alice_to_bob_over_proto<A: TestAddr>(args: &str, expected_return_code: i64) { let mut t = TestSetup::new(A::SUBNET_ADDR.into(), A::SUBNET_PREFIX).await.unwrap(); let alice = t.add_env("alice", A::ALICE_IP.into()).await.unwrap(); let _bob = t.add_env("bob", A::BOB_IP.into()).await.unwrap(); let full_args = format!("{} -v {}", A::BOB_IP, args); assert_ping(&alice, &full_args, expected_return_code).await; } async fn alice_to_bob(args: &str, expected_return_code: i64) { alice_to_bob_over_proto::<TestIpv4Addr>(args, expected_return_code).await; alice_to_bob_over_proto::<TestIpv6Addr>(args, expected_return_code).await; } // Send a simple ping between two clients: Alice and Bob #[fuchsia_async::run_singlethreaded(test)] async fn can_ping() { alice_to_bob("-c 1", 0).await; } // Send a ping with insufficent payload size for a timestamp. #[fuchsia_async::run_singlethreaded(test)] async fn can_ping_without_timestamp() { alice_to_bob("-c 1 -s 0", 0).await; } // Send pings until a timeout. Exit with code 0. #[fuchsia_async::run_singlethreaded(test)] async fn can_timeout() { alice_to_bob("-w 5", 0).await; } // Send a set amount of pings that times out before completion. Exit with code 1. #[fuchsia_async::run_singlethreaded(test)] async fn not_enough_pings_before_timeout() { alice_to_bob("-c 1000 -w 5", 1).await; } // Specify an invalid count argument. Exit with code 2. #[fuchsia_async::run_singlethreaded(test)] async fn invalid_count() { alice_to_bob("-c 0", 2).await; } // Specify an invalid deadline argument. Exit with code 2. #[fuchsia_async::run_singlethreaded(test)] async fn invalid_deadline() { alice_to_bob("-w 0", 2).await; } // Specify an invalid interval argument. Exit with code 2. #[fuchsia_async::run_singlethreaded(test)] async fn invalid_interval() { alice_to_bob("-i 0", 2).await; }
//! REST API types. /// Matrix REST API pub mod matrix; /// Generic REST API mod rest_api; /// Rocket.Chat REST API pub mod rocketchat; pub use self::matrix::MatrixApi; pub use self::rest_api::{RequestData, RestApi}; pub use self::rocketchat::RocketchatApi;
use std::io::{self, Write}; use super::{Stmt, Expr, BodyRef, Function, FunctionPrototype, ParsedModule}; const INDENT_STRING: &str = " "; const SUBITEM_INDENT: &str = " "; fn print_body<W: Write>(body: BodyRef, w: &mut W, indent: usize) -> io::Result<()> { for stmt in body { stmt.print(w, indent)?; } Ok(()) } impl Expr { pub fn print<W: Write>(&self, w: &mut W, indent: usize) -> io::Result<()> { let mut j = String::new(); for _ in 0..indent { j.push_str(INDENT_STRING); } let i = j.clone() + SUBITEM_INDENT; match self { Expr::Variable(name) => { writeln!(w, "{}{}", i, name)?; } Expr::Cast { value, ty } => { writeln!(w, "{}CastExpr to {}", i, ty)?; writeln!(w, "{}Value:", i)?; value.print(w, indent + 1)?; } Expr::Unary { op, value } => { writeln!(w, "{}UnaryExpr", j)?; writeln!(w, "{}Op: {:?}", i, op)?; writeln!(w, "{}Value:", i)?; value.print(w, indent + 1)?; } Expr::Binary { left, op, right } => { writeln!(w, "{}BinaryExpr", j)?; writeln!(w, "{}Op: {:?}", i, op)?; writeln!(w, "{}Left:", i)?; left.print(w, indent + 1)?; writeln!(w, "{}Right:", i)?; right.print(w, indent + 1)?; } Expr::Number { value, .. } => { writeln!(w, "{}{}", i, value)?; } Expr::Array { array, index } => { writeln!(w, "{}ArrayExpr", j)?; writeln!(w, "{}Array:", i)?; array.print(w, indent + 1)?; writeln!(w, "{}Index:", i)?; index.print(w, indent + 1)?; } Expr::Call { target, args } => { writeln!(w, "{}CallExpr", j)?; writeln!(w, "{}Target: {}", i, target)?; writeln!(w, "{}Args:", i)?; for arg in args { arg.print(w, indent + 1)?; } } } Ok(()) } } impl Stmt { pub fn print<W: Write>(&self, w: &mut W, indent: usize) -> io::Result<()> { let mut j = String::new(); for _ in 0..indent { j.push_str(INDENT_STRING); } let i = j.clone() + SUBITEM_INDENT; match self { Stmt::Assign { variable, value } => { writeln!(w, "{}AssignStmt", j)?; writeln!(w, "{}Target:", i)?; variable.print(w, indent + 1)?; writeln!(w, "{}Value:", i)?; value.print(w, indent + 1)?; } Stmt::Declare { ty, decl_ty, name, value, array } => { writeln!(w, "{}DeclareStmt", j)?; writeln!(w, "{}Name: {}", i, name)?; writeln!(w, "{}DeclTy: {}", i, decl_ty)?; writeln!(w, "{}Ty: {}", i, ty)?; if let Some(value) = value { writeln!(w, "{}Value:", i)?; value.print(w, indent + 1)?; } if let Some(array) = array { writeln!(w, "{}ArraySize:", i)?; array.print(w, indent + 1)?; } } Stmt::While { condition, body } => { writeln!(w, "{}WhileStmt", j)?; writeln!(w, "{}Condition:", i)?; condition.print(w, indent + 1)?; writeln!(w, "{}Body:", i)?; print_body(body, w, indent + 1)?; } Stmt::For { init, condition, step, body } => { writeln!(w, "{}ForStmt", j)?; if let Some(init) = init { writeln!(w, "{}Init:", i)?; init.print(w, indent + 1)?; } if let Some(condition) = condition { writeln!(w, "{}Condition:", i)?; condition.print(w, indent + 1)?; } if let Some(step) = step { writeln!(w, "{}Step:", i)?; step.print(w, indent + 1)?; } writeln!(w, "{}Body:", i)?; print_body(body, w, indent + 1)?; } Stmt::If { arms, default } => { writeln!(w, "{}IfStmt", j)?; for (index, arm) in arms.iter().enumerate() { writeln!(w, "{}Arm {} condition:", i, index)?; arm.0.print(w, indent + 1)?; writeln!(w, "{}Arm {} body:", i, index)?; print_body(&arm.1, w, indent + 1)?; } if let Some(default) = default { writeln!(w, "{}Default arm body:", i)?; print_body(default, w, indent + 1)?; } } Stmt::Return(value) => { writeln!(w, "{}ReturnStmt", j)?; if let Some(value) = value { writeln!(w, "{}Value:", i)?; value.print(w, indent + 1)?; } else { writeln!(w, "{}Value: none", i)?; } } Stmt::Expr(value) => { value.print(w, indent)?; } Stmt::Break => writeln!(w, "{}BreakStmt", j)?, Stmt::Continue => writeln!(w, "{}ContinueStmt", j)?, } Ok(()) } } impl FunctionPrototype { pub fn print<W: Write>(&self, w: &mut W) -> io::Result<()> { writeln!(w, "Name: {}", self.name)?; writeln!(w, "ReturnTy: {}", self.return_ty)?; writeln!(w, "Args:")?; for (name, ty) in &self.args { writeln!(w, "{}{} {}", INDENT_STRING, ty, name)?; } Ok(()) } } impl Function { pub fn print<W: Write>(&self, w: &mut W) -> io::Result<()> { self.prototype.print(w)?; if let Some(body) = &self.body { writeln!(w, "Body:")?; print_body(&body, w, 1)?; } else { writeln!(w, "Extern")?; } Ok(()) } } impl ParsedModule { #[allow(unused)] pub fn print<W: Write>(&self, w: &mut W) -> io::Result<()> { for func in &self.functions { func.print(w)?; writeln!(w)?; } Ok(()) } }
use super::logs::Log; use crate::commands::IteratorKind; use crate::errors::Error; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Itr { pub log: String, pub name: String, pub func: String, pub kind: IteratorKind, } impl Itr { pub fn next(&self, log: &Log, offset: usize, count: usize) -> Result<Vec<Vec<u8>>, Error> { let mut output: Vec<Vec<u8>> = Vec::with_capacity(count); let mut error: Option<Error> = None; let lua = rlua::Lua::new(); lua.context(|ctx| { let globals = ctx.globals(); for i in 0..count { // TODO: this will panic if count is out of bounds. // Implement `get` on Log and return None if nothing exists. let msg = log[offset + i].clone(); trace!("pulled msg from log: {:?}", msg); let mut deserializer = serde_cbor::Deserializer::from_slice(&*msg); let serializer = rlua_serde::ser::Serializer { lua: ctx }; let lua_msg = match serde_transcode::transcode(&mut deserializer, serializer) { Ok(msg) => msg, Err(e) => { debug!("error transcoding msgpack to lua: {:?}", e); error = Some(Error::MsgNotValidCbor); break; } }; globals.set("msg", lua_msg).expect("could not set global"); let res = ctx.load(&*self.func).eval::<rlua::Value>(); if let Err(e) = res { debug!("error running lua: {:?} {:?}", e, msg); error = Some(Error::ErrRunningLua); break; }; let mut buf: Vec<u8> = vec![]; let value = res.expect("couldnt unwrap response from eval"); let deserializer = rlua_serde::de::Deserializer { value: value.clone(), }; let mut serializer = serde_cbor::Serializer::new(&mut buf); match serde_transcode::transcode(deserializer, &mut serializer) { Ok(_ok) => (), Err(e) => { debug!("error transcoding lua to msgpack: {:?} {:?}", e, value); error = Some(Error::ErrReadingLuaResponse); } }; output.push(buf); } }); if let Some(e) = error { return Err(e); } Ok(output) } }
use magnum_opus::Decoder; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use std::io::{self, Read, Write, Cursor}; /* https://github.com/s1lentq/revoice/blob/master/revoice/src/VoiceEncoder_Opus.cpp#L173-L255 acc//unttänään klo 07.07 after 0x06 there's 2 bytes which are "total length" then there's 2 bytes of frame length, if it's 0xffff then ignore after these 2 bytes is your opus frame with said length you have to iterate over total length until you reach zero there can be multiple "frames" i don't actually know the terms ah yes if length is not zero, then there will be also 2 bytes of "sequence number", it can be ignored too sequence number doesn't count towards frame length edeilen klo 12.09 damn I always miss the good discussion I think I would call them frames too. There's opus frames and the steam voice frames. Steam voice frames with type OPUSCODEC_PLC contain a data section which can be one or more opus frames, if that makes sense https://github.com/Meachamp/gm_8bit/blob/master/templates/steam_voice.bt I put the template I wrote to visualize all this on github there, so you can use that if you get stuck */ const MAX_CHANNELS: usize = 1; const FRAME_SIZE: usize = 160; const MAX_FRAME_SIZE: usize = 3 * FRAME_SIZE; const MAX_PACKET_LOSS: usize = 10; enum SteamVoiceOp { codec_opusplc = 6, samplerate = 11, unk = 10, silence = 0, codec_legacy = 1, codec_unk = 2, codec_raw = 3, codec_opus = 5, codec_silk = 4 } pub struct OpusFrame { pub sample_rate: u16, pub data: Vec<u8> } pub fn decode(buffer: &[u8]) -> Vec<OpusFrame> { if buffer.len() < 8 { return Vec::new() } // last 4 bytes is CRC let mut input = Cursor::new(&buffer[0..buffer.len() - 4]); let _sid = input.read_u64::<LittleEndian>().unwrap(); let mut frames = Vec::new(); let mut sample_rate = 24000; loop { let op = match input.read_u8() { Ok(l) => l, Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break, _ => panic!() }; println!("processing op: {}", op); if op == SteamVoiceOp::samplerate as u8 { sample_rate = input.read_u16::<LittleEndian>().unwrap(); } else if op == SteamVoiceOp::codec_opusplc as u8 { let data_len = input.read_u16::<LittleEndian>().unwrap(); // if (nPayloadSize == 0xFFFF) // { // ResetState(); // m_nDecodeSeq = 0; // break; // } println!("steam frame size: {}", data_len); let mut steam_frame = vec![0; data_len as usize]; input.read_exact(&mut steam_frame).unwrap(); let mut c = Cursor::new(steam_frame); loop { let frame_len = match c.read_i16::<LittleEndian>() { Ok(l) => l, Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break, _ => panic!() }; if frame_len == -1 { break; } let _seq = c.read_u16::<LittleEndian>().unwrap(); let mut frame_data = vec![0; frame_len as usize]; c.read_exact(&mut frame_data).unwrap(); frames.push(OpusFrame { sample_rate: sample_rate, data: frame_data }); } } else if op == SteamVoiceOp::codec_opus as u8 || op == SteamVoiceOp::codec_legacy as u8 || op == SteamVoiceOp::codec_silk as u8 { let data_len = input.read_u16::<LittleEndian>().unwrap(); io::copy(&mut Read::by_ref(&mut input).take(data_len as u64), &mut io::sink()); } else if op == SteamVoiceOp::codec_raw as u8 { break; // bruh } else if op == SteamVoiceOp::unk as u8 { input.read_u8().unwrap(); input.read_u8().unwrap(); } else if op == SteamVoiceOp::silence as u8 { let _silent_samples = input.read_u16::<LittleEndian>().unwrap(); } else { println!("unknown op {}", op); } } frames } /// Decode Steam + decode Opus pub fn process<W: Write>(buffer: &[u8], out: &mut W) { let frames = decode(buffer); let mut decoder = Decoder::new(24000, magnum_opus::Channels::Mono).unwrap(); for frame in frames { let mut buffer = vec![0i16; MAX_FRAME_SIZE]; let size = decoder.decode(&frame.data, &mut buffer[..], false).unwrap(); println!("decoded {} from {}", size, &frame.data.len()); let mut bytes_buffer = [0u8; MAX_FRAME_SIZE*2]; LittleEndian::write_i16_into(&buffer[0..size], &mut bytes_buffer[0..size * 2]); out.write(&bytes_buffer[0..size * 2]).unwrap(); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_opus() { let mut buf = std::fs::read("compressed.dat").unwrap(); let mut fout = std::fs::File::create("decomp.dat").unwrap(); process(&buf, &mut fout); } }
use core::fmt; use std::fmt::{Debug, Formatter}; #[macro_export] macro_rules! if_opt { ($child_expr: expr, $some_expr: expr) => { if $child_expr { Some($some_expr) } else { None } }; } pub struct DebugFn<'a, F: Fn(&mut Formatter) -> fmt::Result>(pub &'a F); impl<'a, F: Fn(&mut Formatter) -> fmt::Result> Debug for DebugFn<'a, F> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let func = self.0; (func)(f) } } #[macro_export] macro_rules! debug_fn { ($content: expr) => { &crate::macros::DebugFn(&$content) }; }
//! This module exposes bare C API functions. As most of them are provided with a "safe" wrapper //! function with an intuitive name and intuitive implementation for Rust, there is no gain to //! darely use these functions. //! //! The only exceptions are `k` and `knk` which are not provided with a "safe" wrapper because //! these functions are using elipsis (`...`) as their argument. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // Load Libraries // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// use super::{S, const_S, U, I, J, F, V, K}; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// // External C Functions // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// extern "C"{ //%% Constructors %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Creates an atom of the specified type. pub fn ka(qtype: I) -> K; /// Constructor of q bool object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_bool(_: K) -> K{ /// unsafe{kb(1)} /// } /// ``` /// ```q /// q)yes: libc_api_examples 2: (`create_bool; 1); /// q)yes[] /// 1b /// ``` pub fn kb(boolean: I) -> K; /// Constructor of q GUID object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_guid(_: K) -> K{ /// unsafe{ku(U::new([0x1e_u8, 0x11, 0x17, 0x0c, 0x42, 0x24, 0x25, 0x2c, 0x1c, 0x14, 0x1e, 0x22, 0x4d, 0x3d, 0x46, 0x24]))} /// } /// ``` /// ```q /// q)create_guid: libc_api_examples 2: (`create_guid; 1); /// q)create_guid[] /// 1e11170c-4224-252c-1c14-1e224d3d4624 /// ``` pub fn ku(array: U) -> K; /// Constructor of q byte object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_byte(_: K) -> K{ /// unsafe{kg(0x3c)} /// } /// ``` /// ```q /// q)create_byte: libc_api_examples 2: (`create_byte; 1); /// q)create_byte[] /// 0x3c /// ``` pub fn kg(byte: I) -> K; /// Constructor of q short object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_short(_: K) -> K{ /// unsafe{kh(-144)} /// } /// ``` /// ```q /// q)shortage: libc_api_examples 2: (`create_short; 1); /// q)shortage[] /// -144h /// ``` pub fn kh(short: I) -> K; /// Constructor of q int object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_int(_: K) -> K{ /// unsafe{ki(86400000)} /// } /// ``` /// ```q /// q)trvial: libc_api_examples 2: (`create_int; 1); /// q)trivial[] /// 86400000i /// ``` pub fn ki(int: I) -> K; /// Constructor of q long object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_long(_: K) -> K{ /// unsafe{kj(-668541276001729000)} /// } /// ``` /// ```q /// q)lengthy: libc_api_examples 2: (`create_long; 1); /// q)lengthy[] /// -668541276001729000 /// ``` pub fn kj(long: J) -> K; /// Constructor of q real object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_real(_: K) -> K{ /// unsafe{ke(0.00324)} /// } /// ``` /// ```q /// q)reality: libc_api_examples 2: (`create_real; 1); /// q)reality[] /// 0.00324e /// ``` pub fn ke(real: F) -> K; /// Constructor of q float object. /// # Example /// ``` /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_float(_: K) -> K{ /// unsafe{kf(-6302.620)} /// } /// ``` /// ```q /// q)coffee_float: libc_api_examples 2: (`create_float; 1); /// q)coffee_float[] /// -6302.62 /// ``` pub fn kf(float: F) -> K; /// Constructor of q char object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_char(_: K) -> K{ /// unsafe{kc('q' as I)} /// } /// ``` /// ```q /// q)quiz: libc_api_examples 2: (`create_char; 1); /// q)quiz[] /// "q" /// ``` pub fn kc(character: I) -> K; /// Constructor of q symbol object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_symbol(_: K) -> K{ /// unsafe{ks(str_to_S!("symbolism"))} /// } /// ``` /// ```q /// q)formal: libc_api_examples 2: (`create_symbol; 1); /// q)formal[] /// `symbolism /// q)`symbolism ~ formal[] /// 1b /// ``` pub fn ks(symbol: S) -> K; /// Constructor of q timestamp from elapsed time in nanoseconds since kdb+ epoch (`2000.01.01`) or timespan object from nanoseconds. /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_timestamp(_: K) -> K{ /// // 2015.03.16D00:00:00:00.000000000 /// unsafe{ktj(-qtype::TIMESTAMP as I, 479779200000000000)} /// } /// /// #[no_mangle] /// pub extern "C" fn create_timespan(_: K) -> K{ /// // -1D01:30:00.001234567 /// unsafe{ktj(-qtype::TIMESPAN as I, -91800001234567)} /// } /// ``` /// ```q /// q)hanko: libc_api_examples 2: (`create_timestamp; 1); /// q)hanko[] /// 2015.03.16D00:00:00.000000000 /// q)duration: libc_api_examples 2: (`create_timespan; 1); /// q)duration[] /// -1D01:30:00.001234567 /// ``` pub fn ktj(qtype: I, nanoseconds: J) -> K; /// Constructor of q date object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_date(_: K) -> K{ /// // 1999.12.25 /// unsafe{kd(-7)} /// } /// ``` /// ```q /// q)christmas_at_the_END: libc_api_examples 2: (`create_date; 1); /// q)christmas_at_the_END[] /// 1999.12.25 /// ``` pub fn kd(date: I) -> K; /// Constructor of q datetime object from the number of days since kdb+ epoch (`2000.01.01`). /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_datetime(_: K) -> K{ /// // 2015.03.16T12:00:00:00.000 /// unsafe{kz(5553.5)} /// } /// ``` /// ```q /// q)omega_date: libc_api_examples 2: (`create_datetime; 1); /// q)omega_date[] /// 2015.03.16T12:00:00.000 /// ``` pub fn kz(datetime: F) -> K; /// Constructor of q time object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_time(_: K) -> K{ /// // -01:30:00.123 /// unsafe{kt(-5400123)} /// } /// ``` /// ```q /// q)ancient: libc_api_examples 2: (`create_time; 1); /// q)ancient[] /// -01:30:00.123 /// ``` pub fn kt(milliseconds: I) -> K; /// Constructor of q compound list. /// # Example /// See the example of [`xD`](fn.xD.html). pub fn knk(qtype: I, ...) -> K; /// Constructor of q simple list. /// # Example /// See the example of [`xD`](fn.xD.html). pub fn ktn(qtype: I, length: J) -> K; /// Constructor of q string object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_string(_: K) -> K{ /// unsafe{kp(str_to_S!("this is a text."))} /// } /// ``` /// ```q /// q)text: libc_api_examples 2: (`create_string; 1); /// q)text[] /// "this is a text." /// ``` pub fn kp(chararray: S) -> K; /// Constructor if q string object with a fixed length. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_string2(_: K) -> K{ /// unsafe{kpn(str_to_S!("The meeting was too long and I felt it s..."), 24)} /// } /// ``` /// ```q /// q)speak_inwardly: libc_api_examples 2: (`create_string2; 1); /// q)speak_inwardly[] /// "The meeting was too long" /// ``` pub fn kpn(chararray: S, length: J) -> K; /// Constructor of q table object from q dictionary object. /// # Note /// Basically this is a `flip` command of q. Hence the value of the dictionary must have /// lists as its elements. /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_table(_: K) -> K{ /// let keys=unsafe{ktn(qtype::SYMBOL as I, 2)}; /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=unsafe{ss(str_to_S!("time"))}; /// keys_slice[1]=unsafe{ss(str_to_S!("temperature"))}; /// let values=unsafe{knk(2)}; /// let time=unsafe{ktn(qtype::TIMESTAMP as I, 3)}; /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=unsafe{ktn(qtype::FLOAT as I, 3)}; /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// unsafe{xT(xD(keys, values))} /// } /// ``` /// ```q /// q)climate_change: libc_api_examples 2: (`create_table; 1); /// q)climate_change[] /// time temperature /// ----------------------------------------- /// 2003.10.10D02:24:19.167018272 22.1 /// 2006.05.24D06:16:49.419710368 24.7 /// 2008.08.12D23:12:24.018691392 30.5 /// ``` pub fn xT(dictionary: K) -> K; /// Constructor of simple q table object from q keyed table object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_table(_: K) -> K{ /// let keys=unsafe{ktn(qtype::SYMBOL as I, 2)}; /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=unsafe{ss(str_to_S!("time"))}; /// keys_slice[1]=unsafe{ss(str_to_S!("temperature"))}; /// let values=unsafe{knk(2)}; /// let time=unsafe{ktn(qtype::TIMESTAMP as I, 3)}; /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=unsafe{ktn(qtype::FLOAT as I, 3)}; /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// unsafe{xT(xD(keys, values))} /// } /// /// #[no_mangle] /// pub extern "C" fn create_keyed_table(dummy: K) -> K{ /// unsafe{knt(1, create_table(dummy))} /// } /// /// #[no_mangle] /// pub extern "C" fn keyed_to_simple_table(dummy: K) -> K{ /// unsafe{ktd(create_keyed_table(dummy))} /// } /// ``` /// ```q /// q)unkey: libc_api_examples 2: (`keyed_to_simple_table; 1); /// q)unkey[] /// time temperature /// ----------------------------------------- /// 2003.10.10D02:24:19.167018272 22.1 /// 2006.05.24D06:16:49.419710368 24.7 /// 2008.08.12D23:12:24.018691392 30.5 /// ``` pub fn ktd(keyedtable: K) -> K; /// Constructor of q keyed table object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_table(_: K) -> K{ /// let keys=unsafe{ktn(qtype::SYMBOL as I, 2)}; /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=unsafe{ss(str_to_S!("time"))}; /// keys_slice[1]=unsafe{ss(str_to_S!("temperature"))}; /// let values=unsafe{knk(2)}; /// let time=unsafe{ktn(qtype::TIMESTAMP as I, 3)}; /// // 2003.10.10D02:24:19.167018272 2006.05.24D06:16:49.419710368 2008.08.12D23:12:24.018691392 /// time.as_mut_slice::<J>().copy_from_slice(&[119067859167018272_i64, 201766609419710368, 271897944018691392]); /// let temperature=unsafe{ktn(qtype::FLOAT as I, 3)}; /// temperature.as_mut_slice::<F>().copy_from_slice(&[22.1_f64, 24.7, 30.5]); /// values.as_mut_slice::<K>().copy_from_slice(&[time, temperature]); /// unsafe{xT(xD(keys, values))} /// } /// /// #[no_mangle] /// pub extern "C" fn create_keyed_table(dummy: K) -> K{ /// unsafe{knt(1, create_table(dummy))} /// } /// ``` /// ```q /// q)locker: libc_api_examples 2: (`create_keyed_table; 1); /// q)locker[] /// time | temperature /// -----------------------------| ----------- /// 2003.10.10D02:24:19.167018272| 22.1 /// 2006.05.24D06:16:49.419710368| 24.7 /// 2008.08.12D23:12:24.018691392| 30.5 /// ``` pub fn knt(keynum: J, table: K) -> K; /// Constructor of q dictionary object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_dictionary() -> K{ /// let keys=unsafe{ktn(qtype::INT as I, 2)}; /// keys.as_mut_slice::<I>()[0..2].copy_from_slice(&[0, 1]); /// let values=unsafe{knk(2)}; /// let date_list=unsafe{ktn(qtype::DATE as I, 3)}; /// // 2000.01.01 2000.01.02 2000.01.03 /// date_list.as_mut_slice::<I>()[0..3].copy_from_slice(&[0, 1, 2]); /// let string=unsafe{kp(str_to_S!("I'm afraid I would crash the application..."))}; /// values.as_mut_slice::<K>()[0..2].copy_from_slice(&[date_list, string]); /// unsafe{xD(keys, values)} /// } /// ``` /// ```q /// q)create_dictionary: `libc_api_examples 2: (`create_dictionary; 1); /// q)create_dictionary[] /// 0| 2000.01.01 2000.01.02 2000.01.03 /// 1| "I'm afraid I would crash the application..." /// ``` pub fn xD(keys: K, values: K) -> K; /// Constructor of q error. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// pub extern "C" fn thai_kick(_: K) -> K{ /// unsafe{ /// krr(null_terminated_str_to_const_S("Thai kick unconditionally!!\0")) /// } /// } /// ``` /// ```q /// q)monstrous: `libc_api_examples 2: (`thai_kick; 1); /// q)monstrous[] /// 'Thai kick unconditionally!! /// [0] monstrous[] /// ^ /// ``` pub fn krr(message: const_S) -> K; /// Similar to krr but this function appends a system-error message to string S before passing it to `krr`. pub fn orr(message: const_S) -> K; /// Add a raw value to a q simple list and returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_simple_list(_: K) -> K{ /// let mut list=unsafe{ktn(qtype::TIMESTAMP as I, 0)}; /// for i in 0..5{ /// let mut timestamp=86400000000000 * i as J; /// unsafe{ja(&mut list, std::mem::transmute::<*mut J, *mut V>(&mut timestamp))}; /// } /// list /// } /// ``` /// # Note /// For symbol list, use [`js`](#fn.js). pub fn ja(list: *mut K, value: *mut V) -> K; /// Append a q list object to a q list. /// Returns a pointer to the (potentially reallocated) `K` object. /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn concat_list(mut list1: K, list2: K) -> K{ /// unsafe{ /// jv(&mut list1, list2); /// r1(list1) /// } /// } /// ``` /// ```q /// q)glue: `libc_api_examples 2: (`concat_list; 2); /// q)glue[(::; `metals; `fire); ("clay"; 316)] /// :: /// `metals /// `fire /// "clay" /// 316 /// q)glue[1 2 3; 4 5] /// 1 2 3 4 5 /// q)glue[`a`b`c; `d`e] /// `a`b`c`d`e /// ``` pub fn jv(list1: *mut K, list2: K) -> K; /// Add a q object to a q compound list. /// Returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ``` /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_compound_list(_: K) -> K{ /// unsafe{ /// let mut list=knk(0); /// jk(&mut list, ks(str_to_S!("1st"))); /// jk(&mut list, ki(2)); /// jk(&mut list, kpn(str_to_S!("3rd"), "3rd".chars().count() as i64)); /// list /// } /// } /// ``` /// ```q /// q)ranks: `libc_api_examples 2: (`create_compound_list; 1); /// q)ranks[] /// `1st /// 2i /// "3rd" /// ``` /// # Note /// In this example we did not allocate an array as `knk(0)` to use `jk`. As `knk` initializes the /// internal list size `n` with its argument, preallocating memory with `knk` and then using `jk` will crash. /// If you want to allocate a memory in advance, you can substitute a value after converting /// the q list object into a slice with [`as_mut_slice`](../trait.KUtility.html#tymethod.as_mut_slice). pub fn jk(list: *mut K, value: K) -> K; /// Add an internalized char array to a symbol list. /// Returns a pointer to the (potentially reallocated) `K` object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn create_symbol_list(_: K) -> K{ /// unsafe{ /// let mut list=ktn(qtype::SYMBOL as I, 0); /// js(&mut list, ss(str_to_S!("Abraham"))); /// js(&mut list, ss(str_to_S!("Isaac"))); /// js(&mut list, ss(str_to_S!("Jacob"))); /// js(&mut list, sn(str_to_S!("Josephine"), 6)); /// list /// } /// } /// ``` /// ```q /// q)summon:`libc_api_examples 2: (`create_symbol_list; 1) /// q)summon[] /// `Abraham`Isaac`Jacob`Joseph /// q)`Abraham`Isaac`Jacob`Joseph ~ summon[] /// 1b /// ``` /// # Note /// In this example we did not allocate an array as `ktn(qtype::SYMBOL as I, 0)` to use `js`. As `ktn` initializes /// the internal list size `n` with its argument, preallocating memory with `ktn` and then using `js` will crash. /// If you want to allocate a memory in advance, you can substitute a value after converting the q list object /// into a slice with [`as_mut_slice`](../trait.KUtility.html#tymethod.as_mut_slice). pub fn js(list: *mut K, symbol: S) -> K; /// Intern `n` chars from a char array. /// Returns an interned char array and should be used to add char array to a symbol vector. /// # Example /// See the example of [`js`](fn.js.html). pub fn sn(string: S, n: I) -> S; /// Intern a null-terminated char array. /// Returns an interned char array and should be used to add char array to a symbol vector. /// # Example /// See the example of [`js`](fn.js.html). pub fn ss(string: S) -> S; /// Capture (and reset) error string into usual error object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// extern "C" fn catchy(func: K, args: K) -> K{ /// unsafe{ /// let result=ee(dot(func, args)); /// if (*result).qtype == qtype::ERROR{ /// println!("error: {}", S_to_str((*result).value.symbol)); /// // Decrement reference count of the error object /// r0(result); /// KNULL /// } /// else{ /// result /// } /// } /// } /// ``` /// ```q /// q)catchy: `libc_api_examples 2: (`catchy; 2); /// q)catchy[$; ("J"; "42")] /// 42 /// q)catchy[+; (1; `a)] /// error: type /// ``` pub fn ee(result: K) -> K; //%% IPC Functions %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Send a text query or evaluate the text query in a process which are loading the shared library. /// As this library is purposed to build shared object, the only choice of `socket` is `0`. This /// executes against the kdb+ process in which it is loaded. /// ``` /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn dictionary_list_to_table() -> K{ /// let dicts=unsafe{knk(3)}; /// let dicts_slice=dicts.as_mut_slice::<K>(); /// for i in 0..3{ /// let keys=unsafe{ktn(qtype::SYMBOL as I, 2)}; /// let keys_slice=keys.as_mut_slice::<S>(); /// keys_slice[0]=unsafe{ss(str_to_S!("a"))}; /// keys_slice[1]=unsafe{ss(str_to_S!("b"))}; /// let values=unsafe{ktn(qtype::INT as I, 4)}; /// values.as_mut_slice::<I>()[0..2].copy_from_slice(&[i*10, i*100]); /// dicts_slice[i as usize]=unsafe{xD(keys, values)}; /// } /// // Format list of dictionary as a table. /// // ([] a: 0 10 20i; b: 0 100 200i) /// unsafe{k(0, str_to_S!("{[dicts] -1 _ dicts, (::)}"), dicts, KNULL)} /// } /// ``` /// ```q /// q)unfortunate_fact: `libc_api_examples 2: (`dictionary_list_to_table; 1); /// q)unfortunate_fact[] /// a b /// ------ /// 0 0 /// 10 100 /// 20 200 /// ``` pub fn k(socket: I, query: const_S,...) -> K; /// Serialize q object and return serialized q byte list object on success: otherwise null. /// Mode is either of: /// - -1: Serialize within the same process. /// - 1: retain enumerations, allow serialization of timespan and timestamp: Useful for passing data between threads /// - 2: unenumerate, allow serialization of timespan and timestamp /// - 3: unenumerate, compress, allow serialization of timespan and timestamp /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn conceal(object: K)->K{ /// unsafe{b9(3, object)} /// } /// ``` /// ```q /// q)jamming: `libc_api_examples 2: (`conceal; 1); /// q)jamming til 3 /// 0x0100000026000000070003000000000000000000000001000000000000000200000000000000 /// q)-9!jamming "Look! HE has come!!" /// "Look! HE has come!!" /// ``` pub fn b9(mode: I, qobject: K) -> K; /// Deserialize a bytes into q object. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn reveal(bytes: K)->K{ /// unsafe{d9(bytes)} /// } /// ``` /// ```q /// q)cancelling: `libc_api_examples 2: (`reveal; 1); /// q)cancelling -8!(`contact`from; "space"; 12); /// `contact`from /// "space" /// 12 /// ``` /// # Note /// On success, returns deserialized `K` object. On error, `(K) 0` is returned; use [`ee`](#fn.ee) to retrieve the error string. /// pub fn d9(bytes: K) -> K; /// Remove callback from the associated kdb+ socket and call `kclose`. /// Return null if the socket is invalid or not the one which had been registered by `sd1`. /// # Note /// A function which calls this function must be executed at the exit of the process. pub fn sd0(socket: I) -> V; /// Remove callback from the associated kdb+ socket and call `kclose` if the given condition is satisfied. /// Return null if the socket is invalid or not the one which had been registered by `sd1`. /// # Note /// A function which calls this function must be executed at the exit of the process. pub fn sd0x(socket: I, condition: I) -> V; /// Register callback to the associated kdb+ socket. /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// use std::ffi::c_void; /// /// // Send asynchronous query to the q process which sent a query to the caller of this function. /// extern "C" fn counter(socket: I) -> K{ /// let extra_query="show `$\"Counter_punch!!\"".as_bytes(); /// let query_length=extra_query.len(); /// // header (8) + list header (6) + data length /// let total_length=8+6+query_length; /// // Buffer /// let mut message: Vec<u8>=Vec::with_capacity(total_length); /// // Little endian, async, uncompress, reserved /// message.extend_from_slice(&[1_u8, 0, 0, 0]); /// // Total message length /// message.extend_from_slice(&(total_length as i32).to_le_bytes()); /// // Data type, attribute /// message.extend_from_slice(&[10_u8, 0]); /// // Length of data /// message.extend_from_slice(&(query_length as i32).to_le_bytes()); /// // Data /// message.extend_from_slice(extra_query); /// // Send /// unsafe{libc::send(socket, message.as_slice().as_ptr() as *const c_void, total_length, 0)}; /// KNULL /// } /// /// #[no_mangle] /// pub extern "C" fn enable_counter(socket: K) -> K{ /// unsafe{ /// let result=sd1(socket.get_int().expect("oh no"), counter); /// if result.get_type()== qtype::NULL || result.get_type()== qtype::ERROR{ /// return krr(null_terminated_str_to_const_S("Failed to hook\0")); /// } /// else{ /// KNULL /// } /// } /// } /// ``` /// ```q /// q)// process1 /// q)enable_counter: `libc_api_examples 2: (`enable_counter; 1) /// q)\p 5000 /// ``` /// ```q /// q)// process2 /// q)h:hopen `:unix://5000 /// ``` /// ```q /// q)// process1 /// q).z.W /// 5| /// q)enable_counter[5i] /// ``` /// ```q /// q)// process2 /// q)h "1+2" /// `Counter_punch!! /// 3 /// q)neg[h] "1+2" /// `Counter_punch!! /// ``` pub fn sd1(socket: I, function: extern fn(I) -> K) -> K; //%% Reference Count %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Decrement reference count of the q object. The decrement must be done when `k` function gets an error /// object whose type is `qtype::ERROR` and when you created an object but do not intend to return it to /// q side. See details on [the reference page](https://code.kx.com/q/interfaces/c-client-for-q/#managing-memory-and-reference-counting). /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn idle_man(_: K)->K{ /// unsafe{ /// // Creare an int object. /// let int=ki(777); /// // Changed the mind. Discard it. /// r0(int); /// } /// // Return null. /// KNULL /// } /// ``` /// ```q /// q)idle_man: libc_api_examples 2: (`idle_man; 1); /// q)idle_man[] /// q) /// ``` pub fn r0(qobject: K) -> V; /// Increment reference count of the q object. Increment must be done when you passed arguments /// to Rust function and intends to return it to q side or when you pass some `K` objects to `k` /// function and intend to use the parameter after the call. /// See details on [the reference page](https://code.kx.com/q/interfaces/c-client-for-q/#managing-memory-and-reference-counting). /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn pass_through_cave(pedestrian: K) -> K{ /// let item=unsafe{k(0, str_to_S!("get_item1"), r1(pedestrian), KNULL)}; /// println!("What do you see, son of man?: {}", item.get_str().expect("oh no")); /// unsafe{r0(item)}; /// let item=unsafe{k(0, str_to_S!("get_item2"), r1(pedestrian), KNULL)}; /// println!("What do you see, son of man?: {}", item.get_str().expect("oh no")); /// unsafe{ /// r0(item); /// r1(pedestrian) /// } /// } /// ``` /// ```q /// q)get_item1:{[man] "a basket of summer fruit"}; /// q)get_item2:{[man] "boiling pot, facing away from the north"} /// q).capi.pass_through_cave[`son_of_man] /// What do you see, son of man?: a basket of summer fruit /// What do you see, son of man?: boiling pot, facing away from the north /// `son_of_man /// ``` pub fn r1(qobject: K) -> K; //%% Miscellaneous %%//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/ /// Apply a function to q list object `.[func; args]`. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn rust_parse(dollar: K, type_and_text: K) -> K{ /// unsafe{ /// dot(dollar, type_and_text) /// } /// } /// ``` /// ```q /// q)rust_parse:`libc_api_examples 2: (`rust_parse; 2); /// q)rust_parse[$; ("S"; "text")] /// `text /// ``` pub fn dot(func: K, args: K) -> K; /// Release the memory allocated for the thread's pool. /// Call when the thread is about to complete, releasing the memory allocated for that thread's pool. pub fn m9() -> V; /// Set whether interning symbols uses a lock: `lock` is either 0 or 1. /// Returns the previously set value. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// #[no_mangle] /// pub extern "C" fn parallel_sym_change(list: K) -> K{ /// unsafe{ /// // `K` cannot have `Send` because it is a pointer but `k0` does. /// let mut inner=*list; /// // Lock symbol before creating an internal symbol on another thread. /// setm(1); /// let task=std::thread::spawn(move || { /// inner.as_mut_slice::<S>()[0]=ss(str_to_S!("replaced")); /// inner /// }); /// list.as_mut_slice::<S>()[1]=ss(str_to_S!("symbolbol")); /// match task.join(){ /// Err(_) => { /// // Unlock. /// setm(0); /// krr(null_terminated_str_to_const_S("oh no")) /// }, /// Ok(l) => { /// // Unlock. /// setm(0); /// (*list)=l; /// // Increment reference count for copy. /// r1(list) /// } /// } /// } /// } /// ``` /// ```q /// q)alms_with_left_hand: `libc_api_examples 2: (`parallel_sym_change; 2); /// q)alms_with_left_hand[`a`b]; /// `replaced`symbolbol /// ``` pub fn setm(lock: I) -> I; /// Load C function as q function (`K` object). /// # Parameters /// - `func`: A function takes a C function that would take `n` `K` objects as arguments and returns a `K` object. /// - `n`: The number of arguments for the function. pub fn dl(func: *const V, n: J) -> K; /// Convert ymd to the number of days from `2000.01.01`. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// fn main(){ /// /// let days=unsafe{ymd(2020, 4, 1)}; /// assert_eq!(days, 7396); /// /// } /// ``` pub fn ymd(year: I, month: I, date:I) -> I; /// Convert days from `2000.01.01` to a number expressed as `yyyymmdd`. /// # Example /// ```no_run /// use kdb_c_api::*; /// use kdb_c_api::native::*; /// /// fn main(){ /// /// let number=unsafe{dj(7396)}; /// assert_eq!(number, 20200401); /// /// } /// ``` pub fn dj(days: I) -> I; /* Unsupported /// Connect with timeout (millisecond) and capability. The value of capability is: /// - 1: 1TB limit /// - 2: use TLS /// Return value is either of: /// - 0 Authentication error /// - -1 Connection error /// - -2 Timeout error /// - -3 OpenSSL initialization failed /// # Note /// Standalone application only. Not for a shared library. pub fn khpunc(host: S, port: I, credential: S, timeout_millis: I, capability: I) -> I; /// Connect with timeout (millisecond). /// Return value is either of: /// - 0 Authentication error /// - -1 Connection error /// - -2 Timeout error /// # Note /// Standalone application only. Not for a shared library. pub fn khpun(host: const_S, port: I, credential: const_S, timeout_millis: I) -> I; /// Connect with no timeout. pub fn khpu(host: const_S, port: I, credential: const_S) -> I; /// Connect anonymously. pub fn khp(host: const_S, port: I) -> I; /// Close the socket to a q process. /// # Note /// Standalone application only. Not for a shared library. pub fn kclose(socket: I) -> V; /// Verify that the received bytes is a valid IPC message. /// The message is not modified. /// Returns `0` if not valid. /// # Note /// Decompressed data only. pub fn okx(bytes: K) -> I; /// Return a dictionary of TLS setting. See `-26!`. /// # Note /// As this library is purposed to build shared object, this function will not add a value. pub fn sslInfo(_: K) -> K; /// Return kdb+ release date. /// # Note /// This function seems not exist (`undefined symbol`). pub fn ver() -> I; /// Variadic version of `knk`. fn vaknk(qtype: I, args: va_list) -> K; /// Variadic version of `k`. fn vak(qtype: I, query: const_S, args: va_list) -> K; */ }
//! This module implements a SMB2 negotiate request //! The SMB2 NEGOTIATE Request packet is used by the client to notify the server what dialects of the SMB 2 Protocol the client understands. //! This request is composed of an SMB2 header, followed by this request structure. use rand::{ distributions::{Distribution, Standard}, Rng, }; use crate::smb2::helper_functions::negotiate_context::{NegVec, NegotiateContext}; /// negotiate request size of 36 bytes const STRUCTURE_SIZE: &[u8; 2] = b"\x24\x00"; /// A struct that represents a negotiate request #[derive(Debug, PartialEq, Eq, Clone)] pub struct Negotiate { /// StructureSize (2 bytes): The client MUST set this field to 36, /// indicating the size of a NEGOTIATE request. This is not the size /// of the structure with a single dialect in the Dialects[] array. /// This value MUST be set regardless of the number of dialects or /// number of negotiate contexts sent. pub structure_size: Vec<u8>, /// DialectCount (2 bytes): The number of dialects that are contained /// in the Dialects[] array. This value MUST be greater than 0. pub dialect_count: Vec<u8>, /// SecurityMode (2 bytes): When set, indicates that security signatures are enabled on the client. /// The client MUST set this bit if the SMB2_NEGOTIATE_SIGNING_REQUIRED bit is not set, /// and MUST NOT set this bit if the SMB2_NEGOTIATE_SIGNING_REQUIRED bit is set. /// The server MUST ignore this bit. pub security_mode: Vec<u8>, /// Reserved (2 bytes): The client MUST set this to 0, and /// the server SHOULD ignore it on receipt. pub reserved: Vec<u8>, /// Capabilities (4 bytes): If the client implements the SMB 3.x dialect family, /// the Capabilities field MUST be constructed. To have multiple capabilities, add up /// the individual hex values. e.g. all capabilities would be 0x0000007f /// Otherwise, this field MUST be set to 0. pub capabilities: Vec<u8>, /// ClientGuid (16 bytes): It MUST be a GUID (as specified in [MS-DTYP] section 2.3.4.2) /// generated by the client. pub client_guid: Vec<u8>, /// NegotiateContextOffset (4 bytes): The offset, in bytes, from the beginning /// of the SMB2 header to the first, 8-byte-aligned negotiate context in the NegotiateContextList. /// NOTE: This implementation focuses on the dialect 0x311 which does not use the Client Start Time field. pub negotiate_context_offset: Vec<u8>, /// NegotiateContextCount (2 bytes): The number of negotiate contexts in NegotiateContextList. /// NOTE: This implementation focuses on the dialect 0x311 which does not use the Client Start Time field. pub negotiate_context_count: Vec<u8>, /// Reserved2 (2 bytes): The client MUST set this to 0, and the server MUST ignore it on receipt. /// NOTE: This implementation focuses on the dialect 0x311 which does not use the Client Start Time field. pub reserved2: Vec<u8>, /// ClientStartTime (8 bytes): This field MUST NOT be used and MUST be reserved. /// The client MUST set this to 0, and the server MUST ignore it on receipt. /// NOTE: This implementation focuses on the dialects < 0x311. pub client_start_time: Vec<u8>, /// Dialects (variable): An array of one or more 16-bit integers specifying /// the supported dialect revision numbers. The array MUST contain at least one value. pub dialects: Vec<Vec<u8>>, /// Padding (variable): Optional padding between the end of the Dialects array and /// the first negotiate context in NegotiateContextList so that the first negotiate context is 8-byte aligned. pub padding: Vec<u8>, /// NegotiateContextList (variable): If the Dialects field contains 0x0311, /// then this field will contain an array of SMB2 NEGOTIATE_CONTEXTs. /// The first negotiate context in the list MUST appear at the byte offset indicated by the /// SMB2 NEGOTIATE request's NegotiateContextOffset field. Subsequent negotiate contexts MUST appear /// at the first 8-byte-aligned offset following the previous negotiate context. pub negotiate_context_list: Vec<NegotiateContext>, } impl Negotiate { pub fn default() -> Self { Negotiate { structure_size: STRUCTURE_SIZE.to_vec(), dialect_count: Vec::new(), security_mode: Vec::new(), reserved: vec![0; 2], capabilities: Vec::new(), client_guid: Vec::new(), negotiate_context_offset: Vec::new(), negotiate_context_count: Vec::new(), reserved2: vec![0; 2], client_start_time: Vec::new(), dialects: Vec::new(), padding: Vec::new(), negotiate_context_list: Vec::new(), } } } /// Represents all supported dialects #[derive(Debug, PartialEq, Eq, Clone)] pub enum Dialects { Smb202, Smb21, Smb30, Smb302, Smb311, } impl Dialects { /// Return the corresponding byte code (4 bytes) for each dialect. pub fn unpack_byte_code(&self) -> Vec<u8> { match self { Dialects::Smb202 => b"\x02\x02".to_vec(), Dialects::Smb21 => b"\x10\x02".to_vec(), Dialects::Smb30 => b"\x00\x03".to_vec(), Dialects::Smb302 => b"\x02\x03".to_vec(), Dialects::Smb311 => b"\x11\x03".to_vec(), } } /// Return the dialect array of all SMB2 dialects as a byte sequence. pub fn get_all_dialects() -> Vec<Vec<u8>> { vec![ Dialects::Smb202.unpack_byte_code(), Dialects::Smb21.unpack_byte_code(), Dialects::Smb30.unpack_byte_code(), Dialects::Smb302.unpack_byte_code(), Dialects::Smb311.unpack_byte_code(), ] } } impl Distribution<Dialects> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Dialects { match rng.gen_range(0..=5) { 0 => Dialects::Smb202, 1 => Dialects::Smb21, 2 => Dialects::Smb30, 3 => Dialects::Smb302, _ => Dialects::Smb311, } } } impl std::fmt::Display for Negotiate { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "\tNegotiate Request: \n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\ \n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{:?}\n\t\t{}", self.structure_size, self.dialect_count, self.security_mode, self.reserved, self.capabilities, self.client_guid, self.negotiate_context_offset, self.negotiate_context_count, self.reserved2, self.client_start_time, self.dialects, self.padding, NegVec(&self.negotiate_context_list), ) } }
use winapi::um::{ winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS}, wingdi::DeleteObject }; use winapi::shared::windef::HBRUSH; use crate::win32::window_helper as wh; use crate::win32::base_helper::check_hwnd; use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler}; use super::{ControlBase, ControlHandle}; use std::cell::RefCell; const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object"; const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!"; bitflags! { /** The label flags * NONE: No flags. Equivalent to a invisible blank label. * VISIBLE: The label is immediatly visible after creation * DISABLED: The label cannot be interacted with by the user. It also has a grayed out look. */ pub struct LabelFlags: u32 { const NONE = 0; const VISIBLE = WS_VISIBLE; const DISABLED = WS_DISABLED; /// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines. const ELIPSIS = SS_WORDELLIPSIS; } } /** A label is a single line of static text. Use `\r\n` to split the text on multiple lines. Label is not behind any features. **Builder parameters:** * `parent`: **Required.** The label parent container. * `text`: The label text. * `size`: The label size. * `position`: The label position. * `enabled`: If the label is enabled. A disabled label won't trigger events * `flags`: A combination of the LabelFlags values. * `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi * `font`: The font used for the label text * `background_color`: The background color of the label * `h_align`: The horizontal aligment of the label **Control events:** * `OnLabelClick`: When the user click the label * `OnLabelDoubleClick`: When the user double click a label * `MousePress(_)`: Generic mouse press events on the label * `OnMouseMove`: Generic mouse mouse event * `OnMouseWheel`: Generic mouse wheel event ** Example ** ```rust use native_windows_gui as nwg; fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) { nwg::Label::builder() .text("Hello") .font(Some(font)) .parent(window) .build(label); } ``` */ #[derive(Default)] pub struct Label { pub handle: ControlHandle, background_brush: Option<HBRUSH>, handler0: RefCell<Option<RawEventHandler>>, handler1: RefCell<Option<RawEventHandler>>, } impl Label { pub fn builder<'a>() -> LabelBuilder<'a> { LabelBuilder { text: "A label", size: (130, 25), position: (0, 0), flags: None, ex_flags: 0, font: None, parent: None, h_align: HTextAlign::Left, v_align: VTextAlign::Center, background_color: None } } /// Return the font of the control pub fn font(&self) -> Option<Font> { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let font_handle = wh::get_window_font(handle); if font_handle.is_null() { None } else { Some(Font { handle: font_handle }) } } /// Set the font of the control pub fn set_font(&self, font: Option<&Font>) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); } } /// Return true if the control currently has the keyboard focus pub fn focus(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_focus(handle) } } /// Set the keyboard focus on the button. pub fn set_focus(&self) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_focus(handle); } } /// Return true if the control user can interact with the control, return false otherwise pub fn enabled(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_enabled(handle) } } /// Enable or disable the control pub fn set_enabled(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_enabled(handle, v) } } /// Return true if the control is visible to the user. Will return true even if the /// control is outside of the parent client view (ex: at the position (10000, 10000)) pub fn visible(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_visibility(handle) } } /// Show or hide the control to the user pub fn set_visible(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_visibility(handle, v) } } /// Return the size of the label in the parent window pub fn size(&self) -> (u32, u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_size(handle) } } /// Set the size of the label in the parent window pub fn set_size(&self, x: u32, y: u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_size(handle, x, y, false) } } /// Return the position of the label in the parent window pub fn position(&self) -> (i32, i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_position(handle) } } /// Set the position of the label in the parent window pub fn set_position(&self, x: i32, y: i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_position(handle, x, y) } } /// Return the label text pub fn text(&self) -> String { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_text(handle) } } /// Set the label text pub fn set_text<'a>(&self, v: &'a str) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_text(handle, v) } } /// Winapi class name used during control creation pub fn class_name(&self) -> &'static str { "STATIC" } /// Winapi base flags used during window creation pub fn flags(&self) -> u32 { use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT}; WS_VISIBLE | SS_NOPREFIX | SS_LEFT } /// Winapi flags required by the control pub fn forced_flags(&self) -> u32 { use winapi::um::winuser::{SS_NOTIFY, WS_CHILD}; WS_CHILD | SS_NOTIFY } /// Center the text vertically. fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) { use crate::bind_raw_event_handler_inner; use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT}; use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT}; use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW}; use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED}; use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW}; use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB}; use std::{mem, ptr}; if self.handle.blank() { panic!("{}", NOT_BOUND); } let handle = self.handle.hwnd().expect(BAD_HANDLE); let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle)); let brush = match bg { Some(c) => { let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) }; self.background_brush = Some(b); b }, None => COLOR_WINDOW as HBRUSH }; unsafe { if bg.is_some() { let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| { match msg { WM_CTLCOLORSTATIC => { let child = l as HWND; if child == handle { return Some(brush as LRESULT); } }, _ => {} } None }); *self.handler0.borrow_mut() = Some(handler0.unwrap()); } let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| { match msg { WM_NCCALCSIZE => { if w == 0 { return None } // Calculate client area height needed for a font let font_handle = wh::get_window_font(hwnd); let mut r: RECT = mem::zeroed(); let dc = GetDC(hwnd); let old = SelectObject(dc, font_handle as HGDIOBJ); let mut newline_count = 1; let buffer_size = GetWindowTextLengthW(handle) as usize; match buffer_size == 0 { true => { let calc: [u16;2] = [75, 121]; DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT); }, false => { let mut buffer: Vec<u16> = vec![0; buffer_size + 1]; if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 { let calc: [u16;2] = [75, 121]; DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT); } else { for &c in buffer.iter() { if c == b'\n' as u16 { newline_count += 1; } } DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT); } } } let client_height = r.bottom * newline_count; SelectObject(dc, old); ReleaseDC(hwnd, dc); // Calculate NC area to center text. let mut client: RECT = mem::zeroed(); let mut window: RECT = mem::zeroed(); GetClientRect(hwnd, &mut client); GetWindowRect(hwnd, &mut window); let window_height = window.bottom - window.top; let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS; let info = &mut *info_ptr; match v_align { VTextAlign::Top => { info.rgrc[0].bottom -= window_height - client_height; }, VTextAlign::Center => { let center = ((window_height - client_height) / 2) - 1; info.rgrc[0].top += center; info.rgrc[0].bottom -= center; }, VTextAlign::Bottom => { info.rgrc[0].top += window_height - client_height; }, } }, WM_NCPAINT => { let mut window: RECT = mem::zeroed(); let mut client: RECT = mem::zeroed(); GetWindowRect(hwnd, &mut window); GetClientRect(hwnd, &mut client); let mut pt1 = POINT {x: window.left, y: window.top}; ScreenToClient(hwnd, &mut pt1); let mut pt2 = POINT {x: window.right, y: window.bottom}; ScreenToClient(hwnd, &mut pt2); let top = RECT { left: 0, top: pt1.y, right: client.right, bottom: client.top }; let bottom = RECT { left: 0, top: client.bottom, right: client.right, bottom: pt2.y }; let dc = GetDC(hwnd); FillRect(dc, &top, brush); FillRect(dc, &bottom, brush); ReleaseDC(hwnd, dc); }, WM_SIZE => { SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED); }, _ => {} } None }); *self.handler1.borrow_mut() = Some(handler1.unwrap()); } } } impl PartialEq for Label { fn eq(&self, other: &Self) -> bool { self.handle == other.handle } } impl Drop for Label { fn drop(&mut self) { let handler = self.handler0.borrow(); if let Some(h) = handler.as_ref() { drop(unbind_raw_event_handler(h)); } let handler = self.handler1.borrow(); if let Some(h) = handler.as_ref() { drop(unbind_raw_event_handler(h)); } if let Some(bg) = self.background_brush { unsafe { DeleteObject(bg as _); } } self.handle.destroy(); } } pub struct LabelBuilder<'a> { text: &'a str, size: (i32, i32), position: (i32, i32), background_color: Option<[u8; 3]>, flags: Option<LabelFlags>, ex_flags: u32, font: Option<&'a Font>, h_align: HTextAlign, v_align: VTextAlign, parent: Option<ControlHandle> } impl<'a> LabelBuilder<'a> { pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> { self.flags = Some(flags); self } pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> { self.ex_flags = flags; self } pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> { self.text = text; self } pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> { self.size = size; self } pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> { self.position = pos; self } pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> { self.font = font; self } pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> { self.background_color = color; self } pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> { self.h_align = align; self } pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> { self.v_align = align; self } pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> { self.parent = Some(p.into()); self } pub fn build(self, out: &mut Label) -> Result<(), NwgError> { use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER}; let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags()); match self.h_align { HTextAlign::Left => { flags |= SS_LEFT; }, HTextAlign::Right => { flags |= SS_RIGHT; }, HTextAlign::Center => { flags |= SS_CENTER; }, } let parent = match self.parent { Some(p) => Ok(p), None => Err(NwgError::no_parent("Label")) }?; // Drop the old object *out = Label::default(); out.handle = ControlBase::build_hwnd() .class_name(out.class_name()) .forced_flags(out.forced_flags()) .flags(flags) .ex_flags(self.ex_flags) .size(self.size) .position(self.position) .text(self.text) .parent(Some(parent)) .build()?; if self.font.is_some() { out.set_font(self.font); } else { out.set_font(Font::global_default().as_ref()); } out.hook_non_client_size(self.background_color, self.v_align); Ok(()) } }
//! Simple consensus runtime. use std::collections::BTreeMap; use oasis_runtime_sdk::{self as sdk, modules, types::token::Denomination, Version}; /// Simple consensus runtime. pub struct Runtime; impl sdk::Runtime for Runtime { const VERSION: Version = sdk::version_from_cargo!(); type Modules = ( modules::accounts::Module, modules::consensus_accounts::Module<modules::accounts::Module, modules::consensus::Module>, modules::core::Module, ); fn genesis_state() -> <Self::Modules as sdk::module::MigrationHandler>::Genesis { ( Default::default(), modules::consensus_accounts::Genesis { parameters: modules::consensus_accounts::Parameters { // These are free, in order to simplify testing. We do test gas accounting // with other methods elsewhere though. gas_costs: Default::default(), }, }, modules::core::Genesis { parameters: modules::core::Parameters { max_batch_gas: 10_000, max_tx_signers: 8, max_multisig_signers: 8, // These are free, in order to simplify testing. gas_costs: Default::default(), min_gas_price: { let mut mgp = BTreeMap::new(); mgp.insert(Denomination::NATIVE, 0); mgp }, }, }, ) } fn migrate_state<C: sdk::Context>(_ctx: &mut C) { // Make sure that there are no spurious state migration invocations. panic!("state migration called when it shouldn't be"); } }
//! Syscalls for process //! //! - fork //! - vfork //! - clone //! - wait4 //! - execve //! - gettid //! - getpid //! - getppid use super::*; use bitflags::bitflags; use core::fmt::Debug; use linux_object::fs::INodeExt; use linux_object::loader::LinuxElfLoader; use linux_object::thread::{CurrentThreadExt, ThreadExt}; use linux_object::time::*; impl Syscall<'_> { /// Fork the current process. Return the child's PID. pub fn sys_fork(&self) -> SysResult { info!("fork:"); let new_proc = Process::fork_from(self.zircon_process(), false)?; // old pt NULL here let new_thread = Thread::create_linux(&new_proc)?; #[cfg(not(target_arch = "riscv64"))] new_thread.start_with_regs(GeneralRegs::new_fork(self.regs), self.thread_fn)?; #[cfg(target_arch = "riscv64")] new_thread.start_with_context(self.context, self.thread_fn)?; info!("fork: {} -> {}", self.zircon_process().id(), new_proc.id()); Ok(new_proc.id() as usize) } /// creates a child process of the calling process, similar to fork but wait for execve pub async fn sys_vfork(&self) -> SysResult { info!("vfork:"); let new_proc = Process::fork_from(self.zircon_process(), true)?; let new_thread = Thread::create_linux(&new_proc)?; #[cfg(not(target_arch = "riscv64"))] new_thread.start_with_regs(GeneralRegs::new_fork(self.regs), self.thread_fn)?; #[cfg(target_arch = "riscv64")] new_thread.start_with_context(self.context, self.thread_fn)?; let new_proc: Arc<dyn KernelObject> = new_proc; info!( "vfork: {} -> {}. Waiting for execve SIGNALED", self.zircon_process().id(), new_proc.id() ); new_proc.wait_signal(Signal::SIGNALED).await; // wait for execve Ok(new_proc.id() as usize) } /// Create a new thread in the current process. /// The new thread's stack pointer will be set to `newsp`, /// and thread pointer will be set to `newtls`. /// The child tid will be stored at both `parent_tid` and `child_tid`. /// This is partially implemented for musl only. pub fn sys_clone( &self, flags: usize, newsp: usize, mut parent_tid: UserOutPtr<i32>, mut child_tid: UserOutPtr<i32>, newtls: usize, ) -> SysResult { let _flags = CloneFlags::from_bits_truncate(flags); info!( "clone: flags={:#x}, newsp={:#x}, parent_tid={:?}, child_tid={:?}, newtls={:#x}", flags, newsp, parent_tid, child_tid, newtls ); if flags == 0x4111 || flags == 0x11 { warn!("sys_clone is calling sys_fork instead, ignoring other args"); //unimplemented!() return self.sys_fork(); } if flags != 0x7d_0f00 && flags != 0x5d_0f00 { // 0x5d0f00: gcc of alpine linux // 0x7d0f00: pthread_create of alpine linux // warn!("sys_clone only support musl pthread_create"); panic!("unsupported sys_clone flags: {:#x}", flags); } let new_thread = Thread::create_linux(self.zircon_process())?; #[cfg(not(target_arch = "riscv64"))] { let regs = GeneralRegs::new_clone(self.regs, newsp, newtls); new_thread.start_with_regs(regs, self.thread_fn)?; } #[cfg(target_arch = "riscv64")] new_thread.start_with_context(self.context, self.thread_fn)?; let tid = new_thread.id(); info!("clone: {} -> {}", self.thread.id(), tid); parent_tid.write(tid as i32)?; child_tid.write(tid as i32)?; new_thread.set_tid_address(child_tid); Ok(tid as usize) } /// Wait for a child process exited. /// /// Return the PID. Store exit code to `wstatus` if it's not null. pub async fn sys_wait4( &self, pid: i32, mut wstatus: UserOutPtr<i32>, options: u32, ) -> SysResult { #[derive(Debug)] enum WaitTarget { AnyChild, AnyChildInGroup, Pid(KoID), } bitflags! { struct WaitFlags: u32 { const NOHANG = 1; const STOPPED = 2; const EXITED = 4; const CONTINUED = 8; const NOWAIT = 0x100_0000; } } let target = match pid { -1 => WaitTarget::AnyChild, 0 => WaitTarget::AnyChildInGroup, p if p > 0 => WaitTarget::Pid(p as KoID), _ => unimplemented!(), }; let flags = WaitFlags::from_bits_truncate(options); let nohang = flags.contains(WaitFlags::NOHANG); info!( "wait4: target={:?}, wstatus={:?}, options={:?}", target, wstatus, flags, ); let (pid, code) = match target { WaitTarget::AnyChild | WaitTarget::AnyChildInGroup => { wait_child_any(self.zircon_process(), nohang).await? } WaitTarget::Pid(pid) => (pid, wait_child(self.zircon_process(), pid, nohang).await?), }; wstatus.write_if_not_null(code)?; Ok(pid as usize) } /// Replaces the current ** process ** with a new process image /// /// `argv` is an array of argument strings passed to the new program. /// `envp` is an array of strings, conventionally of the form `key=value`, /// which are passed as environment to the new program. /// /// NOTICE: `argv` & `envp` can not be NULL (different from Linux) /// /// NOTICE: for multi-thread programs /// A call to any exec function from a process with more than one thread /// shall result in all threads being terminated and the new executable image /// being loaded and executed. pub fn sys_execve( &mut self, path: UserInPtr<u8>, argv: UserInPtr<UserInPtr<u8>>, envp: UserInPtr<UserInPtr<u8>>, ) -> SysResult { let path = path.read_cstring()?; let args = argv.read_cstring_array()?; let envs = envp.read_cstring_array()?; info!( "execve: path: {:?}, argv: {:?}, envs: {:?}", path, argv, envs ); if args.is_empty() { error!("execve: args is null"); return Err(LxError::EINVAL); } // TODO: check and kill other threads // Read program file let proc = self.linux_process(); let inode = proc.lookup_inode(&path)?; let data = inode.read_as_vec()?; proc.remove_cloexec_files(); let vmar = self.zircon_process().vmar(); vmar.clear()?; let loader = LinuxElfLoader { syscall_entry: self.syscall_entry, stack_pages: 8, root_inode: proc.root_inode().clone(), }; let (entry, sp) = loader.load(&vmar, &data, args, envs, path.clone())?; // Activate page table // vmar.activate(); // Modify exec path proc.set_execute_path(&path); // TODO: use right signal //self.zircon_process().signal_set(Signal::SIGNALED); //Workaround, the child process could NOT exit correctly #[cfg(not(target_arch = "riscv64"))] { *self.regs = GeneralRegs::new_fn(entry, sp, 0, 0); } #[cfg(target_arch = "riscv64")] { self.context.general = GeneralRegs::new_fn(entry, sp, 0, 0); self.context.sepc = entry; info!( "execve: PageTable: {:#x}, entry: {:#x}, sp: {:#x}", self.zircon_process().vmar().table_phys(), self.context.sepc, self.context.general.sp ); } Ok(0) } // // pub fn sys_yield(&self) -> SysResult { // thread::yield_now(); // Ok(0) // } // // /// Kill the process // pub fn sys_kill(&self, pid: usize, sig: usize) -> SysResult { // info!( // "kill: thread {} kill process {} with signal {}", // thread::current().id(), // pid, // sig // ); // let current_pid = self.process().pid.get().clone(); // if current_pid == pid { // // killing myself // self.sys_exit_group(sig); // } else { // if let Some(proc_arc) = PROCESSES.read().get(&pid).and_then(|weak| weak.upgrade()) { // let mut proc = proc_arc.lock(); // proc.exit(sig); // Ok(0) // } else { // Err(LxError::EINVAL) // } // } // } /// Get the current thread ID. pub fn sys_gettid(&self) -> SysResult { info!("gettid:"); let tid = self.thread.id(); Ok(tid as usize) } /// Get the current process ID. pub fn sys_getpid(&self) -> SysResult { info!("getpid:"); let proc = self.zircon_process(); let pid = proc.id(); Ok(pid as usize) } /// Get the parent process ID. pub fn sys_getppid(&self) -> SysResult { info!("getppid:"); let proc = self.linux_process(); let ppid = proc.parent().map(|p| p.id()).unwrap_or(0); Ok(ppid as usize) } /// Exit the current thread pub fn sys_exit(&mut self, exit_code: i32) -> SysResult { info!("exit: code={}", exit_code); self.thread.exit_linux(exit_code); Err(LxError::ENOSYS) } /// Exit the current thread group (i.e. process) pub fn sys_exit_group(&mut self, exit_code: i32) -> SysResult { info!("exit_group: code={}", exit_code); let proc = self.zircon_process(); proc.exit(exit_code as i64); Err(LxError::ENOSYS) } /// Allows the calling thread to sleep for /// an interval specified with nanosecond precision pub async fn sys_nanosleep(&self, req: UserInPtr<TimeSpec>) -> SysResult { info!("nanosleep: deadline={:?}", req); let req = req.read()?; kernel_hal::sleep_until(req.into()).await; Ok(0) } // pub fn sys_set_priority(&self, priority: usize) -> SysResult { // let pid = thread::current().id(); // thread_manager().set_priority(pid, priority as u8); // Ok(0) // } /// set pointer to thread ID /// returns the caller's thread ID pub fn sys_set_tid_address(&self, tidptr: UserOutPtr<i32>) -> SysResult { info!("set_tid_address: {:?}", tidptr); self.thread.set_tid_address(tidptr); let tid = self.thread.id(); Ok(tid as usize) } } bitflags! { pub struct CloneFlags: usize { /// const CSIGNAL = 0xff; /// the calling process and the child process run in the same memory space const VM = 1 << 8; /// the caller and the child process share the same filesystem information const FS = 1 << 9; /// the calling process and the child process share the same file descriptor table const FILES = 1 << 10; /// the calling process and the child process share the same table of signal handlers. const SIGHAND = 1 << 11; /// the calling process is being traced const PTRACE = 1 << 13; /// the execution of the calling process is suspended until the child releases its virtual memory resources const VFORK = 1 << 14; /// the parent of the new child will be the same as that of the call‐ing process. const PARENT = 1 << 15; /// the child is placed in the same thread group as the calling process. const THREAD = 1 << 16; /// cloned child is started in a new mount namespace const NEWNS = 1 << 17; /// the child and the calling process share a single list of System V semaphore adjustment values. const SYSVSEM = 1 << 18; /// architecture dependent, The TLS (Thread Local Storage) descriptor is set to tls. const SETTLS = 1 << 19; /// Store the child thread ID at the location in the parent's memory. const PARENT_SETTID = 1 << 20; /// Clear (zero) the child thread ID const CHILD_CLEARTID = 1 << 21; /// the parent not to receive a signal when the child terminated const DETACHED = 1 << 22; /// a tracing process cannot force CLONE_PTRACE on this child process. const UNTRACED = 1 << 23; /// Store the child thread ID const CHILD_SETTID = 1 << 24; /// Create the process in a new cgroup namespace. const NEWCGROUP = 1 << 25; /// create the process in a new UTS namespace const NEWUTS = 1 << 26; /// create the process in a new IPC namespace. const NEWIPC = 1 << 27; /// create the process in a new user namespace const NEWUSER = 1 << 28; /// create the process in a new PID namespace const NEWPID = 1 << 29; /// create the process in a new net‐work namespace. const NEWNET = 1 << 30; /// the new process shares an I/O context with the calling process. const IO = 1 << 31; } } trait RegExt { fn new_fn(entry: usize, sp: usize, arg1: usize, arg2: usize) -> Self; fn new_clone(regs: &Self, newsp: usize, newtls: usize) -> Self; fn new_fork(regs: &Self) -> Self; } #[cfg(target_arch = "x86_64")] impl RegExt for GeneralRegs { fn new_fn(entry: usize, sp: usize, arg1: usize, arg2: usize) -> Self { GeneralRegs { rip: entry, rsp: sp, rdi: arg1, rsi: arg2, ..Default::default() } } fn new_clone(regs: &Self, newsp: usize, newtls: usize) -> Self { GeneralRegs { rax: 0, rsp: newsp, fsbase: newtls, ..*regs } } fn new_fork(regs: &Self) -> Self { GeneralRegs { rax: 0, ..*regs } } } #[cfg(target_arch = "riscv64")] impl RegExt for GeneralRegs { fn new_fn(entry: usize, sp: usize, arg1: usize, arg2: usize) -> Self { info!( "new_fn(), Did NOT save ip:{:#x} register! x_x Saved sp: {:#x}", entry, sp ); GeneralRegs { sp: sp, a0: arg1, a1: arg2, ..Default::default() } } fn new_clone(regs: &Self, newsp: usize, newtls: usize) -> Self { GeneralRegs { a0: 0, sp: newsp, tp: newtls, ..*regs } } //设置了返回值为0 fn new_fork(regs: &Self) -> Self { GeneralRegs { a0: 0, ..*regs } } }
#[macro_use] extern crate nom; #[macro_use] extern crate derive_read_cstruct; use nom::IResult; use nom::le_u32; trait ReadCStruct { type Item; fn parse(input: &[u8]) -> IResult<&[u8], Self::Item>; } #[derive(PartialEq, Debug, ReadCStruct)] struct Person { age: u32, } fn main() { let input = &[0x10, 0, 0, 0]; let person = Person::parse(input); println!("{:?}", person); assert_eq!(Person{age: 16}, person.unwrap().1); }
use std::fmt::Display; use std::path::PathBuf; use nu_ansi_term::Color; use crate::traits::{CompatibleWithObservations, CorpusDelta, Pool, SaveToStatsFolder, Sensor, Stats}; use crate::{CSVField, PoolStorageIndex, ToCSV}; const NBR_ARTIFACTS_PER_ERROR_AND_CPLX: usize = 8; pub(crate) static mut TEST_FAILURE: Option<TestFailure> = None; /// A type describing a test failure. /// /// It is uniquely identifiable through `self.id` and displayable through `self.display`. #[derive(Debug, Clone)] pub struct TestFailure { pub display: String, pub id: u64, } /// A sensor that records test failures. #[derive(Default)] pub struct TestFailureSensor { error: Option<TestFailure>, } impl Sensor for TestFailureSensor { type Observations = Option<TestFailure>; #[no_coverage] fn start_recording(&mut self) { self.error = None; unsafe { TEST_FAILURE = None; } } #[no_coverage] fn stop_recording(&mut self) { unsafe { self.error = TEST_FAILURE.clone(); } } #[no_coverage] fn get_observations(&mut self) -> Option<TestFailure> { std::mem::take(&mut self.error) } } impl SaveToStatsFolder for TestFailureSensor { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { vec![] } } #[derive(Clone, Copy)] pub struct TestFailurePoolStats { pub count: usize, } impl Display for TestFailurePoolStats { #[no_coverage] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.count == 0 { write!(f, "failures({})", self.count) } else { write!(f, "{}", Color::Red.paint(format!("failures({})", self.count))) } } } impl ToCSV for TestFailurePoolStats { #[no_coverage] fn csv_headers(&self) -> Vec<CSVField> { vec![CSVField::String("test_failures_count".to_string())] } #[no_coverage] fn to_csv_record(&self) -> Vec<CSVField> { vec![CSVField::Integer(self.count as isize)] } } impl Stats for TestFailurePoolStats {} struct TestFailureList { error: TestFailure, inputs: Vec<TestFailureListForError>, } struct TestFailureListForError { cplx: f64, inputs: Vec<PoolStorageIndex>, } /// A pool that saves failing test cases. /// /// It categorizes the test cases by their failure information and sort them by complexity. pub struct TestFailurePool { name: String, inputs: Vec<TestFailureList>, rng: fastrand::Rng, } impl TestFailurePool { #[no_coverage] pub(crate) fn new(name: &str) -> Self { Self { name: name.to_string(), inputs: vec![], rng: fastrand::Rng::new(), } } } impl Pool for TestFailurePool { type Stats = TestFailurePoolStats; #[no_coverage] fn stats(&self) -> Self::Stats { TestFailurePoolStats { count: self.inputs.len(), } } #[no_coverage] fn get_random_index(&mut self) -> Option<PoolStorageIndex> { if self.inputs.is_empty() { return None; } let error_choice = self.rng.usize(0..self.inputs.len()); let list_for_error = &self.inputs[error_choice]; let complexity_choice = list_for_error.inputs.len() - 1; let least_complexity = &list_for_error.inputs[complexity_choice]; if least_complexity.inputs.is_empty() { return None; } let input_choice = self.rng.usize(0..least_complexity.inputs.len()); Some(least_complexity.inputs[input_choice]) } } impl SaveToStatsFolder for TestFailurePool { #[no_coverage] fn save_to_stats_folder(&self) -> Vec<(PathBuf, Vec<u8>)> { cfg_if::cfg_if! { if #[cfg(feature = "serde_json_serializer")] { let path = PathBuf::new().join("test_failures.json"); let content = serde_json::to_string(&self.inputs.iter().map( #[no_coverage] |tf| (tf.error.id, tf.error.display.clone()) ).collect::<Vec<_>>()).unwrap(); vec![(path, content.into_bytes())] } else { vec![] } } } } impl CompatibleWithObservations<Option<TestFailure>> for TestFailurePool { #[no_coverage] fn process( &mut self, input_idx: PoolStorageIndex, observations: &Option<TestFailure>, complexity: f64, ) -> Vec<CorpusDelta> { let error = observations; enum PositionOfNewInput { NewError, ExistingErrorNewCplx(usize), ExistingErrorAndCplx(usize), } let mut is_interesting = None; if let Some(error) = error { if let Some(list_index) = self.inputs.iter().position( #[no_coverage] |xs| xs.error.id == error.id, ) { let list = &self.inputs[list_index]; if let Some(least_complex) = list.inputs.last() { if least_complex.cplx > complexity { is_interesting = Some(PositionOfNewInput::ExistingErrorNewCplx(list_index)); } else if least_complex.cplx == complexity { if least_complex.inputs.len() < NBR_ARTIFACTS_PER_ERROR_AND_CPLX && !self.inputs.iter().any( #[no_coverage] |xs| xs.error.display == error.display, ) { is_interesting = Some(PositionOfNewInput::ExistingErrorAndCplx(list_index)); } } } else { is_interesting = Some(PositionOfNewInput::ExistingErrorNewCplx(list_index)); } } else { // a new error we haven't seen before is_interesting = Some(PositionOfNewInput::NewError); } if let Some(position) = is_interesting { let mut path = PathBuf::new(); path.push(&self.name); path.push(format!("{}", error.id)); path.push(format!("{:.4}", complexity)); match position { PositionOfNewInput::NewError => { self.inputs.push(TestFailureList { error: error.clone(), inputs: vec![TestFailureListForError { cplx: complexity, inputs: vec![input_idx], }], }); } PositionOfNewInput::ExistingErrorNewCplx(error_idx) => { // TODO: handle event self.inputs[error_idx].inputs.push(TestFailureListForError { cplx: complexity, inputs: vec![input_idx], }); } PositionOfNewInput::ExistingErrorAndCplx(error_idx) => { // NOTE: the complexity must be the last one // TODO: handle event self.inputs[error_idx].inputs.last_mut().unwrap().inputs.push(input_idx); } }; let delta = CorpusDelta { path, add: true, remove: vec![], }; return vec![delta]; } } vec![] } }
extern crate futures; extern crate futures_cpupool; extern crate protobuf; extern crate grpc; extern crate tls_api; extern crate frank_jwt; pub mod jwt; pub mod jwt_grpc;
//! # Yet Another Progress Bar //! //! This library provides lightweight tools for rendering progress indicators and related information. Unlike most //! similar libraries, it performs no IO internally, instead providing `Display` implementations. Handling the details //! of any particular output device is left to the user. //! //! # Examples //! The `termion` crate can be used to implement good behavior on an ANSI terminal: //! //! ```no_run //! extern crate yapb; //! extern crate termion; //! use std::{thread, time}; //! use std::io::{self, Write}; //! use yapb::{Bar, Progress}; //! //! fn main() { //! let mut bar = Bar::new(); //! print!("{}", termion::cursor::Save); //! for i in 0..100 { //! bar.set(i as f32 / 100.0); //! let (width, _) = termion::terminal_size().unwrap(); //! print!("{}{}[{:width$}]", //! termion::clear::AfterCursor, termion::cursor::Restore, //! bar, width = width as usize - 2); //! io::stdout().flush().unwrap(); //! thread::sleep(time::Duration::from_millis(100)); //! } //! } //! ``` use std::fmt::{self, Display, Write}; pub mod prefix; /// Indicators that communicate a proportion of progress towards a known end point pub trait Progress: Display { /// Set the amount of progress /// /// `value` must be in [0, 1]. Implementations should be trivial, with any complexity deferred to the /// `Display` implementation. fn set(&mut self, value: f32); } /// An unusually high-resolution progress bar using Unicode block elements /// /// # Examples /// ``` /// # use yapb::*; /// let mut bar = Bar::new(); /// bar.set(0.55); /// assert_eq!(format!("[{:10}]", bar), "[█████▌ ]"); /// ``` #[derive(Debug, Copy, Clone)] pub struct Bar { progress: f32, } impl Bar { pub fn new() -> Self { Bar { progress: 0.0 } } pub fn get(&self) -> f32 { self.progress } } impl Progress for Bar { fn set(&mut self, value: f32) { self.progress = value; } } impl Display for Bar { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let width = f.width().unwrap_or(80) as u32; // Scale by width, rounding to nearest let count = width as f32 * self.progress.max(0.0).min(1.0); let whole = count.trunc() as u32; for _ in 0..whole { f.write_char('█')?; } let fraction = (count.fract() * 8.0).trunc() as u32; let fill = f.fill(); if whole < width { f.write_char(match fraction { 0 => fill, 1 => '▏', 2 => '▎', 3 => '▍', 4 => '▌', 5 => '▋', 6 => '▊', 7 => '▉', _ => unreachable!(), })?; for _ in whole..(width - 1) { f.write_char(fill)?; } } Ok(()) } } /// Indicators that animate through some number of states to indicate activity with indefinite duration /// /// Incrementing a state by 1 advances by one frame of animation. Implementations of these two setters should only be a /// handful of instructions, with all complexity deferred to the `Display` impl. pub trait Spinner: Display { /// Set a specific state fn set(&mut self, value: u32); /// Advance the current state `count` times. fn step(&mut self, count: u32); } /// A spinner that cycles through 256 states by counting in binary using braille /// /// # Examples /// ``` /// # use yapb::*; /// let mut spinner = Counter256::new(); /// assert_eq!(format!("{}", spinner), "⠀"); /// spinner.step(0x0F); /// assert_eq!(format!("{}", spinner), "⡇"); /// spinner.step(0xF0); /// assert_eq!(format!("{}", spinner), "⣿"); /// ``` #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)] pub struct Counter256 { state: u8, } impl Counter256 { pub fn new() -> Self { Self { state: 0 } } } impl Spinner for Counter256 { fn set(&mut self, state: u32) { self.state = state as u8; } fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8); } } fn braille_binary(value: u8) -> char { // Rearrange bits for consistency let value = (value & 0b10000111) | ((value & 0b00001000) << 3) | ((value & 0b01110000) >> 1); unsafe { ::std::char::from_u32_unchecked(0x2800 + value as u32) } } impl Display for Counter256 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char(braille_binary(self.state)) } } /// A spinner that cycles through 8 states with a single spinning braille dot #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)] pub struct Spinner8 { state: u8, } const SPINNER8_STATES: [char; 8] = ['⡀', '⠄', '⠂', '⠁', '⠈', '⠐', '⠠', '⢀']; impl Spinner8 { pub fn new() -> Self { Self { state: 0 } } } impl Spinner for Spinner8 { fn set(&mut self, state: u32) { self.state = state as u8 % SPINNER8_STATES.len() as u8; } fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % SPINNER8_STATES.len() as u8; } } impl Display for Spinner8 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char(*unsafe { SPINNER8_STATES.get_unchecked(self.state as usize) }) } } /// A spinner that cycles through 16 states by counting in binary using block elements #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)] pub struct Counter16 { state: u8, } const COUNTER16_STATES: [char; 16] = [ ' ', '▘', '▖', '▌', '▝', '▀', '▞', '▛', '▗', '▚', '▄', '▙', '▐', '▜', '▟', '█', ]; impl Counter16 { pub fn new() -> Self { Self { state: 0 } } } impl Spinner for Counter16 { fn set(&mut self, state: u32) { self.state = state as u8 % COUNTER16_STATES.len() as u8; } fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % COUNTER16_STATES.len() as u8; } } impl Display for Counter16 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char(*unsafe { COUNTER16_STATES.get_unchecked(self.state as usize) }) } } /// A spinner that cycles through 4 states with a single spinning block element #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)] pub struct Spinner4 { state: u8, } const SPINNER4_STATES: [char; 4] = ['▖', '▘', '▝', '▗']; impl Spinner4 { pub fn new() -> Self { Self { state: 0 } } } impl Spinner for Spinner4 { fn set(&mut self, state: u32) { self.state = state as u8 % SPINNER4_STATES.len() as u8; } fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count as u8) % SPINNER4_STATES.len() as u8; } } impl Display for Spinner4 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_char(*unsafe { SPINNER4_STATES.get_unchecked(self.state as usize) }) } } /// A spinner that cycles through many states with a snake made of 1-6 braille dots #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone)] pub struct Snake { state: u32, } impl Snake { pub fn new() -> Self { Self { state: 0 } } } impl Spinner for Snake { fn set(&mut self, state: u32) { self.state = state; } fn step(&mut self, count: u32) { self.state = self.state.wrapping_add(count); } } impl Display for Snake { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { const WOBBLE: u32 = 5; let length = (((self.state % (2 * WOBBLE)) as i32 - (WOBBLE as i32)).abs() + 1) as u32; let bits = !(0xFFu8 << length); let position = (WOBBLE * (self.state / (2 * WOBBLE)) + (self.state % (2 * WOBBLE)).saturating_sub(WOBBLE)) as u8; let snake = bits.rotate_right(position as u32); // Reverse most significant nybble let value = snake & 0xF | ((snake & 0b10000000) >> 3) | ((snake & 0b01000000) >> 1) | ((snake & 0b00100000) << 1) | ((snake & 0b00010000) << 3); f.write_char(braille_binary(value)) } } /// Exponential moving average, useful for computing throughput #[derive(Debug, Copy, Clone)] pub struct MovingAverage { alpha: f32, value: f32, } impl MovingAverage { /// `alpha` is in (0, 1] describing how responsive to be to each update pub fn new(alpha: f32, initial: f32) -> Self { Self { alpha, value: initial, } } /// Update with a new sample pub fn update(&mut self, value: f32) { self.value = self.alpha * value + (1.0 - self.alpha) * self.value; } /// Get the current average value pub fn get(&self) -> f32 { self.value } } #[cfg(test)] mod tests { use super::*; #[test] fn bar_sanity() { let mut bar = Bar::new(); assert_eq!(format!("{:10}", bar), " "); bar.set(1.0); assert_eq!(format!("{:10}", bar), "██████████"); } }
#[doc = "Reader of register C1_AHB4LPENR"] pub type R = crate::R<u32, super::C1_AHB4LPENR>; #[doc = "Writer for register C1_AHB4LPENR"] pub type W = crate::W<u32, super::C1_AHB4LPENR>; #[doc = "Register C1_AHB4LPENR `reset()`'s with value 0"] impl crate::ResetValue for super::C1_AHB4LPENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "GPIO peripheral clock enable during CSleep mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum GPIOALPEN_A { #[doc = "0: The selected clock is disabled during csleep mode"] DISABLED = 0, #[doc = "1: The selected clock is enabled during csleep mode"] ENABLED = 1, } impl From<GPIOALPEN_A> for bool { #[inline(always)] fn from(variant: GPIOALPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `GPIOALPEN`"] pub type GPIOALPEN_R = crate::R<bool, GPIOALPEN_A>; impl GPIOALPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> GPIOALPEN_A { match self.bits { false => GPIOALPEN_A::DISABLED, true => GPIOALPEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == GPIOALPEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == GPIOALPEN_A::ENABLED } } #[doc = "Write proxy for field `GPIOALPEN`"] pub struct GPIOALPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOALPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOALPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOBLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOBLPEN`"] pub type GPIOBLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOBLPEN`"] pub struct GPIOBLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOBLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOBLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOCLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOCLPEN`"] pub type GPIOCLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOCLPEN`"] pub struct GPIOCLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOCLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOCLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIODLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIODLPEN`"] pub type GPIODLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIODLPEN`"] pub struct GPIODLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIODLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIODLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOELPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOELPEN`"] pub type GPIOELPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOELPEN`"] pub struct GPIOELPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOELPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOELPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOFLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOFLPEN`"] pub type GPIOFLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOFLPEN`"] pub struct GPIOFLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOFLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOFLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOGLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOGLPEN`"] pub type GPIOGLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOGLPEN`"] pub struct GPIOGLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOGLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOGLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOHLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOHLPEN`"] pub type GPIOHLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOHLPEN`"] pub struct GPIOHLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOHLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOHLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOILPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOILPEN`"] pub type GPIOILPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOILPEN`"] pub struct GPIOILPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOILPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOILPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOJLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOJLPEN`"] pub type GPIOJLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOJLPEN`"] pub struct GPIOJLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOJLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOJLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "GPIO peripheral clock enable during CSleep mode"] pub type GPIOKLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `GPIOKLPEN`"] pub type GPIOKLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `GPIOKLPEN`"] pub struct GPIOKLPEN_W<'a> { w: &'a mut W, } impl<'a> GPIOKLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: GPIOKLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "CRC peripheral clock enable during CSleep mode"] pub type CRCLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `CRCLPEN`"] pub type CRCLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `CRCLPEN`"] pub struct CRCLPEN_W<'a> { w: &'a mut W, } impl<'a> CRCLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CRCLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "BDMA Clock Enable During CSleep Mode"] pub type BDMALPEN_A = GPIOALPEN_A; #[doc = "Reader of field `BDMALPEN`"] pub type BDMALPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `BDMALPEN`"] pub struct BDMALPEN_W<'a> { w: &'a mut W, } impl<'a> BDMALPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BDMALPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "ADC3 Peripheral Clocks Enable During CSleep Mode"] pub type ADC3LPEN_A = GPIOALPEN_A; #[doc = "Reader of field `ADC3LPEN`"] pub type ADC3LPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `ADC3LPEN`"] pub struct ADC3LPEN_W<'a> { w: &'a mut W, } impl<'a> ADC3LPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC3LPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Backup RAM Clock Enable During CSleep Mode"] pub type BKPRAMLPEN_A = GPIOALPEN_A; #[doc = "Reader of field `BKPRAMLPEN`"] pub type BKPRAMLPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `BKPRAMLPEN`"] pub struct BKPRAMLPEN_W<'a> { w: &'a mut W, } impl<'a> BKPRAMLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BKPRAMLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "SRAM4 Clock Enable During CSleep Mode"] pub type SRAM4LPEN_A = GPIOALPEN_A; #[doc = "Reader of field `SRAM4LPEN`"] pub type SRAM4LPEN_R = crate::R<bool, GPIOALPEN_A>; #[doc = "Write proxy for field `SRAM4LPEN`"] pub struct SRAM4LPEN_W<'a> { w: &'a mut W, } impl<'a> SRAM4LPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SRAM4LPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(GPIOALPEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } impl R { #[doc = "Bit 0 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioalpen(&self) -> GPIOALPEN_R { GPIOALPEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioblpen(&self) -> GPIOBLPEN_R { GPIOBLPEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioclpen(&self) -> GPIOCLPEN_R { GPIOCLPEN_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiodlpen(&self) -> GPIODLPEN_R { GPIODLPEN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioelpen(&self) -> GPIOELPEN_R { GPIOELPEN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioflpen(&self) -> GPIOFLPEN_R { GPIOFLPEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioglpen(&self) -> GPIOGLPEN_R { GPIOGLPEN_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiohlpen(&self) -> GPIOHLPEN_R { GPIOHLPEN_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioilpen(&self) -> GPIOILPEN_R { GPIOILPEN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiojlpen(&self) -> GPIOJLPEN_R { GPIOJLPEN_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioklpen(&self) -> GPIOKLPEN_R { GPIOKLPEN_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 19 - CRC peripheral clock enable during CSleep mode"] #[inline(always)] pub fn crclpen(&self) -> CRCLPEN_R { CRCLPEN_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 21 - BDMA Clock Enable During CSleep Mode"] #[inline(always)] pub fn bdmalpen(&self) -> BDMALPEN_R { BDMALPEN_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 24 - ADC3 Peripheral Clocks Enable During CSleep Mode"] #[inline(always)] pub fn adc3lpen(&self) -> ADC3LPEN_R { ADC3LPEN_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 28 - Backup RAM Clock Enable During CSleep Mode"] #[inline(always)] pub fn bkpramlpen(&self) -> BKPRAMLPEN_R { BKPRAMLPEN_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - SRAM4 Clock Enable During CSleep Mode"] #[inline(always)] pub fn sram4lpen(&self) -> SRAM4LPEN_R { SRAM4LPEN_R::new(((self.bits >> 29) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioalpen(&mut self) -> GPIOALPEN_W { GPIOALPEN_W { w: self } } #[doc = "Bit 1 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioblpen(&mut self) -> GPIOBLPEN_W { GPIOBLPEN_W { w: self } } #[doc = "Bit 2 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioclpen(&mut self) -> GPIOCLPEN_W { GPIOCLPEN_W { w: self } } #[doc = "Bit 3 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiodlpen(&mut self) -> GPIODLPEN_W { GPIODLPEN_W { w: self } } #[doc = "Bit 4 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioelpen(&mut self) -> GPIOELPEN_W { GPIOELPEN_W { w: self } } #[doc = "Bit 5 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioflpen(&mut self) -> GPIOFLPEN_W { GPIOFLPEN_W { w: self } } #[doc = "Bit 6 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioglpen(&mut self) -> GPIOGLPEN_W { GPIOGLPEN_W { w: self } } #[doc = "Bit 7 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiohlpen(&mut self) -> GPIOHLPEN_W { GPIOHLPEN_W { w: self } } #[doc = "Bit 8 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioilpen(&mut self) -> GPIOILPEN_W { GPIOILPEN_W { w: self } } #[doc = "Bit 9 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpiojlpen(&mut self) -> GPIOJLPEN_W { GPIOJLPEN_W { w: self } } #[doc = "Bit 10 - GPIO peripheral clock enable during CSleep mode"] #[inline(always)] pub fn gpioklpen(&mut self) -> GPIOKLPEN_W { GPIOKLPEN_W { w: self } } #[doc = "Bit 19 - CRC peripheral clock enable during CSleep mode"] #[inline(always)] pub fn crclpen(&mut self) -> CRCLPEN_W { CRCLPEN_W { w: self } } #[doc = "Bit 21 - BDMA Clock Enable During CSleep Mode"] #[inline(always)] pub fn bdmalpen(&mut self) -> BDMALPEN_W { BDMALPEN_W { w: self } } #[doc = "Bit 24 - ADC3 Peripheral Clocks Enable During CSleep Mode"] #[inline(always)] pub fn adc3lpen(&mut self) -> ADC3LPEN_W { ADC3LPEN_W { w: self } } #[doc = "Bit 28 - Backup RAM Clock Enable During CSleep Mode"] #[inline(always)] pub fn bkpramlpen(&mut self) -> BKPRAMLPEN_W { BKPRAMLPEN_W { w: self } } #[doc = "Bit 29 - SRAM4 Clock Enable During CSleep Mode"] #[inline(always)] pub fn sram4lpen(&mut self) -> SRAM4LPEN_W { SRAM4LPEN_W { w: self } } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::HB16TIME4 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct EPI_HB16TIME4_RDWSMR { bits: bool, } impl EPI_HB16TIME4_RDWSMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16TIME4_RDWSMW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16TIME4_RDWSMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16TIME4_WRWSMR { bits: bool, } impl EPI_HB16TIME4_WRWSMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _EPI_HB16TIME4_WRWSMW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16TIME4_WRWSMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16TIME4_CAPWIDTHR { bits: u8, } impl EPI_HB16TIME4_CAPWIDTHR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _EPI_HB16TIME4_CAPWIDTHW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16TIME4_CAPWIDTHW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 12); self.w.bits |= ((value as u32) & 3) << 12; self.w } } #[doc = "Possible values of the field `EPI_HB16TIME4_PSRAMSZ`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16TIME4_PSRAMSZR { #[doc = "No row size limitation"] EPI_HB16TIME4_PSRAMSZ_0, #[doc = "128 B"] EPI_HB16TIME4_PSRAMSZ_128B, #[doc = "256 B"] EPI_HB16TIME4_PSRAMSZ_256B, #[doc = "512 B"] EPI_HB16TIME4_PSRAMSZ_512B, #[doc = "1024 B"] EPI_HB16TIME4_PSRAMSZ_1KB, #[doc = "2048 B"] EPI_HB16TIME4_PSRAMSZ_2KB, #[doc = "4096 B"] EPI_HB16TIME4_PSRAMSZ_4KB, #[doc = "8192 B"] EPI_HB16TIME4_PSRAMSZ_8KB, } impl EPI_HB16TIME4_PSRAMSZR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_0 => 0, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_128B => 1, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_256B => 2, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_512B => 3, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_1KB => 4, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_2KB => 5, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_4KB => 6, EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_8KB => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> EPI_HB16TIME4_PSRAMSZR { match value { 0 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_0, 1 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_128B, 2 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_256B, 3 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_512B, 4 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_1KB, 5 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_2KB, 6 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_4KB, 7 => EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_8KB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_0`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_0(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_0 } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_128B`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_128b(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_128B } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_256B`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_256b(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_256B } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_512B`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_512b(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_512B } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_1KB`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_1kb(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_1KB } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_2KB`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_2kb(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_2KB } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_4KB`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_4kb(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_4KB } #[doc = "Checks if the value of the field is `EPI_HB16TIME4_PSRAMSZ_8KB`"] #[inline(always)] pub fn is_epi_hb16time4_psramsz_8kb(&self) -> bool { *self == EPI_HB16TIME4_PSRAMSZR::EPI_HB16TIME4_PSRAMSZ_8KB } } #[doc = "Values that can be written to the field `EPI_HB16TIME4_PSRAMSZ`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPI_HB16TIME4_PSRAMSZW { #[doc = "No row size limitation"] EPI_HB16TIME4_PSRAMSZ_0, #[doc = "128 B"] EPI_HB16TIME4_PSRAMSZ_128B, #[doc = "256 B"] EPI_HB16TIME4_PSRAMSZ_256B, #[doc = "512 B"] EPI_HB16TIME4_PSRAMSZ_512B, #[doc = "1024 B"] EPI_HB16TIME4_PSRAMSZ_1KB, #[doc = "2048 B"] EPI_HB16TIME4_PSRAMSZ_2KB, #[doc = "4096 B"] EPI_HB16TIME4_PSRAMSZ_4KB, #[doc = "8192 B"] EPI_HB16TIME4_PSRAMSZ_8KB, } impl EPI_HB16TIME4_PSRAMSZW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_0 => 0, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_128B => 1, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_256B => 2, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_512B => 3, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_1KB => 4, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_2KB => 5, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_4KB => 6, EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_8KB => 7, } } } #[doc = r"Proxy"] pub struct _EPI_HB16TIME4_PSRAMSZW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16TIME4_PSRAMSZW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EPI_HB16TIME4_PSRAMSZW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "No row size limitation"] #[inline(always)] pub fn epi_hb16time4_psramsz_0(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_0) } #[doc = "128 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_128b(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_128B) } #[doc = "256 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_256b(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_256B) } #[doc = "512 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_512b(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_512B) } #[doc = "1024 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_1kb(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_1KB) } #[doc = "2048 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_2kb(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_2KB) } #[doc = "4096 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_4kb(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_4KB) } #[doc = "8192 B"] #[inline(always)] pub fn epi_hb16time4_psramsz_8kb(self) -> &'a mut W { self.variant(EPI_HB16TIME4_PSRAMSZW::EPI_HB16TIME4_PSRAMSZ_8KB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 16); self.w.bits |= ((value as u32) & 7) << 16; self.w } } #[doc = r"Value of the field"] pub struct EPI_HB16TIME4_IRDYDLYR { bits: u8, } impl EPI_HB16TIME4_IRDYDLYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r"Proxy"] pub struct _EPI_HB16TIME4_IRDYDLYW<'a> { w: &'a mut W, } impl<'a> _EPI_HB16TIME4_IRDYDLYW<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 24); self.w.bits |= ((value as u32) & 3) << 24; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - CS3n Read Wait State Minus One"] #[inline(always)] pub fn epi_hb16time4_rdwsm(&self) -> EPI_HB16TIME4_RDWSMR { let bits = ((self.bits >> 0) & 1) != 0; EPI_HB16TIME4_RDWSMR { bits } } #[doc = "Bit 4 - CS3n Write Wait State Minus One"] #[inline(always)] pub fn epi_hb16time4_wrwsm(&self) -> EPI_HB16TIME4_WRWSMR { let bits = ((self.bits >> 4) & 1) != 0; EPI_HB16TIME4_WRWSMR { bits } } #[doc = "Bits 12:13 - CS3n Inter-transfer Capture Width"] #[inline(always)] pub fn epi_hb16time4_capwidth(&self) -> EPI_HB16TIME4_CAPWIDTHR { let bits = ((self.bits >> 12) & 3) as u8; EPI_HB16TIME4_CAPWIDTHR { bits } } #[doc = "Bits 16:18 - PSRAM Row Size"] #[inline(always)] pub fn epi_hb16time4_psramsz(&self) -> EPI_HB16TIME4_PSRAMSZR { EPI_HB16TIME4_PSRAMSZR::_from(((self.bits >> 16) & 7) as u8) } #[doc = "Bits 24:25 - CS3n Input Ready Delay"] #[inline(always)] pub fn epi_hb16time4_irdydly(&self) -> EPI_HB16TIME4_IRDYDLYR { let bits = ((self.bits >> 24) & 3) as u8; EPI_HB16TIME4_IRDYDLYR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - CS3n Read Wait State Minus One"] #[inline(always)] pub fn epi_hb16time4_rdwsm(&mut self) -> _EPI_HB16TIME4_RDWSMW { _EPI_HB16TIME4_RDWSMW { w: self } } #[doc = "Bit 4 - CS3n Write Wait State Minus One"] #[inline(always)] pub fn epi_hb16time4_wrwsm(&mut self) -> _EPI_HB16TIME4_WRWSMW { _EPI_HB16TIME4_WRWSMW { w: self } } #[doc = "Bits 12:13 - CS3n Inter-transfer Capture Width"] #[inline(always)] pub fn epi_hb16time4_capwidth(&mut self) -> _EPI_HB16TIME4_CAPWIDTHW { _EPI_HB16TIME4_CAPWIDTHW { w: self } } #[doc = "Bits 16:18 - PSRAM Row Size"] #[inline(always)] pub fn epi_hb16time4_psramsz(&mut self) -> _EPI_HB16TIME4_PSRAMSZW { _EPI_HB16TIME4_PSRAMSZW { w: self } } #[doc = "Bits 24:25 - CS3n Input Ready Delay"] #[inline(always)] pub fn epi_hb16time4_irdydly(&mut self) -> _EPI_HB16TIME4_IRDYDLYW { _EPI_HB16TIME4_IRDYDLYW { w: self } } }
use super::{Blocks, Chunks, SuccinctBitVector}; impl SuccinctBitVector { /// Returns `i`-th element of the `SuccinctBitVector`. /// /// # Panics /// When _`i` >= length of the `SuccinctBitVector`_. pub fn access(&self, i: u64) -> bool { self.rbv.access(i) } /// Returns the number of _1_ in _[0, `i`]_ elements of the `SuccinctBitVector`. /// /// # Panics /// When _`i` >= length of the `SuccinctBitVector`_. /// /// # Implementation detail /// /// ```text /// 00001000 01000001 00000100 11000000 00100000 00000101 00100000 00010000 001 Raw data (N=67) /// ^ /// i = 51 /// | 7 | 12 | Chunk (size = (log N)^2 = 36) /// ^ /// chunk_left i_chunk = 1 chunk_right /// /// |0 |1 |1 |2 |2 |3 |3 |4 |6 |6 |6 |7 |0 |0 |0 |2 |3 |3 |4 |4 |4 |5 |5| Block (size = log N / 2 = 3) /// ^ /// i_block = 17 /// block_left | block_right /// ``` /// /// 1. Find `i_chunk`. _`i_chunk` = `i` / `chunk_size`_. /// 2. Get _`chunk_left` = Chunks[`i_chunk` - 1]_ only if _`i_chunk` > 0_. /// 3. Get _rank from chunk_left_ if `chunk_left` exists. /// 4. Get _`chunk_right` = Chunks[`i_chunk`]_. /// 5. Find `i_block`. _`i_block` = (`i` - `i_chunk` * `chunk_size`) / block size_. /// 6. Get _`block_left` = `chunk_right.blocks`[ `i_block` - 1]`_ only if _`i_block` > 0_. /// 7. Get _rank from block_left_ if `block_left` exists. /// 8. Get inner-block data _`block_bits`. `block_bits` must be of _block size_ length, fulfilled with _0_ in right bits. /// 9. Calculate _rank of `block_bits`_ in _O(1)_ using a table memonizing _block size_ bit's popcount. pub fn rank(&self, i: u64) -> u64 { let n = self.rbv.length(); assert!(i < n); let chunk_size = Chunks::calc_chunk_size(n); let block_size = Blocks::calc_block_size(n); // 1. let i_chunk = i / chunk_size as u64; // 3. let rank_from_chunk = if i_chunk == 0 { 0 } else { // 2., 3. let chunk_left = self.chunks.access(i_chunk - 1); chunk_left.value() }; // 4. let chunk_right = self.chunks.access(i_chunk); // 5. let i_block = (i - i_chunk * chunk_size as u64) / block_size as u64; // 7. let rank_from_block = if i_block == 0 { 0 } else { // 6., 7. let block_left = chunk_right.blocks.access(i_block - 1); block_left.value() }; // 8. let block_right = chunk_right.blocks.access(i_block); let pos_block_start = i_chunk * chunk_size as u64 + i_block * block_size as u64; assert!(i - pos_block_start < block_right.length() as u64); let block_right_rbv = self .rbv .copy_sub(pos_block_start, block_right.length() as u64); let block_right_as_u32 = block_right_rbv.as_u32(); let bits_to_use = i - pos_block_start + 1; let block_bits = block_right_as_u32 >> (32 - bits_to_use); let rank_from_table = self.table.popcount(block_bits as u64); // 9. rank_from_chunk + rank_from_block as u64 + rank_from_table as u64 } /// Returns the number of _0_ in _[0, `i`]_ elements of the `SuccinctBitVector`. /// /// # Panics /// When _`i` >= length of the `SuccinctBitVector`_. pub fn rank0(&self, i: u64) -> u64 { (i + 1) - self.rank(i) } /// Returns the minimum position (0-origin) `i` where _`rank(i)` == num_ of `num`-th _1_ if exists. Else returns None. /// /// # Panics /// When _`num` > length of the `SuccinctBitVector`_. /// /// # Implementation detail /// Binary search using `rank()`. pub fn select(&self, num: u64) -> Option<u64> { let n = self.rbv.length(); assert!(num <= n); if num == 0 || num == 1 && self.access(0) == true { return Some(0); } if self.rank(n - 1) < num { return None; }; let mut ng = 0; let mut ok = n - 1; while ok - ng > 1 { let mid = (ok + ng) / 2; if self.rank(mid) >= num { ok = mid; } else { ng = mid; } } Some(ok) } /// Returns the minimum position (0-origin) `i` where _`rank(i)` == num_ of `num`-th _0_ if exists. Else returns None. /// /// # Panics /// When _`num` > length of the `SuccinctBitVector`_. pub fn select0(&self, num: u64) -> Option<u64> { let n = self.rbv.length(); assert!(num <= n); if num == 0 || num == 1 && self.access(0) == false { return Some(0); } if self.rank0(n - 1) < num { return None; }; let mut ng = 0; let mut ok = n - 1; while ok - ng > 1 { let mid = (ok + ng) / 2; if self.rank0(mid) >= num { ok = mid; } else { ng = mid; } } Some(ok) } } #[cfg(test)] mod access_success_tests { // well-tested in succinct_bit_vector_builder::{builder_from_length_success_tests, builder_from_bit_string_success_tests} } #[cfg(test)] mod access_failure_tests { use super::super::SuccinctBitVectorBuilder; #[test] #[should_panic] fn over_upper_bound() { let bv = SuccinctBitVectorBuilder::from_length(2).build(); let _ = bv.access(2); } } #[cfg(test)] #[allow(non_snake_case)] mod rank_success_tests { use super::super::{BitString, SuccinctBitVectorBuilder}; macro_rules! parameterized_tests { ($($name:ident: $value:expr,)*) => { $( #[test] fn $name() { let (in_bv_str, in_i, expected_rank) = $value; assert_eq!( SuccinctBitVectorBuilder::from_bit_string(BitString::new(in_bv_str)) .build().rank(in_i), expected_rank); } )* } } parameterized_tests! { rank1_1: ("0", 0, 0), rank2_1: ("00", 0, 0), rank2_2: ("00", 1, 0), rank3_1: ("01", 0, 0), rank3_2: ("01", 1, 1), rank4_1: ("10", 0, 1), rank4_2: ("10", 1, 1), rank5_1: ("11", 0, 1), rank5_2: ("11", 1, 2), rank6_1: ("10010", 0, 1), rank6_2: ("10010", 1, 1), rank6_3: ("10010", 2, 1), rank6_4: ("10010", 3, 2), rank6_5: ("10010", 4, 2), bugfix_11110110_11010101_01000101_11101111_10101011_10100101_01100011_00110100_01010101_10010000_01001100_10111111_00110011_00111110_01110101_11011100: ( "11110110_11010101_01000101_11101111_10101011_10100101_01100011_00110100_01010101_10010000_01001100_10111111_00110011_00111110_01110101_11011100", 49, 31, ), bugfix_10100001_01010011_10101100_11100001_10110010_10000110_00010100_01001111_01011100_11010011_11110000_00011010_01101111_10101010_11000111_0110011: ( "10100001_01010011_10101100_11100001_10110010_10000110_00010100_01001111_01011100_11010011_11110000_00011010_01101111_10101010_11000111_0110011", 111, 55, ), bugfix_100_111_101_011_011_100_101_001_111_001_001_101_100_011_000_111_1___01_000_101_100_101_101_001_011_110_010_001_101_010_010_010_111_111_111_001_111_001_100_010_001_010_101_11: ( "100_111_101_011_011_100_101_001_111_001_001_101_100_011_000_111_1___01_000_101_100_101_101_001_011_110_010_001_101_010_010_010_111_111_111_001_111_001_100_010_001_010_101_11", 48, 28, ), bugfix_11100100_10110100_10000000_10111111_01110101_01100110_00101111_11101001_01100100_00001000_11010100_10100000_00010001_10100101_01100100_0010010: ( "11100100_10110100_10000000_10111111_01110101_01100110_00101111_11101001_01100100_00001000_11010100_10100000_00010001_10100101_01100100_0010010", 126, 56, ), } // Tested more in tests/ (integration test) } #[cfg(test)] mod rank_failure_tests { use super::super::SuccinctBitVectorBuilder; #[test] #[should_panic] fn rank_over_upper_bound() { let bv = SuccinctBitVectorBuilder::from_length(2).build(); let _ = bv.rank(2); } } #[cfg(test)] #[allow(non_snake_case)] mod rank0_success_tests { use super::super::{BitString, SuccinctBitVectorBuilder}; macro_rules! parameterized_tests { ($($name:ident: $value:expr,)*) => { $( #[test] fn $name() { let (in_bv_str, in_i, expected_rank0) = $value; assert_eq!( SuccinctBitVectorBuilder::from_bit_string(BitString::new(in_bv_str)) .build().rank0(in_i), expected_rank0); } )* } } parameterized_tests! { rank0_1_1: ("0", 0, 1), rank0_2_1: ("00", 0, 1), rank0_2_2: ("00", 1, 2), rank0_3_1: ("01", 0, 1), rank0_3_2: ("01", 1, 1), rank0_4_1: ("10", 0, 0), rank0_4_2: ("10", 1, 1), rank0_5_1: ("11", 0, 0), rank0_5_2: ("11", 1, 0), rank0_6_1: ("10010", 0, 0), rank0_6_2: ("10010", 1, 1), rank0_6_3: ("10010", 2, 2), rank0_6_4: ("10010", 3, 2), rank0_6_5: ("10010", 4, 3), } // Tested more in tests/ (integration test) } #[cfg(test)] mod rank0_0_failure_tests { use super::super::SuccinctBitVectorBuilder; #[test] #[should_panic] fn rank0_over_upper_bound() { let bv = SuccinctBitVectorBuilder::from_length(2).build(); let _ = bv.rank0(2); } } #[cfg(test)] mod select_success_tests { // Tested well in tests/ (integration test) } #[cfg(test)] mod select_failure_tests { use super::super::SuccinctBitVectorBuilder; #[test] #[should_panic] fn select_over_max_rank() { let bv = SuccinctBitVectorBuilder::from_length(2).build(); let _ = bv.select(3); } } #[cfg(test)] mod select0_success_tests { // Tested well in tests/ (integration test) } #[cfg(test)] mod select0_failure_tests { use super::super::SuccinctBitVectorBuilder; #[test] #[should_panic] fn select_over_max_rank() { let bv = SuccinctBitVectorBuilder::from_length(2).build(); let _ = bv.select0(3); } }
use super::*; use crate::engine::{Event, Logger}; pub struct CliState { pub(crate) visible: bool, input: String, pub(crate) auto_focus: bool, pub(crate) auto_scroll: bool, } impl Default for CliState { fn default() -> Self { Self { visible: false, input: Default::default(), auto_focus: true, auto_scroll: true, } } } impl IVisit for CliState { fn visit(&mut self, f: &mut dyn FnMut(&mut dyn INode)) { f(&mut cvar::Property("visible", &mut self.visible, false)); } } impl CliState { pub fn build_ui(&mut self, eng: &Engine<'_>) { if !self.visible { return; } let egui_ctx = eng.egui_ctx; let mut visible = self.visible; egui::Window::new("Command Line Interface") .open(&mut visible) .resizable(true) .show(egui_ctx, |ui| { let scroll_height = ui.fonts()[egui::TextStyle::Monospace].row_height() * 25.; egui::ScrollArea::from_max_height(scroll_height) // .always_show_scroll(true) .show(ui, |ui| { for (level, _time, line) in Logger::get_log().read().unwrap().iter() { ui.add( egui::Label::new(line) .text_style(egui::TextStyle::Monospace) .text_color(match level { log::Level::Info => egui::Color32::WHITE, log::Level::Warn => egui::Color32::YELLOW, log::Level::Error => egui::Color32::RED, log::Level::Debug | log::Level::Trace => { // should not really happen egui::Color32::BLACK } }), ); } if self.auto_scroll { self.auto_scroll = false; ui.scroll_to_cursor(egui::Align::BOTTOM); } }); let edit = ui.add( egui::TextEdit::singleline(&mut self.input) .code_editor() .desired_width(f32::INFINITY), ); if self.auto_focus { self.auto_focus = false; edit.request_focus(); } if edit.lost_focus() && ui.input().key_pressed(egui::Key::Enter) { let input = self.input.trim(); if !input.is_empty() { if let Err(err) = eng.event_sender.try_send(Event::Command(input.to_string())) { log::error!("Cannot send Command Event: {}", err); } self.input.clear(); self.auto_scroll = true; self.auto_focus = true; } } }); self.visible = visible; } }
pub mod board_logic; pub mod console_display; pub mod piece_logic; /// Engine for the boardgame "chess" /// /// Minimal interaction example: /// ``` /// fn example() -> Result<String, String> { /// # use maltebl_chess::{chess_game::*, *}; /// let mut game = init_standard_chess(); /// /// // construct command from clicked tiles /// let origin = (0 as usize, 1 as usize); /// let target = (0 as usize, 2 as usize); /// let command = format!("{} {}", to_notation(origin)?, to_notation(target)?); /// /// let msg = game.move_piece(command.clone())?; /// /// game.print_board(); /// /// // get the character for a piece at a specific position /// let piece_char = game.get_board()[0][0].as_ref() /// .map(|p| format!("{}", p)) /// .unwrap_or(" ".to_owned()); /// /// println!("{}, {}, {}", piece_char, msg, command); /// Ok("".to_owned()) /// } /// example().unwrap(); /// ```` pub mod chess_game { use super::*; use crate::{board_logic::*, piece_logic::*}; pub struct ChessGame { chess_board: ChessBoard, history: Vec<String>, turn: (Color, usize), } impl ChessGame { pub fn get_board(&self) -> Board { self.chess_board.get_board() } pub fn pick_piece(&self, input: String) -> Result<Vec<String>, String> { let piece_position = to_coords(input).expect("Error:"); if let Some(piece) = self.chess_board.ref_piece(piece_position) { if piece.color != self.turn.0 { return Err("That's not your piece!".to_string()); } } else { return Err(format!("There is no piece at {:?}", piece_position)); } let mut possible_moves: Vec<String> = Vec::new(); for (mov, _) in self.chess_board.get_moves(piece_position) { possible_moves.push(to_notation(mov).unwrap()); } Ok(possible_moves) } pub fn current_player(&self) -> Color { self.turn.0 } pub fn move_piece(&mut self, input: String) -> Result<String, String> { if input.len() == 5 { let mut input = input.split_whitespace(); let move_from = to_coords(input.next().unwrap().to_string())?; let move_to = to_coords(input.next().unwrap().to_string())?; if let Some(piece) = self.chess_board.ref_piece(move_from) { if piece.color != self.current_player() { return Err("That is not your piece!".to_string()); } } else { return Err(format!("There is no piece at {:?}", move_from)); } let mut result = self.chess_board.move_piece(move_from, move_to); if result.is_ok() { let mov = result.clone().unwrap(); let mov = mov.trim(); let mut history = format!("{}. ", self.turn.1); history.push_str(mov); self.history.push(history); self.turn = ( match self.current_player() { Color::Black => Color::White, Color::White => Color::Black, }, 1 + self.turn.1, ); if self.chess_board.is_checked(self.current_player()) { result = Ok(result.unwrap() + " Check!"); } if self.chess_board.is_checkmate(self.current_player()) { return Ok("Game is over! It's a checkmate!".to_string()); } } result } else { Err("Error: enter move as e.g:a4 a3".to_string()) } } pub fn promotion(&mut self, input: String) -> Result<String, String> { if input.len() == 3 { let mut chars = input.chars(); let position = to_coords(format!( "{}{}", chars.next().unwrap(), chars.next().unwrap() ))?; let piece_type = match chars.next() { Some('Q') => PieceType::Queen, Some('B') => PieceType::Bishop, Some('N') => PieceType::Knight, Some('R') => PieceType::Rook, _ => PieceType::Pawn, }; if piece_type == PieceType::Pawn { return Err("Must provide promotion input as e.g:a8Q".to_string()); } self.chess_board.promote(position, piece_type) } else { Err("Must provide promotion input as e.g:a8Q".to_string()) } } pub fn print_board(&self) { console_display::print_board(self.chess_board.ref_board()); } } pub fn init_standard_chess() -> ChessGame { let mut board = init_board(); board.standard_pieces(Color::White); board.standard_pieces(Color::Black); ChessGame { chess_board: board, history: Vec::new(), turn: (Color::White, 1), } } } pub fn to_coords(input: String) -> Result<(usize, usize), String> { if input.len() == 2 { let mut input = input.chars(); let mut pos_x = input.next().unwrap() as isize - 96; let mut pos_y: isize = input.next().unwrap().to_string().parse().unwrap(); pos_x -= 1; pos_y -= 1; if pos_x < 0 || pos_x > 7 || pos_y < 0 || pos_y > 7 { println!("{}{}", pos_x, pos_y); return Err(String::from("tried to access non-existent boardspace")); } Ok((pos_x as usize, pos_y as usize)) } else { Err(String::from( "invalid notation, cannot find coords on board", )) } } pub fn to_notation(position: (usize, usize)) -> Result<String, String> { let (x, y) = position; if x > 8 || y > 8 { return Err(String::from("tried to access non-existent boardspace")); } Ok(format!("{}{}", (x + 97) as u8 as char, y + 1)) }
/// A simple macro for defining bitfield accessors/mutators. #[cfg(feature = "alloc")] macro_rules! define_bool { ($bit:expr, $is_fn_name:ident, $set_fn_name:ident) => { fn $is_fn_name(&self) -> bool { self.bools & (0b1 << $bit) > 0 } fn $set_fn_name(&mut self, yes: bool) { if yes { self.bools |= 1 << $bit; } else { self.bools &= !(1 << $bit); } } }; } macro_rules! log { ($($tt:tt)*) => { #[cfg(feature = "logging")] { $($tt)* } } } macro_rules! trace { ($($tt:tt)*) => { log!(log::trace!($($tt)*)) } }
#![deny(warnings)] mod config; pub mod filesearch; pub mod search_paths; pub use self::config::*; pub use self::filesearch::{FileMatch, FileSearch}; pub use self::search_paths::{PathKind, SearchPath};
use simplemm::{error, state, types}; use snafu::{ErrorCompat, ResultExt}; use std::os::unix::fs::PermissionsExt; use std::os::unix::net::{UnixListener, UnixStream}; static PROGRAM: &str = "simplemmd daemon"; fn main() { if let Err(e) = run() { error_abort(e) } } fn run() -> error::Result<()> { initialize_syslog()?; let config = read_config()?; pre_daemonize_checks(&config)?; let socket = bind_to_socket(&config)?; daemonize(&config)?; handle_requests(socket); Ok(()) } fn read_config() -> error::Result<types::Config> { let arg_matches = parse_args(); let config_file_name = arg_matches .value_of("config") .unwrap_or("/etc/simplemm.conf"); let config = simplemm::config::read_config(config_file_name)?; Ok(config) } fn parse_args<'a>() -> clap::ArgMatches<'a> { let matches = clap::App::new(PROGRAM) .version(state::get_server_version()) .author("by Cohomology, 2020") .arg( clap::Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("configuration file") .takes_value(true), ) .get_matches(); matches } fn pre_daemonize_checks(config: &types::Config) -> error::Result<()> { simplemm::database::check_database(&config)?; simplemm::file::check_working_dir(&config)?; simplemm::file::check_pid_file(&config)?; Ok(()) } fn daemonize(config: &types::Config) -> error::Result<()> { let daemonize = daemonize::Daemonize::new() .pid_file(&config.pid_file) .chown_pid_file(true) .working_directory(&config.working_dir) .user(config.uid) .group(config.gid) .umask(0o777); daemonize.start().context(error::DaemonizeError {})?; simplemm::state::start_server(&config)?; Ok(()) } fn bind_to_socket(config: &types::Config) -> error::Result<UnixListener> { let path = std::path::Path::new(&config.socket); let _ = std::fs::remove_file(&path); let listener = UnixListener::bind(&path).context(error::SocketBindError { path: path.to_string_lossy().to_string(), })?; set_socket_permissions(&config.socket)?; Ok(listener) } fn handle_requests(listener: UnixListener) { for stream in listener.incoming() { match stream { Ok(stream) => { std::thread::spawn(move || handle_client(stream)); } Err(err) => { log::error!("Error: {}", err); break; } } } } fn handle_client(stream: UnixStream) { let reader = std::io::BufReader::new(&stream); let command: error::Result<types::Command> = serde_json::from_reader(reader).context(error::RequestParseError {}); match command { Ok(command) => simplemm::request::process_request(command, stream), Err(err) => log::warn!("Could not parse request: {:?}", err), } } fn initialize_syslog() -> error::Result<()> { let formatter = syslog::Formatter3164 { facility: syslog::Facility::LOG_USER, hostname: None, process: "simplemmd".into(), pid: 0, }; let logger = syslog::unix(formatter).context(error::SyslogError {})?; log::set_boxed_logger(Box::new(syslog::BasicLogger::new(logger))) .map(|()| log::set_max_level(log::LevelFilter::Info)) .context(error::SetLoggerError {})?; Ok(()) } fn error_abort(error: error::Error) -> ! { log::error!("Error: {}", error); eprintln!("Error: {}", error); if let Some(backtrace) = ErrorCompat::backtrace(&error) { log::error!("{}", backtrace); eprintln!("{}", backtrace); } std::process::exit(-1) } fn set_socket_permissions(socket: &str) -> error::Result<()> { std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o777)) .context(error::SocketPermissionError { socket }) }
use gobs_core::cubic_surface_extractor::extract_cubic_mesh; use gobs_core::raw_volume::RawVolume; use gobs_core::raw_volume_sampler::RawVolumeSampler; use gobs_core::region::Region; use gobs_core::volume::Volume; #[test] fn basic_case() { let region = Region::cubic(16); let mut volume: RawVolume<i32> = RawVolume::new(region); volume.set_voxel_at(8, 8, 8, 1).unwrap(); let mut sampler = RawVolumeSampler::new(&volume); let mesh = extract_cubic_mesh(&mut sampler, &Region::cubic(16)).unwrap(); assert_eq!(mesh.vertices.len(), 8); assert_eq!(mesh.indices.len(), 36); } #[test] fn combine_two_voxels_case() { let region = Region::cubic(16); let mut volume: RawVolume<i32> = RawVolume::new(region); volume.set_voxel_at(8, 8, 8, 1).unwrap(); volume.set_voxel_at(9, 8, 8, 1).unwrap(); let mut sampler = RawVolumeSampler::new(&volume); let mesh = extract_cubic_mesh(&mut sampler, &Region::cubic(16)).unwrap(); assert_eq!(mesh.vertices.len(), 8); assert_eq!(mesh.indices.len(), 36); }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Debug; use std::marker::PhantomData; use std::ops::Range; use common_arrow::arrow::buffer::Buffer; use enum_as_inner::EnumAsInner; use itertools::Itertools; use lexical_core::ToLexicalWithOptions; use num_traits::NumCast; use ordered_float::OrderedFloat; use serde::Deserialize; use serde::Serialize; use crate::property::Domain; use crate::types::ArgType; use crate::types::DataType; use crate::types::GenericMap; use crate::types::ValueType; use crate::utils::arrow::buffer_into_mut; use crate::values::Column; use crate::values::Scalar; use crate::ColumnBuilder; use crate::ScalarRef; pub type F32 = OrderedFloat<f32>; pub type F64 = OrderedFloat<f64>; pub const ALL_UNSIGNED_INTEGER_TYPES: &[NumberDataType] = &[ NumberDataType::UInt8, NumberDataType::UInt16, NumberDataType::UInt32, NumberDataType::UInt64, ]; pub const ALL_INTEGER_TYPES: &[NumberDataType] = &[ NumberDataType::UInt8, NumberDataType::UInt16, NumberDataType::UInt32, NumberDataType::UInt64, NumberDataType::Int8, NumberDataType::Int16, NumberDataType::Int32, NumberDataType::Int64, ]; pub const ALL_FLOAT_TYPES: &[NumberDataType] = &[NumberDataType::Float32, NumberDataType::Float64]; pub const ALL_NUMERICS_TYPES: &[NumberDataType] = &[ NumberDataType::UInt8, NumberDataType::UInt16, NumberDataType::UInt32, NumberDataType::UInt64, NumberDataType::Int8, NumberDataType::Int16, NumberDataType::Int32, NumberDataType::Int64, NumberDataType::Float32, NumberDataType::Float64, ]; #[derive(Debug, Clone, PartialEq, Eq)] pub struct NumberType<T: Number>(PhantomData<T>); pub type Int8Type = NumberType<i8>; pub type Int16Type = NumberType<i16>; pub type Int32Type = NumberType<i32>; pub type Int64Type = NumberType<i64>; pub type UInt8Type = NumberType<u8>; pub type UInt16Type = NumberType<u16>; pub type UInt32Type = NumberType<u32>; pub type UInt64Type = NumberType<u64>; pub type Float32Type = NumberType<F32>; pub type Float64Type = NumberType<F64>; impl<Num: Number> ValueType for NumberType<Num> { type Scalar = Num; type ScalarRef<'a> = Num; type Column = Buffer<Num>; type Domain = SimpleDomain<Num>; type ColumnIterator<'a> = std::iter::Cloned<std::slice::Iter<'a, Num>>; type ColumnBuilder = Vec<Num>; #[inline] fn upcast_gat<'short, 'long: 'short>(long: Num) -> Num { long } fn to_owned_scalar<'a>(scalar: Self::ScalarRef<'a>) -> Self::Scalar { scalar } fn to_scalar_ref<'a>(scalar: &'a Self::Scalar) -> Self::ScalarRef<'a> { *scalar } fn try_downcast_scalar<'a>(scalar: &'a ScalarRef) -> Option<Self::ScalarRef<'a>> { Num::try_downcast_scalar(scalar.as_number()?) } fn try_downcast_column<'a>(col: &'a Column) -> Option<Self::Column> { Num::try_downcast_column(col.as_number()?) } fn try_downcast_domain(domain: &Domain) -> Option<Self::Domain> { Num::try_downcast_domain(domain.as_number()?) } fn try_downcast_builder<'a>( builder: &'a mut ColumnBuilder, ) -> Option<&'a mut Self::ColumnBuilder> { match builder { ColumnBuilder::Number(num) => Num::try_downcast_builder(num), _ => None, } } fn upcast_scalar(scalar: Self::Scalar) -> Scalar { Scalar::Number(Num::upcast_scalar(scalar)) } fn upcast_column(col: Self::Column) -> Column { Column::Number(Num::upcast_column(col)) } fn upcast_domain(domain: SimpleDomain<Num>) -> Domain { Domain::Number(Num::upcast_domain(domain)) } fn column_len<'a>(col: &'a Self::Column) -> usize { col.len() } fn index_column<'a>(col: &'a Self::Column, index: usize) -> Option<Self::ScalarRef<'a>> { col.get(index).cloned() } unsafe fn index_column_unchecked<'a>( col: &'a Self::Column, index: usize, ) -> Self::ScalarRef<'a> { *col.get_unchecked(index) } fn slice_column<'a>(col: &'a Self::Column, range: Range<usize>) -> Self::Column { col.clone().sliced(range.start, range.end - range.start) } fn iter_column<'a>(col: &'a Self::Column) -> Self::ColumnIterator<'a> { col.iter().cloned() } fn column_to_builder(col: Self::Column) -> Self::ColumnBuilder { buffer_into_mut(col) } fn builder_len(builder: &Self::ColumnBuilder) -> usize { builder.len() } fn push_item(builder: &mut Self::ColumnBuilder, item: Self::Scalar) { builder.push(item); } fn push_default(builder: &mut Self::ColumnBuilder) { builder.push(Num::default()); } fn append_column(builder: &mut Self::ColumnBuilder, other: &Self::Column) { builder.extend_from_slice(other); } fn build_column(builder: Self::ColumnBuilder) -> Self::Column { builder.into() } fn build_scalar(builder: Self::ColumnBuilder) -> Self::Scalar { assert_eq!(builder.len(), 1); builder[0] } } impl<Num: Number> ArgType for NumberType<Num> { fn data_type() -> DataType { DataType::Number(Num::data_type()) } fn full_domain() -> Self::Domain { SimpleDomain { min: Num::MIN, max: Num::MAX, } } fn create_builder(capacity: usize, _generics: &GenericMap) -> Self::ColumnBuilder { Vec::with_capacity(capacity) } fn column_from_vec(vec: Vec<Self::Scalar>, _generics: &GenericMap) -> Self::Column { vec.into() } fn column_from_iter(iter: impl Iterator<Item = Self::Scalar>, _: &GenericMap) -> Self::Column { iter.collect() } fn column_from_ref_iter<'a>( iter: impl Iterator<Item = Self::ScalarRef<'a>>, _: &GenericMap, ) -> Self::Column { iter.collect() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, EnumAsInner)] pub enum NumberDataType { UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64, } #[derive(Clone, Copy, PartialEq, Eq, EnumAsInner, Serialize, Deserialize)] pub enum NumberScalar { UInt8(u8), UInt16(u16), UInt32(u32), UInt64(u64), Int8(i8), Int16(i16), Int32(i32), Int64(i64), Float32(F32), Float64(F64), } #[derive(Clone, PartialEq, EnumAsInner)] pub enum NumberColumn { UInt8(Buffer<u8>), UInt16(Buffer<u16>), UInt32(Buffer<u32>), UInt64(Buffer<u64>), Int8(Buffer<i8>), Int16(Buffer<i16>), Int32(Buffer<i32>), Int64(Buffer<i64>), Float32(Buffer<F32>), Float64(Buffer<F64>), } #[derive(Debug, Clone, PartialEq, Eq, EnumAsInner)] pub enum NumberColumnBuilder { UInt8(Vec<u8>), UInt16(Vec<u16>), UInt32(Vec<u32>), UInt64(Vec<u64>), Int8(Vec<i8>), Int16(Vec<i16>), Int32(Vec<i32>), Int64(Vec<i64>), Float32(Vec<F32>), Float64(Vec<F64>), } #[derive(Debug, Clone, PartialEq, Eq, EnumAsInner)] pub enum NumberDomain { UInt8(SimpleDomain<u8>), UInt16(SimpleDomain<u16>), UInt32(SimpleDomain<u32>), UInt64(SimpleDomain<u64>), Int8(SimpleDomain<i8>), Int16(SimpleDomain<i16>), Int32(SimpleDomain<i32>), Int64(SimpleDomain<i64>), Float32(SimpleDomain<F32>), Float64(SimpleDomain<F64>), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SimpleDomain<T> { pub min: T, pub max: T, } impl NumberDataType { pub const fn new(bit_width: u8, is_signed: bool, is_float: bool) -> Self { match (bit_width, is_signed, is_float) { (8, false, false) => NumberDataType::UInt8, (16, false, false) => NumberDataType::UInt16, (32, false, false) => NumberDataType::UInt32, (64, false, false) => NumberDataType::UInt64, (8, true, false) => NumberDataType::Int8, (16, true, false) => NumberDataType::Int16, (32, true, false) => NumberDataType::Int32, (64, true, false) => NumberDataType::Int64, (32, true, true) => NumberDataType::Float32, (64, true, true) => NumberDataType::Float64, _ => panic!("unsupported numeric type"), } } pub const fn bit_width(&self) -> u8 { match self { NumberDataType::UInt8 => 8, NumberDataType::UInt16 => 16, NumberDataType::UInt32 => 32, NumberDataType::UInt64 => 64, NumberDataType::Int8 => 8, NumberDataType::Int16 => 16, NumberDataType::Int32 => 32, NumberDataType::Int64 => 64, NumberDataType::Float32 => 32, NumberDataType::Float64 => 64, } } pub const fn is_signed(&self) -> bool { match self { NumberDataType::UInt8 => false, NumberDataType::UInt16 => false, NumberDataType::UInt32 => false, NumberDataType::UInt64 => false, NumberDataType::Int8 => true, NumberDataType::Int16 => true, NumberDataType::Int32 => true, NumberDataType::Int64 => true, NumberDataType::Float32 => true, NumberDataType::Float64 => true, } } pub const fn is_float(&self) -> bool { match self { NumberDataType::UInt8 => false, NumberDataType::UInt16 => false, NumberDataType::UInt32 => false, NumberDataType::UInt64 => false, NumberDataType::Int8 => false, NumberDataType::Int16 => false, NumberDataType::Int32 => false, NumberDataType::Int64 => false, NumberDataType::Float32 => true, NumberDataType::Float64 => true, } } pub const fn can_lossless_cast_to(self, dest: Self) -> bool { match (self.is_float(), dest.is_float()) { (true, true) => self.bit_width() <= dest.bit_width(), (true, false) => false, (false, true) => self.bit_width() < dest.bit_width(), (false, false) => match (self.is_signed(), dest.is_signed()) { (true, true) | (false, false) => self.bit_width() <= dest.bit_width(), (false, true) => { if let Some(self_next_bit_width) = next_bit_width(self.bit_width()) { self_next_bit_width <= dest.bit_width() } else { false } } (true, false) => false, }, } } } const fn next_bit_width(width: u8) -> Option<u8> { match width { 8 => Some(16), 16 => Some(32), 32 => Some(64), 64 => None, _ => panic!("invalid bit width"), } } impl PartialOrd for NumberScalar { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { crate::with_number_type!(|NUM_TYPE| match (self, other) { (NumberScalar::NUM_TYPE(lhs), NumberScalar::NUM_TYPE(rhs)) => lhs.partial_cmp(rhs), _ => None, }) } } impl PartialOrd for NumberColumn { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { crate::with_number_type!(|NUM_TYPE| match (self, other) { (NumberColumn::NUM_TYPE(lhs), NumberColumn::NUM_TYPE(rhs)) => lhs.iter().partial_cmp(rhs.iter()), _ => None, }) } } impl NumberScalar { pub fn domain(&self) -> NumberDomain { crate::with_number_type!(|NUM_TYPE| match self { NumberScalar::NUM_TYPE(num) => NumberDomain::NUM_TYPE(SimpleDomain { min: *num, max: *num, }), }) } } impl NumberColumn { pub fn len(&self) -> usize { crate::with_number_type!(|NUM_TYPE| match self { NumberColumn::NUM_TYPE(col) => col.len(), }) } pub fn index(&self, index: usize) -> Option<NumberScalar> { crate::with_number_type!(|NUM_TYPE| match self { NumberColumn::NUM_TYPE(col) => Some(NumberScalar::NUM_TYPE(col.get(index).cloned()?)), }) } /// # Safety /// /// Calling this method with an out-of-bounds index is *[undefined behavior]* pub unsafe fn index_unchecked(&self, index: usize) -> NumberScalar { crate::with_number_type!(|NUM_TYPE| match self { NumberColumn::NUM_TYPE(col) => NumberScalar::NUM_TYPE(*col.get_unchecked(index)), }) } pub fn slice(&self, range: Range<usize>) -> Self { assert!( range.end <= self.len(), "range {:?} out of len {}", range, self.len() ); crate::with_number_type!(|NUM_TYPE| match self { NumberColumn::NUM_TYPE(col) => { NumberColumn::NUM_TYPE(col.clone().sliced(range.start, range.end - range.start)) } }) } pub fn domain(&self) -> NumberDomain { assert!(self.len() > 0); crate::with_number_type!(|NUM_TYPE| match self { NumberColumn::NUM_TYPE(col) => { let (min, max) = col.iter().minmax().into_option().unwrap(); NumberDomain::NUM_TYPE(SimpleDomain { min: *min, max: *max, }) } }) } } impl NumberColumnBuilder { pub fn from_column(col: NumberColumn) -> Self { crate::with_number_type!(|NUM_TYPE| match col { NumberColumn::NUM_TYPE(col) => NumberColumnBuilder::NUM_TYPE(buffer_into_mut(col)), }) } pub fn repeat(scalar: NumberScalar, n: usize) -> NumberColumnBuilder { crate::with_number_type!(|NUM_TYPE| match scalar { NumberScalar::NUM_TYPE(num) => NumberColumnBuilder::NUM_TYPE(vec![num; n]), }) } pub fn len(&self) -> usize { crate::with_number_type!(|NUM_TYPE| match self { NumberColumnBuilder::NUM_TYPE(col) => col.len(), }) } pub fn with_capacity(ty: &NumberDataType, capacity: usize) -> Self { crate::with_number_type!(|NUM_TYPE| match ty { NumberDataType::NUM_TYPE => NumberColumnBuilder::NUM_TYPE(Vec::with_capacity(capacity)), }) } pub fn push(&mut self, item: NumberScalar) { crate::with_number_type!(|NUM_TYPE| match (self, item) { (NumberColumnBuilder::NUM_TYPE(builder), NumberScalar::NUM_TYPE(value)) => { builder.push(value) } (builder, scalar) => unreachable!("unable to push {scalar:?} to {builder:?}"), }) } pub fn push_default(&mut self) { crate::with_number_mapped_type!(|NUM_TYPE| match self { NumberColumnBuilder::NUM_TYPE(builder) => builder.push(NUM_TYPE::default()), }) } pub fn append_column(&mut self, other: &NumberColumn) { crate::with_number_type!(|NUM_TYPE| match (self, other) { (NumberColumnBuilder::NUM_TYPE(builder), NumberColumn::NUM_TYPE(other)) => { builder.extend_from_slice(other); } (this, other) => unreachable!("unable append {other:?} onto {this:?}"), }) } pub fn build(self) -> NumberColumn { crate::with_number_type!(|NUM_TYPE| match self { NumberColumnBuilder::NUM_TYPE(builder) => NumberColumn::NUM_TYPE(builder.into()), }) } pub fn build_scalar(self) -> NumberScalar { assert_eq!(self.len(), 1); crate::with_number_type!(|NUM_TYPE| match self { NumberColumnBuilder::NUM_TYPE(builder) => NumberScalar::NUM_TYPE(builder[0]), }) } pub fn pop(&mut self) -> Option<NumberScalar> { crate::with_number_type!(|NUM_TYPE| match self { NumberColumnBuilder::NUM_TYPE(builder) => builder.pop().map(NumberScalar::NUM_TYPE), }) } } impl<T: Number> SimpleDomain<T> { /// Returns the saturating cast domain and a flag denoting whether overflow happened. pub fn overflow_cast<U: Number>(&self) -> (SimpleDomain<U>, bool) { self.overflow_cast_with_minmax(U::MIN, U::MAX) } pub fn overflow_cast_with_minmax<U: Number>(&self, min: U, max: U) -> (SimpleDomain<U>, bool) { let (min, min_overflowing) = overflow_cast_with_minmax::<T, U>(self.min, min, max).unwrap_or((min, true)); let (max, max_overflowing) = overflow_cast_with_minmax::<T, U>(self.max, min, max).unwrap_or((max, true)); ( SimpleDomain { min, max }, min_overflowing || max_overflowing, ) } } fn overflow_cast_with_minmax<T: Number, U: Number>(src: T, min: U, max: U) -> Option<(U, bool)> { let dest_min: T = num_traits::cast(min).unwrap_or(T::MIN); let dest_max: T = num_traits::cast(max).unwrap_or(T::MAX); let src_clamp: T = src.clamp(dest_min, dest_max); let overflowing = src != src_clamp; // It will have errors if the src type is Inf/NaN let dest: U = num_traits::cast(src_clamp)?; Some((dest, overflowing)) } #[macro_export] macro_rules! with_number_type { ( | $t:tt | $($tail:tt)* ) => { match_template::match_template! { $t = [UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64], $($tail)* } } } #[macro_export] macro_rules! with_unsigned_number_mapped_type { (| $t:tt | $($tail:tt)*) => { match_template::match_template! { $t = [ UInt8 => u8, UInt16 => u16, UInt32 => u32, UInt64 => u64 ], $($tail)* } } } #[macro_export] macro_rules! with_integer_mapped_type { (| $t:tt | $($tail:tt)*) => { match_template::match_template! { $t = [ UInt8 => u8, UInt16 => u16, UInt32 => u32, UInt64 => u64, Int8 => i8, Int16 => i16, Int32 => i32, Int64 => i64, ], $($tail)* } } } #[macro_export] macro_rules! with_float_mapped_type { (| $t:tt | $($tail:tt)*) => { match_template::match_template! { $t = [ Float32 => $crate::types::number::F32, Float64 => $crate::types::number::F64 ], $($tail)* } } } #[macro_export] macro_rules! with_number_mapped_type { (| $t:tt | $($tail:tt)*) => { match_template::match_template! { $t = [ UInt8 => u8, UInt16 => u16, UInt32 => u32, UInt64 => u64, Int8 => i8, Int16 => i16, Int32 => i32, Int64 => i64, Float32 => $crate::types::number::F32, Float64 => $crate::types::number::F64 ], $($tail)* } } } pub trait Number: Copy + Debug + NumCast + Default + Clone + Copy + PartialEq + Eq + PartialOrd + Ord + Sync + Send + 'static { type Native: ToLexicalWithOptions; const MIN: Self; const MAX: Self; const FLOATING: bool; fn data_type() -> NumberDataType; fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self>; fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>>; fn try_downcast_builder(col: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>>; fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>>; fn upcast_scalar(scalar: Self) -> NumberScalar; fn upcast_column(col: Buffer<Self>) -> NumberColumn; fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain; fn lexical_options() -> <Self::Native as ToLexicalWithOptions>::Options { <Self::Native as ToLexicalWithOptions>::Options::default() } } impl Number for u8 { type Native = Self; const MIN: Self = u8::MIN; const MAX: Self = u8::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::UInt8 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_u_int8().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_u_int8().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_u_int8_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_u_int8().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::UInt8(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::UInt8(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::UInt8(domain) } } impl Number for u16 { type Native = Self; const MIN: Self = u16::MIN; const MAX: Self = u16::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::UInt16 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_u_int16().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_u_int16().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_u_int16_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_u_int16().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::UInt16(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::UInt16(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::UInt16(domain) } } impl Number for u32 { type Native = Self; const MIN: Self = u32::MIN; const MAX: Self = u32::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::UInt32 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_u_int32().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_u_int32().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_u_int32_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_u_int32().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::UInt32(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::UInt32(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::UInt32(domain) } } impl Number for u64 { type Native = Self; const MIN: Self = u64::MIN; const MAX: Self = u64::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::UInt64 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_u_int64().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_u_int64().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_u_int64_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_u_int64().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::UInt64(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::UInt64(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::UInt64(domain) } } impl Number for i8 { type Native = Self; const MIN: Self = i8::MIN; const MAX: Self = i8::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::Int8 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_int8().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_int8().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_int8_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_int8().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Int8(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Int8(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Int8(domain) } } impl Number for i16 { type Native = Self; const MIN: Self = i16::MIN; const MAX: Self = i16::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::Int16 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_int16().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_int16().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_int16_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_int16().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Int16(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Int16(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Int16(domain) } } impl Number for i32 { type Native = Self; const MIN: Self = i32::MIN; const MAX: Self = i32::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::Int32 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_int32().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_int32().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_int32_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_int32().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Int32(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Int32(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Int32(domain) } } impl Number for i64 { type Native = Self; const MIN: Self = i64::MIN; const MAX: Self = i64::MAX; const FLOATING: bool = false; fn data_type() -> NumberDataType { NumberDataType::Int64 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_int64().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_int64().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_int64_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_int64().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Int64(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Int64(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Int64(domain) } } impl Number for F32 { type Native = f32; const MIN: Self = OrderedFloat(f32::NEG_INFINITY); const MAX: Self = OrderedFloat(f32::NAN); const FLOATING: bool = true; fn data_type() -> NumberDataType { NumberDataType::Float32 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_float32().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_float32().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_float32_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_float32().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Float32(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Float32(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Float32(domain) } fn lexical_options() -> <Self::Native as ToLexicalWithOptions>::Options { unsafe { lexical_core::WriteFloatOptions::builder() .trim_floats(true) .build_unchecked() } } } impl Number for F64 { type Native = f64; const MIN: Self = OrderedFloat(f64::NEG_INFINITY); const MAX: Self = OrderedFloat(f64::NAN); const FLOATING: bool = true; fn data_type() -> NumberDataType { NumberDataType::Float64 } fn try_downcast_scalar(scalar: &NumberScalar) -> Option<Self> { scalar.as_float64().cloned() } fn try_downcast_column(col: &NumberColumn) -> Option<Buffer<Self>> { col.as_float64().cloned() } fn try_downcast_builder(builder: &mut NumberColumnBuilder) -> Option<&mut Vec<Self>> { builder.as_float64_mut() } fn try_downcast_domain(domain: &NumberDomain) -> Option<SimpleDomain<Self>> { domain.as_float64().cloned() } fn upcast_scalar(scalar: Self) -> NumberScalar { NumberScalar::Float64(scalar) } fn upcast_column(col: Buffer<Self>) -> NumberColumn { NumberColumn::Float64(col) } fn upcast_domain(domain: SimpleDomain<Self>) -> NumberDomain { NumberDomain::Float64(domain) } fn lexical_options() -> <Self::Native as ToLexicalWithOptions>::Options { unsafe { lexical_core::WriteFloatOptions::builder() .trim_floats(true) .build_unchecked() } } }
table! { ommu_conversations (conversation_id) { conversation_id -> Integer, publish -> Integer, buddy_talent_id -> Nullable<Integer>, member_id -> Nullable<Integer>, creator_id -> Integer, user_id -> Integer, conversation_start -> Nullable<Datetime>, conversation_finish -> Nullable<Datetime>, creation_date -> Nullable<Timestamp>, modified_date -> Nullable<Timestamp>, modified_id -> Integer, updated_date -> Nullable<Timestamp>, } } table! { posts (id) { id -> Integer, title -> Text, body -> Nullable<Text>, published -> Integer, } }
// This file was generated by `cargo dev update_lints`. // Use that command to update this file and do not edit by hand. // Manual edits will be overwritten. store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec![ LintId::of(attrs::DEPRECATED_CFG_ATTR), LintId::of(booleans::NONMINIMAL_BOOL), LintId::of(casts::CHAR_LIT_AS_U8), LintId::of(casts::UNNECESSARY_CAST), LintId::of(derivable_impls::DERIVABLE_IMPLS), LintId::of(double_comparison::DOUBLE_COMPARISONS), LintId::of(double_parens::DOUBLE_PARENS), LintId::of(duration_subsec::DURATION_SUBSEC), LintId::of(eval_order_dependence::DIVERGING_SUB_EXPRESSION), LintId::of(explicit_write::EXPLICIT_WRITE), LintId::of(format::USELESS_FORMAT), LintId::of(functions::TOO_MANY_ARGUMENTS), LintId::of(get_last_with_len::GET_LAST_WITH_LEN), LintId::of(identity_op::IDENTITY_OP), LintId::of(int_plus_one::INT_PLUS_ONE), LintId::of(lifetimes::EXTRA_UNUSED_LIFETIMES), LintId::of(lifetimes::NEEDLESS_LIFETIMES), LintId::of(loops::EXPLICIT_COUNTER_LOOP), LintId::of(loops::MANUAL_FLATTEN), LintId::of(loops::SINGLE_ELEMENT_LOOP), LintId::of(loops::WHILE_LET_LOOP), LintId::of(manual_strip::MANUAL_STRIP), LintId::of(manual_unwrap_or::MANUAL_UNWRAP_OR), LintId::of(map_unit_fn::OPTION_MAP_UNIT_FN), LintId::of(map_unit_fn::RESULT_MAP_UNIT_FN), LintId::of(matches::MATCH_AS_REF), LintId::of(matches::MATCH_SINGLE_BINDING), LintId::of(matches::WILDCARD_IN_OR_PATTERNS), LintId::of(methods::BIND_INSTEAD_OF_MAP), LintId::of(methods::CLONE_ON_COPY), LintId::of(methods::FILTER_MAP_IDENTITY), LintId::of(methods::FILTER_NEXT), LintId::of(methods::FLAT_MAP_IDENTITY), LintId::of(methods::INSPECT_FOR_EACH), LintId::of(methods::ITER_COUNT), LintId::of(methods::MANUAL_FILTER_MAP), LintId::of(methods::MANUAL_FIND_MAP), LintId::of(methods::MANUAL_SPLIT_ONCE), LintId::of(methods::MAP_IDENTITY), LintId::of(methods::NEEDLESS_SPLITN), LintId::of(methods::OPTION_AS_REF_DEREF), LintId::of(methods::OPTION_FILTER_MAP), LintId::of(methods::SEARCH_IS_SOME), LintId::of(methods::SKIP_WHILE_NEXT), LintId::of(methods::UNNECESSARY_FILTER_MAP), LintId::of(methods::USELESS_ASREF), LintId::of(misc::SHORT_CIRCUIT_STATEMENT), LintId::of(misc_early::UNNEEDED_WILDCARD_PATTERN), LintId::of(misc_early::ZERO_PREFIXED_LITERAL), LintId::of(needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE), LintId::of(needless_bool::BOOL_COMPARISON), LintId::of(needless_bool::NEEDLESS_BOOL), LintId::of(needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE), LintId::of(needless_option_as_deref::NEEDLESS_OPTION_AS_DEREF), LintId::of(needless_question_mark::NEEDLESS_QUESTION_MARK), LintId::of(needless_update::NEEDLESS_UPDATE), LintId::of(neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD), LintId::of(no_effect::NO_EFFECT), LintId::of(no_effect::UNNECESSARY_OPERATION), LintId::of(overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL), LintId::of(partialeq_ne_impl::PARTIALEQ_NE_IMPL), LintId::of(precedence::PRECEDENCE), LintId::of(ptr_offset_with_cast::PTR_OFFSET_WITH_CAST), LintId::of(ranges::RANGE_ZIP_WITH_LEN), LintId::of(redundant_closure_call::REDUNDANT_CLOSURE_CALL), LintId::of(redundant_slicing::REDUNDANT_SLICING), LintId::of(reference::DEREF_ADDROF), LintId::of(reference::REF_IN_DEREF), LintId::of(repeat_once::REPEAT_ONCE), LintId::of(strings::STRING_FROM_UTF8_AS_BYTES), LintId::of(strlen_on_c_strings::STRLEN_ON_C_STRINGS), LintId::of(swap::MANUAL_SWAP), LintId::of(temporary_assignment::TEMPORARY_ASSIGNMENT), LintId::of(transmute::CROSSPOINTER_TRANSMUTE), LintId::of(transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS), LintId::of(transmute::TRANSMUTE_BYTES_TO_STR), LintId::of(transmute::TRANSMUTE_FLOAT_TO_INT), LintId::of(transmute::TRANSMUTE_INT_TO_BOOL), LintId::of(transmute::TRANSMUTE_INT_TO_CHAR), LintId::of(transmute::TRANSMUTE_INT_TO_FLOAT), LintId::of(transmute::TRANSMUTE_NUM_TO_BYTES), LintId::of(transmute::TRANSMUTE_PTR_TO_REF), LintId::of(types::BORROWED_BOX), LintId::of(types::TYPE_COMPLEXITY), LintId::of(types::VEC_BOX), LintId::of(unit_types::UNIT_ARG), LintId::of(unnecessary_sort_by::UNNECESSARY_SORT_BY), LintId::of(unwrap::UNNECESSARY_UNWRAP), LintId::of(useless_conversion::USELESS_CONVERSION), LintId::of(zero_div_zero::ZERO_DIVIDED_BY_ZERO), ])
fn main() { println!("tree"); }
use diesel; use diesel::prelude::*; use diesel::PgConnection; use schema::users; #[derive(Serialize, Deserialize, Queryable)] pub struct User { pub id: Option<i32>, pub first_name: String, pub last_name: String, pub user_name: String, pub cell_number: String, pub cell_verified: bool, pub email: String, pub public_key: String, pub private_key: String, pub eth_address: String } #[table_name = "users"] #[derive(Serialize, Deserialize)] pub struct NewUser { pub id: Option<i32>, pub first_name: String, pub last_name: String, pub user_name: String, pub cell_number: String, pub cell_verified: bool, pub email: String, pub public_key: String, pub private_key: String, pub eth_address: String } //#[derive(Insertable)] //#[table_name="users"] //pub struct NewPerson<'a> { // pub id: Uuid, // pub name: &'a str, //} // this is called in main.rs create() function impl User { pub fn create(user: User, connection: &PgConnection) -> User { diesel::insert_into(users::table) .values(&user) .execute(connection) .expect("Error creating new user"); users::table.order(users::id.desc()).first(connection).unwrap() } pub fn read(connection: &PgConnection) -> Vec<User> { users::table.order(users::id.asc()) .load::<User>(connection) .unwrap() } pub fn update(id: i32, user: User, connection: &PgConnection) -> bool { diesel::update(users::table.find(id)).set(&user).execute(connection).is_ok() } pub fn delete(id: i32, connection: &PgConnection) -> bool { diesel::delete(users::table.find(id)) .execute(connection) .is_ok() } } // println!("\n\n -----------------------------------------------"); // println!("1 user.create() "); // println!("-----------------------------------------------"); // // // execute a cli to generate a key pair // let output = Command::new("/Users/tim.siwula/Desktop/parity/target/debug/./ethkey") // .arg("generate") // .arg("random") // .output() // .expect("./ethkey failed to execute"); // assert!(output.status.success()); // // let mut data = String::from_utf8_lossy(&output.stdout); // let mut secret = String::new(); // secret = data[9..73].to_string(); // println!("\nsecret = {:?}", secret); // // let mut public = String::new(); // public = data[83..211].to_string(); // println!("\npublic = {:?}", public); // // // let mut address: String = "0x".to_owned(); // let borrowed_string: &str = &data[221..261]; // // address.push_str(borrowed_string); // // println!("\naddress = {:?}", address); // // // &user.pubKey = public; // &user.privKey = secret; // &user.address = address; // // // println!("\n\n -----------------------------------------------"); // println!("2 post assignment "); // println!("-----------------------------------------------");
#[doc = "Reader of register MMCRXIM"] pub type R = crate::R<u32, super::MMCRXIM>; #[doc = "Writer for register MMCRXIM"] pub type W = crate::W<u32, super::MMCRXIM>; #[doc = "Register MMCRXIM `reset()`'s with value 0"] impl crate::ResetValue for super::MMCRXIM { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `GBF`"] pub type GBF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GBF`"] pub struct GBF_W<'a> { w: &'a mut W, } impl<'a> GBF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `CRCERR`"] pub type CRCERR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CRCERR`"] pub struct CRCERR_W<'a> { w: &'a mut W, } impl<'a> CRCERR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `ALGNERR`"] pub type ALGNERR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ALGNERR`"] pub struct ALGNERR_W<'a> { w: &'a mut W, } impl<'a> ALGNERR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `UCGF`"] pub type UCGF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UCGF`"] pub struct UCGF_W<'a> { w: &'a mut W, } impl<'a> UCGF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } impl R { #[doc = "Bit 0 - MMC Receive Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn gbf(&self) -> GBF_R { GBF_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 5 - MMC Receive CRC Error Frame Counter Interrupt Mask"] #[inline(always)] pub fn crcerr(&self) -> CRCERR_R { CRCERR_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - MMC Receive Alignment Error Frame Counter Interrupt Mask"] #[inline(always)] pub fn algnerr(&self) -> ALGNERR_R { ALGNERR_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 17 - MMC Receive Unicast Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn ucgf(&self) -> UCGF_R { UCGF_R::new(((self.bits >> 17) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - MMC Receive Good Bad Frame Counter Interrupt Mask"] #[inline(always)] pub fn gbf(&mut self) -> GBF_W { GBF_W { w: self } } #[doc = "Bit 5 - MMC Receive CRC Error Frame Counter Interrupt Mask"] #[inline(always)] pub fn crcerr(&mut self) -> CRCERR_W { CRCERR_W { w: self } } #[doc = "Bit 6 - MMC Receive Alignment Error Frame Counter Interrupt Mask"] #[inline(always)] pub fn algnerr(&mut self) -> ALGNERR_W { ALGNERR_W { w: self } } #[doc = "Bit 17 - MMC Receive Unicast Good Frame Counter Interrupt Mask"] #[inline(always)] pub fn ucgf(&mut self) -> UCGF_W { UCGF_W { w: self } } }
#[macro_use] mod common; mod bool_tests; mod float_tests; mod int_tests; mod misc_tests; mod none_tests;
use std::ffi::{CStr, CString}; use tui::{backend::Backend, Terminal}; use pam::Converse; use crate::loginform::LoginForm; pub struct DynamicConv<'a, B> where B: Backend, { username: Option<String>, form: LoginForm, term: &'a mut Terminal<B>, } impl<'a, B> DynamicConv<'a, B> where B: Backend, { pub fn new(term: &'a mut Terminal<B>) -> DynamicConv<'a, B> { DynamicConv { username: None, form: LoginForm::default(), term, } } pub fn error_string(&mut self, error: String) { self.form.error(error); } } impl<B> Converse for DynamicConv<'_, B> where B: Backend, { fn prompt_echo(&mut self, msg: &CStr) -> Result<CString, ()> { let title = msg.to_string_lossy().to_string(); self.form.add_input(title.clone(), false); if let Ok(input) = self.form.get_next_input(self.term) { if title == "login:" { self.username = Some(input.clone()); } if let Ok(ret) = CString::new(input) { Ok(ret) } else { Err(()) } } else { Err(()) } } fn prompt_blind(&mut self, msg: &CStr) -> Result<CString, ()> { self.form .add_input(msg.to_string_lossy().to_owned().to_string(), true); if let Ok(input) = self.form.get_next_input(self.term) { if let Ok(ret) = CString::new(input) { Ok(ret) } else { Err(()) } } else { Err(()) } } fn info(&mut self, msg: &CStr) { self.form .message(msg.to_string_lossy().to_owned().to_string()); self.form.draw_form(self.term); } fn error(&mut self, msg: &CStr) { self.form .error(msg.to_string_lossy().to_owned().to_string()); self.form.draw_form(self.term); } fn username(&self) -> &str { if let Some(ret) = &self.username { &ret } else { "" } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use ringbuf::*; use spin::Mutex; use core::cell::RefCell; use core::marker::PhantomData; use alloc::collections::vec_deque::VecDeque; use core::ops::Deref; use super::common::*; // multple producer single consumer pub struct MpScRing<T> { pub consumer: RefCell<Consumer<T>>, pub producer: Mutex<Producer<T>>, pub resource_type: PhantomData<T>, } unsafe impl <T> Sync for MpScRing<T> {} impl <T> MpScRing <T> { pub fn New(size: usize) -> Self { let r = RingBuffer::new(size); let (p, c) = r.split(); return Self { consumer: RefCell::new(c), producer: Mutex::new(p), resource_type: PhantomData, } } pub fn Push(&self, data: T) -> Result<()> { match self.producer.lock().push(data) { Ok(()) => return Ok(()), _ => return Err(Error::QueueFull) } } pub fn TryPush(&self, data: T) -> Option<T> { let mut p = match self.producer.try_lock() { None => return Some(data), Some(p) => p }; if p.is_full() { return Some(data); } match p.push(data) { Ok(()) => (), _ => panic!("TryPush fail"), } return None; } pub fn Pop(&self) -> Option<T> { return self.consumer.borrow_mut().pop() } pub fn Count(&self) -> usize { return self.producer.lock().len(); } pub fn IsFull(&self) -> bool { return self.producer.lock().is_full(); } pub fn IsEmpty(&self) -> bool { return self.producer.lock().is_empty(); } pub fn CountLockless(&self) -> usize { return self.consumer.borrow().len(); } } //single producer multple consumer pub struct SpMcRing <T> { pub consumer: Mutex<Consumer<T>>, pub producer: RefCell<Producer<T>>, pub resource_type: PhantomData<T>, } unsafe impl <T> Sync for SpMcRing<T> {} impl <T> SpMcRing <T> { pub fn New(size: usize) -> Self { let r = RingBuffer::new(size); let (p, c) = r.split(); return Self { consumer: Mutex::new(c), producer: RefCell::new(p), resource_type: PhantomData, } } pub fn Push(&self, data: T) -> Result<()> { match self.producer.borrow_mut().push(data) { Ok(()) => return Ok(()), _ => return Err(Error::QueueFull) } } pub fn Pop(&self) -> Option<T> { return self.consumer.lock().pop() } pub fn TryPop(&self) -> Option<T> { let mut c = match self.consumer.try_lock() { None => return None, Some(d) => d, }; return c.pop(); } pub fn Count(&self) -> usize { return self.consumer.lock().len(); } pub fn IsFull(&self) -> bool { return self.consumer.lock().is_full(); } pub fn IsEmpty(&self) -> bool { return self.consumer.lock().is_empty(); } pub fn CountLockless(&self) -> usize { return self.producer.borrow().len(); } } pub struct QRingBuf<T:Clone + Copy>(Mutex<VecDeque<T>>); impl <T:Clone + Copy> Deref for QRingBuf <T> { type Target = Mutex<VecDeque<T>>; fn deref(&self) -> &Mutex<VecDeque<T>> { &self.0 } } impl <T:Clone + Copy> QRingBuf <T> { pub fn New(size: usize) -> Self { return Self(Mutex::new(VecDeque::with_capacity(size))) } pub fn Push(&self, data: &T) -> Result<()> { let mut p = self.lock(); if p.len() == p.capacity() { return Err(Error::QueueFull); } p.push_back(*data); return Ok(()); } pub fn TryPush(&self, data: &T) -> Result<()> { let mut p = match self.try_lock() { None => return Err(Error::NoData), Some(p) => p }; if p.len() == p.capacity() { return Err(Error::QueueFull); } p.push_back(*data); return Ok(()); } pub fn Pop(&self) -> Option<T> { return self.lock().pop_front() } pub fn TryPop(&self) -> Option<T> { let mut p = match self.try_lock() { None => return None, Some(p) => p }; return p.pop_front(); } pub fn Count(&self) -> usize { return self.lock().len(); } pub fn IsFull(&self) -> bool { let q = self.lock(); return q.len() == q.capacity(); } pub fn IsEmpty(&self) -> bool { return self.lock().len() == 0; } pub fn CountLockless(&self) -> usize { return self.lock().len(); } }
use opentelemetry::trace::{SpanId, TraceId}; use rand::prelude::*; use std::fmt::Display; use std::str::FromStr; pub(crate) struct BuildId { trace: u128, span: u64, } impl BuildId { pub(crate) fn generate() -> Self { Self { trace: rand::thread_rng().gen(), span: rand::thread_rng().gen(), } } pub(crate) fn trace_id(&self) -> TraceId { TraceId::from_u128(self.trace) } pub(crate) fn span_id(&self) -> SpanId { SpanId::from_u64(self.span) } } impl FromStr for BuildId { type Err = Box<dyn std::error::Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.len() != 48 { return Err("string len is not 48".into()); } let (s_trace, s_span) = s.split_at(32); let trace = u128::from_str_radix(s_trace, 16)?; let span = u64::from_str_radix(s_span, 16)?; Ok(Self { trace, span }) } } impl Display for BuildId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:032x}{:016x}", self.trace, self.span) } } pub(crate) struct StepId(BuildId); impl StepId { pub(crate) fn span_id(&self) -> SpanId { self.0.span_id() } } impl FromStr for StepId { type Err = Box<dyn std::error::Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { BuildId::from_str(s).map(Self) } } impl Display for StepId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } }
use std::io; use std::str::FromStr; fn main() { let mut input = String::new(); if let Err(_) = io::stdin().read_line(&mut input) { panic!("Failed to read a line"); } let gallons = f64::from_str(input.trim()); let gallons = match gallons { Ok(value) => value, Err(_) => panic!("Failed to parse gallons") }; println!("Equivalent of {} gallons in cubic feet is {}", gallons, gallons / 7.481f64); }
//! `pipe` and related APIs. //! //! # Safety //! //! `vmsplice` is an unsafe function. #![allow(unsafe_code)] use crate::fd::OwnedFd; use crate::{backend, io}; #[cfg(not(any( solarish, windows, target_os = "espidf", target_os = "haiku", target_os = "redox", target_os = "wasi", )))] use backend::c; #[cfg(linux_kernel)] use backend::fd::AsFd; #[cfg(not(apple))] pub use backend::pipe::types::PipeFlags; #[cfg(linux_kernel)] pub use backend::pipe::types::{IoSliceRaw, SpliceFlags}; /// `PIPE_BUF`—The maximum length at which writes to a pipe are atomic. /// /// # References /// - [Linux] /// - [POSIX] /// /// [Linux]: https://man7.org/linux/man-pages/man7/pipe.7.html /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html #[cfg(not(any( solarish, windows, target_os = "espidf", target_os = "haiku", target_os = "redox", target_os = "wasi", )))] pub const PIPE_BUF: usize = c::PIPE_BUF; /// `pipe()`—Creates a pipe. /// /// This function creates a pipe and returns two file descriptors, for the /// reading and writing ends of the pipe, respectively. /// /// # References /// - [POSIX] /// - [Linux] /// - [Apple] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// - [glibc] /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html /// [Linux]: https://man7.org/linux/man-pages/man2/pipe.2.html /// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/pipe.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=pipe&sektion=2 /// [NetBSD]: https://man.netbsd.org/pipe.2 /// [OpenBSD]: https://man.openbsd.org/pipe.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=pipe&section=2 /// [illumos]: https://illumos.org/man/2/pipe /// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Creating-a-Pipe.html #[inline] pub fn pipe() -> io::Result<(OwnedFd, OwnedFd)> { backend::pipe::syscalls::pipe() } /// `pipe2(flags)`—Creates a pipe, with flags. /// /// This function creates a pipe and returns two file descriptors, for the /// reading and writing ends of the pipe, respectively. /// /// # References /// - [Linux] /// - [FreeBSD] /// - [NetBSD] /// - [OpenBSD] /// - [DragonFly BSD] /// - [illumos] /// /// [Linux]: https://man7.org/linux/man-pages/man2/pipe2.2.html /// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=pipe2&sektion=2 /// [NetBSD]: https://man.netbsd.org/pipe2.2 /// [OpenBSD]: https://man.openbsd.org/pipe2.2 /// [DragonFly BSD]: https://man.dragonflybsd.org/?command=pipe2&section=2 /// [illumos]: https://illumos.org/man/2/pipe2 #[cfg(not(any( apple, target_os = "aix", target_os = "espidf", target_os = "haiku", target_os = "nto" )))] #[inline] #[doc(alias = "pipe2")] pub fn pipe_with(flags: PipeFlags) -> io::Result<(OwnedFd, OwnedFd)> { backend::pipe::syscalls::pipe_with(flags) } /// `splice(fd_in, off_in, fd_out, off_out, len, flags)`—Transfer data between /// a file and a pipe. /// /// This function transfers up to `len` bytes of data from the file descriptor /// `fd_in` to the file descriptor `fd_out`, where one of the file descriptors /// must refer to a pipe. /// /// `off_*` must be `None` if the corresponding fd refers to a pipe. /// Otherwise its value points to the starting offset to the file, /// from which the data is read/written. /// on success the number of bytes read/written is added to the offset. /// /// passing `None` causes the read/write to start from the file offset, /// and the file offset is adjusted appropriately. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/splice.2.html #[cfg(linux_kernel)] #[inline] pub fn splice<FdIn: AsFd, FdOut: AsFd>( fd_in: FdIn, off_in: Option<&mut u64>, fd_out: FdOut, off_out: Option<&mut u64>, len: usize, flags: SpliceFlags, ) -> io::Result<usize> { backend::pipe::syscalls::splice(fd_in.as_fd(), off_in, fd_out.as_fd(), off_out, len, flags) } /// `vmsplice(fd, bufs, flags)`—Transfer data between memory and a pipe. /// /// If `fd` is the write end of the pipe, /// the function maps the memory pointer at by `bufs` to the pipe. /// /// If `fd` is the read end of the pipe, /// the function writes data from the pipe to said memory. /// /// # Safety /// /// If the memory must not be mutated (such as when `bufs` were originally /// immutable slices), it is up to the caller to ensure that the write end of /// the pipe is placed in `fd`. /// /// Additionally if `SpliceFlags::GIFT` is set, the caller must also ensure /// that the contents of `bufs` in never modified following the call, /// and that all of the pointers in `bufs` are page aligned, /// and the lengths are multiples of a page size in bytes. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/vmsplice.2.html #[cfg(linux_kernel)] #[inline] pub unsafe fn vmsplice<PipeFd: AsFd>( fd: PipeFd, bufs: &[IoSliceRaw], flags: SpliceFlags, ) -> io::Result<usize> { backend::pipe::syscalls::vmsplice(fd.as_fd(), bufs, flags) } /// `tee(fd_in, fd_out, len, flags)`—Copy data between pipes without /// consuming it. /// /// This reads up to `len` bytes from `in_fd` without consuming them, and /// writes them to `out_fd`. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/tee.2.html #[cfg(linux_kernel)] #[inline] pub fn tee<FdIn: AsFd, FdOut: AsFd>( fd_in: FdIn, fd_out: FdOut, len: usize, flags: SpliceFlags, ) -> io::Result<usize> { backend::pipe::syscalls::tee(fd_in.as_fd(), fd_out.as_fd(), len, flags) } /// `ioctl(fd, F_GETPIPE_SZ)`—Return the buffer capacity of a pipe. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html #[cfg(linux_kernel)] #[inline] pub fn fcntl_getpipe_size<Fd: AsFd>(fd: Fd) -> io::Result<usize> { backend::pipe::syscalls::fcntl_getpipe_sz(fd.as_fd()) } /// `ioctl(fd, F_SETPIPE_SZ)`—Set the buffer capacity of a pipe. /// /// # References /// - [Linux] /// /// [Linux]: https://man7.org/linux/man-pages/man2/fcntl.2.html #[cfg(linux_kernel)] #[inline] pub fn fcntl_setpipe_size<Fd: AsFd>(fd: Fd, size: usize) -> io::Result<()> { backend::pipe::syscalls::fcntl_setpipe_sz(fd.as_fd(), size) }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtCore/qatomic.h // dst-file: /src/core/qatomic.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QAtomicInt_Class_Size() -> c_int; // proto: void QAtomicInt::QAtomicInt(int value); fn C_ZN10QAtomicIntC2Ei(arg0: c_int) -> u64; } // <= ext block end // body block begin => // class sizeof(QAtomicInt)=1 #[derive(Default)] pub struct QAtomicInt { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QAtomicInt { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QAtomicInt { return QAtomicInt{qclsinst: qthis, ..Default::default()}; } } // proto: void QAtomicInt::QAtomicInt(int value); impl /*struct*/ QAtomicInt { pub fn new<T: QAtomicInt_new>(value: T) -> QAtomicInt { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QAtomicInt_new { fn new(self) -> QAtomicInt; } // proto: void QAtomicInt::QAtomicInt(int value); impl<'a> /*trait*/ QAtomicInt_new for (Option<i32>) { fn new(self) -> QAtomicInt { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QAtomicIntC2Ei()}; let ctysz: c_int = unsafe{QAtomicInt_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap()}) as c_int; let qthis: u64 = unsafe {C_ZN10QAtomicIntC2Ei(arg0)}; let rsthis = QAtomicInt{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // <= body block end
tag colour { red; green; } obj foo[T]() { fn meth(x: &T) { } } fn main() { foo[colour]().meth(red); }
use efflux::prelude::*; /// The struct which implements the `Reducer` trait for PageRank. /// Should be called repeatedly to refine the PageRank. pub struct PageRankReducer; /// A PageRank reducer. /// Receives the same kind of output as it emits. /// The input is a list of ΔPageRank scores from in nodes, plus a list of all the out nodes. impl Reducer for PageRankReducer { fn reduce(&mut self, key: &[u8], values: &[&[u8]], ctx: &mut Context) { // Convert from raw bytes into str let values = values .iter() .map(|value| std::str::from_utf8(value).expect("Invalid UTF-8")) .collect::<Vec<&str>>(); // The page rank and out nodes are both included in the aggregate values. let mut page_rank = 0.0; let mut out_nodes: Vec<&str> = Vec::new(); for value in &values { if value.starts_with("Δ") { page_rank += &value[2..].parse::<f64>().unwrap(); } else { out_nodes = value.split(",").collect::<Vec<&str>>(); } } // Compute ΔPageRank for each outgoing node and output to the stage let page_rank = page_rank / out_nodes.len() as f64; for node in &out_nodes { let page_rank = format!("Δ{:.16}", page_rank); ctx.write_fmt(node, page_rank); } // Output the total pagerank for this node as well as outgoing nodes if out_nodes.len() > 0 { ctx.write(key, out_nodes.join(",").as_bytes()); } } } pub struct PageRankCombineReducer; /// A PageRank reducer. /// Receives the same kind of output as it emits. /// The input is a list of ΔPageRank scores from in nodes, plus a list of all the out nodes. impl Reducer for PageRankCombineReducer { fn reduce(&mut self, key: &[u8], values: &[&[u8]], ctx: &mut Context) { // Convert from raw bytes into str let values = values .iter() .map(|value| std::str::from_utf8(value).expect("Invalid UTF-8")) .collect::<Vec<&str>>(); // The page rank and out nodes are both included in the aggregate values. let mut page_rank = 0.0; let mut out_nodes = ""; for value in &values { if value.starts_with("Δ") { page_rank += &value[2..].parse::<f64>().unwrap(); } else { out_nodes = value; } } let page_rank = format!("Δ{}", page_rank); ctx.write(key, page_rank.as_bytes()); // Output the total pagerank for this node as well as outgoing nodes if out_nodes.len() > 0 { ctx.write(key, out_nodes.to_string().as_bytes()); } } }
use super::{bool_to_enum, enum_to_bool, BitArray64, BooleanEnum}; #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] pub enum Bool { /// False = 0, /// True = 1, } unsafe impl BooleanEnum for Bool { const FALSE: Self = Self::False; const TRUE: Self = Self::True; } #[test] fn with_count() { for count in 0..=64 { let bits = BitArray64::<Bool>::with_count(count); for i in 0..64 { assert_eq!( bits.at(i) == Bool::True, i < count, "count={} bits={:?}", count, bits.bits() ); } } } #[test] fn set_bits() { let mut bits = BitArray64::with_count(8); assert_eq!(0b_1111_1111, bits.bits()); { let mut bits = bits; bits = bits.set(0, Bool::False); assert_eq!(0b_1111_1110, bits.bits()); bits = bits.set(2, Bool::False); assert_eq!(0b_1111_1010, bits.bits()); bits = bits.set(1, Bool::False); assert_eq!(0b_1111_1000, bits.bits()); } bits = bits.set(3, Bool::False); assert_eq!(0b_1111_0111, bits.bits()); bits = bits.set(5, Bool::False); assert_eq!(0b_1101_0111, bits.bits()); bits = bits.set(6, Bool::False); assert_eq!(0b_1001_0111, bits.bits()); bits = bits.set(10, Bool::True); assert_eq!(0b_0100_1001_0111, bits.bits()); bits = bits.set(63, Bool::True); assert_eq!((1 << 63) | 0b_0100_1001_0111, bits.bits()); } #[test] fn empty() { let bits = BitArray64::empty(); for i in 0..64 { assert!( matches!(bits.at(i), Bool::False), "i={} bits={:b}", i, bits.bits() ); } } #[test] fn iter_test() { let iter = BitArray64::with_count(8) .set(1, Bool::False) .set(3, Bool::False) .iter() .take(10) .map(enum_to_bool); let expected = vec![ true, false, true, false, true, true, true, true, false, false, ]; let expected_rev = expected.iter().cloned().rev().collect::<Vec<bool>>(); assert_eq!(iter.clone().collect::<Vec<bool>>(), expected); assert_eq!(iter.rev().collect::<Vec<bool>>(), expected_rev); } #[test] fn enum_roundtrip() { assert_eq!(bool_to_enum::<Bool>(false), Bool::False); assert_eq!(bool_to_enum::<Bool>(true), Bool::True); assert_eq!(enum_to_bool(Bool::False), false); assert_eq!(enum_to_bool(Bool::True), true); } #[test] fn bool_roundtrip() { assert_eq!(bool_to_enum::<bool>(false), false); assert_eq!(bool_to_enum::<bool>(true), true); assert_eq!(enum_to_bool(false), false); assert_eq!(enum_to_bool(true), true); }
//! Implementation of [Stream] that performs gap-filling on tables. use std::{ pin::Pin, sync::Arc, task::{Context, Poll}, }; use arrow::{ array::{ArrayRef, TimestampNanosecondArray}, datatypes::SchemaRef, record_batch::RecordBatch, }; use arrow_util::optimize::optimize_dictionaries; use datafusion::{ error::{DataFusionError, Result}, execution::memory_pool::MemoryReservation, physical_plan::{ expressions::Column, metrics::{BaselineMetrics, RecordOutput}, ExecutionPlan, PhysicalExpr, RecordBatchStream, SendableRecordBatchStream, }, }; use futures::{ready, Stream, StreamExt}; use super::{algo::GapFiller, buffered_input::BufferedInput, params::GapFillParams, GapFillExec}; /// An implementation of a gap-filling operator that uses the [Stream] trait. /// /// This type takes responsibility for: /// - Reading input record batches /// - Accounting for memory /// - Extracting arrays for processing by [`GapFiller`] /// - Recording metrics /// - Sending record batches to next operator (by implementing [`Self::poll_next']) #[allow(dead_code)] pub(super) struct GapFillStream { /// The schema of the input and output. schema: SchemaRef, /// The column from the input that contains the timestamps for each row. /// This column has already had `date_bin` applied to it by a previous `Aggregate` /// operator. time_expr: Arc<dyn PhysicalExpr>, /// The other columns from the input that appeared in the GROUP BY clause of the /// original query. group_expr: Vec<Arc<dyn PhysicalExpr>>, /// The aggregate columns from the select list of the original query. aggr_expr: Vec<Arc<dyn PhysicalExpr>>, /// The producer of the input record batches. input: SendableRecordBatchStream, /// Input that has been read from the iput stream. buffered_input: BufferedInput, /// The thing that does the gap filling. gap_filler: GapFiller, /// This is true as long as there are more input record batches to read from `input`. more_input: bool, /// For tracking memory. reservation: MemoryReservation, /// Baseline metrics. baseline_metrics: BaselineMetrics, } impl GapFillStream { /// Creates a new GapFillStream. pub fn try_new( exec: &GapFillExec, batch_size: usize, input: SendableRecordBatchStream, reservation: MemoryReservation, metrics: BaselineMetrics, ) -> Result<Self> { let schema = exec.schema(); let GapFillExec { sort_expr, aggr_expr, params, .. } = exec; if sort_expr.is_empty() { return Err(DataFusionError::Internal( "empty sort_expr vector for gap filling; should have at least a time expression" .to_string(), )); } let mut group_expr = sort_expr .iter() .map(|se| Arc::clone(&se.expr)) .collect::<Vec<_>>(); let aggr_expr = aggr_expr.to_owned(); let time_expr = group_expr.split_off(group_expr.len() - 1).pop().unwrap(); let group_cols = group_expr.iter().map(expr_to_index).collect::<Vec<_>>(); let params = GapFillParams::try_new(Arc::clone(&schema), params)?; let buffered_input = BufferedInput::new(&params, group_cols); let gap_filler = GapFiller::new(params, batch_size); Ok(Self { schema, time_expr, group_expr, aggr_expr, input, buffered_input, gap_filler, more_input: true, reservation, baseline_metrics: metrics, }) } } impl RecordBatchStream for GapFillStream { fn schema(&self) -> arrow::datatypes::SchemaRef { Arc::clone(&self.schema) } } impl Stream for GapFillStream { type Item = Result<RecordBatch>; /// Produces a gap-filled record batch from its input stream. /// /// For details on implementation, see [`GapFiller`]. fn poll_next( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<RecordBatch>>> { let last_output_row_offset = self.gap_filler.last_output_row_offset(); while self.more_input && self.buffered_input.need_more(last_output_row_offset)? { match ready!(self.input.poll_next_unpin(cx)) { Some(Ok(batch)) => { self.reservation.try_grow(batch.get_array_memory_size())?; self.buffered_input.push(batch); } Some(Err(e)) => { return Poll::Ready(Some(Err(e))); } None => { self.more_input = false; } } } let input_batch = match self.take_buffered_input() { Ok(None) => return Poll::Ready(None), Ok(Some(input_batch)) => { // If we have consumed all of our input, and there is no more work if self.gap_filler.done(input_batch.num_rows()) { // leave the input batch taken so that its reference // count goes to zero. self.reservation.shrink(input_batch.get_array_memory_size()); return Poll::Ready(None); } input_batch } Err(e) => return Poll::Ready(Some(Err(e))), }; match self.process(input_batch) { Ok((output_batch, remaining_input_batch)) => { self.buffered_input.push(remaining_input_batch); self.reservation .shrink(output_batch.get_array_memory_size()); Poll::Ready(Some(Ok(output_batch))) } Err(e) => Poll::Ready(Some(Err(e))), } } } impl GapFillStream { /// If any buffered input batches are present, concatenates it all together /// and returns an owned batch to the caller, leaving `self.buffered_input_batches` empty. fn take_buffered_input(&mut self) -> Result<Option<RecordBatch>> { let batches = self.buffered_input.take(); if batches.is_empty() { return Ok(None); } let old_size = batches.iter().map(|rb| rb.get_array_memory_size()).sum(); let mut batch = arrow::compute::concat_batches(&self.schema, &batches) .map_err(DataFusionError::ArrowError)?; self.reservation.try_grow(batch.get_array_memory_size())?; if batches.len() > 1 { // Optimize the dictionaries. The output of this operator uses the take kernel to produce // its output. Since the input batches will usually be smaller than the output, it should // be less work to optimize here vs optimizing the output. batch = optimize_dictionaries(&batch).map_err(DataFusionError::ArrowError)?; } self.reservation.shrink(old_size); Ok(Some(batch)) } /// Produces a 2-tuple of [RecordBatch]es: /// - The gap-filled output /// - Remaining buffered input fn process(&mut self, mut input_batch: RecordBatch) -> Result<(RecordBatch, RecordBatch)> { let elapsed_compute = self.baseline_metrics.elapsed_compute().clone(); let input_time_array = self .time_expr .evaluate(&input_batch)? .into_array(input_batch.num_rows()); let input_time_array: &TimestampNanosecondArray = input_time_array .as_any() .downcast_ref() .ok_or(DataFusionError::Internal( "time array must be a TimestampNanosecondArray".to_string(), ))?; let input_time_array = (expr_to_index(&self.time_expr), input_time_array); let group_arrays = self.group_arrays(&input_batch)?; let aggr_arrays = self.aggr_arrays(&input_batch)?; let timer = elapsed_compute.timer(); let output_batch = self .gap_filler .build_gapfilled_output( Arc::clone(&self.schema), input_time_array, &group_arrays, &aggr_arrays, ) .record_output(&self.baseline_metrics)?; timer.done(); self.reservation .try_grow(output_batch.get_array_memory_size())?; // Slice the input to just what is needed moving forward, with one context // row before the next input offset. input_batch = self.gap_filler.slice_input_batch(input_batch)?; Ok((output_batch, input_batch)) } /// Produces the arrays for the group columns in the input. /// The first item in the 2-tuple is the arrays offset in the schema. fn group_arrays(&self, input_batch: &RecordBatch) -> Result<Vec<(usize, ArrayRef)>> { self.group_expr .iter() .map(|e| { Ok(( expr_to_index(e), e.evaluate(input_batch)?.into_array(input_batch.num_rows()), )) }) .collect::<Result<Vec<_>>>() } /// Produces the arrays for the aggregate columns in the input. /// The first item in the 2-tuple is the arrays offset in the schema. fn aggr_arrays(&self, input_batch: &RecordBatch) -> Result<Vec<(usize, ArrayRef)>> { self.aggr_expr .iter() .map(|e| { Ok(( expr_to_index(e), e.evaluate(input_batch)?.into_array(input_batch.num_rows()), )) }) .collect::<Result<Vec<_>>>() } } /// Returns the index of the given expression in the schema, /// assuming that it is a column. /// /// # Panic /// Panics if the expression is not a column. fn expr_to_index(expr: &Arc<dyn PhysicalExpr>) -> usize { expr.as_any() .downcast_ref::<Column>() .expect("all exprs should be columns") .index() }
/* Ownership Rules 1) Each value in Rust has a variable that’s called its owner. 2) There can only be one owner at a time. 3) When the owner goes out of scope, the value will be dropped. */ fn main() { simple_scope(); copy_bind(); move_example(); clone_example(); stack_only_copy(); ownership_and_functions(); return_values_and_scope(); return_value_ownership_transfer(); } fn simple_scope() { // s is not valid here, it’s not yet declared let s = "hello"; // s is valid from this point forward println!("The value of s in simple_scope is {}.", s); } // this scope is now over, and s is no longer valid fn copy_bind() { /* Bind the value 5 to x; then make a copy of the value in x and bind it to y. We now have two variables, x and y, and both equal 5. This is indeed what is happening, because integers are simple values with a known, fixed size, and these two 5 values are pushed onto the stack. */ let x = 5; let y = x; println!("In copy_bind, x is {} and y is {}.", x, y); } fn move_example() { /* Because Rust also invalidates the first variable, instead of being called a shallow copy, it’s known as a move. In this example, we would say that s1 was moved into s2. With only s2 valid, when it goes out of scope, it alone will free the memory. This allows us to avoid a problem that occurs in other languages (like C): when s2 and s1 go out of scope, they will both try to free the same memory. This is known as a double free error. Rust avoids the double free error by invalidating the first variable with a "move". */ let s1 = String::from("hello"); let s2 = s1; println!("In move_example, s2 is {}.", s2); // Uncommenting the next println line results in compiler error, because s1 // was invalidated by a "move". // println!("{}, world!", s1); } fn clone_example() { /* If we do want to deeply copy the heap data of the String, not just the stack data, we can use a common method called clone. */ let s1 = String::from("hello"); let s2 = s1.clone(); // The next line works just fine, because the heap data does get copied. println!("In clone_example, s1 is {} and s2 is {}.", s1, s2); } fn stack_only_copy() { /* Types such as integers that have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make. There’s no difference between deep and shallow copying here, so calling clone wouldn’t do anything different from the usual shallow copying and we can leave it out. */ let x = 5; let y = x; println!("In stack_only_copy, x = {}, y = {}.", x, y); } fn ownership_and_functions() { let s = String::from("hello"); // s comes into scope takes_ownership(s); // s's value moves into the function... // ... and so is no longer valid here let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it’s okay to still // use x afterward println!("In ownership_and_functions, x is {}.", x); } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope println!("In takes_ownership, some_string is {}.", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("In makes_copy, some_integer is {}.", some_integer); } // Here, some_integer goes out of scope. Nothing special happens. fn return_values_and_scope() { let s1 = gives_ownership(); // gives_ownership moves its return // value into s1 let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 is moved into // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was // moved, so nothing happens. s1 goes out of scope and is dropped. fn gives_ownership() -> String { // gives_ownership will move its // return value into the function // that calls it let some_string = String::from("hello"); // some_string comes into scope some_string // some_string is returned and // moves out to the calling // function } // takes_and_gives_back will take a String and return one fn takes_and_gives_back(a_string: String) -> String { // a_string comes into // scope a_string // a_string is returned and moves out to the calling function } fn return_value_ownership_transfer() { /* Taking ownership and then returning ownership with every function is a bit tedious. What if we want to let a function use a value but not take ownership? It’s quite annoying that anything we pass in also needs to be passed back if we want to use it again, in addition to any data resulting from the body of the function that we might want to return as well. It’s possible to return multiple values using a tuple. But this is too much ceremony and a lot of work for a concept that should be common. Luckily for us, Rust has a feature for this concept, called references. */ let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); println!("In return_value_ownership_transfer, the length of '{}' is {}.", s2, len); } fn calculate_length(s: String) -> (String, usize) { let length = s.len(); // len() returns the length of a String (s, length) }
use crate::models::launch::{Launch, LaunchID}; use crate::services::DB; use anyhow::Result; use chrono::{DateTime, Utc}; use sqlx::postgres::PgQueryResult; #[derive(Debug, sqlx::FromRow)] pub struct DBLaunch { pub launch_id: LaunchID, pub name: String, pub net: DateTime<Utc>, pub vid_url: Option<String>, pub image_url: Option<String>, pub dispatched: bool, pub status: i32, pub description: Option<String>, } impl From<Launch> for DBLaunch { fn from(l: Launch) -> Self { DBLaunch { launch_id: l.id, name: l.name, net: l.net, vid_url: l.vid_urls.get(0).map(|v| v.url.to_owned()), image_url: l.rocket.configuration.image_url, dispatched: false, status: l.status.id as i32, description: l.mission.as_ref().map(|m| m.description.to_owned()), } } } impl DB { pub async fn get_launch(&self, id: &LaunchID, dispatched: bool) -> Option<DBLaunch> { sqlx::query_as("SELECT * FROM astra.launches WHERE launch_id = $1 AND dispatched = $2") .bind(id) .bind(dispatched) .fetch_optional(&self.pool) .await .unwrap() } pub async fn get_launches(&self) -> Vec<DBLaunch> { sqlx::query_as("SELECT * FROM astra.launches WHERE net > now() ORDER BY net") .fetch_all(&self.pool) .await .unwrap() } pub async fn get_limited_launches(&self) -> Vec<DBLaunch> { sqlx::query_as( "SELECT * FROM astra.launches WHERE net <= (now() + interval '24 hours') AND status = 1;" ) .fetch_all(&self.pool) .await .unwrap() } pub async fn set_net(&self, launch: &Launch) -> Result<PgQueryResult, sqlx::Error> { sqlx::query("UPDATE astra.launches SET net = $1 WHERE launch_id = $2") .bind(&launch.net) .bind(&launch.id) .execute(&self.pool) .await } pub async fn set_launch(&self, launch: DBLaunch) -> Result<PgQueryResult, sqlx::Error> { sqlx::query( "INSERT INTO astra.launches (launch_id, name, net, vid_url, \ image_url, dispatched, status, description) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \ ON CONFLICT (launch_id) DO \ UPDATE SET net = $3, vid_url = $4, dispatched = $6, \ status = $7, description = $8;", ) .bind(launch.launch_id) .bind(launch.name) .bind(launch.net) .bind(launch.vid_url) .bind(launch.image_url) .bind(launch.dispatched) .bind(launch.status) .bind(launch.description) .execute(&self.pool) .await } }
pub mod bus; pub mod cartridge; pub mod cpu; pub mod sound; pub mod input; pub mod ppu; pub mod timer; mod memory; use anyhow::Result; use bus::Bus; use cartridge::{load_rom}; use cpu::Cpu; use ppu::{PpuInterrupt}; use crate::gui::{self, Message}; pub struct Emu { cpu: Cpu, bus: Bus, } impl Emu { pub fn new(rom_name: &str) -> Result<Self> { let rom = load_rom(rom_name)?; let bus = Bus::new(rom)?; let mut cpu = Cpu::new(); cpu.reset(); Ok(Self { cpu, bus }) } pub fn get_next_frame(&mut self, events: &[Message], rendering_texture: &mut [u8; gui::SIZE]) { let mut frame_done = false; loop { self.cpu.tick(&mut self.bus); match self.bus.ppu.tick() { PpuInterrupt::None => {} PpuInterrupt::VBlank => { self.bus.requested_interrupts |= bus::VBLANK; frame_done = true; } PpuInterrupt::Stat => { self.bus.requested_interrupts |= bus::LCD_STAT; } } if self.bus.timer.tick() { self.bus.requested_interrupts |= bus::TIMER; } for ev in events { if self.bus.joypad.update(ev) { self.bus.requested_interrupts |= bus::JOYPAD }; } if frame_done { self.bus.ppu.render(rendering_texture); break; } } } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::Arc; use common_exception::ErrorCode; use common_exception::Result; use common_expression::BlockThresholds; use common_expression::DataBlock; use super::Compactor; use super::TransformCompact; pub struct BlockCompactor { thresholds: BlockThresholds, // A flag denoting whether it is a recluster operation. // Will be removed later. is_recluster: bool, aborting: Arc<AtomicBool>, } impl BlockCompactor { pub fn new(thresholds: BlockThresholds, is_recluster: bool) -> Self { BlockCompactor { thresholds, is_recluster, aborting: Arc::new(AtomicBool::new(false)), } } } impl Compactor for BlockCompactor { fn name() -> &'static str { "BlockCompactTransform" } fn use_partial_compact() -> bool { true } fn interrupt(&self) { self.aborting.store(true, Ordering::Release); } fn compact_partial(&mut self, blocks: &mut Vec<DataBlock>) -> Result<Vec<DataBlock>> { if blocks.is_empty() { return Ok(vec![]); } let size = blocks.len(); let mut res = Vec::with_capacity(size); let block = blocks[size - 1].clone(); // perfect block if self .thresholds .check_perfect_block(block.num_rows(), block.memory_size()) { res.push(block); blocks.remove(size - 1); } else { let accumulated_rows: usize = blocks.iter_mut().map(|b| b.num_rows()).sum(); let accumulated_bytes: usize = blocks.iter_mut().map(|b| b.memory_size()).sum(); let merged = DataBlock::concat(blocks)?; blocks.clear(); if accumulated_rows >= self.thresholds.max_rows_per_block { // Used for recluster operation, will be removed later. if self.is_recluster { let mut offset = 0; let mut remain_rows = accumulated_rows; while remain_rows >= self.thresholds.max_rows_per_block { let cut = merged.slice(offset..(offset + self.thresholds.max_rows_per_block)); res.push(cut); offset += self.thresholds.max_rows_per_block; remain_rows -= self.thresholds.max_rows_per_block; } if remain_rows > 0 { blocks.push(merged.slice(offset..(offset + remain_rows))); } } else { // we can't use slice here, it did not deallocate memory res.push(merged); } } else if accumulated_bytes >= self.thresholds.max_bytes_per_block { // too large for merged block, flush to results res.push(merged); } else { // keep the merged block into blocks for future merge blocks.push(merged); } } Ok(res) } fn compact_final(&self, blocks: &[DataBlock]) -> Result<Vec<DataBlock>> { let mut res = Vec::with_capacity(blocks.len()); let mut temp_blocks = vec![]; let mut accumulated_rows = 0; for block in blocks.iter() { if self.aborting.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } // Perfect block, no need to compact if self .thresholds .check_perfect_block(block.num_rows(), block.memory_size()) { res.push(block.clone()); } else { let block = if block.num_rows() > self.thresholds.max_rows_per_block { let b = block.slice(0..self.thresholds.max_rows_per_block); res.push(b); block.slice(self.thresholds.max_rows_per_block..block.num_rows()) } else { block.clone() }; accumulated_rows += block.num_rows(); temp_blocks.push(block); while accumulated_rows >= self.thresholds.max_rows_per_block { if self.aborting.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } let block = DataBlock::concat(&temp_blocks)?; res.push(block.slice(0..self.thresholds.max_rows_per_block)); accumulated_rows -= self.thresholds.max_rows_per_block; temp_blocks.clear(); if accumulated_rows != 0 { temp_blocks.push( block.slice(self.thresholds.max_rows_per_block..block.num_rows()), ); } } } } if accumulated_rows != 0 { if self.aborting.load(Ordering::Relaxed) { return Err(ErrorCode::AbortedQuery( "Aborted query, because the server is shutting down or the query was killed.", )); } let block = DataBlock::concat(&temp_blocks)?; res.push(block); } Ok(res) } } pub type TransformBlockCompact = TransformCompact<BlockCompactor>;
use std::collections::VecDeque; use proconio::{input, marker::Usize1}; fn main() { input! { n: usize, }; let mut g = vec![vec![]; n]; for i in 0..n { input! { c: usize, p: [Usize1; c], }; g[i] = p; } let mut visited = vec![false; n]; let mut que = VecDeque::new(); que.push_back(0); while let Some(i) = que.pop_front() { for &j in &g[i] { if visited[j] { continue; } visited[j] = true; que.push_back(j); } } let mut deg = vec![0; n]; let mut rg = vec![vec![]; n]; for i in 0..n { deg[i] = g[i].len(); for &j in &g[i] { rg[j].push(i); } } let mut que = VecDeque::new(); for i in 0..n { if visited[i] && deg[i] == 0 { que.push_back(i); } } let mut ans = Vec::new(); while let Some(i) = que.pop_front() { if i == 0 { break; } ans.push(i); for &j in &rg[i] { assert!(deg[j] >= 1); deg[j] -= 1; if visited[j] && deg[j] == 0 { que.push_back(j); } } } let ans = ans .into_iter() .map(|i| i + 1) .map(|i| i.to_string()) .collect::<Vec<_>>() .join(" "); println!("{}", ans); }
#[derive(PartialEq, PartialOrd, Debug)] pub enum SyntaxKind { UnknownToken, WordlyToken, NumberToken, // Number like: 12 or 1.2 StringToken, // String like "Sina#" CharToken, // A character WhitespaceToken, // :D QuotationToken, // " SingleQouteToken, // ' CaretToken, // ^ OpenBracketToken, // } OpenSquareBracketToken, // [ CloseBracketToken, // } CloseSquareBracketToken, // ] AdditionToken, // + SubstractionToken, // - IncrementToken, // ++ DecrementToken, // -- MultiplicationToken, // * DivisionToken, // / ModulusToken, // % AssignToken, // = GTToken, // > LTToken, // < GTOEToken, // >= LTOEToken, // <= EqualToken, // == ParenthesesOpenToken, // ( ParenthesesCloseToken, // ) CommaToken, // , StringNumToken, // %d StringCharToken, // %c StringFloatToken, // %f PrintToken, // Benevis -> printf ScanToken, // Begir -> scanf ConditionToken, // agar -> if LoopToken, // ta -> while FloatDefToken, // Ashari -> float IntegerDefToken, // Sahih -> int CharacterDefToken, // Harf -> char } impl SyntaxKind { pub fn copy(&self) -> SyntaxKind { match self { SyntaxKind::StringNumToken => SyntaxKind::StringNumToken, SyntaxKind::StringCharToken => SyntaxKind::StringCharToken, SyntaxKind::StringFloatToken => SyntaxKind::StringFloatToken, SyntaxKind::SingleQouteToken => SyntaxKind::SingleQouteToken, SyntaxKind::CharToken => SyntaxKind::CharToken, SyntaxKind::ParenthesesCloseToken => SyntaxKind::ParenthesesCloseToken, SyntaxKind::ParenthesesOpenToken => SyntaxKind::ParenthesesOpenToken, SyntaxKind::CommaToken => SyntaxKind::CommaToken, SyntaxKind::WordlyToken => SyntaxKind::WordlyToken, SyntaxKind::NumberToken => SyntaxKind::NumberToken, SyntaxKind::StringToken => SyntaxKind::StringToken, SyntaxKind::WhitespaceToken => SyntaxKind::WhitespaceToken, SyntaxKind::QuotationToken => SyntaxKind::QuotationToken, SyntaxKind::CaretToken => SyntaxKind::CaretToken, SyntaxKind::OpenBracketToken => SyntaxKind::OpenBracketToken, SyntaxKind::OpenSquareBracketToken => SyntaxKind::OpenSquareBracketToken, SyntaxKind::CloseBracketToken => SyntaxKind::CloseBracketToken, SyntaxKind::CloseSquareBracketToken => SyntaxKind::CloseSquareBracketToken, SyntaxKind::AdditionToken => SyntaxKind::AdditionToken, SyntaxKind::SubstractionToken => SyntaxKind::SubstractionToken, SyntaxKind::IncrementToken => SyntaxKind::IncrementToken, SyntaxKind::DecrementToken => SyntaxKind::DecrementToken, SyntaxKind::MultiplicationToken => SyntaxKind::MultiplicationToken, SyntaxKind::DivisionToken => SyntaxKind::DivisionToken, SyntaxKind::ModulusToken => SyntaxKind::ModulusToken, SyntaxKind::AssignToken => SyntaxKind::AssignToken, SyntaxKind::GTToken => SyntaxKind::GTToken, SyntaxKind::LTToken => SyntaxKind::LTToken, SyntaxKind::GTOEToken => SyntaxKind::GTOEToken, SyntaxKind::LTOEToken => SyntaxKind::LTOEToken, SyntaxKind::EqualToken => SyntaxKind::EqualToken, SyntaxKind::PrintToken => SyntaxKind::PrintToken, SyntaxKind::ScanToken => SyntaxKind::ScanToken, SyntaxKind::ConditionToken => SyntaxKind::ConditionToken, SyntaxKind::LoopToken => SyntaxKind::LoopToken, SyntaxKind::FloatDefToken => SyntaxKind::FloatDefToken, SyntaxKind::IntegerDefToken => SyntaxKind::IntegerDefToken, SyntaxKind::CharacterDefToken => SyntaxKind::CharacterDefToken, _ => SyntaxKind::UnknownToken, } } }
// origin: FreeBSD /usr/src/lib/msun/src/s_cos.c */ // // ==================================================== // Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. // // Developed at SunPro, a Sun Microsystems, Inc. business. // Permission to use, copy, modify, and distribute this // software is freely granted, provided that this notice // is preserved. // ==================================================== use super::{k_cos, k_sin, rem_pio2}; // cos(x) // Return cosine function of x. // // kernel function: // k_sin ... sine function on [-pi/4,pi/4] // k_cos ... cosine function on [-pi/4,pi/4] // rem_pio2 ... argument reduction routine // // Method. // Let S,C and T denote the sin, cos and tan respectively on // [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 // in [-pi/4 , +pi/4], and let n = k mod 4. // We have // // n sin(x) cos(x) tan(x) // ---------------------------------------------------------- // 0 S C T // 1 C -S -1/T // 2 -S -C T // 3 -C S -1/T // ---------------------------------------------------------- // // Special cases: // Let trig be any of sin, cos, or tan. // trig(+-INF) is NaN, with signals; // trig(NaN) is that NaN; // // Accuracy: // TRIG(x) returns trig(x) nearly rounded // #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn cos(x: f64) -> f64 { let ix = (f64::to_bits(x) >> 32) as u32 & 0x7fffffff; /* |x| ~< pi/4 */ if ix <= 0x3fe921fb { if ix < 0x3e46a09e { /* if x < 2**-27 * sqrt(2) */ /* raise inexact if x != 0 */ if x as i32 == 0 { return 1.0; } } return k_cos(x, 0.0); } /* cos(Inf or NaN) is NaN */ if ix >= 0x7ff00000 { return x - x; } /* argument reduction needed */ let (n, y0, y1) = rem_pio2(x); match n & 3 { 0 => k_cos(y0, y1), 1 => -k_sin(y0, y1, 1), 2 => -k_cos(y0, y1), _ => k_sin(y0, y1, 1), } }
pub mod utils; pub mod ftp;
use join::Join; use proconio::input; fn main() { input! { n: usize, }; let mut s = vec![]; for i in 1..=n { let mut t = Vec::new(); t.extend(s.clone()); t.push(i); t.extend(s); s = t; } println!("{}", s.iter().join(" ")); }
use crate::misc::RawSend; use crate::parker::Parker; use crate::tag::{with_tag, Tag}; use crate::worker::{Entry, Shared}; use std::future::Future; use std::pin::Pin; use std::ptr; use std::task::{Context, Poll, Waker}; pub(super) struct WaitFuture<'a, F> where F: Future, { /// The future being polled. pub(super) future: ptr::NonNull<F>, /// Where to store output. pub(super) output: ptr::NonNull<Option<F::Output>>, pub(super) parker: ptr::NonNull<Parker>, pub(super) complete: bool, pub(super) shared: &'a Shared, } impl<'a, F> Future for WaitFuture<'a, F> where F: Future, { type Output = F::Output; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { unsafe { let this = Pin::get_unchecked_mut(self.as_mut()); if this.complete { panic!("task already completed"); } let mut task = into_task( RawSend((&mut this.complete).into()), RawSend(this.future), RawSend(this.output), RawSend(cx.waker().into()), ); let entry = Entry::new(&mut task, this.parker); this.shared.schedule_in_place(this.parker, entry); if this.complete { panic!("background thread panicked"); } if let Some(output) = this.output.as_mut().take() { this.complete = true; Poll::Ready(output) } else { Poll::Pending } } } } unsafe impl<F> Send for WaitFuture<'_, F> where F: Future {} fn into_task<F>( mut complete: RawSend<bool>, mut future: RawSend<F>, mut output: RawSend<Option<F::Output>>, waker: RawSend<Waker>, ) -> impl FnMut(Tag) + Send where F: Future, { use std::panic; move |tag| { unsafe { // Safety: At this point, we know the waker has been // replaced by the polling task and can safely deref it into // the underlying waker. let waker = waker.0.as_ref(); let mut cx = Context::from_waker(waker); let future = Pin::new_unchecked(future.0.as_mut()); let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { if let Poll::Ready(ready) = with_tag(tag, || future.poll(&mut cx)) { *output.0.as_mut() = Some(ready); } })); if result.is_err() { *complete.0.as_mut() = true; } } } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::vec::Vec; use super::super::task::*; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::qlib::addr::*; use super::super::qlib::linux::time::*; use super::super::SignalDef::*; use super::super::syscalls::syscalls::*; use super::super::kernel::time::*; use super::super::kernel::timer::*; use super::super::kernel::waiter::*; use super::super::kernel::fd_table::*; use super::super::kernel::epoll::epoll::*; use super::super::kernel::epoll::epoll_entry::*; // CreateEpoll implements the epoll_create(2) linux syscall. pub fn CreateEpoll(task: &Task, closeOnExec: bool) -> Result<i64> { let file = NewEventPoll(task); let flags = FDFlags { CloseOnExec: closeOnExec, }; let fd = task.NewFDFrom(0, &file, &flags)?; return Ok(fd as i64); } // AddEpoll implements the epoll_ctl(2) linux syscall when op is EPOLL_CTL_ADD. pub fn AddEpoll(task: &Task, epfd: i32, fd: i32, flags: EntryFlags, mask: EventMask, userData: [i32; 2]) -> Result<()> { // Get epoll from the file descriptor. let epollfile = task.GetFile(epfd)?; // Get the target file id. let file = task.GetFile(fd)?; let inode = file.Dirent.Inode(); //the fd doesn't support epoll let inodeOp = inode.lock().InodeOp.clone(); if !inodeOp.WouldBlock() { //error!("AddEpoll 1.1 inodetype is {:?}, fopstype is {:?}", inode.InodeType(), fops.FopsType()); return Err(Error::SysError(SysErr::EINVAL)) } let fops = epollfile.FileOp.clone(); let ep = match fops.as_any().downcast_ref::<EventPoll>() { None => return Err(Error::SysError(SysErr::EBADF)), Some(ep) => ep, }; return ep.AddEntry(task, FileIdentifier { File: file.Downgrade(), Fd: fd, }, flags, mask, userData) } // UpdateEpoll implements the epoll_ctl(2) linux syscall when op is EPOLL_CTL_MOD. pub fn UpdateEpoll(task: &Task, epfd: i32, fd: i32, flags: EntryFlags, mask: EventMask, userData: [i32; 2]) -> Result<()> { // Get epoll from the file descriptor. let epollfile = task.GetFile(epfd)?; // Get the target file id. let file = task.GetFile(fd)?; /*let inode = file.Dirent.Inode(); //the fd doesn't support epoll let inodeOp = inode.lock().InodeOp.clone(); if !inodeOp.WouldBlock() { return Err(Error::SysError(SysErr::EINVAL)) }*/ let fops = epollfile.FileOp.clone(); let ep = match fops.as_any().downcast_ref::<EventPoll>() { None => return Err(Error::SysError(SysErr::EBADF)), Some(ep) => ep, }; return ep.UpdateEntry(task, &FileIdentifier { File: file.Downgrade(), Fd: fd, }, flags, mask, userData) } pub fn RemoveEpoll(task: &Task, epfd: i32, fd: i32) -> Result<()> { // Get epoll from the file descriptor. let epollfile = task.GetFile(epfd)?; // Get the target file id. let file = task.GetFile(fd)?; /*let inode = file.Dirent.Inode(); //the fd doesn't support epoll let inodeOp = inode.lock().InodeOp.clone(); if !inodeOp.WouldBlock() { return Err(Error::SysError(SysErr::EINVAL)) }*/ let fops = epollfile.FileOp.clone(); let ep = match fops.as_any().downcast_ref::<EventPoll>() { None => return Err(Error::SysError(SysErr::EBADF)), Some(ep) => ep, }; // Try to remove the entry. return ep.RemoveEntry(task, &FileIdentifier { File: file.Downgrade(), Fd: fd, }) } // WaitEpoll implements the epoll_wait(2) linux syscall. pub fn WaitEpoll(task: &Task, epfd: i32, max: i32, timeout: i32) -> Result<Vec<Event>> { // Get epoll from the file descriptor. let epollfile = task.GetFile(epfd)?; let fops = epollfile.FileOp.clone(); let ep = match fops.as_any().downcast_ref::<EventPoll>() { None => return Err(Error::SysError(SysErr::EBADF)), Some(ep) => ep, }; // Try to read events and return right away if we got them or if the // caller requested a non-blocking "wait". let r = ep.ReadEvents(task, max); if r.len() != 0 || timeout == 0 { return Ok(r) } // We'll have to wait. Set up the timer if a timeout was specified and // and register with the epoll object for readability events. let mut deadline = None; if timeout > 0 { let now = MonotonicNow(); deadline = Some(Time(now + timeout as i64 * MILLISECOND)); } let general = task.blocker.generalEntry.clone(); ep.EventRegister(task, &general, EVENT_READ); defer!(ep.EventUnregister(task, &general)); // Try to read the events again until we succeed, timeout or get // interrupted. loop { let r = ep.ReadEvents(task, max); if r.len() != 0 { return Ok(r) } //let start = super::super::asm::Rdtsc(); match task.blocker.BlockWithMonoTimer(true, deadline) { Err(Error::ErrInterrupted) => { return Err(Error::SysError(SysErr::EINTR)); } Err(e) => { return Err(e); } _ => () } //error!("WaitEpoll after block timeout is {}", timeout); } } // EpollCreate1 implements the epoll_create1(2) linux syscall. pub fn SysEpollCreate1(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let flags = args.arg0 as i32; if flags & !LibcConst::EPOLL_CLOEXEC as i32 != 0 { return Err(Error::SysError(SysErr::EINVAL)) } let closeOnExec = flags & LibcConst::EPOLL_CLOEXEC as i32 != 0; let fd = CreateEpoll(task, closeOnExec)?; return Ok(fd) } // EpollCreate implements the epoll_create(2) linux syscall. pub fn SysEpollCreate(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let size = args.arg0 as i32; if size <= 0 { return Err(Error::SysError(SysErr::EINVAL)) } let fd = CreateEpoll(task, false)?; return Ok(fd) } // EpollCtl implements the epoll_ctl(2) linux syscall. pub fn SysEpollCtl(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let epfd = args.arg0 as i32; let op = args.arg1 as i32; let fd = args.arg2 as i32; let eventAddr = args.arg3 as u64; // Capture the event state if needed. let mut flags = 0; let mut mask = 0; let mut data : [i32; 2] = [0, 0]; if op != LibcConst::EPOLL_CTL_DEL as i32 { let e : EpollEvent = task.CopyInObj(eventAddr)?; if e.Events & LibcConst::EPOLLONESHOT as u32 != 0 { flags |= ONE_SHOT; } if e.Events & (-LibcConst::EPOLLET) as u32 != 0 { flags |= EDGE_TRIGGERED; } mask = EventMaskFromLinux(e.Events); data[0] = e.FD; data[1] = e.Pad; } // Perform the requested operations. match op as u64 { LibcConst::EPOLL_CTL_ADD => { // See fs/eventpoll.c. mask |= EVENT_HUP | EVENT_ERR; AddEpoll(task, epfd, fd, flags, mask, data)?; return Ok(0) } LibcConst::EPOLL_CTL_DEL => { RemoveEpoll(task, epfd, fd)?; return Ok(0) } LibcConst::EPOLL_CTL_MOD => { // Same as EPOLL_CTL_ADD. UpdateEpoll(task, epfd, fd, flags, mask, data)?; return Ok(0) } _ => { return Err(Error::SysError(SysErr::EINVAL)) } } } // copyOutEvents copies epoll events from the kernel to user memory. pub fn CopyOutEvents(task: &Task, addr: u64, e: &[Event]) -> Result<()> { let itemLen : usize = 12; Addr(addr).AddLen((itemLen * e.len()) as u64)?; //error!("epool CopyOutEvents events is {:x?}", e); for i in 0..e.len() { /*let output : &mut Event = task.GetTypeMut(addr + (i * itemLen) as u64)?; output.Events = e[i].Events; output.Data[0] = e[i].Data[0]; output.Data[1] = e[i].Data[1];*/ task.CopyOutObj(&e[i], addr + (i * itemLen) as u64)?; } return Ok(()) } // EpollWait implements the epoll_wait(2) linux syscall. pub fn SysEpollWait(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let epfd = args.arg0 as i32; let eventAddr = args.arg1 as u64; let maxEvents = args.arg2 as i32; let timeout = args.arg3 as i32; let r = match WaitEpoll(task, epfd, maxEvents, timeout) { Err(Error::SysError(SysErr::ETIMEDOUT)) => { return Ok(0) } Err(e) => { return Err(e) } Ok(r) => r, }; if r.len() != 0 { CopyOutEvents(task, eventAddr, &r)?; } return Ok(r.len() as i64) } // EpollPwait implements the epoll_pwait(2) linux syscall. pub fn SysPwait(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let maskAddr = args.arg4 as u64; let maskSize = args.arg5 as u32; if maskAddr != 0 { let mask = CopyInSigSet(task, maskAddr, maskSize as usize)?; let thread = task.Thread(); let oldmask = thread.SignalMask(); thread.SetSignalMask(mask); thread.SetSavedSignalMask(oldmask); } return SysEpollWait(task, args) }
#[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; mod db; mod ser; mod util; use std::{ error::Error, future::ready, io, sync::{Arc, Mutex}, }; use bytes::Bytes; use xitca_http::http::{ header::{HeaderValue, CONTENT_TYPE, SERVER}, Method, }; use xitca_web::{dev::fn_service, request::WebRequest, App, HttpServer}; use self::db::Client; use self::util::{ internal, json, json_response, not_found, plain_text, AppState, HandleResult, QueryParse, }; type State = AppState<Client>; #[tokio::main(flavor = "current_thread")] async fn main() -> io::Result<()> { let config = "postgres://benchmarkdbuser:benchmarkdbpass@tfb-database/hello_world"; let cores = core_affinity::get_core_ids().unwrap_or_else(Vec::new); let cores = Arc::new(Mutex::new(cores)); HttpServer::new(move || { App::with_async_state(move || async move { let client = db::create(config).await; AppState::new(client) }) .service(fn_service(handle)) }) .force_flat_buf() .max_request_headers::<8>() .on_worker_start(move || { if let Some(core) = cores.lock().unwrap().pop() { core_affinity::set_for_current(core); } ready(()) }) .bind("0.0.0.0:8080")? .run() .await } async fn handle(req: &mut WebRequest<'_, State>) -> HandleResult { let inner = req.request_mut(); match (inner.method(), inner.uri().path()) { (&Method::GET, "/plaintext") => plain_text(req), (&Method::GET, "/json") => json(req), (&Method::GET, "/db") => db(req).await, (&Method::GET, "/fortunes") => fortunes(req).await, (&Method::GET, "/queries") => queries(req).await, (&Method::GET, "/updates") => updates(req).await, _ => not_found(), } } async fn db(req: &mut WebRequest<'_, State>) -> HandleResult { match req.state().client().get_world().await { Ok(ref world) => json_response(req, world), Err(_) => internal(), } } async fn fortunes(req: &mut WebRequest<'_, State>) -> HandleResult { match _fortunes(req.state().client()).await { Ok(body) => { let mut res = req.as_response(body); res.headers_mut() .append(SERVER, HeaderValue::from_static("TFB")); res.headers_mut().append( CONTENT_TYPE, HeaderValue::from_static("text/html; charset=utf-8"), ); Ok(res) } Err(_) => internal(), } } async fn queries(req: &mut WebRequest<'_, State>) -> HandleResult { let num = req.request_mut().uri().query().parse_query(); match req.state().client().get_worlds(num).await { Ok(worlds) => json_response(req, worlds.as_slice()), Err(_) => internal(), } } async fn updates(req: &mut WebRequest<'_, State>) -> HandleResult { let num = req.request_mut().uri().query().parse_query(); match req.state().client().update(num).await { Ok(worlds) => json_response(req, worlds.as_slice()), Err(_) => internal(), } } #[inline] async fn _fortunes(client: &Client) -> Result<Bytes, Box<dyn Error>> { use sailfish::TemplateOnce; let fortunes = client.tell_fortune().await?.render_once()?; Ok(fortunes.into()) }
use std::time::Instant; use std::fs; use std::cmp::max; pub fn get_sids(rows: Vec<String>)->Vec<u16>{ let mut sids:Vec<u16>=vec![]; for row in rows { let r: String = row.get(0..7).unwrap().chars().map(|x| match x { 'B' => '1', 'F' => '0', _ => panic!("Not expecting that char") }).collect(); let c: String = row.get(7..10).unwrap().chars().map(|x| match x { 'R' => '1', 'L' => '0', _ => panic!("Not expecting that char") }).collect(); let row_number = u8::from_str_radix(&*r, 2).unwrap(); let col_number = u8::from_str_radix(&*c, 2).unwrap(); let sid = (row_number as u16) * 8 + (col_number as u16); sids.push(sid); } sids } fn part1(rows: Vec<String>) -> u16 { *get_sids(rows).iter().max().expect("at least one element") } pub fn part2(rows: Vec<String>) -> u16 { let sids=get_sids(rows); for i in 1..1023 { if !sids.contains(&(i as u16)) && sids.contains(&(i+1 as u16)) && sids.contains(&(i-1 as u16)){ return i; } } 0 } fn main() { let input = fs::read_to_string("input/test.txt") .expect("Something went wrong reading the file"); let lines = input.lines(); let mut rows: Vec<String> = vec![]; for line in lines { rows.push(line.parse::<String>().expect("Ouf that's not a string !")) } println!("Running part1"); let now = Instant::now(); println!("Found {}", part1(rows.clone())); println!("Took {}us", now.elapsed().as_micros()); println!("Running part2"); let now = Instant::now(); println!("Found {}", part2(rows.clone())); println!("Took {}us", now.elapsed().as_micros()); }
use actix_web::{http::StatusCode, FromRequest, HttpResponse, Json, Path, Query}; use bigneon_api::controllers::organizations; use bigneon_api::controllers::organizations::*; use bigneon_api::models::{Paging, PagingParameters, PathParameters, Payload, SortingDir}; use bigneon_db::models::*; use chrono::NaiveDateTime; use serde_json; use support; use support::database::TestDatabase; use support::test_request::TestRequest; use uuid::Uuid; pub fn index(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database .create_organization() .with_name("Organization 1".to_string()) .finish(); let organization2 = if ![Roles::User, Roles::Admin].contains(&role) { database.create_organization_with_user(&user, role == Roles::OrgOwner) } else { database.create_organization() }.with_name("Organization 2".to_string()) .finish(); let user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); // reload organization let organization = Organization::find(organization.id, &database.connection).unwrap(); let expected_organizations = if role != Roles::User { vec![organization.clone(), organization2] } else { Vec::new() }; let test_request = TestRequest::create_with_uri(&format!("/limits?")); let query_parameters = Query::<PagingParameters>::from_request(&test_request.request, &()).unwrap(); let response: HttpResponse = organizations::index((database.connection.into(), query_parameters, user)).into(); let body = support::unwrap_body_to_string(&response).unwrap(); let counter = expected_organizations.len() as u64; let wrapped_expected_orgs = Payload { data: expected_organizations, paging: Paging { page: 0, limit: counter, sort: "".to_string(), dir: SortingDir::None, total: counter, tags: Vec::new(), }, }; let expected_json = serde_json::to_string(&wrapped_expected_orgs).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); assert_eq!(body, expected_json); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let expected_json = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(body, expected_json); } } pub fn show(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); // reload organization let organization = Organization::find(organization.id, &database.connection).unwrap(); let organization_expected_json = serde_json::to_string(&organization).unwrap(); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::show((database.connection.into(), path, auth_user.clone())).into(); if !should_succeed { support::expects_unauthorized(&response); return; } assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); assert_eq!(body, organization_expected_json); } pub fn index_for_all_orgs(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let user2 = database.create_user().finish(); let organization = database .create_organization() .with_name("Organization 1".to_string()) .with_owner(&user) .finish(); let organization2 = database .create_organization() .with_name("Organization 2".to_string()) .with_owner(&user2) .finish(); let mut expected_organizations = vec![organization.clone(), organization2]; if role == Roles::OrgMember { let index = expected_organizations .iter() .position(|x| x.owner_user_id == user2.id) .unwrap(); expected_organizations.remove(index); } let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create_with_uri(&format!("/limits?")); let query_parameters = Query::<PagingParameters>::from_request(&test_request.request, &()).unwrap(); let response: HttpResponse = organizations::index_for_all_orgs(( database.connection.into(), query_parameters, auth_user, )).into(); let body = support::unwrap_body_to_string(&response).unwrap(); let counter = expected_organizations.len() as u64; let wrapped_expected_orgs = Payload { data: expected_organizations, paging: Paging { page: 0, limit: counter, sort: "".to_string(), dir: SortingDir::None, total: counter, tags: Vec::new(), }, }; let expected_json = serde_json::to_string(&wrapped_expected_orgs).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); assert_eq!(body, expected_json); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let expected_json = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(body, expected_json); } } pub fn create(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let name = "Organization Example"; let user = database.create_user().finish(); let auth_user = support::create_auth_user(role, None, &database); FeeSchedule::create( "Zero fees".to_string(), vec![NewFeeScheduleRange { min_price: 0, fee_in_cents: 0, }], ).commit(&*database.connection) .unwrap(); let json = Json(NewOrganizationRequest { owner_user_id: user.id, name: name.to_string(), event_fee_in_cents: None, address: None, city: None, state: None, postal_code: None, country: None, phone: None, }); let response: HttpResponse = organizations::create((database.connection.into(), json, auth_user)).into(); let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); let org: Organization = serde_json::from_str(&body).unwrap(); assert_eq!(org.name, name); } else { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); let temp_json = HttpResponse::Unauthorized().json(json!({"error": "Unauthorized"})); let organization_expected_json = support::unwrap_body_to_string(&temp_json).unwrap(); assert_eq!(body, organization_expected_json); } } pub fn update(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let new_name = "New Name"; let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let json = Json(OrganizationEditableAttributes { name: Some(new_name.to_string()), address: Some("address".to_string()), city: Some("city".to_string()), state: Some("state".to_string()), country: Some("country".to_string()), postal_code: Some("postal_code".to_string()), phone: Some("phone".to_string()), fee_schedule_id: None, event_fee_in_cents: Some(100), }); let response: HttpResponse = organizations::update((database.connection.into(), path, json, auth_user.clone())).into(); if !should_succeed { support::expects_unauthorized(&response); return; } assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); let updated_organization: Organization = serde_json::from_str(&body).unwrap(); assert_eq!(updated_organization.name, new_name); } pub fn remove_user(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let user2 = database.create_user().finish(); let user3 = database.create_user().finish(); let organization = database .create_organization() .with_user(&user2) .with_user(&user3) .finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create(); let json = Json(user3.id); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::remove_user((database.connection.into(), path, json, auth_user.clone())) .into(); let count = 1; let body = support::unwrap_body_to_string(&response).unwrap(); if should_test_succeed { assert_eq!(response.status(), StatusCode::OK); let removed_entries: usize = serde_json::from_str(&body).unwrap(); assert_eq!(removed_entries, count); } else { support::expects_unauthorized(&response); } } pub fn add_user(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let user2 = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create(); let json = Json(organizations::AddUserRequest { user_id: user2.id }); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::add_user((database.connection.into(), path, json, auth_user.clone())).into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); } else { support::expects_unauthorized(&response); } } pub fn add_venue(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create(); let name = "Venue"; let json = Json(NewVenue { name: name.to_string(), ..Default::default() }); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::add_venue((database.connection.into(), path, json, auth_user.clone())) .into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); let body = support::unwrap_body_to_string(&response).unwrap(); let venue: Venue = serde_json::from_str(&body).unwrap(); assert_eq!(venue.name, name); } else { support::expects_unauthorized(&response); } } pub fn add_artist(role: Roles, should_test_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create(); let name = "Artist Example"; let bio = "Bio"; let website_url = "http://www.example.com"; let json = Json(NewArtist { name: name.to_string(), bio: bio.to_string(), website_url: Some(website_url.to_string()), ..Default::default() }); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::add_artist((database.connection.into(), path, json, auth_user.clone())) .into(); if should_test_succeed { assert_eq!(response.status(), StatusCode::CREATED); let body = support::unwrap_body_to_string(&response).unwrap(); let artist: Artist = serde_json::from_str(&body).unwrap(); assert_eq!(artist.name, name); } else { support::expects_unauthorized(&response); } } pub fn update_owner(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let new_owner = database.create_user().finish(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); let test_request = TestRequest::create(); let update_owner_request = UpdateOwnerRequest { owner_user_id: new_owner.id, }; let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let json = Json(update_owner_request); let response: HttpResponse = organizations::update_owner((database.connection.into(), path, json, auth_user)).into(); if !should_succeed { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); return; } assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); let updated_organization: Organization = serde_json::from_str(&body).unwrap(); assert_eq!(updated_organization.owner_user_id, new_owner.id); } pub fn list_organization_members(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let user1 = database .create_user() .with_last_name("User1".into()) .finish(); let user2 = database .create_user() .with_last_name("User2".into()) .finish(); let organization = database.create_organization().with_user(&user2).finish(); let auth_user = support::create_auth_user_from_user(&user1, role, Some(&organization), &database); let mut organization_members = Vec::new(); if role != Roles::OrgOwner { organization_members.push(DisplayUser::from( organization.owner(&database.connection).unwrap(), )); } if Roles::Admin != role { organization_members.push(DisplayUser::from(user1.clone())); } organization_members.push(DisplayUser::from(user2.clone())); organization_members[0].is_org_owner = true; let count = organization_members.len(); let wrapped_expected_date = Payload { data: organization_members, paging: Paging { page: 0, limit: count as u64, sort: "".to_string(), dir: SortingDir::None, total: count as u64, tags: Vec::new(), }, }; let expected_json = serde_json::to_string(&wrapped_expected_date).unwrap(); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let test_request = TestRequest::create_with_uri(&format!("/limits?")); let query_parameters = Query::<PagingParameters>::from_request(&test_request.request, &()).unwrap(); let response: HttpResponse = organizations::list_organization_members(( database.connection.into(), path, query_parameters, auth_user.clone(), )).into(); if !should_succeed { support::expects_unauthorized(&response); return; } assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); assert_eq!(body, expected_json.to_string()); } pub fn show_fee_schedule(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let user = database.create_user().finish(); let fee_schedule = database.create_fee_schedule().finish(); let fee_schedule_ranges = fee_schedule.ranges(&database.connection); let organization = database .create_organization() .with_fee_schedule(&fee_schedule) .finish(); let auth_user = support::create_auth_user_from_user(&user, role, Some(&organization), &database); #[derive(Serialize)] struct FeeScheduleWithRanges { id: Uuid, name: String, version: i64, created_at: NaiveDateTime, ranges: Vec<FeeScheduleRange>, } let expected_data = FeeScheduleWithRanges { id: fee_schedule.id, name: fee_schedule.name, version: 0, created_at: fee_schedule.created_at, ranges: fee_schedule_ranges.unwrap(), }; let expected_json = serde_json::to_string(&expected_data).unwrap(); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::show_fee_schedule((database.connection.into(), path, auth_user.clone())) .into(); if !should_succeed { support::expects_unauthorized(&response); return; } assert_eq!(response.status(), StatusCode::OK); let body = support::unwrap_body_to_string(&response).unwrap(); assert_eq!(body, expected_json.to_string()); } pub fn add_fee_schedule(role: Roles, should_succeed: bool) { let database = TestDatabase::new(); let organization = database.create_organization().finish(); let auth_user = support::create_auth_user(role, Some(&organization), &database); let json = Json(NewFeeSchedule { name: "Fees".to_string(), ranges: vec![ NewFeeScheduleRange { min_price: 20, fee_in_cents: 10, }, NewFeeScheduleRange { min_price: 1000, fee_in_cents: 100, }, ], }); let test_request = TestRequest::create(); let mut path = Path::<PathParameters>::extract(&test_request.request).unwrap(); path.id = organization.id; let response: HttpResponse = organizations::add_fee_schedule((database.connection.into(), path, json, auth_user)).into(); if !should_succeed { assert_eq!(response.status(), StatusCode::UNAUTHORIZED); return; } assert_eq!(response.status(), StatusCode::CREATED); let body = support::unwrap_body_to_string(&response).unwrap(); let result: FeeScheduleWithRanges = serde_json::from_str(&body).unwrap(); assert_eq!(result.name, "Fees".to_string()); }
/* cargo run -p async-ssh2-lite-demo-smol --bin inspect_ssh_agent */ use std::io; #[cfg(not(unix))] use std::net::TcpListener; #[cfg(unix)] use std::os::unix::net::UnixListener; #[cfg(unix)] use tempfile::tempdir; use async_io::Async; use futures::executor::block_on; use async_ssh2_lite::AsyncAgent; fn main() -> io::Result<()> { block_on(run()) } async fn run() -> io::Result<()> { let stream = { cfg_if::cfg_if! { if #[cfg(unix)] { let dir = tempdir()?; let path = dir.path().join("ssh_agent"); Async::<UnixListener>::bind(&path)? } else { Async::<TcpListener>::bind(([127, 0, 0, 1], 0))? } } }; let mut agent = AsyncAgent::new(stream)?; agent.connect().await?; agent.list_identities().await?; for identity in agent.identities()? { println!("identity comment: {}", identity.comment()); } println!("done"); Ok(()) }
use super::moving_object::MovingObject; use super::config; use std::collections::HashMap; use piston::input::keyboard::Key; use std::rc::Rc; use std::cell::RefCell; use piston_window::rectangle; use graphics::*; use opengl_graphics::GlGraphics; use graphics::Context; use super::texture_loader::TextureLoader; use super::animation_manager::AnimationManager; use super::colors; use super::map::Map; pub struct Enemy { current_animator: String, animation_manager: AnimationManager, turned_back: bool, box_size_x: f64, box_size_y: f64 } impl Enemy { pub fn new(tex_loader: Rc<TextureLoader>, box_size_x: f64, box_size_y: f64) -> Enemy { let mut animation_manager = AnimationManager::new(tex_loader); animation_manager.add_sequence("idle".to_string(), "Enemy/idle", 0.1, 1, 9, [box_size_x, box_size_y]); Enemy { current_animator: "idle".to_string(), animation_manager: animation_manager, turned_back: false, box_size_x: box_size_x, box_size_y: box_size_y } } pub fn character_update(&mut self, delta: f64, map: &Map, moving_object: &mut MovingObject){ self.handle_stand(delta, moving_object); moving_object.update_physics(delta, &map); self.animation_manager.get_animator(self.current_animator.to_string()).next(delta); } fn handle_stand(&mut self, _delta: f64, moving_object: &mut MovingObject) { self.current_animator = "idle".to_string(); } pub fn render(&mut self, ctx: &Context, gl: &mut GlGraphics, moving_object: &mut MovingObject) { let mut color = colors::BLUE; let character_x = moving_object.position[0]; let character_y = moving_object.position[1]; let point_trans = ctx .transform .trans(character_x, character_y); // rectangle(color, [0.0, 0.0, self.box_size_x, self.box_size_y], point_trans, gl); self.animation_manager .get_animator(self.current_animator.to_string()) .render(ctx, gl, moving_object.position, self.turned_back) } }
extern crate vcpkg; fn main() { if cfg!(windows) && cfg!(target_env = "msvc") { vcpkg::find_package("sqlite3").unwrap(); } }
#[doc = "Reader of register FTSR2"] pub type R = crate::R<u32, super::FTSR2>; #[doc = "Writer for register FTSR2"] pub type W = crate::W<u32, super::FTSR2>; #[doc = "Register FTSR2 `reset()`'s with value 0"] impl crate::ResetValue for super::FTSR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Falling trigger event configuration bit of line 35\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FT35_A { #[doc = "0: Falling edge trigger is disabled"] DISABLED = 0, #[doc = "1: Falling edge trigger is enabled"] ENABLED = 1, } impl From<FT35_A> for bool { #[inline(always)] fn from(variant: FT35_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FT35`"] pub type FT35_R = crate::R<bool, FT35_A>; impl FT35_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FT35_A { match self.bits { false => FT35_A::DISABLED, true => FT35_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == FT35_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == FT35_A::ENABLED } } #[doc = "Write proxy for field `FT35`"] pub struct FT35_W<'a> { w: &'a mut W, } impl<'a> FT35_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FT35_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(FT35_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(FT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Falling trigger event configuration bit of line 36"] pub type FT36_A = FT35_A; #[doc = "Reader of field `FT36`"] pub type FT36_R = crate::R<bool, FT35_A>; #[doc = "Write proxy for field `FT36`"] pub struct FT36_W<'a> { w: &'a mut W, } impl<'a> FT36_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FT36_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(FT35_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(FT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Falling trigger event configuration bit of line 37"] pub type FT37_A = FT35_A; #[doc = "Reader of field `FT37`"] pub type FT37_R = crate::R<bool, FT35_A>; #[doc = "Write proxy for field `FT37`"] pub struct FT37_W<'a> { w: &'a mut W, } impl<'a> FT37_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FT37_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(FT35_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(FT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Falling trigger event configuration bit of line 38"] pub type FT38_A = FT35_A; #[doc = "Reader of field `FT38`"] pub type FT38_R = crate::R<bool, FT35_A>; #[doc = "Write proxy for field `FT38`"] pub struct FT38_W<'a> { w: &'a mut W, } impl<'a> FT38_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FT38_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Falling edge trigger is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(FT35_A::DISABLED) } #[doc = "Falling edge trigger is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(FT35_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } impl R { #[doc = "Bit 3 - Falling trigger event configuration bit of line 35"] #[inline(always)] pub fn ft35(&self) -> FT35_R { FT35_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Falling trigger event configuration bit of line 36"] #[inline(always)] pub fn ft36(&self) -> FT36_R { FT36_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Falling trigger event configuration bit of line 37"] #[inline(always)] pub fn ft37(&self) -> FT37_R { FT37_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Falling trigger event configuration bit of line 38"] #[inline(always)] pub fn ft38(&self) -> FT38_R { FT38_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 3 - Falling trigger event configuration bit of line 35"] #[inline(always)] pub fn ft35(&mut self) -> FT35_W { FT35_W { w: self } } #[doc = "Bit 4 - Falling trigger event configuration bit of line 36"] #[inline(always)] pub fn ft36(&mut self) -> FT36_W { FT36_W { w: self } } #[doc = "Bit 5 - Falling trigger event configuration bit of line 37"] #[inline(always)] pub fn ft37(&mut self) -> FT37_W { FT37_W { w: self } } #[doc = "Bit 6 - Falling trigger event configuration bit of line 38"] #[inline(always)] pub fn ft38(&mut self) -> FT38_W { FT38_W { w: self } } }
// Copyright 2012-2014 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. // run-pass // aux-build:issue13507.rs extern crate issue13507; use issue13507::testtypes; use std::any::TypeId; pub fn type_ids() -> Vec<TypeId> { use issue13507::testtypes::*; vec![ TypeId::of::<FooBool>(), TypeId::of::<FooInt>(), TypeId::of::<FooUint>(), TypeId::of::<FooFloat>(), TypeId::of::<FooStr>(), TypeId::of::<FooArray>(), TypeId::of::<FooSlice>(), TypeId::of::<FooBox>(), TypeId::of::<FooPtr>(), TypeId::of::<FooRef>(), TypeId::of::<FooFnPtr>(), TypeId::of::<FooNil>(), TypeId::of::<FooTuple>(), TypeId::of::<FooTrait>(), TypeId::of::<FooStruct>(), TypeId::of::<FooEnum>() ] } pub fn main() { let othercrate = issue13507::testtypes::type_ids(); let thiscrate = type_ids(); assert_eq!(thiscrate, othercrate); }
fn main() { println!("cargo:rerun-if-changed=bootil"); println!("cargo:rerun-if-changed=build.rs"); // Build Bootil LZMA cc::Build::new() .file("bootil/src/3rdParty/lzma/LzFind.c") .file("bootil/src/3rdParty/lzma/LzmaLib.c") .file("bootil/src/3rdParty/lzma/LzmaDec.c") .file("bootil/src/3rdParty/lzma/LzmaEnc.c") .file("bootil/src/3rdParty/lzma/Alloc.c") .compile("lzma"); }
use proconio::{input, marker::Bytes}; fn main() { input!(h:usize, w:usize, k:usize, c:[Bytes; h]); println!("h={:?}", h); println!("1<<h={:?}", 1<<h); println!("{:?}", w); println!("{:?}", k); println!("{:?}", c); let mut r = 0; for a in 0..1<<h{ for b in 0..1<<w{ let mut v=0; println!("a={:?}", a); println!("b={:?}", b); println!() } }; }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::Mutex; use alloc::vec::Vec; use super::super::super::super::qlib::common::*; use super::super::super::super::qlib::linux_def::*; use super::super::super::super::qlib::auth::*; use super::super::super::super::memmgr::mm::*; use super::super::super::fsutil::file::readonly_file::*; use super::super::super::fsutil::inode::simple_file_inode::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::file::*; use super::super::super::flags::*; use super::super::super::dirent::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::super::threadmgr::thread::*; use super::super::inode::*; pub fn NewStatm(task: &Task, thread: &Thread, msrc: &Arc<Mutex<MountSource>>) -> Inode { let v = NewStatmSimpleFileInode(task, thread, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o400)), FSMagic::PROC_SUPER_MAGIC); return NewProcInode(&Arc::new(v), msrc, InodeType::SpecialFile, Some(thread.clone())) } pub fn NewStatmSimpleFileInode(task: &Task, thread: &Thread, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> SimpleFileInode<StatmData> { let io = StatmData{mm: thread.lock().memoryMgr.clone()}; return SimpleFileInode::New(task, owner, perms, typ, false, io) } pub struct StatmData { mm: MemoryManager, } impl StatmData { pub fn GenSnapshot(&self, task: &Task,) -> Vec<u8> { return self.mm.GenStatmSnapshot(task) } } impl SimpleFileTrait for StatmData { fn GetFile(&self, task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { let fops = NewSnapshotReadonlyFileOperations(self.GenSnapshot(task)); let file = File::New(dirent, &flags, fops); return Ok(file); } }
/// This is a template for ./main/main.cpp pub fn main_cpp(name: &str) -> String { format!("#include <iostream>\n#include \"{}.h\"\n#include \"lib/proconlib.h\"\n#include <vector>\n#include <algorithm>\n// using namespace std;\n\nint main() {{\n std::cout << \"Hello, world\" << std::endl;\n return 0;\n}}\n", &name) } /// This is a template for ./main/BUILD pub fn build_main(name: String) -> String { format!( "cc_library (\n name = \"{}\",\n srcs = [\"{}.cpp\"],\n hdrs = [\"{}.h\"],\n)\n\ncc_binary (\n name = \"main\",\n srcs = [\"main.cpp\"],\n deps = [\n \":{}\",\n \"//lib:proconlib\",\n ],\n)\n", &name, &name, &name, name ) } /// This is a template for ./lib/BUILD pub fn build_lib() -> String { "cc_library (\n name = \"proconlib\",\n srcs = [\"proconlib.cpp\"],\n hdrs = [\"proconlib.h\"],\n visibility = [\"//main:__pkg__\"],\n)\n".to_string() } /// This is a template for ./WORKSPACE pub fn workspace() -> String { "\n".to_string() } /// This is a template for ./.gitignore pub fn git_ignore() -> String { "/bazel-*\n".to_string() } pub fn config(name: &String) -> String { format!("{}", name) } pub fn name_cpp() -> String { "// Let's start coding!\n// Coder: DenTaku\n\nvoid somefunc() {\n //\n}\n".to_string() } pub fn name_h() -> String { "// write signiture as prototype declaration.\n\nvoid somefunc();\n".to_string() } pub fn proconlib_cpp() -> String { "// for libraries ...\n// I'll add codes in the future...\n\nvoid somelib() {\n //\n}\n" .to_string() } pub fn proconlib_h() -> String { "// prototype declarations will be written here...\n\nvoid somelib();\n".to_string() }
//! Heru Handika //! 31 October 2020 //! Range and Summary use std::iter::Iterator; // For sum function struct Range<T> { min: T, max: T, } fn main() { let vec: Vec<f64> = vec![10.0, 20.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0]; print_vector(&vec); let values = range_value(&vec); println!("Value range: {}-{}", values.min, values.max); println!("Mean: {}", mean_vec(&vec)); } fn print_vector(vec: &Vec<f64>) { print!("Vector values: "); for &i in vec { print!("{} ",i); } println!(); } fn min_vector(vec: &Vec<f64>) -> f64 { let mut min = vec[0]; for &value in vec.iter() { if value < min { min = value; } } min } fn max_vector(vec: &Vec<f64>) -> f64 { let mut max = vec[0]; for &value in vec.iter() { if value > max { max = value; } } max } fn range_value(vec: &Vec<f64>) -> Range<f64> { let values = Range{min: min_vector(&vec), max: max_vector(&vec)}; values } // Using iterator for sum. Functional style. // More compact, but not sure about performance. // For loop implementation for sum is available // in 0_vectors/vector.rs fn mean_vec(vec: &Vec<f64>) -> f64 { let sum: f64 = Iterator::sum(vec.iter()); let mean = sum / vec.len() as f64; mean }