text
stringlengths
8
4.13M
pub mod filesystem; pub mod prelude; use crate::core::Client; use azure_core::No; pub trait Filesystem<C> where C: Client, { fn create_filesystem<'a>(&'a self) -> filesystem::requests::CreateFilesystemBuilder<'a, C, No>; fn delete_filesystem<'a>(&'a self) -> filesystem::requests::DeleteFilesystemBuilder<'a, C, No>; fn get_filesystem_properties<'a>( &'a self, ) -> filesystem::requests::GetFilesystemPropertiesBuilder<'a, C, No>; fn list_filesystems<'a>(&'a self) -> filesystem::requests::ListFilesystemsBuilder<'a, C>; fn set_filesystem_properties<'a>( &'a self, ) -> filesystem::requests::SetFilesystemPropertiesBuilder<'a, C, No>; } impl<C> Filesystem<C> for C where C: Client, { fn create_filesystem<'a>(&'a self) -> filesystem::requests::CreateFilesystemBuilder<'a, C, No> { filesystem::requests::CreateFilesystemBuilder::new(self) } fn delete_filesystem<'a>(&'a self) -> filesystem::requests::DeleteFilesystemBuilder<'a, C, No> { filesystem::requests::DeleteFilesystemBuilder::new(self) } fn get_filesystem_properties<'a>( &'a self, ) -> filesystem::requests::GetFilesystemPropertiesBuilder<'a, C, No> { filesystem::requests::GetFilesystemPropertiesBuilder::new(self) } fn list_filesystems<'a>(&'a self) -> filesystem::requests::ListFilesystemsBuilder<'a, C> { filesystem::requests::ListFilesystemsBuilder::new(self) } fn set_filesystem_properties<'a>( &'a self, ) -> filesystem::requests::SetFilesystemPropertiesBuilder<'a, C, No> { filesystem::requests::SetFilesystemPropertiesBuilder::new(self) } }
use crate::{ client::Binance, error::Error, model::{ AccountInformation, AssetDetail, Balance, DepositAddressData, DepositHistory, Order, OrderCanceled, TradeHistory, Transaction, }, }; use chrono::prelude::*; use failure::Fallible; use futures::prelude::*; use serde_json::json; use std::collections::HashMap; use crate::model::OrderRequest; const ORDER_TYPE_LIMIT: &str = "LIMIT"; const ORDER_TYPE_MARKET: &str = "MARKET"; const ORDER_SIDE_BUY: &str = "BUY"; const ORDER_SIDE_SELL: &str = "SELL"; const TIME_IN_FORCE_GTC: &str = "GTC"; const API_V3_ORDER: &str = "/api/v3/order"; impl Binance { // Account Information pub fn get_account(&self) -> Fallible<impl Future<Output = Fallible<AccountInformation>>> { let account_info = self .transport .signed_get::<_, ()>("/api/v3/account", None)?; Ok(account_info) } // Balance for ONE Asset pub fn get_balance(&self, asset: &str) -> Fallible<impl Future<Output = Fallible<Balance>>> { let asset = asset.to_string(); let search = move |account: AccountInformation| { let balance = account .balances .into_iter() .find(|balance| balance.asset == asset); future::ready(balance.ok_or_else(|| Error::AssetsNotFound.into())) }; let balance = self.get_account()?.and_then(search); Ok(balance) } // Current open orders for ONE symbol pub fn get_open_orders( &self, symbol: &str, ) -> Fallible<impl Future<Output = Fallible<Vec<Order>>>> { let params = json! {{"symbol": symbol}}; let orders = self .transport .signed_get("/api/v3/openOrders", Some(params))?; Ok(orders) } // All current open orders pub fn get_all_open_orders(&self) -> Fallible<impl Future<Output = Fallible<Vec<Order>>>> { let orders = self .transport .signed_get::<_, ()>("/api/v3/openOrders", None)?; Ok(orders) } // Check an order's status pub fn order_status( &self, symbol: &str, order_id: u64, ) -> Fallible<impl Future<Output = Fallible<Order>>> { let params = json! {{"symbol": symbol, "orderId": order_id}}; let order = self.transport.signed_get(API_V3_ORDER, Some(params))?; Ok(order) } /* // Place a LIMIT order - BUY pub fn limit_buy( &self, symbol: &str, qty: f64, price: f64, ) -> Fallible<impl Future<Output = Fallible<Transaction>>> { let order = OrderRequest { symbol: symbol.into(), qty, price, order_side: ORDER_SIDE_BUY.to_string(), order_type: ORDER_TYPE_LIMIT.to_string(), time_in_force: TIME_IN_FORCE_GTC.to_string(), }; let params = Self::build_order(order); let transaction = self.transport.signed_post(API_V3_ORDER, Some(params))?; Ok(transaction) } // Place a LIMIT order - SELL pub fn limit_sell( &self, symbol: &str, qty: f64, price: f64, ) -> Fallible<impl Future<Output = Fallible<Transaction>>> { let order = OrderRequest { symbol: symbol.into(), qty, price, order_side: ORDER_SIDE_SELL.to_string(), order_type: ORDER_TYPE_LIMIT.to_string(), time_in_force: TIME_IN_FORCE_GTC.to_string(), }; let params = Self::build_order(order); let transaction = self.transport.signed_post(API_V3_ORDER, Some(params))?; Ok(transaction) } // Place a MARKET order - BUY pub fn market_buy( &self, symbol: &str, qty: f64, ) -> Fallible<impl Future<Output = Fallible<Transaction>>> { let order = OrderRequest { symbol: symbol.into(), qty, price: 0.0, order_side: ORDER_SIDE_BUY.to_string(), order_type: ORDER_TYPE_MARKET.to_string(), time_in_force: TIME_IN_FORCE_GTC.to_string(), }; let params = Self::build_order(order); let transaction = self.transport.signed_post(API_V3_ORDER, Some(params))?; Ok(transaction) } // Place a MARKET order - SELL pub fn market_sell( &self, symbol: &str, qty: f64, ) -> Fallible<impl Future<Output = Fallible<Transaction>>> { let order = OrderRequest { symbol: symbol.into(), qty, price: 0.0, order_side: ORDER_SIDE_SELL.to_string(), order_type: ORDER_TYPE_MARKET.to_string(), time_in_force: TIME_IN_FORCE_GTC.to_string(), }; let params = Self::build_order(order); let transaction = self.transport.signed_post(API_V3_ORDER, Some(params))?; Ok(transaction) } */ // Check an order's status pub fn cancel_order( &self, symbol: &str, order_id: u64, ) -> Fallible<impl Future<Output = Fallible<OrderCanceled>>> { let params = json! {{"symbol":symbol, "orderId":order_id}}; let order_canceled = self.transport.signed_delete(API_V3_ORDER, Some(params))?; Ok(order_canceled) } // Trade history pub fn trade_history( &self, symbol: &str, ) -> Fallible<impl Future<Output = Fallible<Vec<TradeHistory>>>> { let params = json! {{"symbol":symbol}}; let trade_history = self .transport .signed_get("/api/v3/myTrades", Some(params))?; Ok(trade_history) } pub fn get_deposit_address( &self, symbol: &str, ) -> Fallible<impl Future<Output = Fallible<DepositAddressData>>> { let params = json! {{"asset":symbol}}; let deposit_address = self .transport .signed_get("/wapi/v3/depositAddress.html", Some(params))?; Ok(deposit_address) } pub fn get_deposit_history( &self, symbol: Option<&str>, start_time: Option<DateTime<Utc>>, end_time: Option<DateTime<Utc>>, ) -> Fallible<impl Future<Output = Fallible<DepositHistory>>> { let params = json! {{"asset":symbol, "startTime":start_time.map(|t| t.timestamp_millis()), "endTime":end_time.map(|t| t.timestamp_millis())}}; let deposit_history = self .transport .signed_get("/wapi/v3/depositHistory.html", Some(params))?; Ok(deposit_history) } pub fn asset_detail(&self) -> Fallible<impl Future<Output = Fallible<AssetDetail>>> { let asset_detail = self .transport .signed_get::<_, ()>("/wapi/v3/assetDetail.html", None)?; Ok(asset_detail) } fn build_order(order: OrderRequest) -> HashMap<&'static str, String> { let mut params: HashMap<&str, String> = maplit::hashmap! { "symbol" => order.symbol, "side" => order.order_side.to_string(), "type" => order.order_type, "quantity" => order.qty.to_string(), }; if order.price != 0.0 { params.insert("price", order.price.to_string()); params.insert("timeInForce", order.time_in_force.to_string()); } params } }
// #![feature(plugin, custom_derive)] // #![feature(proc_macro_hygiene, decl_macro)] should I use this new api? #![feature(proc_macro_hygiene, decl_macro, plugin, custom_derive)] #![plugin(rocket_codegen)] #[macro_use] // rocket application for query string in the next version extern crate rocket; extern crate rocket_contrib; // custom extern crate sl_lib; // database extern crate diesel; // template use hash map instead? test later extern crate tera; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; // environment variable and api etc extern crate dotenv; // HTTP extern crate reqwest; // regex for path and others // extern crate regex; // #[macro_use] // extern crate lazy_static; // lib file use sl_lib::*; mod route; use route::{ static_files, get, posts, error}; mod web_service; use web_service::{video, vlog}; // use web_service::video::{ count }; // #[cfg(test)] // mod tests; // Write your own module // Template use rocket_contrib::Template; // application fn rocket() -> rocket::Rocket { rocket::ignite() .manage(sl_lib::init_pool()) .attach(Template::fairing()) .mount( "/", routes![ static_files::file, posts::read_post::read, posts::show_posts::index, posts::show_posts::from_search, get::index, get::home, get::about, get::video, get::videos, get::code, get::markdown, get::jsx, get::web, video::count, // search and search_without_chnnael should be integrated with new rocket api and search query video::search, video::search_without_channel, video::search_by_id, vlog::read, ], ) .catch(catchers![error::not_found]) } fn main() { rocket().launch(); }
/// # Safety /// Unsafe method which casts immutable reference to mutable reference without any checks. #[allow(clippy::mut_from_ref)] pub unsafe fn as_mut<T>(reference: &T) -> &mut T { let const_ptr = reference as *const T; let mut_ptr = const_ptr as *mut T; &mut *mut_ptr }
// Copyright 2017-2021 Parity Technologies // // 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. //! Derives serialization and deserialization codec for complex structs for simple marshalling. #![recursion_limit = "128"] extern crate proc_macro; #[macro_use] extern crate syn; #[macro_use] extern crate quote; use crate::utils::{codec_crate_path, is_lint_attribute}; use syn::{spanned::Spanned, Data, DeriveInput, Error, Field, Fields}; mod decode; mod encode; mod max_encoded_len; mod trait_bounds; mod utils; /// Wraps the impl block in a "dummy const" fn wrap_with_dummy_const( input: DeriveInput, impl_block: proc_macro2::TokenStream, ) -> proc_macro::TokenStream { let attrs = input.attrs.into_iter().filter(is_lint_attribute); let generated = quote! { #[allow(deprecated)] const _: () = { #(#attrs)* #impl_block }; }; generated.into() } /// Derive `parity_scale_codec::Encode` and `parity_scale_codec::EncodeLike` for struct and enum. /// /// # Top level attributes /// /// By default the macro will add [`Encode`] and [`Decode`] bounds to all types, but the bounds can /// be specified manually with the top level attributes: /// * `#[codec(encode_bound(T: Encode))]`: a custom bound added to the `where`-clause when deriving /// the `Encode` trait, overriding the default. /// * `#[codec(decode_bound(T: Decode))]`: a custom bound added to the `where`-clause when deriving /// the `Decode` trait, overriding the default. /// /// # Struct /// /// A struct is encoded by encoding each of its fields successively. /// /// Fields can have some attributes: /// * `#[codec(skip)]`: the field is not encoded. It must derive `Default` if Decode is derived. /// * `#[codec(compact)]`: the field is encoded in its compact representation i.e. the field must /// implement `parity_scale_codec::HasCompact` and will be encoded as `HasCompact::Type`. /// * `#[codec(encoded_as = "$EncodeAs")]`: the field is encoded as an alternative type. $EncodedAs /// type must implement `parity_scale_codec::EncodeAsRef<'_, $FieldType>` with $FieldType the type /// of the field with the attribute. This is intended to be used for types implementing /// `HasCompact` as shown in the example. /// /// ``` /// # use parity_scale_codec_derive::Encode; /// # use parity_scale_codec::{Encode as _, HasCompact}; /// #[derive(Encode)] /// struct StructType { /// #[codec(skip)] /// a: u32, /// #[codec(compact)] /// b: u32, /// #[codec(encoded_as = "<u32 as HasCompact>::Type")] /// c: u32, /// } /// ``` /// /// # Enum /// /// The variable is encoded with one byte for the variant and then the variant struct encoding. /// The variant number is: /// * if variant has attribute: `#[codec(index = "$n")]` then n /// * else if variant has discriminant (like 3 in `enum T { A = 3 }`) then the discriminant. /// * else its position in the variant set, excluding skipped variants, but including variant with /// discriminant or attribute. Warning this position does collision with discriminant or attribute /// index. /// /// variant attributes: /// * `#[codec(skip)]`: the variant is not encoded. /// * `#[codec(index = "$n")]`: override variant index. /// /// field attributes: same as struct fields attributes. /// /// ``` /// # use parity_scale_codec_derive::Encode; /// # use parity_scale_codec::Encode as _; /// #[derive(Encode)] /// enum EnumType { /// #[codec(index = 15)] /// A, /// #[codec(skip)] /// B, /// C = 3, /// D, /// } /// /// assert_eq!(EnumType::A.encode(), vec![15]); /// assert_eq!(EnumType::B.encode(), vec![]); /// assert_eq!(EnumType::C.encode(), vec![3]); /// assert_eq!(EnumType::D.encode(), vec![2]); /// ``` #[proc_macro_derive(Encode, attributes(codec))] pub fn encode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut input: DeriveInput = match syn::parse(input) { Ok(input) => input, Err(e) => return e.to_compile_error().into(), }; if let Err(e) = utils::check_attributes(&input) { return e.to_compile_error().into() } let crate_path = match codec_crate_path(&input.attrs) { Ok(crate_path) => crate_path, Err(error) => return error.into_compile_error().into(), }; if let Err(e) = trait_bounds::add( &input.ident, &mut input.generics, &input.data, utils::custom_encode_trait_bound(&input.attrs), parse_quote!(#crate_path::Encode), None, utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { return e.to_compile_error().into() } let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let encode_impl = encode::quote(&input.data, name, &crate_path); let impl_block = quote! { #[automatically_derived] impl #impl_generics #crate_path::Encode for #name #ty_generics #where_clause { #encode_impl } #[automatically_derived] impl #impl_generics #crate_path::EncodeLike for #name #ty_generics #where_clause {} }; wrap_with_dummy_const(input, impl_block) } /// Derive `parity_scale_codec::Decode` and for struct and enum. /// /// see derive `Encode` documentation. #[proc_macro_derive(Decode, attributes(codec))] pub fn decode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut input: DeriveInput = match syn::parse(input) { Ok(input) => input, Err(e) => return e.to_compile_error().into(), }; if let Err(e) = utils::check_attributes(&input) { return e.to_compile_error().into() } let crate_path = match codec_crate_path(&input.attrs) { Ok(crate_path) => crate_path, Err(error) => return error.into_compile_error().into(), }; if let Err(e) = trait_bounds::add( &input.ident, &mut input.generics, &input.data, utils::custom_decode_trait_bound(&input.attrs), parse_quote!(#crate_path::Decode), Some(parse_quote!(Default)), utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { return e.to_compile_error().into() } let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let ty_gen_turbofish = ty_generics.as_turbofish(); let input_ = quote!(__codec_input_edqy); let decoding = decode::quote(&input.data, name, &quote!(#ty_gen_turbofish), &input_, &crate_path); let decode_into_body = decode::quote_decode_into( &input.data, &crate_path, &input_, &input.attrs ); let impl_decode_into = if let Some(body) = decode_into_body { quote! { fn decode_into<__CodecInputEdqy: #crate_path::Input>( #input_: &mut __CodecInputEdqy, dst_: &mut ::core::mem::MaybeUninit<Self>, ) -> ::core::result::Result<#crate_path::DecodeFinished, #crate_path::Error> { #body } } } else { quote! {} }; let impl_block = quote! { #[automatically_derived] impl #impl_generics #crate_path::Decode for #name #ty_generics #where_clause { fn decode<__CodecInputEdqy: #crate_path::Input>( #input_: &mut __CodecInputEdqy ) -> ::core::result::Result<Self, #crate_path::Error> { #decoding } #impl_decode_into } }; wrap_with_dummy_const(input, impl_block) } /// Derive `parity_scale_codec::Compact` and `parity_scale_codec::CompactAs` for struct with single /// field. /// /// Attribute skip can be used to skip other fields. /// /// # Example /// /// ``` /// # use parity_scale_codec_derive::CompactAs; /// # use parity_scale_codec::{Encode, HasCompact}; /// # use std::marker::PhantomData; /// #[derive(CompactAs)] /// struct MyWrapper<T>(u32, #[codec(skip)] PhantomData<T>); /// ``` #[proc_macro_derive(CompactAs, attributes(codec))] pub fn compact_as_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut input: DeriveInput = match syn::parse(input) { Ok(input) => input, Err(e) => return e.to_compile_error().into(), }; if let Err(e) = utils::check_attributes(&input) { return e.to_compile_error().into() } let crate_path = match codec_crate_path(&input.attrs) { Ok(crate_path) => crate_path, Err(error) => return error.into_compile_error().into(), }; if let Err(e) = trait_bounds::add::<()>( &input.ident, &mut input.generics, &input.data, None, parse_quote!(#crate_path::CompactAs), None, utils::has_dumb_trait_bound(&input.attrs), &crate_path, ) { return e.to_compile_error().into() } let name = &input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); fn val_or_default(field: &Field) -> proc_macro2::TokenStream { let skip = utils::should_skip(&field.attrs); if skip { quote_spanned!(field.span()=> Default::default()) } else { quote_spanned!(field.span()=> x) } } let (inner_ty, inner_field, constructor) = match input.data { Data::Struct(ref data) => match data.fields { Fields::Named(ref fields) if utils::filter_skip_named(fields).count() == 1 => { let recurse = fields.named.iter().map(|f| { let name_ident = &f.ident; let val_or_default = val_or_default(f); quote_spanned!(f.span()=> #name_ident: #val_or_default) }); let field = utils::filter_skip_named(fields).next().expect("Exactly one field"); let field_name = &field.ident; let constructor = quote!( #name { #( #recurse, )* }); (&field.ty, quote!(&self.#field_name), constructor) }, Fields::Unnamed(ref fields) if utils::filter_skip_unnamed(fields).count() == 1 => { let recurse = fields.unnamed.iter().enumerate().map(|(_, f)| { let val_or_default = val_or_default(f); quote_spanned!(f.span()=> #val_or_default) }); let (id, field) = utils::filter_skip_unnamed(fields).next().expect("Exactly one field"); let id = syn::Index::from(id); let constructor = quote!( #name(#( #recurse, )*)); (&field.ty, quote!(&self.#id), constructor) }, _ => return Error::new( data.fields.span(), "Only structs with a single non-skipped field can derive CompactAs", ) .to_compile_error() .into(), }, Data::Enum(syn::DataEnum { enum_token: syn::token::Enum { span }, .. }) | Data::Union(syn::DataUnion { union_token: syn::token::Union { span }, .. }) => return Error::new(span, "Only structs can derive CompactAs").to_compile_error().into(), }; let impl_block = quote! { #[automatically_derived] impl #impl_generics #crate_path::CompactAs for #name #ty_generics #where_clause { type As = #inner_ty; fn encode_as(&self) -> &#inner_ty { #inner_field } fn decode_from(x: #inner_ty) -> ::core::result::Result<#name #ty_generics, #crate_path::Error> { ::core::result::Result::Ok(#constructor) } } #[automatically_derived] impl #impl_generics From<#crate_path::Compact<#name #ty_generics>> for #name #ty_generics #where_clause { fn from(x: #crate_path::Compact<#name #ty_generics>) -> #name #ty_generics { x.0 } } }; wrap_with_dummy_const(input, impl_block) } /// Derive `parity_scale_codec::MaxEncodedLen` for struct and enum. /// /// # Top level attribute /// /// By default the macro will try to bound the types needed to implement `MaxEncodedLen`, but the /// bounds can be specified manually with the top level attribute: /// ``` /// # use parity_scale_codec_derive::Encode; /// # use parity_scale_codec::MaxEncodedLen; /// # #[derive(Encode, MaxEncodedLen)] /// #[codec(mel_bound(T: MaxEncodedLen))] /// # struct MyWrapper<T>(T); /// ``` #[cfg(feature = "max-encoded-len")] #[proc_macro_derive(MaxEncodedLen, attributes(max_encoded_len_mod))] pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::TokenStream { max_encoded_len::derive_max_encoded_len(input) }
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod context; pub mod filters; pub mod handlers; pub mod runtime; #[cfg(any(test))] pub(crate) mod tests;
use juice_sdk_rs::{client, transports}; #[tokio::main] async fn main() -> juice_sdk_rs::Result<()> { let transport = transports::http::Http::new("http://10.1.1.40:7009")?; let client = client::Client::new(transport, true); let number = client.block_number(String::from("sys")).await?; println!("{}", number); Ok(()) }
use rand; use rand::prelude::IteratorRandom; use rand::Rng; use std::ops::Add; use std::thread; use std::thread::JoinHandle; use std::time::{Duration, Instant}; use wkvstore; use wkvstore::KVStore; const START_KEYS: u32 = 6_000_000; const SAMPLES: u32 = 100_000; fn spawn_run( num: u16, store: &KVStore<Vec<u8>>, keys: Vec<String>, ) -> JoinHandle<Vec<(String, u128)>> { let c1 = store.get_client(); thread::spawn(move || { let mut rng = rand::thread_rng(); let mut results = Vec::new(); for _ in 0..SAMPLES { thread::sleep(Duration::from_millis(rng.gen_range(1..5))); let k = keys.iter().choose(&mut rng).unwrap(); let start = Instant::now(); let v = c1.retrieve(k); let dur = start.elapsed(); let s = format!("key {} val {:?} in {} nanos\n", k, v, dur.as_nanos()); if v.is_none() { println!("Handle{} {} ", num, s); } results.push((s, dur.as_nanos())); } results }) } #[ignore] #[test] fn max_load() { let store = wkvstore::KVStore::<Vec<u8>>::new(); let client = store.get_client(); let mut rng = rand::thread_rng(); let mut keys = Vec::new(); for x in 1..START_KEYS { let v: f64 = rng.gen(); let v = (x as f64) * v; let k = format!("mykey:{}-{:.8}", x, v); let with_exp = if x % 10 == 0 { keys.push(k.clone()); let exp_threshold: f64 = rng.gen(); if exp_threshold > 0.5f64 { Some( Duration::from_secs(rng.gen_range(1..340)) .add(Duration::from_millis(rng.gen_range(100..900))), ) } else { None } } else { None }; if let Some(exp) = with_exp { // println!("WITH EXPIRATION IN {}, key{}", exp.as_secs_f64(), k); client.insert_with_expiration(&k, k.as_bytes().to_vec(), exp); } else { client.insert(&k, k.as_bytes().to_vec()); } } let handle1 = spawn_run(1, &store, keys.clone()); let handle2 = spawn_run(2, &store, keys.clone()); let handle3 = spawn_run(3, &store, keys.clone()); let mut res1 = handle1.join().unwrap(); let mut res2 = handle2.join().unwrap(); let mut res3 = handle3.join().unwrap(); let mut max = 0; let mut avg = 0; let n = (res1.len() + res2.len() + res3.len()) as u128; res1.drain(..).for_each(|(_out, dur)| { if dur > max { max = dur; } avg += dur; }); res2.drain(..).for_each(|(_out, dur)| { if dur > max { max = dur; } avg += dur; }); res3.drain(..).for_each(|(_out, dur)| { if dur > max { max = dur; } avg += dur; }); let done = format!("Stats: max={}ns avg={}ns", max, avg / n); println!("{}", done); } //RUNS // Stats: max=884391ns avg=64145ns test run: 623.20 seconds (1000 Samples) 100 to 900 // Stats: max=374247ns avg=67546ns test run: 5140 (10000 Samples) 100 to 900 // Stats: max=266953ns avg=33161ns test run: 1656.25 (10000 Samples) 100 to 200 sleeps
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TIM4 control register 1"] pub tim4_cr1: TIM4_CR1, _reserved1: [u8; 0x02], #[doc = "0x04 - TIM4 control register 2"] pub tim4_cr2: TIM4_CR2, #[doc = "0x08 - TIM4 slave mode control register"] pub tim4_smcr: TIM4_SMCR, #[doc = "0x0c - TIM4 DMA/Interrupt enable register"] pub tim4_dier: TIM4_DIER, #[doc = "0x10 - TIM4 status register"] pub tim4_sr: TIM4_SR, #[doc = "0x14 - TIM4 event generation register"] pub tim4_egr: TIM4_EGR, _reserved6: [u8; 0x02], _reserved_6_tim4_ccmr1: [u8; 0x04], _reserved_7_tim4_ccmr2: [u8; 0x04], #[doc = "0x20 - TIM4 capture/compare enable register"] pub tim4_ccer: TIM4_CCER, _reserved9: [u8; 0x02], #[doc = "0x24 - TIM4 counter"] pub tim4_cnt: TIM4_CNT, #[doc = "0x28 - TIM4 prescaler"] pub tim4_psc: TIM4_PSC, _reserved11: [u8; 0x02], #[doc = "0x2c - TIM4 auto-reload register"] pub tim4_arr: TIM4_ARR, _reserved12: [u8; 0x04], #[doc = "0x34 - TIM4 capture/compare register 1"] pub tim4_ccr1: TIM4_CCR1, #[doc = "0x38 - TIM4 capture/compare register 2"] pub tim4_ccr2: TIM4_CCR2, #[doc = "0x3c - TIM4 capture/compare register 3"] pub tim4_ccr3: TIM4_CCR3, #[doc = "0x40 - TIM4 capture/compare register 4"] pub tim4_ccr4: TIM4_CCR4, _reserved16: [u8; 0x14], #[doc = "0x58 - TIM4 timer encoder control register"] pub tim4_ecr: TIM4_ECR, #[doc = "0x5c - TIM4 timer input selection register"] pub tim4_tisel: TIM4_TISEL, #[doc = "0x60 - TIM4 alternate function register 1"] pub tim4_af1: TIM4_AF1, #[doc = "0x64 - TIM4 alternate function register 2"] pub tim4_af2: TIM4_AF2, _reserved20: [u8; 0x0374], #[doc = "0x3dc - TIM4 DMA control register"] pub tim4_dcr: TIM4_DCR, #[doc = "0x3e0 - TIM4 DMA address for full transfer"] pub tim4_dmar: TIM4_DMAR, } impl RegisterBlock { #[doc = "0x18 - TIM4 capture/compare mode register 1 \\[alternate\\]"] #[inline(always)] pub const fn tim4_ccmr1_output(&self) -> &TIM4_CCMR1_OUTPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x18 - TIM4 capture/compare mode register 1 \\[alternate\\]"] #[inline(always)] pub const fn tim4_ccmr1_input(&self) -> &TIM4_CCMR1_INPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x1c - TIM4 capture/compare mode register 2 \\[alternate\\]"] #[inline(always)] pub const fn tim4_ccmr2_output(&self) -> &TIM4_CCMR2_OUTPUT { unsafe { &*(self as *const Self).cast::<u8>().add(28usize).cast() } } #[doc = "0x1c - TIM4 capture/compare mode register 2 \\[alternate\\]"] #[inline(always)] pub const fn tim4_ccmr2_input(&self) -> &TIM4_CCMR2_INPUT { unsafe { &*(self as *const Self).cast::<u8>().add(28usize).cast() } } } #[doc = "TIM4_CR1 (rw) register accessor: TIM4 control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_cr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_cr1`] module"] pub type TIM4_CR1 = crate::Reg<tim4_cr1::TIM4_CR1_SPEC>; #[doc = "TIM4 control register 1"] pub mod tim4_cr1; #[doc = "TIM4_CR2 (rw) register accessor: TIM4 control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_cr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_cr2`] module"] pub type TIM4_CR2 = crate::Reg<tim4_cr2::TIM4_CR2_SPEC>; #[doc = "TIM4 control register 2"] pub mod tim4_cr2; #[doc = "TIM4_SMCR (rw) register accessor: TIM4 slave mode control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_smcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_smcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_smcr`] module"] pub type TIM4_SMCR = crate::Reg<tim4_smcr::TIM4_SMCR_SPEC>; #[doc = "TIM4 slave mode control register"] pub mod tim4_smcr; #[doc = "TIM4_DIER (rw) register accessor: TIM4 DMA/Interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_dier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_dier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_dier`] module"] pub type TIM4_DIER = crate::Reg<tim4_dier::TIM4_DIER_SPEC>; #[doc = "TIM4 DMA/Interrupt enable register"] pub mod tim4_dier; #[doc = "TIM4_SR (rw) register accessor: TIM4 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_sr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_sr`] module"] pub type TIM4_SR = crate::Reg<tim4_sr::TIM4_SR_SPEC>; #[doc = "TIM4 status register"] pub mod tim4_sr; #[doc = "TIM4_EGR (w) register accessor: TIM4 event generation register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_egr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_egr`] module"] pub type TIM4_EGR = crate::Reg<tim4_egr::TIM4_EGR_SPEC>; #[doc = "TIM4 event generation register"] pub mod tim4_egr; #[doc = "TIM4_CCMR1_Input (rw) register accessor: TIM4 capture/compare mode register 1 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccmr1_input::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccmr1_input::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccmr1_input`] module"] pub type TIM4_CCMR1_INPUT = crate::Reg<tim4_ccmr1_input::TIM4_CCMR1_INPUT_SPEC>; #[doc = "TIM4 capture/compare mode register 1 \\[alternate\\]"] pub mod tim4_ccmr1_input; #[doc = "TIM4_CCMR1_Output (rw) register accessor: TIM4 capture/compare mode register 1 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccmr1_output::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccmr1_output::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccmr1_output`] module"] pub type TIM4_CCMR1_OUTPUT = crate::Reg<tim4_ccmr1_output::TIM4_CCMR1_OUTPUT_SPEC>; #[doc = "TIM4 capture/compare mode register 1 \\[alternate\\]"] pub mod tim4_ccmr1_output; #[doc = "TIM4_CCMR2_Input (rw) register accessor: TIM4 capture/compare mode register 2 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccmr2_input::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccmr2_input::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccmr2_input`] module"] pub type TIM4_CCMR2_INPUT = crate::Reg<tim4_ccmr2_input::TIM4_CCMR2_INPUT_SPEC>; #[doc = "TIM4 capture/compare mode register 2 \\[alternate\\]"] pub mod tim4_ccmr2_input; #[doc = "TIM4_CCMR2_Output (rw) register accessor: TIM4 capture/compare mode register 2 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccmr2_output::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccmr2_output::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccmr2_output`] module"] pub type TIM4_CCMR2_OUTPUT = crate::Reg<tim4_ccmr2_output::TIM4_CCMR2_OUTPUT_SPEC>; #[doc = "TIM4 capture/compare mode register 2 \\[alternate\\]"] pub mod tim4_ccmr2_output; #[doc = "TIM4_CCER (rw) register accessor: TIM4 capture/compare enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccer::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccer`] module"] pub type TIM4_CCER = crate::Reg<tim4_ccer::TIM4_CCER_SPEC>; #[doc = "TIM4 capture/compare enable register"] pub mod tim4_ccer; #[doc = "TIM4_CNT (rw) register accessor: TIM4 counter\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_cnt::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_cnt::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_cnt`] module"] pub type TIM4_CNT = crate::Reg<tim4_cnt::TIM4_CNT_SPEC>; #[doc = "TIM4 counter"] pub mod tim4_cnt; #[doc = "TIM4_PSC (rw) register accessor: TIM4 prescaler\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_psc::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_psc::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_psc`] module"] pub type TIM4_PSC = crate::Reg<tim4_psc::TIM4_PSC_SPEC>; #[doc = "TIM4 prescaler"] pub mod tim4_psc; #[doc = "TIM4_ARR (rw) register accessor: TIM4 auto-reload register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_arr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_arr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_arr`] module"] pub type TIM4_ARR = crate::Reg<tim4_arr::TIM4_ARR_SPEC>; #[doc = "TIM4 auto-reload register"] pub mod tim4_arr; #[doc = "TIM4_CCR1 (rw) register accessor: TIM4 capture/compare register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccr1`] module"] pub type TIM4_CCR1 = crate::Reg<tim4_ccr1::TIM4_CCR1_SPEC>; #[doc = "TIM4 capture/compare register 1"] pub mod tim4_ccr1; #[doc = "TIM4_CCR2 (rw) register accessor: TIM4 capture/compare register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccr2`] module"] pub type TIM4_CCR2 = crate::Reg<tim4_ccr2::TIM4_CCR2_SPEC>; #[doc = "TIM4 capture/compare register 2"] pub mod tim4_ccr2; #[doc = "TIM4_CCR3 (rw) register accessor: TIM4 capture/compare register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccr3`] module"] pub type TIM4_CCR3 = crate::Reg<tim4_ccr3::TIM4_CCR3_SPEC>; #[doc = "TIM4 capture/compare register 3"] pub mod tim4_ccr3; #[doc = "TIM4_CCR4 (rw) register accessor: TIM4 capture/compare register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ccr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ccr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ccr4`] module"] pub type TIM4_CCR4 = crate::Reg<tim4_ccr4::TIM4_CCR4_SPEC>; #[doc = "TIM4 capture/compare register 4"] pub mod tim4_ccr4; #[doc = "TIM4_ECR (rw) register accessor: TIM4 timer encoder control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_ecr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_ecr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_ecr`] module"] pub type TIM4_ECR = crate::Reg<tim4_ecr::TIM4_ECR_SPEC>; #[doc = "TIM4 timer encoder control register"] pub mod tim4_ecr; #[doc = "TIM4_TISEL (rw) register accessor: TIM4 timer input selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_tisel::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_tisel::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_tisel`] module"] pub type TIM4_TISEL = crate::Reg<tim4_tisel::TIM4_TISEL_SPEC>; #[doc = "TIM4 timer input selection register"] pub mod tim4_tisel; #[doc = "TIM4_AF1 (rw) register accessor: TIM4 alternate function register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_af1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_af1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_af1`] module"] pub type TIM4_AF1 = crate::Reg<tim4_af1::TIM4_AF1_SPEC>; #[doc = "TIM4 alternate function register 1"] pub mod tim4_af1; #[doc = "TIM4_AF2 (rw) register accessor: TIM4 alternate function register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_af2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_af2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_af2`] module"] pub type TIM4_AF2 = crate::Reg<tim4_af2::TIM4_AF2_SPEC>; #[doc = "TIM4 alternate function register 2"] pub mod tim4_af2; #[doc = "TIM4_DCR (rw) register accessor: TIM4 DMA control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_dcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_dcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_dcr`] module"] pub type TIM4_DCR = crate::Reg<tim4_dcr::TIM4_DCR_SPEC>; #[doc = "TIM4 DMA control register"] pub mod tim4_dcr; #[doc = "TIM4_DMAR (rw) register accessor: TIM4 DMA address for full transfer\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim4_dmar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim4_dmar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim4_dmar`] module"] pub type TIM4_DMAR = crate::Reg<tim4_dmar::TIM4_DMAR_SPEC>; #[doc = "TIM4 DMA address for full transfer"] pub mod tim4_dmar;
fn main() { let x = " "; let x = x.len(); println!("Hello, world! {}", x); }
use serde::Deserialize; use super::media::MediaBase; use super::user::UserBase; use crate::utils::{na_long_str, synopsis}; #[derive(Clone, Deserialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ActivityType { Text, AnimeList, MangaList, Message, MediaList, } #[derive(Clone, Deserialize, Debug)] #[serde(rename_all = "PascalCase")] pub enum ActivityUnion { TextActivity, ListActivity, MessageActivity, } #[derive(Clone, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Activity { #[serde(rename = "__typename")] pub __typename: ActivityUnion, pub id: u32, pub r#type: ActivityType, pub created_at: u64, pub site_url: String, pub user: Option<UserBase>, // MessageActivity fields pub text: Option<String>, // ListActivity fields status: Option<String>, progress: Option<String>, pub media: Option<MediaBase>, // MessageActivity fields pub recipient: Option<UserBase>, pub messenger: Option<UserBase>, pub message: Option<String>, } impl Activity { pub fn status(&self) -> String { let status = self.status.clone().unwrap_or_else(String::new); let progress = self.progress.clone().unwrap_or_else(String::new); format!("{} {}", status, progress) } pub fn description(&self) -> String { match self.__typename { ActivityUnion::TextActivity => { let text = self.text.clone(); text.map_or_else(na_long_str, |text| synopsis(text, 1000)) } ActivityUnion::ListActivity => { let media = self.media.clone().unwrap(); format!( "**{} [{}]({})**", self.status().trim(), media.title.user_preferred, media.site_url ) } ActivityUnion::MessageActivity => { let recipient = self.recipient.clone().unwrap(); let message = self.message.clone().unwrap_or_else(na_long_str); format!( "**Sent a message to [{}]({})**\n\n{}", recipient.name, recipient.site_url, message ) } } } }
use std::{ any::Any, borrow::Cow, collections::HashMap, convert::Infallible, marker::PhantomData, path::Path, sync::Arc, u8, }; use async_trait::async_trait; #[cfg(feature = "keyvalue")] use bonsaidb_core::kv::{KeyOperation, Kv, Output}; use bonsaidb_core::{ connection::{AccessPolicy, Connection, QueryKey, ServerConnection}, document::{Document, Header, KeyId}, limits::{LIST_TRANSACTIONS_DEFAULT_RESULT_COUNT, LIST_TRANSACTIONS_MAX_RESULTS}, networking::{self}, permissions::Permissions, schema::{ self, view::{self, map}, CollectionName, Key, Map, MappedDocument, MappedValue, Schema, Schematic, ViewName, }, transaction::{ self, ChangedDocument, Command, Executed, Operation, OperationResult, Transaction, }, }; use byteorder::{BigEndian, ByteOrder}; use itertools::Itertools; use nebari::{ io::fs::StdFile, tree::{KeyEvaluation, UnversionedTreeRoot, VersionedTreeRoot}, Buffer, ExecutingTransaction, Roots, TransactionTree, Tree, }; use ranges::GenericRange; use crate::{ config::Configuration, error::Error, open_trees::OpenTrees, storage::OpenDatabase, vault::Vault, views::{ mapper::{self, ViewEntryCollection}, view_document_map_tree_name, view_entries_tree_name, view_invalidated_docs_tree_name, view_omitted_docs_tree_name, ViewEntry, }, Storage, }; #[cfg(feature = "keyvalue")] pub mod kv; #[cfg(feature = "pubsub")] pub mod pubsub; /// A local, file-based database. #[derive(Debug)] pub struct Database<DB> { pub(crate) data: Arc<Data<DB>>, } #[derive(Debug)] pub struct Data<DB> { pub name: Arc<Cow<'static, str>>, context: Context, pub(crate) storage: Storage, pub(crate) schema: Arc<Schematic>, pub(crate) effective_permissions: Option<Permissions>, _schema: PhantomData<DB>, } impl<DB> Clone for Database<DB> { fn clone(&self) -> Self { Self { data: self.data.clone(), } } } impl<DB> Database<DB> where DB: Schema, { /// Opens a local file as a bonsaidb. pub(crate) async fn new<S: Into<Cow<'static, str>> + Send>( name: S, context: Context, storage: Storage, ) -> Result<Self, Error> { let name = name.into(); let schema = Arc::new(DB::schematic()?); let db = Self { data: Arc::new(Data { name: Arc::new(name), context, storage: storage.clone(), schema, effective_permissions: None, _schema: PhantomData::default(), }), }; if db.data.storage.check_view_integrity_on_database_open() { for view in db.data.schema.views() { db.data .storage .tasks() .spawn_integrity_check(view, &db) .await?; } } #[cfg(feature = "keyvalue")] storage.tasks().spawn_key_value_expiration_loader(&db).await; Ok(db) } /// Returns a clone with `effective_permissions`. Replaces any previously applied permissions. /// /// # Unstable /// /// See [this issue](https://github.com/khonsulabs/bonsaidb/issues/68). #[doc(hidden)] #[must_use] pub fn with_effective_permissions(&self, effective_permissions: Permissions) -> Self { Self { data: Arc::new(Data { name: self.data.name.clone(), context: self.data.context.clone(), storage: self.data.storage.clone(), schema: self.data.schema.clone(), effective_permissions: Some(effective_permissions), _schema: PhantomData::default(), }), } } /// Returns the name of the database. #[must_use] pub fn name(&self) -> &str { self.data.name.as_ref() } /// Creates a `Storage` with a single-database named "default" with its data stored at `path`. pub async fn open_local<P: AsRef<Path> + Send>( path: P, configuration: Configuration, ) -> Result<Self, Error> { let storage = Storage::open_local(path, configuration).await?; storage.register_schema::<DB>().await?; match storage.create_database::<DB>("default").await { Ok(_) | Err(bonsaidb_core::Error::DatabaseNameAlreadyTaken(_)) => {} err => err?, } Ok(storage.database("default").await?) } /// Returns the [`Storage`] that this database belongs to. #[must_use] pub fn storage(&self) -> &'_ Storage { &self.data.storage } /// Returns the [`Schematic`] for `DB`. #[must_use] pub fn schematic(&self) -> &'_ Schematic { &self.data.schema } pub(crate) fn roots(&self) -> &'_ nebari::Roots<StdFile> { &self.data.context.roots } async fn for_each_in_view< F: FnMut(ViewEntryCollection) -> Result<(), bonsaidb_core::Error> + Send + Sync, >( &self, view: &dyn view::Serialized, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, mut callback: F, ) -> Result<(), bonsaidb_core::Error> { if matches!(access_policy, AccessPolicy::UpdateBefore) { self.data .storage .tasks() .update_view_if_needed(view, self) .await?; } let view_entries = self .roots() .tree(view_entries_tree_name(&view.view_name()?)) .map_err(Error::from)?; { for entry in self.create_view_iterator(&view_entries, key, view)? { callback(entry)?; } } if matches!(access_policy, AccessPolicy::UpdateAfter) { let db = self.clone(); let view_name = view.view_name()?; tokio::task::spawn(async move { let view = db .data .schema .view_by_name(&view_name) .expect("query made with view that isn't registered with this database"); db.data .storage .tasks() .update_view_if_needed(view, &db) .await }); } Ok(()) } async fn for_each_view_entry< V: schema::View, F: FnMut(ViewEntryCollection) -> Result<(), bonsaidb_core::Error> + Send + Sync, >( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, callback: F, ) -> Result<(), bonsaidb_core::Error> { let view = self .data .schema .view::<V>() .expect("query made with view that isn't registered with this database"); self.for_each_in_view( view, key.map(|key| key.serialized()).transpose()?, access_policy, callback, ) .await } async fn get_from_collection_id( &self, id: u64, collection: &CollectionName, ) -> Result<Option<Document<'static>>, bonsaidb_core::Error> { let task_self = self.clone(); let collection = collection.clone(); tokio::task::spawn_blocking(move || { let tree = task_self .data .context .roots .tree::<VersionedTreeRoot, _>(document_tree_name(&collection)) .map_err(Error::from)?; if let Some(vec) = tree .get( &id.as_big_endian_bytes() .map_err(view::Error::KeySerialization)?, ) .map_err(Error::from)? { Ok(Some(task_self.deserialize_document(&vec)?.to_owned())) } else { Ok(None) } }) .await .unwrap() } async fn get_multiple_from_collection_id( &self, ids: &[u64], collection: &CollectionName, ) -> Result<Vec<Document<'static>>, bonsaidb_core::Error> { let task_self = self.clone(); let ids = ids.to_vec(); let collection = collection.clone(); tokio::task::spawn_blocking(move || { let tree = task_self .data .context .roots .tree::<VersionedTreeRoot, _>(document_tree_name(&collection)) .map_err(Error::from)?; let mut found_docs = Vec::new(); for id in ids { if let Some(vec) = tree .get( &id.as_big_endian_bytes() .map_err(view::Error::KeySerialization)?, ) .map_err(Error::from)? { found_docs.push(task_self.deserialize_document(&vec)?.to_owned()); } } Ok(found_docs) }) .await .unwrap() } async fn reduce_in_view( &self, view_name: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, ) -> Result<Vec<u8>, bonsaidb_core::Error> { let view = self .data .schema .view_by_name(view_name) .ok_or(bonsaidb_core::Error::CollectionNotFound)?; let mut mappings = self .grouped_reduce_in_view(view_name, key, access_policy) .await?; let result = if mappings.len() == 1 { mappings.pop().unwrap().value } else { view.reduce( &mappings .iter() .map(|map| (map.key.as_ref(), map.value.as_ref())) .collect::<Vec<_>>(), true, ) .map_err(Error::View)? }; Ok(result) } async fn grouped_reduce_in_view( &self, view_name: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedValue<Vec<u8>, Vec<u8>>>, bonsaidb_core::Error> { let view = self .data .schema .view_by_name(view_name) .ok_or(bonsaidb_core::Error::CollectionNotFound)?; let mut mappings = Vec::new(); self.for_each_in_view(view, key, access_policy, |entry| { let entry = ViewEntry::from(entry); mappings.push(MappedValue { key: entry.key, value: entry.reduced_value, }); Ok(()) }) .await?; Ok(mappings) } pub(crate) fn deserialize_document<'a>( &self, bytes: &'a [u8], ) -> Result<Document<'a>, bonsaidb_core::Error> { let mut document = bincode::deserialize::<Document<'_>>(bytes).map_err(Error::from)?; if let Some(_decryption_key) = &document.header.encryption_key { let decrypted_contents = self .storage() .vault() .decrypt_payload(&document.contents, self.data.effective_permissions.as_ref())?; document.contents = Cow::Owned(decrypted_contents); } Ok(document) } fn serialize_document(&self, document: &Document<'_>) -> Result<Vec<u8>, bonsaidb_core::Error> { if let Some(encryption_key) = &document.header.encryption_key { let encrypted_contents = self.storage().vault().encrypt_payload( encryption_key, &document.contents, self.data.effective_permissions.as_ref(), )?; bincode::serialize(&Document { header: document.header.clone(), contents: Cow::from(encrypted_contents), }) } else { bincode::serialize(document) } .map_err(Error::from) .map_err(bonsaidb_core::Error::from) } fn execute_operation( &self, operation: &Operation<'_>, transaction: &mut ExecutingTransaction<StdFile>, tree_index_map: &HashMap<String, usize>, ) -> Result<OperationResult, Error> { match &operation.command { Command::Insert { contents, encryption_key, } => self.execute_insert( operation, transaction, tree_index_map, contents.clone(), encryption_key .as_ref() .or_else(|| self.collection_encryption_key(&operation.collection)) .cloned(), ), Command::Update { header, contents } => self.execute_update( operation, transaction, tree_index_map, header, contents.clone(), ), Command::Delete { header } => { self.execute_delete(operation, transaction, tree_index_map, header) } } } fn execute_update( &self, operation: &Operation<'_>, transaction: &mut ExecutingTransaction<StdFile>, tree_index_map: &HashMap<String, usize>, header: &Header, contents: Cow<'_, [u8]>, ) -> Result<OperationResult, crate::Error> { let documents = transaction .tree(tree_index_map[&document_tree_name(&operation.collection)]) .unwrap(); let document_id = header.id.as_big_endian_bytes().unwrap(); if let Some(vec) = documents.get(document_id.as_ref())? { let doc = self.deserialize_document(&vec)?; if doc.header.revision == header.revision { if let Some(mut updated_doc) = doc.create_new_revision(contents) { // Copy the encryption key if it's been updated. if updated_doc.header.encryption_key != header.encryption_key { updated_doc.header.to_mut().encryption_key = header.encryption_key.clone(); } self.save_doc(documents, &updated_doc)?; self.update_unique_views(&document_id, operation, transaction, tree_index_map)?; Ok(OperationResult::DocumentUpdated { collection: operation.collection.clone(), header: updated_doc.header.as_ref().clone(), }) } else { // If no new revision was made, it means an attempt to // save a document with the same contents was made. // We'll return a success but not actually give a new // version Ok(OperationResult::DocumentUpdated { collection: operation.collection.clone(), header: doc.header.as_ref().clone(), }) } } else { Err(Error::Core(bonsaidb_core::Error::DocumentConflict( operation.collection.clone(), header.id, ))) } } else { Err(Error::Core(bonsaidb_core::Error::DocumentNotFound( operation.collection.clone(), header.id, ))) } } fn execute_insert( &self, operation: &Operation<'_>, transaction: &mut ExecutingTransaction<StdFile>, tree_index_map: &HashMap<String, usize>, contents: Cow<'_, [u8]>, encryption_key: Option<KeyId>, ) -> Result<OperationResult, Error> { let documents = transaction .tree::<VersionedTreeRoot>(tree_index_map[&document_tree_name(&operation.collection)]) .unwrap(); let last_key = documents .last_key()? .map(|bytes| BigEndian::read_u64(&bytes)) .unwrap_or_default(); let doc = Document::new(last_key + 1, contents, encryption_key); let serialized: Vec<u8> = self.serialize_document(&doc)?; let document_id = Buffer::from(doc.header.id.as_big_endian_bytes().unwrap().to_vec()); documents.set(document_id.clone(), serialized)?; self.update_unique_views(&document_id, operation, transaction, tree_index_map)?; Ok(OperationResult::DocumentUpdated { collection: operation.collection.clone(), header: doc.header.as_ref().clone(), }) } fn execute_delete( &self, operation: &Operation<'_>, transaction: &mut ExecutingTransaction<StdFile>, tree_index_map: &HashMap<String, usize>, header: &Header, ) -> Result<OperationResult, Error> { let documents = transaction .tree::<VersionedTreeRoot>(tree_index_map[&document_tree_name(&operation.collection)]) .unwrap(); let document_id = header.id.as_big_endian_bytes().unwrap(); if let Some(vec) = documents.remove(&document_id)? { let doc = self.deserialize_document(&vec)?; if doc.header.as_ref() == header { self.update_unique_views( document_id.as_ref(), operation, transaction, tree_index_map, )?; Ok(OperationResult::DocumentDeleted { collection: operation.collection.clone(), id: header.id, }) } else { Err(Error::Core(bonsaidb_core::Error::DocumentConflict( operation.collection.clone(), header.id, ))) } } else { Err(Error::Core(bonsaidb_core::Error::DocumentNotFound( operation.collection.clone(), header.id, ))) } } fn update_unique_views( &self, document_id: &[u8], operation: &Operation<'_>, transaction: &mut ExecutingTransaction<StdFile>, tree_index_map: &HashMap<String, usize>, ) -> Result<(), Error> { if let Some(unique_views) = self .data .schema .unique_views_in_collection(&operation.collection) { for view in unique_views { let name = view.view_name().map_err(bonsaidb_core::Error::from)?; mapper::DocumentRequest { database: self, document_id, map_request: &mapper::Map { database: self.data.name.clone(), collection: operation.collection.clone(), view_name: name.clone(), }, transaction, document_map_index: tree_index_map[&view_document_map_tree_name(&name)], documents_index: tree_index_map[&document_tree_name(&operation.collection)], omitted_entries_index: tree_index_map[&view_omitted_docs_tree_name(&name)], view_entries_index: tree_index_map[&view_entries_tree_name(&name)], view, } .map()?; } } Ok(()) } fn save_doc( &self, tree: &mut TransactionTree<VersionedTreeRoot, StdFile>, doc: &Document<'_>, ) -> Result<(), Error> { let serialized: Vec<u8> = self.serialize_document(doc)?; tree.set( doc.header .id .as_big_endian_bytes() .unwrap() .as_ref() .to_vec(), serialized, )?; Ok(()) } fn create_view_iterator<'a, K: Key + 'a>( &'a self, view_entries: &'a Tree<UnversionedTreeRoot, StdFile>, key: Option<QueryKey<K>>, view: &'a dyn view::Serialized, ) -> Result<Vec<ViewEntryCollection>, Error> { let mut values = Vec::new(); if let Some(key) = key { match key { QueryKey::Range(range) => { if view.keys_are_encryptable() { return Err(Error::from(view::Error::RangeQueryNotSupported)); } let start = Buffer::from( range .start .as_big_endian_bytes() .map_err(view::Error::KeySerialization)? .to_vec(), ); let end = Buffer::from( range .end .as_big_endian_bytes() .map_err(view::Error::KeySerialization)? .to_vec(), ); view_entries.scan::<Infallible, _, _, _>( start..end, true, |_| KeyEvaluation::ReadData, |_key, value| { values.push(value); Ok(()) }, )?; } QueryKey::Matches(key) => { let key = key .as_big_endian_bytes() .map_err(view::Error::KeySerialization)? .to_vec(); let key = if view.keys_are_encryptable() && self.view_encryption_key(view).is_some() { mapper::hash_key(&key).to_vec() } else { key }; values.extend(view_entries.get(&key)?); } QueryKey::Multiple(list) => { let list = list .into_iter() .map(|key| { key.as_big_endian_bytes() .map(|bytes| bytes.to_vec()) .map_err(view::Error::KeySerialization) }) .collect::<Result<Vec<_>, _>>()?; let list = if view.keys_are_encryptable() && self.view_encryption_key(view).is_some() { list.into_iter() .map(|key| mapper::hash_key(&key).to_vec()) .collect() } else { list }; values.extend( view_entries .get_multiple(&list.iter().map(Vec::as_slice).collect::<Vec<_>>())? .into_iter() .map(|(_, value)| value), ); } } } else { view_entries.scan::<Infallible, _, _, _>( .., true, |_| KeyEvaluation::ReadData, |_, value| { values.push(value); Ok(()) }, )?; } values .into_iter() .map(|value| { self.storage() .vault() .decrypt_serialized(self.data.effective_permissions.as_ref(), &value) }) .collect::<Result<Vec<_>, Error>>() } pub(crate) fn collection_encryption_key(&self, collection: &CollectionName) -> Option<&KeyId> { self.schematic() .encryption_key_for_collection(collection) .or_else(|| self.storage().default_encryption_key()) } pub(crate) fn view_encryption_key(&self, view: &dyn view::Serialized) -> Option<&KeyId> { view.collection() .ok() .and_then(|name| self.collection_encryption_key(&name)) } #[cfg(feature = "keyvalue")] pub(crate) fn update_key_expiration(&self, update: kv::ExpirationUpdate) { self.data.context.update_key_expiration(update); } } #[async_trait] impl<'a, DB> Connection for Database<DB> where DB: Schema, { async fn apply_transaction( &self, transaction: Transaction<'static>, ) -> Result<Vec<OperationResult>, bonsaidb_core::Error> { let task_self = self.clone(); tokio::task::spawn_blocking::<_, Result<Vec<OperationResult>, Error>>(move || { let mut open_trees = OpenTrees::default(); for op in &transaction.operations { if !task_self.data.schema.contains_collection_id(&op.collection) { return Err(Error::Core(bonsaidb_core::Error::CollectionNotFound)); } match &op.command { Command::Update { .. } | Command::Insert { .. } | Command::Delete { .. } => { open_trees.open_trees_for_document_change( &op.collection, &task_self.data.schema, )?; } } } let mut roots_transaction = task_self .data .context .roots .transaction(&open_trees.trees)?; let mut results = Vec::new(); let mut changed_documents = Vec::new(); for op in &transaction.operations { let result = task_self.execute_operation( op, &mut roots_transaction, &open_trees.trees_index_by_name, )?; match &result { OperationResult::DocumentUpdated { header, collection } => { changed_documents.push(ChangedDocument { collection: collection.clone(), id: header.id, deleted: false, }); } OperationResult::DocumentDeleted { id, collection } => { changed_documents.push(ChangedDocument { collection: collection.clone(), id: *id, deleted: true, }); } OperationResult::Success => {} } results.push(result); } // Insert invalidations for each record changed for (collection, changed_documents) in &changed_documents .iter() .group_by(|doc| doc.collection.clone()) { if let Some(views) = task_self.data.schema.views_in_collection(&collection) { let changed_documents = changed_documents.collect::<Vec<_>>(); for view in views { if !view.unique() { let view_name = view.view_name().map_err(bonsaidb_core::Error::from)?; for changed_document in &changed_documents { let invalidated_docs = roots_transaction .tree::<UnversionedTreeRoot>( open_trees.trees_index_by_name [&view_invalidated_docs_tree_name(&view_name)], ) .unwrap(); invalidated_docs.set( changed_document.id.as_big_endian_bytes().unwrap().to_vec(), b"", )?; } } } } } roots_transaction .entry_mut() .set_data(bincode::serialize(&changed_documents)?)?; roots_transaction.commit()?; Ok(results) }) .await .map_err(|err| bonsaidb_core::Error::Database(err.to_string()))? .map_err(bonsaidb_core::Error::from) } async fn get<C: schema::Collection>( &self, id: u64, ) -> Result<Option<Document<'static>>, bonsaidb_core::Error> { self.get_from_collection_id(id, &C::collection_name()?) .await } async fn get_multiple<C: schema::Collection>( &self, ids: &[u64], ) -> Result<Vec<Document<'static>>, bonsaidb_core::Error> { self.get_multiple_from_collection_id(ids, &C::collection_name()?) .await } async fn list_executed_transactions( &self, starting_id: Option<u64>, result_limit: Option<usize>, ) -> Result<Vec<transaction::Executed<'static>>, bonsaidb_core::Error> { let result_limit = result_limit .unwrap_or(LIST_TRANSACTIONS_DEFAULT_RESULT_COUNT) .min(LIST_TRANSACTIONS_MAX_RESULTS); if result_limit > 0 { let task_self = self.clone(); tokio::task::spawn_blocking::<_, Result<Vec<transaction::Executed<'static>>, Error>>( move || { let range = if let Some(starting_id) = starting_id { GenericRange::from(starting_id..) } else { GenericRange::from(..) }; let mut entries = Vec::new(); task_self.roots().transactions().scan(range, |entry| { entries.push(entry); entries.len() < result_limit })?; entries .into_iter() .map(|entry| { let changed_documents = bincode::deserialize(entry.data().unwrap())?; Ok(transaction::Executed { id: entry.id, changed_documents, }) }) .collect::<Result<Vec<_>, Error>>() }, ) .await .unwrap() .map_err(bonsaidb_core::Error::from) } else { // A request was made to return an empty result? This should probably be // an error, but technically this is a correct response. Ok(Vec::default()) } } #[must_use] async fn query<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<Map<V::Key, V::Value>>, bonsaidb_core::Error> where Self: Sized, { let mut results = Vec::new(); self.for_each_view_entry::<V, _>(key, access_policy, |collection| { let entry = ViewEntry::from(collection); let key = <V::Key as Key>::from_big_endian_bytes(&entry.key) .map_err(view::Error::KeySerialization) .map_err(Error::from)?; for entry in entry.mappings { results.push(Map { source: entry.source, key: key.clone(), value: serde_cbor::from_slice(&entry.value).map_err(Error::Serialization)?, }); } Ok(()) }) .await?; Ok(results) } async fn query_with_docs<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedDocument<V::Key, V::Value>>, bonsaidb_core::Error> where Self: Sized, { let results = Connection::query::<V>(self, key, access_policy).await?; let mut documents = self .get_multiple::<V::Collection>(&results.iter().map(|m| m.source).collect::<Vec<_>>()) .await? .into_iter() .map(|doc| (doc.header.id, doc)) .collect::<HashMap<_, _>>(); Ok(results .into_iter() .filter_map(|map| { if let Some(document) = documents.remove(&map.source) { Some(MappedDocument { key: map.key, value: map.value, document, }) } else { None } }) .collect()) } async fn reduce<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<V::Value, bonsaidb_core::Error> where Self: Sized, { let view = self .data .schema .view::<V>() .expect("query made with view that isn't registered with this database"); let result = self .reduce_in_view( &view.view_name()?, key.map(|key| key.serialized()).transpose()?, access_policy, ) .await?; let value = serde_cbor::from_slice(&result).map_err(Error::Serialization)?; Ok(value) } async fn reduce_grouped<V: schema::View>( &self, key: Option<QueryKey<V::Key>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedValue<V::Key, V::Value>>, bonsaidb_core::Error> where Self: Sized, { let view = self .data .schema .view::<V>() .expect("query made with view that isn't registered with this database"); let results = self .grouped_reduce_in_view( &view.view_name()?, key.map(|key| key.serialized()).transpose()?, access_policy, ) .await?; results .into_iter() .map(|map| { Ok(MappedValue { key: V::Key::from_big_endian_bytes(&map.key) .map_err(view::Error::KeySerialization)?, value: serde_cbor::from_slice(&map.value)?, }) }) .collect::<Result<Vec<_>, bonsaidb_core::Error>>() } async fn last_transaction_id(&self) -> Result<Option<u64>, bonsaidb_core::Error> { Ok(self.roots().transactions().current_transaction_id()) } } type ViewIterator<'a> = Box<dyn Iterator<Item = Result<(Buffer<'static>, Buffer<'static>), Error>> + 'a>; struct ViewEntryCollectionIterator<'a> { iterator: ViewIterator<'a>, permissions: Option<&'a Permissions>, vault: &'a Vault, } impl<'a> Iterator for ViewEntryCollectionIterator<'a> { type Item = Result<ViewEntryCollection, crate::Error>; fn next(&mut self) -> Option<Self::Item> { self.iterator.next().map(|item| { item.map_err(crate::Error::from) .and_then(|(_, value)| self.vault.decrypt_serialized(self.permissions, &value)) }) } } #[derive(Debug, Clone)] pub(crate) struct Context { pub(crate) roots: Roots<StdFile>, #[cfg(feature = "keyvalue")] kv_expirer: Arc<std::sync::RwLock<Option<flume::Sender<kv::ExpirationUpdate>>>>, } impl Context { pub(crate) fn new(roots: Roots<StdFile>) -> Self { Self { roots, #[cfg(feature = "keyvalue")] kv_expirer: Arc::default(), } } #[cfg_attr(not(feature = "keyvalue"), allow(clippy::unused_self))] pub(crate) fn shutdown(&self) { #[cfg(feature = "keyvalue")] { let mut expirer = self.kv_expirer.write().unwrap(); *expirer = None; } } #[cfg(feature = "keyvalue")] pub(crate) fn update_key_expiration(&self, update: kv::ExpirationUpdate) { { let sender = self.kv_expirer.read().unwrap(); if let Some(sender) = sender.as_ref() { drop(sender.send(update)); return; } } // If we fall through, we need to initialize the expirer task let mut sender = self.kv_expirer.write().unwrap(); if let Some(kv_sender) = sender.as_ref() { drop(kv_sender.send(update)); } else { let (kv_sender, kv_expirer_receiver) = flume::unbounded(); kv_sender.send(update).unwrap(); let context = self.clone(); tokio::task::spawn_blocking(move || { kv::expiration_thread(context, kv_expirer_receiver) }); *sender = Some(kv_sender); } } } pub fn document_tree_name(collection: &CollectionName) -> String { format!("collection.{}", collection) } #[async_trait] impl<DB> OpenDatabase for Database<DB> where DB: Schema, { fn as_any(&self) -> &'_ dyn Any { self } async fn get_from_collection_id( &self, id: u64, collection: &CollectionName, permissions: &Permissions, ) -> Result<Option<Document<'static>>, bonsaidb_core::Error> { self.with_effective_permissions(permissions.clone()) .get_from_collection_id(id, collection) .await } async fn get_multiple_from_collection_id( &self, ids: &[u64], collection: &CollectionName, permissions: &Permissions, ) -> Result<Vec<Document<'static>>, bonsaidb_core::Error> { self.with_effective_permissions(permissions.clone()) .get_multiple_from_collection_id(ids, collection) .await } async fn apply_transaction( &self, transaction: Transaction<'static>, permissions: &Permissions, ) -> Result<Vec<OperationResult>, bonsaidb_core::Error> { <Self as Connection>::apply_transaction( &self.with_effective_permissions(permissions.clone()), transaction, ) .await } async fn query( &self, view: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, ) -> Result<Vec<map::Serialized>, bonsaidb_core::Error> { if let Some(view) = self.schematic().view_by_name(view) { let mut results = Vec::new(); self.for_each_in_view(view, key, access_policy, |collection| { let entry = ViewEntry::from(collection); for mapping in entry.mappings { results.push(map::Serialized { source: mapping.source, key: entry.key.clone(), value: mapping.value, }); } Ok(()) }) .await?; Ok(results) } else { Err(bonsaidb_core::Error::CollectionNotFound) } } async fn query_with_docs( &self, view: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, permissions: &Permissions, ) -> Result<Vec<networking::MappedDocument>, bonsaidb_core::Error> { let results = OpenDatabase::query(self, view, key, access_policy).await?; let view = self.schematic().view_by_name(view).unwrap(); // query() will fail if it's not present let mut documents = self .with_effective_permissions(permissions.clone()) .get_multiple_from_collection_id( &results.iter().map(|m| m.source).collect::<Vec<_>>(), &view.collection()?, ) .await? .into_iter() .map(|doc| (doc.header.id, doc)) .collect::<HashMap<_, _>>(); Ok(results .into_iter() .filter_map(|map| { if let Some(source) = documents.remove(&map.source) { Some(networking::MappedDocument { key: map.key, value: map.value, source, }) } else { None } }) .collect()) } async fn reduce( &self, view: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, ) -> Result<Vec<u8>, bonsaidb_core::Error> { self.reduce_in_view(view, key, access_policy).await } async fn reduce_grouped( &self, view: &ViewName, key: Option<QueryKey<Vec<u8>>>, access_policy: AccessPolicy, ) -> Result<Vec<MappedValue<Vec<u8>, Vec<u8>>>, bonsaidb_core::Error> { self.grouped_reduce_in_view(view, key, access_policy).await } async fn list_executed_transactions( &self, starting_id: Option<u64>, result_limit: Option<usize>, ) -> Result<Vec<Executed<'static>>, bonsaidb_core::Error> { Connection::list_executed_transactions(self, starting_id, result_limit).await } async fn last_transaction_id(&self) -> Result<Option<u64>, bonsaidb_core::Error> { Connection::last_transaction_id(self).await } #[cfg(feature = "keyvalue")] async fn execute_key_operation( &self, op: KeyOperation, ) -> Result<Output, bonsaidb_core::Error> { Kv::execute_key_operation(self, op).await } }
/* * Copyright 2017 Eldad Zack * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * https://opensource.org/licenses/MIT * */ use std::fmt; use crate::error::ParseError; use serde_derive::{Serialize, Deserialize}; /* 14 bits unsigned, big endian */ #[derive(Serialize, Deserialize)] pub struct U14BE { host: u16, } impl U14BE { pub fn from_device(bytes: [u8; 2]) -> Result<U14BE, ParseError> { if ((bytes[0] | bytes[1]) & 0x80) == 0x80 { Err(ParseError::new(&format!("ERROR: MSB set on U14 type from device: {:?}", bytes))) } else { Ok(U14BE { host: ((bytes[0] as u16) << 7) | bytes[1] as u16 }) } } pub fn to_device(&self) -> Result<[u8; 2], ParseError> { if self.host & 0xc000 != 0 { Err(ParseError::new(&format!("value too large to convert into u14: {}", self.host))) } else { Ok([ ((self.host & 0x3f80) >> 7) as u8, (self.host & 0x007f) as u8, ]) } } } impl fmt::Display for U14BE { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.host) } } impl fmt::Debug for U14BE { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} ({:?})", self.host, self.to_device()) } }
#![feature(const_generics)] trait Foo {} impl<const N: usize> Foo for [(); N] where Self:FooImpl<{N==0}> {} trait FooImpl<const IS_ZERO: bool>{} fn main() {}
use cgmath::{perspective, EuclideanSpace, Matrix4, Point3, Rad, Vector3, Vector4, Quaternion, Rotation3}; use gl::types::GLuint; use glow::HasContext; pub trait IsCamera { fn get_proj(&self, width: u32, height: u32) -> Matrix4<f32>; fn get_view(&self) -> Matrix4<f32>; fn upload_fields(&self, gl: &glow::Context, handle: GLuint); } #[derive(Copy, Clone)] pub struct Camera { pub fovy: f32, pub z_near: f32, pub z_far: f32, pub aperture: f32, pub shutter_speed: f32, pub iso: f32, pub position: Vector3<f32>, pub rotation: Quaternion<f32>, } impl Camera { pub fn new(fovy: f32, z_near: f32, z_far: f32, aperture: f32, shutter_speed: f32, iso: f32, position: Vector3<f32>, rotation: Quaternion<f32>) -> Camera { //eye: Point3<f32>, look_at: Point3<f32>, up: Vector3<f32> Camera { fovy: fovy, z_near: z_near, z_far: z_far, aperture: aperture, shutter_speed: shutter_speed, iso: iso, position: position, rotation: rotation, } } pub fn default() -> Camera { Camera { fovy: 60.0, z_near: 0.02, z_far: 100.0, aperture: 16.0, shutter_speed: 1.0 / 100.0, iso: 100.0, position: Vector3::new(0.0, 0.0, 0.0), rotation: Rotation3::<f32>::from_angle_y(Rad(0.0)), //Rotation3::<f32>::from_angle_y(Rad(3.14 / 2.0)) } } } impl IsCamera for Camera { fn get_proj(&self, width: u32, height: u32) -> Matrix4<f32> { perspective(Rad(self.fovy / 180.0 * std::f32::consts::PI), width as f32 / height as f32, self.z_near, self.z_far) } fn get_view(&self) -> Matrix4<f32> { let rot_view: Matrix4<f32> = self.rotation.into(); let pos_view: Matrix4<f32> = Matrix4::<f32>::from_translation(-self.position); rot_view * pos_view } fn upload_fields(&self, gl: &glow::Context, handle: GLuint) { unsafe { let pos_loc = gl.get_uniform_location(handle, "camera.position"); gl.uniform_3_f32(pos_loc, self.position.x, self.position.y, self.position.z); let set_loc = gl.get_uniform_location(handle, "camera.settings"); gl.uniform_3_f32(set_loc, self.aperture, self.shutter_speed, self.iso); } } }
pub mod compiler; mod form; mod processor; use std::str; use actix_web::{post, web, HttpResponse, Responder}; use serde::Deserialize; use serde_json::Value; use crate::data::Data; use crate::services::{self, WsError}; pub fn config(cfg: &mut web::ServiceConfig) { cfg.service(compile_documents); } #[derive(Deserialize)] pub struct CompileOptions { pub merge: Option<bool>, } #[post("/compile/{token}")] pub async fn compile_documents( data: web::Data<Data>, token: web::Path<String>, request: web::HttpRequest, bytes: web::Bytes, ) -> impl Responder { match str::from_utf8(&bytes) { Ok(body) => match serde_json::from_str::<Value>(body) { Ok(values) => { if let Some(value) = values.get("data") { match <compiler::PDFillerMap>::deserialize(value) { Ok(ref map) => { if let Some(documents) = data.get_documents_by_token(token.as_str()).await { if documents.is_empty() { return HttpResponse::NotFound().json(WsError { error: "No documents found for this token!".into(), }); } match compiler::compile_documents( data.file.clone(), map, &documents, ) .await { Ok(_) => { if let Some(accept) = services::get_accepted_header(&request) { let export_result = if accept.as_str() == mime::APPLICATION_PDF { compiler::merge_documents( data.file.clone(), documents, true, ) .await } else { compiler::zip_documents( data.file.clone(), documents, true, ) .await }; services::export_content(accept, export_result) } else { HttpResponse::NotAcceptable().json(WsError { error: "Only PDF or Streams are accepted".into(), }) } } Err(compiler::HandlerCompilerError::FillingError(e)) => { HttpResponse::BadRequest().json(WsError { error: format!( "Error during document filling: {:#?}", e ), }) } Err(compiler::HandlerCompilerError::Error(message)) => { HttpResponse::InternalServerError() .json(WsError { error: message }) } } } else { HttpResponse::NotFound().json(WsError { error: "No documents found for this token!".into(), }) } } Err(e) => HttpResponse::BadRequest().json(WsError { error: format!("Not a valid PDFiller request: {:#?}", e), }), } } else { HttpResponse::BadRequest().json(WsError { error: "Not a valid PDFiller request.".into(), }) } } Err(e) => HttpResponse::BadRequest().json(WsError { error: format!("Couldn't decode the body as JSON: {:#?}", e), }), }, Err(e) => HttpResponse::InternalServerError().json(WsError { error: format!("Error decoding the body: {:#?}", e), }), } }
//! Functions and utilities for the [`Diff`](`crate::opt::Diff`) command //! and [`Diff`](`punktf_lib::visit::diff::Diff`) visitor. use crate::opt::DiffFormat; use console::{style, Style}; use punktf_lib::visit::diff::Event; use similar::{ChangeTag, TextDiff}; use std::{fmt, path::Path}; /// Processes diff [`Event`s](`punktf_lib::visit::diff::Event`) from the visitor. pub fn diff(format: DiffFormat, event: Event<'_>) { match event { Event::NewFile(path) => println!("[{}] New file", path.display()), Event::NewDirectory(path) => println!("[{}] New directory", path.display()), Event::Diff { target_path, old_content, new_contnet, } => { if format == DiffFormat::Unified { print_udiff(target_path, &old_content, &new_contnet); } else { print_pretty(target_path, &old_content, &new_contnet); } } } } /// Prints a file diff with the gnu unified format. fn print_udiff(target: &Path, old: &str, new: &str) { let diff = TextDiff::from_lines(old, new); println!("--- {path}\r\n+++ {path}", path = target.display()); diff.unified_diff().to_writer(std::io::stdout()).unwrap(); } /// Used to pretty print diff line numbers. struct Line(Option<usize>); impl fmt::Display for Line { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { None => write!(f, " "), Some(idx) => write!(f, "{:<4}", idx + 1), } } } /// Prints a file diff with ansii escape codes. fn print_pretty(target: &Path, old: &str, new: &str) { let diff = TextDiff::from_lines(old, new); for (idx, group) in diff.grouped_ops(3).iter().enumerate() { if idx == 0 { println!(">> {}", style(target.display()).bold().bright()); } if idx > 0 { println!("{:-^1$}", "-", 80); } for op in group { for change in diff.iter_inline_changes(op) { let (sign, s) = match change.tag() { ChangeTag::Delete => ("-", Style::new().red()), ChangeTag::Insert => ("+", Style::new().green()), ChangeTag::Equal => (" ", Style::new().dim()), }; print!( "{}{} |{}", style(Line(change.old_index())).dim(), style(Line(change.new_index())).dim(), s.apply_to(sign).bold(), ); for (emphasized, value) in change.iter_strings_lossy() { if emphasized { print!("{}", s.apply_to(value).underlined().on_black()); } else { print!("{}", s.apply_to(value)); } } if change.missing_newline() { println!(); } } } } }
#[doc = "Register `OR` reader"] pub type R = crate::R<OR_SPEC>; #[doc = "Register `OR` writer"] pub type W = crate::W<OR_SPEC>; #[doc = "Field `SWP_TBYP` reader - SWP transceiver bypass"] pub type SWP_TBYP_R = crate::BitReader; #[doc = "Field `SWP_TBYP` writer - SWP transceiver bypass"] pub type SWP_TBYP_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SWP_CLASS` reader - SWP class selection"] pub type SWP_CLASS_R = crate::BitReader; #[doc = "Field `SWP_CLASS` writer - SWP class selection"] pub type SWP_CLASS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - SWP transceiver bypass"] #[inline(always)] pub fn swp_tbyp(&self) -> SWP_TBYP_R { SWP_TBYP_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - SWP class selection"] #[inline(always)] pub fn swp_class(&self) -> SWP_CLASS_R { SWP_CLASS_R::new(((self.bits >> 1) & 1) != 0) } } impl W { #[doc = "Bit 0 - SWP transceiver bypass"] #[inline(always)] #[must_use] pub fn swp_tbyp(&mut self) -> SWP_TBYP_W<OR_SPEC, 0> { SWP_TBYP_W::new(self) } #[doc = "Bit 1 - SWP class selection"] #[inline(always)] #[must_use] pub fn swp_class(&mut self) -> SWP_CLASS_W<OR_SPEC, 1> { SWP_CLASS_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "SWPMI Option register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`or::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`or::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct OR_SPEC; impl crate::RegisterSpec for OR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`or::R`](R) reader structure"] impl crate::Readable for OR_SPEC {} #[doc = "`write(|w| ..)` method takes [`or::W`](W) writer structure"] impl crate::Writable for OR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets OR to value 0"] impl crate::Resettable for OR_SPEC { const RESET_VALUE: Self::Ux = 0; }
// Copyright 2019 The Tari Project // SPDX-License-Identifier: BSD-3-Clause //! General definition of public-private key pairs for use in Tari. The traits and structs //! defined here are used in the Tari domain logic layer exclusively (as opposed to any specific //! implementation of ECC curve). The idea being that we can swap out the underlying //! implementation without worrying too much about the impact on upstream code. use core::ops::Add; use rand_core::{CryptoRng, RngCore}; use tari_utilities::ByteArray; use zeroize::{Zeroize, ZeroizeOnDrop}; /// A trait specifying common behaviour for representing `SecretKey`s. Specific elliptic curve /// implementations need to implement this trait for them to be used in Tari. /// /// ## Example /// /// Assuming there is a Ristretto implementation, /// ```edition2018 /// # use tari_crypto::ristretto::{ RistrettoSecretKey, RistrettoPublicKey }; /// # use tari_crypto::keys::{ SecretKey, PublicKey }; /// # use rand; /// let mut rng = rand::thread_rng(); /// let k = RistrettoSecretKey::random(&mut rng); /// let p = RistrettoPublicKey::from_secret_key(&k); /// ``` pub trait SecretKey: ByteArray + Clone + PartialEq + Eq + Add<Output = Self> + Default + Zeroize + ZeroizeOnDrop { /// The length of the byte encoding of a key, in bytes const KEY_LEN: usize; /// The length of the byte encoding of a key, in bytes fn key_length() -> usize { Self::KEY_LEN } /// Generates a random secret key fn random<R: RngCore + CryptoRng>(rng: &mut R) -> Self; } //---------------------------------------- Public Keys ----------------------------------------// /// A trait specifying common behaviour for representing `PublicKey`s. Specific elliptic curve /// implementations need to implement this trait for them to be used in Tari. /// /// See [SecretKey](trait.SecretKey.html) for an example. pub trait PublicKey: ByteArray + Add<Output = Self> + Clone + PartialOrd + Ord + Default + Zeroize { /// The length of the byte encoding of a key, in bytes const KEY_LEN: usize; /// The related [SecretKey](trait.SecretKey.html) type type K: SecretKey; /// Calculate the public key associated with the given secret key. This should not fail; if a /// failure does occur (implementation error?), the function will panic. fn from_secret_key(k: &Self::K) -> Self; /// The length of the byte encoding of a key, in bytes fn key_length() -> usize { Self::KEY_LEN } /// Multiplies each of the items in `scalars` by their respective item in `points` and then adds /// the results to produce a single public key fn batch_mul(scalars: &[Self::K], points: &[Self]) -> Self; /// Generate a random public and secret key fn random_keypair<R: RngCore + CryptoRng>(rng: &mut R) -> (Self::K, Self) { let k = Self::K::random(rng); let pk = Self::from_secret_key(&k); (k, pk) } }
#![no_std] #![feature(llvm_asm)] #![feature(const_fn)] #![feature(const_raw_ptr_to_usize_cast)] #![allow(clippy::identity_op)] pub mod address; pub mod x86; /// Imitate C99's designated initializer #[macro_export] macro_rules! assigned_array { ($default:expr; $len:expr; $([$idx:expr] = $val:expr),*) => {{ let mut tmp = [$default; $len]; $(tmp[$idx] = $val;)* tmp }}; } pub mod prelude { pub use super::address::{PAddr, VAddr}; }
use { http::{Response, StatusCode}, serde_json::json, tsukuyomi::{ error::{Error, HttpError}, // future::{Async, Poll, TryFuture}, handler::{Handler, ModifyHandler}, input::Input, output::IntoResponse, util::Either, }, }; #[derive(Debug, failure::Fail)] pub enum GraphQLParseError { #[fail(display = "the request method is invalid")] InvalidRequestMethod, #[fail(display = "missing query")] MissingQuery, #[fail(display = "missing content-type")] MissingMime, #[fail(display = "the content type is invalid.")] InvalidMime, #[fail(display = "failed to parse input as a JSON object")] ParseJson(#[fail(cause)] serde_json::Error), #[fail(display = "failed to parse HTTP query")] ParseQuery(#[fail(cause)] serde_urlencoded::de::Error), #[fail(display = "failed to decode input as a UTF-8 sequence")] DecodeUtf8(#[fail(cause)] std::str::Utf8Error), } impl HttpError for GraphQLParseError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } /// Creates a `ModifyHandler` that catches the all kind of errors that the handler throws /// and converts them into GraphQL errors. pub fn capture_errors() -> CaptureErrors { CaptureErrors(()) } #[allow(missing_docs)] #[derive(Debug)] pub struct CaptureErrors(()); impl<H> ModifyHandler<H> for CaptureErrors where H: Handler, { type Output = Either<Response<String>, H::Output>; type Error = Error; type Handler = CaptureErrorsHandler<H>; // private; fn modify(&self, inner: H) -> Self::Handler { CaptureErrorsHandler { inner } } } #[derive(Debug)] pub struct CaptureErrorsHandler<H> { inner: H, } impl<H> Handler for CaptureErrorsHandler<H> where H: Handler, { type Output = Either<Response<String>, H::Output>; type Error = Error; type Handle = CaptureErrorsHandle<H::Handle>; fn handle(&self) -> Self::Handle { CaptureErrorsHandle { inner: self.inner.handle(), } } } #[derive(Debug)] pub struct CaptureErrorsHandle<H> { inner: H, } impl<H> TryFuture for CaptureErrorsHandle<H> where H: TryFuture, { type Ok = Either<Response<String>, H::Ok>; type Error = Error; #[inline] fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> { match self.inner.poll_ready(input) { Ok(Async::Ready(ok)) => Ok(Async::Ready(Either::Right(ok))), Ok(Async::NotReady) => Ok(Async::NotReady), Err(err) => { let err = err.into(); let body = json!({ "errors": [ { "message": err.to_string(), } ], }) .to_string(); let mut response = err.into_response().map(|_| body.into()); response.headers_mut().insert( http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json"), ); Ok(Async::Ready(Either::Left(response))) } } } }
//! # Parser methods for the general types use super::types::{ObjectID, ObjectTemplate, Quaternion, Vector3f, WorldID}; //use encoding::{all::UTF_16LE, DecoderTrap, Encoding}; use nom::{ bytes::complete::take, combinator::{map, map_opt, map_res}, error::FromExternalError, multi::length_data, sequence::tuple, }; use nom::{ error::ParseError, number::complete::{le_f32, le_u32, le_u8}, IResult, }; use num_traits::FromPrimitive; use std::{char::decode_utf16, string::FromUtf8Error}; /// Helper method to dump some values #[allow(dead_code)] pub fn dump<T>(val: T) -> T where T: std::fmt::Debug, { println!("{:?}", val); val } type Res<'a, T, E> = IResult<&'a [u8], T, E>; /// Parse a Vector3f pub fn parse_vec3f<'a, E>(input: &'a [u8]) -> Res<'a, Vector3f, E> where E: ParseError<&'a [u8]>, { map(tuple((le_f32, le_f32, le_f32)), |(x, y, z)| { Vector3f::new(x, y, z) })(input) } /// Parse a Quaternion pub fn parse_quat<'a, E>(input: &'a [u8]) -> Res<'a, Quaternion, E> where E: ParseError<&'a [u8]> + 'a, { map(tuple((le_f32, le_f32, le_f32, le_f32)), |(x, y, z, w)| { Quaternion::new(x, y, z, w) })(input) } /// Parse a Quaternion pub fn parse_quat_wxyz<'a, E>(input: &'a [u8]) -> Res<'a, Quaternion, E> where E: ParseError<&'a [u8]>, { map(tuple((le_f32, le_f32, le_f32, le_f32)), |(w, x, y, z)| { Quaternion::new(x, y, z, w) })(input) } /// Parse a WorldID pub fn parse_world_id<'a, E>(input: &'a [u8]) -> Res<'a, WorldID, E> where E: ParseError<&'a [u8]>, { map_opt(le_u32, WorldID::from_u32)(input) } /// Parse an ObjectTemplate pub fn parse_object_template<'a, E>(input: &'a [u8]) -> Res<'a, ObjectTemplate, E> where E: ParseError<&'a [u8]>, { map_opt(le_u32, ObjectTemplate::from_u32)(input) } /// Parse an ObjectID pub fn parse_object_id<'a, E>(input: &'a [u8]) -> Res<'a, ObjectID, E> where E: ParseError<&'a [u8]>, { map(tuple((le_u32, le_u32)), |(a, b)| ObjectID::new(b, a))(input) } fn map_wstring(val: &[u8]) -> Result<String, ()> { let iter = val.chunks_exact(2); if let [] = iter.remainder() { let iter = iter.map(|s| (s[0] as u16) + ((s[1] as u16) << 8)); decode_utf16(iter).map(|r| r.or(Err(()))).collect() } else { Err(()) } } /// Parse a u8 wstring pub fn parse_u8_wstring<'a, E>(input: &'a [u8]) -> Res<'a, String, E> where E: ParseError<&'a [u8]> + FromExternalError<&'a [u8], ()>, { le_u8(input).and_then(|(input, count)| { let len = usize::from(count) * 2; map_res(take(len), map_wstring)(input) }) } /// Parse a u32 wstring pub fn parse_u32_wstring<'a, E>(input: &'a [u8]) -> Res<'a, String, E> where E: ParseError<&'a [u8]> + FromExternalError<&'a [u8], ()>, { le_u32(input).and_then(|(input, count)| { let len = count * 2; map_res(take(len), map_wstring)(input) }) } /// Parse a string with u16 length specifier pub fn parse_string_u16<'a, E>(input: &'a [u8], i: u16) -> Res<'a, String, E> where E: ParseError<&'a [u8]> + FromExternalError<&'a [u8], FromUtf8Error>, { map_res(map(take(i), Vec::from), String::from_utf8)(input) } /// Parse a string after an u8 length specifier pub fn parse_u8_string<'a, E>(input: &'a [u8]) -> Res<'a, String, E> where E: ParseError<&'a [u8]> + FromExternalError<&'a [u8], FromUtf8Error>, { map_res(map(length_data(le_u8), Vec::from), String::from_utf8)(input) } /// Parse a string after an u32 length specifier pub fn parse_u32_string<'a, E>(input: &'a [u8]) -> Res<'a, String, E> where E: ParseError<&'a [u8]> + FromExternalError<&'a [u8], FromUtf8Error>, { map_res(map(length_data(le_u32), Vec::from), String::from_utf8)(input) } /// Parse an u32 boolean pub fn parse_u32_bool<'a, E>(input: &'a [u8]) -> Res<'a, bool, E> where E: ParseError<&'a [u8]>, { map(le_u32, |v| v > 0)(input) } /// Parse an u8 boolean pub fn parse_u8_bool<'a, E>(input: &'a [u8]) -> Res<'a, bool, E> where E: ParseError<&'a [u8]>, { map(le_u8, |v| v > 0)(input) } #[cfg(test)] mod test { use super::parse_u8_wstring; use nom::error::ErrorKind; #[test] fn test_wstring() { assert_eq!( parse_u8_wstring::<'_, (&[u8], ErrorKind)>(&[2, 65, 0, 66, 0]), Ok((&[][..], String::from("AB"))) ); } }
//! Simple bootstrap node implementation #![feature(type_changing_struct_update)] use clap::Parser; use libp2p::identity::ed25519::Keypair; use libp2p::{identity, Multiaddr, PeerId}; use serde::{Deserialize, Serialize}; use std::error::Error; use std::fmt::{Display, Formatter}; use std::sync::Arc; use subspace_networking::libp2p::multiaddr::Protocol; use subspace_networking::{peer_id, Config}; use tracing::{debug, info, Level}; use tracing_subscriber::fmt::Subscriber; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::EnvFilter; #[derive(Debug, Parser)] #[clap(about, version)] enum Command { /// Start bootstrap node Start { /// Multiaddresses of bootstrap nodes to connect to on startup, multiple are supported #[arg(long, alias = "bootstrap-node")] bootstrap_nodes: Vec<Multiaddr>, /// Keypair for node identity, can be obtained with `generate-keypair` command keypair: String, /// Multiaddr to listen on for subspace networking, multiple are supported #[clap(default_value = "/ip4/0.0.0.0/tcp/0")] listen_on: Vec<Multiaddr>, /// Multiaddresses of reserved peers to maintain connections to, multiple are supported #[arg(long, alias = "reserved-peer")] reserved_peers: Vec<Multiaddr>, /// Defines max established incoming connections limit for the peer. #[arg(long, default_value_t = 300)] in_peers: u32, /// Defines max established outgoing connections limit for the peer. #[arg(long, default_value_t = 300)] out_peers: u32, /// Defines max pending incoming connections limit for the peer. #[arg(long, default_value_t = 300)] pending_in_peers: u32, /// Defines max pending outgoing connections limit for the peer. #[arg(long, default_value_t = 300)] pending_out_peers: u32, /// Determines whether we allow keeping non-global (private, shared, loopback..) addresses in Kademlia DHT. #[arg(long, default_value_t = false)] enable_private_ips: bool, /// Protocol version for libp2p stack, should be set as genesis hash of the blockchain for /// production use. #[arg(long)] protocol_version: String, /// Known external addresses #[arg(long, alias = "external-address")] external_addresses: Vec<Multiaddr>, }, /// Generate a new keypair GenerateKeypair { /// Produce an output in JSON format when enabled. #[arg(long, default_value_t = false)] json: bool, }, } /// Helper struct for the `GenerateKeypair` command output. #[derive(Debug, Serialize, Deserialize)] struct KeypairOutput { keypair: String, peer_id: String, } impl Display for KeypairOutput { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { writeln!(f, "PeerId: {}", self.peer_id)?; writeln!(f, "Keypair: {}", self.keypair) } } impl KeypairOutput { fn new(keypair: Keypair) -> Self { Self { keypair: hex::encode(keypair.to_bytes()), peer_id: peer_id_from_keypair(keypair).to_base58(), } } } fn init_logging() { // set default log to info if the RUST_LOG is not set. let env_filter = EnvFilter::builder() .with_default_directive(Level::INFO.into()) .from_env_lossy(); let builder = Subscriber::builder().with_env_filter(env_filter).finish(); builder.init() } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { init_logging(); let command: Command = Command::parse(); match command { Command::Start { bootstrap_nodes, keypair, listen_on, reserved_peers, in_peers, out_peers, pending_in_peers, pending_out_peers, enable_private_ips, protocol_version, external_addresses, } => { debug!( "Libp2p protocol stack instantiated with version: {} ", protocol_version ); let decoded_keypair = Keypair::try_from_bytes(hex::decode(keypair)?.as_mut_slice())?; let keypair = identity::Keypair::from(decoded_keypair); let config = Config { listen_on, allow_non_global_addresses_in_dht: enable_private_ips, reserved_peers, max_established_incoming_connections: in_peers, max_established_outgoing_connections: out_peers, max_pending_incoming_connections: pending_in_peers, max_pending_outgoing_connections: pending_out_peers, // we don't maintain permanent connections with any peer general_connected_peers_handler: None, special_connected_peers_handler: None, bootstrap_addresses: bootstrap_nodes, external_addresses, ..Config::new(protocol_version.to_string(), keypair, (), None) }; let (node, mut node_runner) = subspace_networking::create(config).expect("Networking stack creation failed."); node.on_new_listener(Arc::new({ let node_id = node.id(); move |multiaddr| { info!( "Listening on {}", multiaddr.clone().with(Protocol::P2p(node_id)) ); } })) .detach(); info!("Subspace Bootstrap Node started"); node_runner.run().await; } Command::GenerateKeypair { json } => { let output = KeypairOutput::new(Keypair::generate()); if json { let json_output = serde_json::to_string(&output)?; println!("{json_output}") } else { println!("{output}") } } } Ok(()) } fn peer_id_from_keypair(keypair: Keypair) -> PeerId { peer_id(&libp2p::identity::Keypair::from(keypair)) }
use std::borrow::Borrow; use std::collections::hash_map::*; use std::collections::HashMap; use std::hash::Hash; use std::iter::{FromIterator, IntoIterator}; use std::ops::{Index, IndexMut}; /// A `HashMap` that returns a default when keys are accessed that are not present. #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deserialize))] pub struct DefaultHashMap<K: Eq + Hash, V: Clone> { map: HashMap<K, V>, default: V, } impl<K: Eq + Hash, V: Default + Clone> Default for DefaultHashMap<K, V> { /// The `default()` constructor creates an empty DefaultHashMap with the default of `V` /// as the default for missing keys. /// This is desired default for most use cases, if your case requires a /// different default you should use the `new()` constructor. fn default() -> DefaultHashMap<K, V> { DefaultHashMap { map: HashMap::default(), default: V::default(), } } } impl<K: Eq + Hash, V: Default + Clone> From<HashMap<K, V>> for DefaultHashMap<K, V> { /// If you already have a `HashMap` that you would like to convert to a /// `DefaultHashMap` you can use the `into()` method on the `HashMap` or the /// `from()` constructor of `DefaultHashMap`. /// The default value for missing keys will be `V::default()`, /// if this is not desired `DefaultHashMap::new_with_map()` should be used. fn from(map: HashMap<K, V>) -> DefaultHashMap<K, V> { DefaultHashMap { map, default: V::default(), } } } impl<K: Eq + Hash, V: Clone> Into<HashMap<K, V>> for DefaultHashMap<K, V> { /// The into method can be used to convert a `DefaultHashMap` back into a /// `HashMap`. fn into(self) -> HashMap<K, V> { self.map } } impl<K: Eq + Hash, V: Clone> DefaultHashMap<K, V> { /// Creates an empty `DefaultHashMap` with `default` as the default for missing keys. /// When the provided `default` is equivalent to `V::default()` it is preferred to use /// `DefaultHashMap::default()` instead. pub fn new(default: V) -> DefaultHashMap<K, V> { DefaultHashMap { map: HashMap::new(), default, } } /// Creates a `DefaultHashMap` based on a default and an already existing `HashMap`. /// If `V::default()` is the supplied default, usage of the `from()` constructor or the /// `into()` method on the original `HashMap` is preferred. pub fn new_with_map(default: V, map: HashMap<K, V>) -> DefaultHashMap<K, V> { DefaultHashMap { map, default } } /// Changes the default value permanently or until `set_default()` is called again. pub fn set_default(&mut self, new_default: V) { self.default = new_default; } /// Returns a reference to the value stored for the provided key. /// If the key is not in the `DefaultHashMap` a reference to the default value is returned. /// Usually the `map[key]` method of retrieving keys is preferred over using `get` directly. /// This method accepts both references and owned values as the key. pub fn get<Q, QB: Borrow<Q>>(&self, key: QB) -> &V where K: Borrow<Q>, Q: ?Sized + Hash + Eq, { self.map.get(key.borrow()).unwrap_or(&self.default) } /// Returns a mutable reference to the value stored for the provided key. /// If there is no value stored for the key the default value is first inserted for this /// key before returning the reference. /// Usually the `map[key] = new_val` is prefered over using `get_mut` directly. /// This method only accepts owned values as the key. pub fn get_mut(&mut self, key: K) -> &mut V { let default = &self.default; self.map.entry(key).or_insert_with(|| default.clone()) } } /// Implements the `Index` trait so you can do `map[key]`. /// Nonmutable indexing can be done both by passing a reference or an owned value as the key. impl<'a, K: Eq + Hash, KB: Borrow<K>, V: Clone> Index<KB> for DefaultHashMap<K, V> { type Output = V; fn index(&self, index: KB) -> &V { self.get(index) } } /// Implements the `IndexMut` trait so you can do `map[key] = val`. /// Mutably indexing can only be done when passing an owned value as the key. impl<K: Eq + Hash, V: Clone> IndexMut<K> for DefaultHashMap<K, V> { #[inline] fn index_mut(&mut self, index: K) -> &mut V { self.get_mut(index) } } /// These methods simply forward to the underlying `HashMap`, see that /// [documentation](https://doc.rust-lang.org/std/collections/struct.HashMap.html) for /// the usage of these methods. impl<K: Eq + Hash, V: Clone> DefaultHashMap<K, V> { pub fn capacity(&self) -> usize { self.map.capacity() } #[inline] pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional) } #[inline] pub fn shrink_to_fit(&mut self) { self.map.shrink_to_fit() } #[inline] pub fn keys(&self) -> Keys<K, V> { self.map.keys() } #[inline] pub fn values(&self) -> Values<K, V> { self.map.values() } #[inline] pub fn values_mut(&mut self) -> ValuesMut<K, V> { self.map.values_mut() } #[inline] pub fn iter(&self) -> Iter<K, V> { self.map.iter() } #[inline] pub fn iter_mut(&mut self) -> IterMut<K, V> { self.map.iter_mut() } #[inline] pub fn entry(&mut self, key: K) -> Entry<K, V> { self.map.entry(key) } #[inline] pub fn len(&self) -> usize { self.map.len() } #[inline] pub fn is_empty(&self) -> bool { self.map.is_empty() } #[inline] pub fn drain(&mut self) -> Drain<K, V> { self.map.drain() } #[inline] pub fn clear(&mut self) { self.map.clear() } #[inline] pub fn insert(&mut self, k: K, v: V) -> Option<V> { self.map.insert(k, v) } #[inline] pub fn contains_key<Q>(&self, k: &Q) -> bool where K: Borrow<Q>, Q: ?Sized + Hash + Eq, { self.map.contains_key(k) } #[inline] pub fn remove<Q>(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, Q: ?Sized + Hash + Eq, { self.map.remove(k) } #[inline] pub fn retain<F>(&mut self, f: F) where F: FnMut(&K, &mut V) -> bool, { self.map.retain(f) } } impl<K: Eq + Hash, V: Default + Clone> FromIterator<(K, V)> for DefaultHashMap<K, V> { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = (K, V)>, { Self { map: HashMap::from_iter(iter), default: V::default(), } } } /// The `defaulthashmap!` macro can be used to easily initialize a `DefaultHashMap` in the /// following ways: /// /// ``` /// # #[macro_use] extern crate defaultmap; /// # use defaultmap::*; /// // An empty map with the default as default /// let _: DefaultHashMap<i32, i32> = defaulthashmap!{}; /// /// // An empty map with a specified default /// let _: DefaultHashMap<i32, i32> = defaulthashmap!{5}; /// /// // A prefilled map with the default as the default /// let _: DefaultHashMap<i32, i32> = defaulthashmap!{ /// 1 => 10, /// 5 => 20, /// 6 => 30, /// }; /// /// // A prefilled map with a custom default /// let _: DefaultHashMap<i32, i32> = defaulthashmap!{ /// 5, /// 1 => 10, /// 5 => 20, /// 6 => 30, /// }; /// ``` #[macro_export] macro_rules! defaulthashmap { (@single $($x:tt)*) => (()); (@count $($rest:expr),*) => (<[()]>::len(&[$(defaulthashmap!(@single $rest)),*])); // Copied almost verbatim from maplit (@hashmap $($key:expr => $value:expr),*) => { { let _cap = defaulthashmap!(@count $($key),*); let mut _map = ::std::collections::HashMap::with_capacity(_cap); $( _map.insert($key, $value); )* _map } }; ($($key:expr => $value:expr,)+) => { defaulthashmap!($($key => $value),+) }; ($($key:expr => $value:expr),*) => { { let _map = defaulthashmap!(@hashmap $($key => $value),*); $crate::DefaultHashMap::from(_map) } }; ($default:expr$(, $key:expr => $value:expr)+ ,) => { defaulthashmap!($default, $($key => $value),+) }; ($default:expr$(, $key:expr => $value:expr)*) => { { let _map = defaulthashmap!(@hashmap $($key => $value),*); $crate::DefaultHashMap::new_with_map($default, _map) } }; } #[cfg(test)] mod tests { use super::DefaultHashMap; use std::collections::HashMap; #[test] fn macro_test() { // empty default let macro_map: DefaultHashMap<i32, i32> = defaulthashmap! {}; let normal_map = DefaultHashMap::<i32, i32>::default(); assert_eq!(macro_map, normal_map); // with content let macro_map: DefaultHashMap<_, _> = defaulthashmap! { 1 => 2, 2 => 3, }; let mut normal_map = DefaultHashMap::<_, _>::default(); normal_map[1] = 2; normal_map[2] = 3; assert_eq!(macro_map, normal_map); // empty with custom default let macro_map: DefaultHashMap<i32, i32> = defaulthashmap! {5}; let normal_map = DefaultHashMap::<i32, i32>::new(5); assert_eq!(macro_map, normal_map); // filled hashmap with custom default let macro_map: DefaultHashMap<_, _> = defaulthashmap! { 5, 1 => 2, 2 => 3, }; let mut normal_map = DefaultHashMap::<_, _>::new(5); normal_map[1] = 2; normal_map[2] = 3; assert_eq!(macro_map, normal_map); } #[test] fn add() { let mut map: DefaultHashMap<i32, i32> = DefaultHashMap::default(); *map.get_mut(0) += 1; map[1] += 4; map[2] = map[0] + map.get(&1); assert_eq!(*map.get(0), 1); assert_eq!(*map.get(&0), 1); assert_eq!(map[0], 1); assert_eq!(map[&0], 1); assert_eq!(*map.get(&1), 4); assert_eq!(*map.get(&2), 5); assert_eq!(*map.get(999), 0); assert_eq!(*map.get(&999), 0); assert_eq!(map[999], 0); assert_eq!(map[&999], 0); } #[test] fn counter() { let nums = [1, 4, 3, 3, 4, 2, 4]; let mut counts: DefaultHashMap<i32, i32> = DefaultHashMap::default(); for num in nums.iter() { counts[*num] += 1; } assert_eq!(1, counts[1]); assert_eq!(1, counts[2]); assert_eq!(2, counts[3]); assert_eq!(3, counts[4]); assert_eq!(0, counts[5]); } #[test] fn change_default() { let mut numbers: DefaultHashMap<i32, String> = DefaultHashMap::new("Mexico".to_string()); assert_eq!("Mexico", numbers.get_mut(1)); assert_eq!("Mexico", numbers.get_mut(2)); assert_eq!("Mexico", numbers[3]); numbers.set_default("Cybernetics".to_string()); assert_eq!("Mexico", numbers[1]); assert_eq!("Mexico", numbers[2]); assert_eq!("Cybernetics", numbers[3]); assert_eq!("Cybernetics", numbers[4]); assert_eq!("Cybernetics", numbers[5]); } #[test] fn synonyms() { let synonym_tuples = [ ("nice", "sweet"), ("sweet", "candy"), ("nice", "entertaining"), ("nice", "good"), ("entertaining", "absorbing"), ]; let mut synonym_map: DefaultHashMap<&str, Vec<&str>> = DefaultHashMap::default(); for &(l, r) in synonym_tuples.iter() { synonym_map[l].push(r); synonym_map[r].push(l); } println!("{:#?}", synonym_map); assert_eq!(synonym_map["good"], vec!["nice"]); assert_eq!(synonym_map["nice"], vec!["sweet", "entertaining", "good"]); assert_eq!(synonym_map["evil"], Vec::<&str>::new()); } #[derive(Clone)] struct Clonable; #[derive(Default, Clone)] struct DefaultableValue; #[derive(Hash, Eq, PartialEq)] struct Hashable(i32); #[test] fn minimal_derives() { let _: DefaultHashMap<Hashable, Clonable> = DefaultHashMap::new(Clonable); let _: DefaultHashMap<Hashable, DefaultableValue> = DefaultHashMap::default(); } #[test] fn from() { let normal: HashMap<i32, i32> = vec![(0, 1), (2, 3)].into_iter().collect(); let mut default: DefaultHashMap<_, _> = normal.into(); default.get_mut(4); assert_eq!(default[0], 1); assert_eq!(default[2], 3); assert_eq!(default[1], 0); assert_eq!(default[4], 0); let expected: HashMap<i32, i32> = vec![(0, 1), (2, 3), (4, 0)].into_iter().collect(); assert_eq!(expected, default.into()); } #[cfg(feature = "with-serde")] mod serde_tests { use super::*; #[test] fn deserialize_static() { let s = "{ \"map\" : { \"foo\": 3, \"bar\": 5 }, \"default\":15 }"; let h: Result<DefaultHashMap<&str, i32>, _> = serde_json::from_str(&s); let h = h.unwrap(); assert_eq!(h["foo"] * h["bar"], h["foobar"]) } #[test] fn serialize_and_back() { let h1: DefaultHashMap<i32, u64> = defaulthashmap!(1 => 10, 2 => 20, 3 => 30); let s = serde_json::to_string(&h1).unwrap(); let h2: DefaultHashMap<i32, u64> = serde_json::from_str(&s).unwrap(); assert_eq!(h2, h2); assert_eq!(h2[3], 30); } #[test] fn serialize_default() { let h1: DefaultHashMap<&str, u64> = DefaultHashMap::new(42); let s = serde_json::to_string(&h1).unwrap(); let h2: DefaultHashMap<&str, u64> = serde_json::from_str(&s).unwrap(); assert_eq!(h2["answer"], 42); } #[test] fn std_hashmap() { let h1: DefaultHashMap<i32, i32> = defaulthashmap!(1=> 10, 2=> 20); let stdhm: std::collections::HashMap<i32, i32> = h1.clone().into(); let s = serde_json::to_string(&stdhm).unwrap(); let h2: DefaultHashMap<i32, i32> = DefaultHashMap::new_with_map(i32::default(), serde_json::from_str(&s).unwrap()); assert_eq!(h1, h2); } } }
const INPUT: &str = include_str!("../input.txt"); const SAMPLE_INPUT: &str = include_str!("../sample_input.txt"); fn solve_part_1(input: &str) -> u32 { let mut escape_hex = 0u32; let mut escape_slash = 0u32; let mut escape_quote = 0u32; let mut number_quotes = 0u32; for line in input.trim().lines() { number_quotes += 2; let chars: Vec<char> = line.trim().chars().collect(); let mut i: usize = 1usize; while i < chars.len() { let mut pattern: String = String::new(); pattern.push(chars[i-1]); pattern.push(chars[i]); if pattern == String::from("\\x") { i += 3; escape_hex += 1; } if pattern == String::from("\\\\") { i += 1; escape_slash += 1; } if pattern == String::from("\\\"") { i += 1; escape_quote += 1; } i += 1; } } 3 * escape_hex + escape_slash + escape_quote + number_quotes } fn solve_part_2(input: &str) -> u32 { let mut escape_slash = 0u32; let mut escape_quote = 0u32; let mut number_quotes = 0u32; for line in input.trim().lines() { number_quotes += 2; let chars: Vec<char> = line.trim().chars().collect(); let mut i: usize = 0usize; while i < chars.len() { let mut pattern: String = String::new(); pattern.push(chars[i]); if pattern == String::from("\\") { escape_slash += 1; } if pattern == String::from("\"") { escape_quote += 1; } i += 1; } } escape_slash + escape_quote + number_quotes } fn main() { println!("Answer part 1: {}", solve_part_1(INPUT)); println!("Answer part 2: {}", solve_part_2(INPUT)); }
use std::fs::File; use std::io::Read; use std::path::Path; use std::str::FromStr; fn inputs_directory<'a>() -> &'a Path { Path::new("src/inputs/") } // load file pub fn load_input_file<S>(name: &str) -> Result<S, ()> where S: FromStr, { let input_file = inputs_directory().join(name); let mut contents = String::new(); File::open(input_file) .and_then(|mut file| file.read_to_string(&mut contents)) .map_err(|_| ()) .and_then(|_| S::from_str(&contents).map_err(|_| ())) } pub struct ListInput<S: FromStr>(pub Vec<S>); impl<S> FromStr for ListInput<S> where S: FromStr, { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(ListInput( s.split(',') .map(S::from_str) .filter_map(Result::ok) .collect(), )) } }
use crate::util::{char_to_i32, lines_from_file, vec_to_string}; pub fn day3() { println!("== Day 3 =="); let input = lines_from_file("src/day3/input.txt"); let a = part_a(&input); println!("Part A: {}", a); let b = part_b(&input); println!("Part B: {}", b); } fn part_a(input: &Vec<String>) -> i32 { let x: Vec<Vec<i32>> = input.iter() .map(|s| s.chars() .map(|c| char_to_i32(c)) .collect()) .collect(); let mut sum_of_place = vec![0; x[0].len()]; for line in x { // println!("{:?}",line); for (index, value) in line.iter().enumerate() { sum_of_place[index] += *value; } } // println!("{:?}",sum_of_place); let mut gamma: Vec<i32> = Vec::new(); let mut sigma: Vec<i32> = Vec::new(); let input_length: i32 = input.len() as i32; for value in sum_of_place { if value > input_length / 2 { gamma.push(1); sigma.push(0); } else { gamma.push(0); sigma.push(1); } } // println!("{:?}",gamma); // println!("{:?}",sigma);4139586 let gamma_str = vec_to_string(gamma); let sigma_str = vec_to_string(sigma); let gamma_val = i32::from_str_radix(gamma_str.as_str(), 2).unwrap(); let sigma_val = i32::from_str_radix(sigma_str.as_str(), 2).unwrap(); // println!("{}", gamma_val); return sigma_val * gamma_val; } fn part_b(input: &Vec<String>) -> i32 { let oxygen = reduce(input, 0, true); let carbon = reduce(input, 0, false); // println!("{:?}", oxygen); // println!("{:?}", carbon); let o = i32::from_str_radix(&oxygen[0], 2).unwrap(); let c = i32::from_str_radix(&carbon[0], 2).unwrap(); // println!("{:?}", o); // println!("{:?}", c); return c * o; } fn reduce(input: &Vec<String>, index: i32, most_or_least: bool) -> Vec<String> { // println!("At index {} and most/least is {} and got this as input: {:?}", index, most_or_least,input); // Loop over this until you only have one row in the response if input.len() == 1 { return input.to_vec(); } let mut every_row_at_index = Vec::new(); for line in input { let c = line.chars().nth(index as usize).unwrap(); every_row_at_index.push(c); } // println!("Every row at index {} is {:?}", index, every_row_at_index); let common: char; if most_or_least { common = most_common(every_row_at_index); } else { common = least_common(every_row_at_index); } // println!("Common was {} and {}", most_or_least, common); return reduce(&filter(input, common, index), index + 1, most_or_least); } fn filter(input: &Vec<String>, look_for: char, at_index: i32) -> Vec<String> { let mut ret: Vec<String> = Vec::new(); for line in input { if line.chars().nth(at_index as usize).unwrap() == look_for { ret.push(line.parse().unwrap()); } } ret } fn least_common(input: Vec<char>) -> char { match most_common(input) { '1' => '0', '0' => '1', _ => '1' } } fn most_common(input: Vec<char>) -> char { let sum: i32 = input.iter() .map(|c| char_to_i32(*c)) .sum(); let in_len: f64 = (input.len() as f64) / 2 as f64; let usum = sum as f64; // println!("len {}, In_len {} and usum {}", input.len(), in_len, usum); if usum < in_len { return '0'; } return '1'; } #[cfg(test)] mod tests { use super::*; #[test] fn part_a_test_input() { let filename = "src/day3/test-input.txt"; let input = lines_from_file(filename); let result = part_a(&input); assert_eq!(198, result); } #[test] fn part_a_real() { let filename = "src/day3/input.txt"; let input = lines_from_file(filename); let result = part_a(&input); assert_eq!(4139586, result); } #[test] fn most_common_test() { let vec1 = vec!['1', '0', '1']; let common = most_common(vec1); assert_eq!('1', common) } #[test] fn filter_lines() { let input: Vec<String> = vec![ "101".to_string(), "001".to_string(), "111".to_string(), "000".to_string(), ]; let expected = vec![ "101".to_string(), "111".to_string(), ]; let result = filter(&input, '1', 0); assert_eq!(expected, result) } #[test] fn reduce_lines() { let input: Vec<String> = vec![ "101".to_string(), "000".to_string(), ]; let result = reduce(&input, 0, true); let result2 = reduce(&input, 0, false); assert_eq!(vec!["101".to_string()], result); assert_eq!(vec!["000".to_string()], result2); } #[test] fn part_b_test_input() { let filename = "src/day3/test-input.txt"; let input = lines_from_file(filename); let result = part_b(&input); assert_eq!(230, result); } #[test] fn part_b_real() { let filename = "src/day3/input.txt"; let input = lines_from_file(filename); let result = part_b(&input); assert_eq!(1800151, result); } }
/* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000: */ use std::{u32}; fn main() { println!("{}", sum_of_multiples(3, 5)); } fn sum_of_multiples(x: u32, y: u32) -> u32 { const CAP: u32 = 1000; let mut adder: u32 = 0; for n in 1..CAP { if (n % x == 0) || (n % y == 0) { println!("{}", n); adder += n; } } return adder; // Returned answer = 233168 }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ #[cfg(test)] mod e2e_test { #[repr(C, align(32))] pub struct F32Slice104([f32; 104]); #[repr(C, align(32))] pub struct F16Slice104([Half; 104]); use approx::assert_abs_diff_eq; use crate::half::Half; use crate::l2_float_distance::{distance_l2_vector_f16, distance_l2_vector_f32}; fn no_vector_compare_f32(a: &[f32], b: &[f32]) -> f32 { let mut sum = 0.0; for i in 0..a.len() { let a_f32 = a[i]; let b_f32 = b[i]; let diff = a_f32 - b_f32; sum += diff * diff; } sum } fn no_vector_compare(a: &[Half], b: &[Half]) -> f32 { let mut sum = 0.0; for i in 0..a.len() { let a_f32 = a[i].to_f32(); let b_f32 = b[i].to_f32(); let diff = a_f32 - b_f32; sum += diff * diff; } sum } #[test] fn avx2_matches_novector() { for i in 1..3 { let (f1, f2) = get_test_data(0, i); let distance_f32x8 = distance_l2_vector_f32::<104>(&f1.0, &f2.0); let distance = no_vector_compare_f32(&f1.0, &f2.0); assert_abs_diff_eq!(distance, distance_f32x8, epsilon = 1e-6); } } #[test] fn avx2_matches_novector_random() { let (f1, f2) = get_test_data_random(); let distance_f32x8 = distance_l2_vector_f32::<104>(&f1.0, &f2.0); let distance = no_vector_compare_f32(&f1.0, &f2.0); assert_abs_diff_eq!(distance, distance_f32x8, epsilon = 1e-4); } #[test] fn avx_f16_matches_novector() { for i in 1..3 { let (f1, f2) = get_test_data_f16(0, i); let _a_slice = f1.0.map(|x| x.to_f32().to_string()).join(", "); let _b_slice = f2.0.map(|x| x.to_f32().to_string()).join(", "); let expected = no_vector_compare(f1.0[0..].as_ref(), f2.0[0..].as_ref()); let distance_f16x8 = distance_l2_vector_f16::<104>(&f1.0, &f2.0); assert_abs_diff_eq!(distance_f16x8, expected, epsilon = 1e-4); } } #[test] fn avx_f16_matches_novector_random() { let (f1, f2) = get_test_data_f16_random(); let expected = no_vector_compare(f1.0[0..].as_ref(), f2.0[0..].as_ref()); let distance_f16x8 = distance_l2_vector_f16::<104>(&f1.0, &f2.0); assert_abs_diff_eq!(distance_f16x8, expected, epsilon = 1e-4); } fn get_test_data_f16(i1: usize, i2: usize) -> (F16Slice104, F16Slice104) { let (a_slice, b_slice) = get_test_data(i1, i2); let a_data = a_slice.0.iter().map(|x| Half::from_f32(*x)); let b_data = b_slice.0.iter().map(|x| Half::from_f32(*x)); ( F16Slice104(a_data.collect::<Vec<Half>>().try_into().unwrap()), F16Slice104(b_data.collect::<Vec<Half>>().try_into().unwrap()), ) } fn get_test_data(i1: usize, i2: usize) -> (F32Slice104, F32Slice104) { use base64::{engine::general_purpose, Engine as _}; let b64 = general_purpose::STANDARD.decode(TEST_DATA).unwrap(); let decoded: Vec<Vec<f32>> = bincode::deserialize(&b64).unwrap(); debug_assert!(decoded.len() > i1); debug_assert!(decoded.len() > i2); let mut f1 = F32Slice104([0.0; 104]); let v1 = &decoded[i1]; debug_assert!(v1.len() == 104); f1.0.copy_from_slice(v1); let mut f2 = F32Slice104([0.0; 104]); let v2 = &decoded[i2]; debug_assert!(v2.len() == 104); f2.0.copy_from_slice(v2); (f1, f2) } fn get_test_data_f16_random() -> (F16Slice104, F16Slice104) { let (a_slice, b_slice) = get_test_data_random(); let a_data = a_slice.0.iter().map(|x| Half::from_f32(*x)); let b_data = b_slice.0.iter().map(|x| Half::from_f32(*x)); ( F16Slice104(a_data.collect::<Vec<Half>>().try_into().unwrap()), F16Slice104(b_data.collect::<Vec<Half>>().try_into().unwrap()), ) } fn get_test_data_random() -> (F32Slice104, F32Slice104) { use rand::Rng; let mut rng = rand::thread_rng(); let mut f1 = F32Slice104([0.0; 104]); for i in 0..104 { f1.0[i] = rng.gen_range(-1.0..1.0); } let mut f2 = F32Slice104([0.0; 104]); for i in 0..104 { f2.0[i] = rng.gen_range(-1.0..1.0); } (f1, f2) } const TEST_DATA: &str = "BQAAAAAAAABoAAAAAAAAAPz3Dj7+VgG9z/DDvQkgiT2GryK+nwS4PTeBorz4jpk9ELEqPKKeX73zZrA9uAlRvSqpKT7Gft28LsTuO8XOHL6/lCg+pW/6vJhM7j1fInU+yaSTPC2AAb5T25M8o2YTvWgEAz00cnq8xcUlPPvnBb2AGfk9UmhCvbdUJzwH4jK9UH7Lvdklhz3SoEa+NwsIvt2yYb4q7JA8d4fVvfX/kbtDOJe9boXevbw2CT7n62A9B6hOPlfeNz7CO169vnjcvR3pDz6KZxC+XR/2vTd9PTx7YY492FF2PekiGDt3OSw9IIlGPQooMj5DZcY8EgQgvpg9572paca91GQTPoWpFr7U+t697YAQPYHUXr1d8ow8AQE7PFo6JD3tt+I96ahxvYuvlD3+IW29N4Jtu2/01Ltvvg2+dja+vI8uazvITZO9mXhavpfJ6T2tB8S7OKT3PWWjpj0Mjty9advIPFgucTp3JO69CI6YPaWoDD5pwim9rjUovh2qgr3R/lq+nUi3PI+acL041o081D8lvRCJLTwAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAA6pJO94NE1voDn+rzQ8CY+1rxkvtspaz0xTPw7+0GMvC0ZgbyWwdy8zHcovKdvdb70BLC8DtHKvdK6vz0R9Ys7vBWyvZK1LL0ehYM9aV+JveuvoD2ilvo9NLJ4vbRnPT4MXAW+BhG4POOBaD0Vz5I9s1+1vTUdHb7Kjcw9uVUJvdbgoj3TbBe8WwPSvYoBBj4m6c+9xTXTvVTDaL28+Ac9KtA0Pa3tS73Vq5S8fNLkvf/Gir0yILy9ZYR3vvUdUD2ZB5W9rHI4PXS76L070oG9EsjYPb89S75pz7Q9xFKyvZ5ECT0kDSU+l4AQPsQVqzyq/LW95ZCZPC6nQj0VIBa9XwkhPr1gy72c7mw937XXvQ76ur3sRok9mCUqPXHvgj28jV89LZN8O0eH0T0KMdq9ZzXevYbmPr0fcac8r7j3vYmKCL4Sewm+iLtRviuOjz08XbE9LlYevDI1wz0s7z278oVJvtpjrT20IEU9+mTtvBjMQz1H9Ey+LQEXva1Rwrxmyts9sf1hPRY3xL3RdRU+AAAAAAAAAAAAAAAAAAAAAGgAAAAAAAAARqSTvbYJpLx1x869cW67PeeJhb7/cBu9m0eFPQO3oL0I+L49YQDavTYSez3SmTg96hBGPuh4oL2x2ow6WdCUO6XUSz4xcU88GReAvVfekj0Ph3Y9z43hvBzT5z1I2my9UVy3vAj8jL08Gtm9CfJcPRihTr1+8Yu9TiP+PNrJa77Dfa09IhpEPesJNr0XzFU8yye3PZKFyz3uzJ09FLRUvYq3l73X4X07DDUzvq9VXjwWtg8+JrzYPcFCkr0jDCg9T9zlvZbZjz4Y8pM89xo8PgAcfbvYSnY8XoFKvO05/L36yzE8J+5yPqfe5r2AZFq8ULRDvnkTgrw+S7q9qGYLvQDZYL1T8d09bFikvZw3+jsYLdO8H3GVveHBYT4gnsE8ZBIJPpzOEj7OSDC+ZYu+vFc1Erzko4M9GqLtPBHH5TwpeRs+miC4PBHH5Tw9Z9k9VUsUPjnppj0oC5C9mcqDvY7y1rxdvZU8PdFAPov9lz0bOmq94kdyPBBokTxtOj89fu4avSsazj1P7iE+x8YkPAAAAAAAAAAAAAAAAAAAAABoAAAAAAAAAHEruT3mgKM8JnEvvAsfHL63906+ifhgvldl1r14OeO9waUyuw3yUzx+PDW9UbDhPQP4Lb4KRRk+Oky2vaLfaT30mrA9YMeZPfzPMz4h42M+XfCHva4AGr6MOSM+iBOzvdsaE7xFxgI+gJGXvVMzE75kHY+8oAWNvVqNK7yOx589fU3lvVVPg730Cwk+DKkEPWYtxjqQ2MK9H0T+vTnGQj2yq5w8L49BvrEJrzyB4Yo9AXV7PYGCLr3MxsG9oWM7PTyu8TzEOhW+dyWrvUTxHD2nL+c9+VKFPcthhLsc0PM8FdyPPeLj/z1WAHS8ZvW2PGg4Cb5u3IU9g4CovSHW+L2CWoG++nZnPAi2ST3HmUC9P5rJuxQbU765lwU+7FLBPUPTfL0uGgk+yKy2PYwXaT1I4I+9AU6VPQ5QaDx9mdE8Qg8zPfGCUjzD/io9rr+BvTNDqT0MFNi9mHatvS1iJD0nVrK78WmIPE0QsL3PAQq9cMRgPWXmmr3yTcw9UcXrPccwa76+cBq+5iVOvUg9c70AAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAB/K7k9hCsnPUJXJr2Wg4a9MEtXve33Sj0VJZ89pciEvWLqwLzUgyu8ADTGPAVenL2UZ/c96YtMved+Wr3LUro9H8a7vGTSA77C5n69Lf3pPQj4KD5cFKq9fZ0uvvYQCT7b23G9XGMCPrGuy736Z9A9kZzFPSuCSD7/9/07Y4/6POxLir3/JBS9qFKMvkSzjryPgVY+ugq8PC9yhbsXaiq+O6WfPcvFK7vZXAy+goAQvXpHHj5jwPI87eokvrySET5QoOm8h8ixOhXzKb5s8+A9sjcJPjiLAz598yQ9yCYSPq6eGz4rvjE82lvGvWuIOLx23zK9hHg8vTWOv70/Tse81fA6Pr2wNz34Eza+2Uj3PZ3trr0aXAI9PCkKPiybe721P9U9QkNLO927jT3LpRA+mpJUvUeU6rwC/Qa+lr4Cvgrpnj1pQ/i9TxhSvJqYr72RS6y8aQLTPQzPiz3vSRY94NfrPJl6LL2adjO8iYfPuhRzZz2f7R8+iVskPcUeXr12ZiI+nd3xvIYv8bwqYlg+AAAAAAAAAAAAAAAAAAAAAA=="; }
extern crate piston_window; use piston_window::*; use crate::circbuf::CircBuf; use std::time::SystemTime; // use graphics::glyph_cache::rusttype::GlyphCache; const SIZE: [f64; 2] = [1280., 720.]; const BUFFERED_SECS: usize = 10; pub fn run<I>(mut data: I) where I: Iterator<Item=(f32, f32, f32, f32)> { let frequency = { let mut frequency = 0.; let mut time = 0.; while time < 1. { time += data.next().unwrap().0; frequency += 1.; } frequency / time }; println!("Guessing sample rate: {}/s?", frequency); let circ_buf_size = BUFFERED_SECS * frequency as usize; let mut circ_buf: CircBuf<(f32, f32, f32, f32)> = CircBuf::new(circ_buf_size); println!("Populating the visualizer's buffer... This may take a while..."); for _ in 0..circ_buf_size { circ_buf.push(data.next().unwrap()); } println!("Visualizer's buffer has been populated."); let mut window: PistonWindow = WindowSettings::new("Acceleration Demo", SIZE) .exit_on_esc(true).build().unwrap(); let mut last_accel = (0., 0., 0., 0.); let x_factor = SIZE[0] / 11.; let x_offset = SIZE[0] / 22.; let y_factor = 7. * SIZE[1] / 16e-3; // 10m * 10^-3 for entire FoV let y_offset = SIZE[1] / 2.; // let gc = GlyphCache::new(Font::from_bytes(include_bytes!("../fonts/font.ttf"))); while let Some(e) = window.next() { window.draw_2d(&e, |ctx, g2d, _device| { clear([1.0; 4], g2d); line( [0.0, 0.0, 0.0, 1.0], // black 3.0, [x_offset, y_offset, SIZE[0] - x_offset, y_offset], ctx.transform, g2d, ); for i in 0..=10 { let x = x_offset + i as f64 * x_factor; line( [0.0, 0.0, 0.0, 0.2], // grey 1.0, [x, SIZE[1] / 16., x, SIZE[1] * 15. / 16.], ctx.transform, g2d, ); // text([0.0, 0.0, 0.0, 1.0],24,&format!("{}", i), gc, ctx.transform,g2d); } let mut time = 0.; circ_buf.iter() .filter(|(dt, _, _, _)| *dt > 0.) .for_each(|(dt, ax, ay, az)| { let (dt, ax, ay, az) = (*dt as f64, -*ax as f64, -*ay as f64, -*az as f64); let vsum = (ax.powf(2.) + ay.powf(2.) + az.powf(2.)).sqrt(); if last_accel == (0., 0., 0., 0.) { last_accel = (ax, ay, az, vsum); return; } let xpair = [time * x_factor + x_offset, (time - dt) * x_factor + x_offset]; let x = [xpair[0], last_accel.0 * y_factor + y_offset, xpair[1], ax * y_factor + y_offset]; let y = [xpair[0], last_accel.1 * y_factor + y_offset, xpair[1], ay * y_factor + y_offset]; let z = [xpair[0], last_accel.2 * y_factor + y_offset, xpair[1], az * y_factor + y_offset]; let sum = [xpair[0], last_accel.3 * y_factor + y_offset, xpair[1], vsum * y_factor + y_offset]; line( [1.0, 0.0, 0.0, 1.0], // red 1.0, x, ctx.transform, g2d, ); line( [0.0, 1.0, 0.0, 1.0], // green 1.0, y, ctx.transform, g2d, ); line( [0.0, 0.0, 1.0, 1.0], // blue 1.0, z, ctx.transform, g2d, ); line( [0.0, 0.0, 0.0, 0.5], // grey 1.0, sum, ctx.transform, g2d, ); last_accel = (ax, ay, az, vsum); time += dt; }); last_accel = (0., 0., 0., 0.); let start_of_refresh = SystemTime::now(); while let Ok(delay) = start_of_refresh.elapsed() { // This will limit framerate to 2x refresh if delay.as_millis() > (2e3 / frequency).ceil() as u128 { break; } if let Some(item) = data.next() { circ_buf.push(item); } else { println!("Data stream exhausted!"); } } while circ_buf.fold(0., |t, (dt, _, _, _)| t + dt) > BUFFERED_SECS as f32 { circ_buf.push((0., 0., 0., 0.)); } }); } }
//To use this, please install zfs-fuse use redox::*; pub mod nvpair; pub mod nvstream; pub mod xdr; #[repr(packed)] pub struct VdevLabel { pub blank: [u8; 8 * 1024], pub boot_header: [u8; 8 * 1024], pub nv_pairs: [u8; 112 * 1024], pub uberblocks: [Uberblock; 128], } impl VdevLabel { pub fn from(data: &[u8]) -> Option<Self> { if data.len() >= mem::size_of::<VdevLabel>() { let vdev_label = unsafe { ptr::read(data.as_ptr() as *const VdevLabel) }; Some(vdev_label) } else { Option::None } } } #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct Uberblock { pub magic: u64, pub version: u64, pub txg: u64, pub guid_sum: u64, pub timestamp: u64, pub rootbp: BlockPtr, } impl Uberblock { pub fn magic_little() -> u64 { return 0x0cb1ba00; } pub fn magic_big() -> u64 { return 0x00bab10c; } pub fn from(data: &Vec<u8>) -> Option<Self> { if data.len() >= mem::size_of::<Uberblock>() { let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) }; if uberblock.magic == Uberblock::magic_little() { return Option::Some(uberblock); } else if uberblock.magic == Uberblock::magic_big() { return Option::Some(uberblock); } else if uberblock.magic > 0 { println!("Unknown Magic: {:X}", uberblock.magic as usize); } } Option::None } } #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct DVAddr { pub vdev: u64, pub offset: u64, } impl DVAddr { /// Sector address is the offset plus two vdev labels and one boot block (4 MB, or 8192 sectors) pub fn sector(&self) -> u64 { self.offset + 0x2000 } pub fn asize(&self) -> u64 { self.vdev & 0xFFFFFF + 1 } } #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct BlockPtr { pub dvas: [DVAddr; 3], pub flags_size: u64, pub padding: [u64; 3], pub birth_txg: u64, pub fill_count: u64, pub checksum: [u64; 4], } impl BlockPtr { pub fn lsize(&self) -> u64 { (self.flags_size) & 0xFFFF + 1 } pub fn psize(&self) -> u64 { ((self.flags_size) >> 16) & 0xFFFF + 1 } } #[derive(Copy, Clone, Debug)] #[repr(packed)] pub struct Gang { pub bps: [BlockPtr; 3], pub padding: [u64; 14], pub magic: u64, pub checksum: u64, } impl Gang { pub fn magic() -> u64 { return 0x117a0cb17ada1002; } } pub struct ZFS { disk: File, } impl ZFS { pub fn new(disk: File) -> Self { ZFS { disk: disk } } //TODO: Error handling pub fn read(&mut self, start: usize, length: usize) -> Vec<u8> { let mut ret: Vec<u8> = vec![0; length*512]; self.disk.seek(Seek::Start(start * 512)); self.disk.read(&mut ret); return ret; } pub fn write(&mut self, block: usize, data: &[u8; 512]) { self.disk.seek(Seek::Start(block * 512)); self.disk.write(data); } pub fn uber(&mut self) -> Option<Uberblock> { let mut newest_uberblock: Option<Uberblock> = Option::None; for i in 0..128 { match Uberblock::from(&self.read(256 + i * 2, 2)) { Option::Some(uberblock) => { let mut newest = false; match newest_uberblock { Option::Some(previous) => { if uberblock.txg > previous.txg { newest = true; } } Option::None => newest = true, } if newest { newest_uberblock = Option::Some(uberblock); } } Option::None => (), //Invalid uberblock } } return newest_uberblock; } } //TODO: Find a way to remove all the to_string's pub fn main() { console_title("ZFS"); let red = [255, 127, 127, 255]; let green = [127, 255, 127, 255]; let blue = [127, 127, 255, 255]; println!("Type open zfs.img to open the image file"); let mut zfs_option: Option<ZFS> = Option::None; while let Option::Some(line) = readln!() { let mut args: Vec<String> = Vec::new(); for arg in line.split(' ') { args.push(arg.to_string()); } if let Option::Some(command) = args.get(0) { println!("# {}", line); let mut close = false; match zfs_option { Option::Some(ref mut zfs) => { if *command == "uber".to_string() { //128 KB of ubers after 128 KB of other stuff match zfs.uber() { Some(uberblock) => { println_color!(green, "Newest Uberblock {:X}", uberblock.magic); println!("Version {}", uberblock.version); println!("TXG {}", uberblock.txg); println!("GUID {:X}", uberblock.guid_sum); println!("Timestamp {}", uberblock.timestamp); } None => println_color!(red, "No valid uberblock found!"), } } else if *command == "vdev_label".to_string() { match VdevLabel::from(&zfs.read(0, 256 * 2)) { Some(ref mut vdev_label) => { let mut xdr = xdr::MemOps::new(&mut vdev_label.nv_pairs); let nv_list = nvstream::decode_nv_list(&mut xdr); println_color!(green, "Got nv_list:\n{:?}", nv_list); }, None => { println_color!(red, "Couldn't read vdev_label"); }, } } else if *command == "mos".to_string() { match zfs.uber() { Some(uberblock) => { let mos_dva = uberblock.rootbp.dvas[0]; println_color!(green, "DVA: {:?}", mos_dva); let mut mos = zfs.read(mos_dva.sector() as usize, mos_dva.asize() as usize); let mut xdr = xdr::MemOps::new(&mut mos); let nv_list = nvstream::decode_nv_list(&mut xdr); println_color!(green, "Got nv_list:\n{:?}", nv_list); }, None => println_color!(red, "No valid uberblock found!"), } } else if *command == "dump".to_string() { match args.get(1) { Some(arg) => { let sector = arg.to_num(); println_color!(green, "Dump sector: {}", sector); let data = zfs.read(sector, 1); for i in 0..data.len() { if i % 32 == 0 { print!("\n{:X}:", i); } if let Option::Some(byte) = data.get(i) { print!(" {:X}", *byte); } else { println!(" !"); } } print!("\n"); } None => println_color!(red, "No sector specified!"), } } else if *command == "close".to_string() { println_color!(red, "Closing"); close = true; } else { println_color!(blue, "Commands: uber vdev_label mos dump close"); } } Option::None => { if *command == "open".to_string() { match args.get(1) { Option::Some(arg) => { println_color!(green, "Open: {}", arg); zfs_option = Option::Some(ZFS::new(File::open(arg))); } Option::None => println_color!(red, "No file specified!"), } } else { println_color!(blue, "Commands: open"); } } } if close { zfs_option = Option::None; } } } }
#[macro_use] extern crate serde_derive; extern crate libc; use libc::{c_char, c_int}; use std::ffi::{CStr, CString}; #[link(name = adm_engine)] extern "C" { fn renderAdmContent(input: *mut *const c_char, destination: *mut *const c_char, element_gains_cstr: *mut *const c_char, element_id_to_render_cstr: *mut *const c_char, output_message: *mut *const c_char) -> c_int; } use mcai_worker_sdk::{job::JobResult, prelude::*, MessageEvent}; pub mod built_info { include!(concat!(env!("OUT_DIR"), "/built.rs")); } #[derive(Debug, Default)] struct AdmEngineEvent {} #[derive(Debug, Clone, Deserialize, JsonSchema)] pub struct WorkerParameters { /// # Element ID /// element_id: String, /// # Gain Mapping /// gain_mapping: Vec<String>, destination_path: String, source_path: String, } impl MessageEvent<WorkerParameters> for AdmEngineEvent { fn get_name(&self) -> String { "ADM Engine worker".to_string() } fn get_short_description(&self) -> String { "Worker to rebalance audio loudness".to_string() } fn get_description(&self) -> String { r#"This worker rebalances audio loudness."#.to_string() } fn get_version(&self) -> Version { Version::parse(built_info::PKG_VERSION).expect("unable to locate Package version") } fn process( &self, channel: Option<McaiChannel>, parameters: WorkerParameters, job_result: JobResult, ) -> Result<JobResult> { info!(target: &job_result.get_str_job_id(), "Start ADM Engine Job"); let source_path = CString::new(parameters.source_path).unwrap(); let source_path_ptr: *const c_char = source_path.as_ptr(); let destination_path = CString::new(parameters.destination_path).unwrap(); let destination_path_ptr: *const c_char = destination_path.as_ptr(); // TODO: get whole array let gain_mapping = CString::new(parameters.gain_mapping[0]).unwrap(); let gain_mapping_ptr: *const c_char = gain_mapping.as_ptr(); let element_id = CString::new(parameters.element_id).unwrap(); let element_id_ptr: *const c_char = element_id.as_ptr(); let mut output_message = std::ptr::null(); if renderAdmContent(&mut source_path_ptr, &mut destination_path_ptr, &mut gain_mapping_ptr, &mut element_id_ptr, &mut output_message) != 0 { let message = unsafe { CStr::from_ptr(output_message).to_str().unwrap().to_owned() }; error!(target: &job_result.get_str_job_id(), "{}", message); return Ok(job_result.with_status(JobStatus::Error) .with_message(&message)) } Ok(job_result.with_status(JobStatus::Completed)) } } fn main() { let worker = AdmEngineEvent::default(); start_worker(worker); }
//! The `plan` module provides a domain-specific language for payment plans. Users create Budget objects that //! are given to an interpreter. The interpreter listens for `Witness` transactions, //! which it uses to reduce the payment plan. When the plan is reduced to a //! `Payment`, the payment is executed. use chrono::prelude::*; use signature::PublicKey; /// The types of events a payment plan can process. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub enum Witness { /// The current time. Timestamp(DateTime<Utc>), /// A siganture from PublicKey. Signature(PublicKey), } /// Some amount of tokens that should be sent to the `to` `PublicKey`. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub struct Payment { /// Amount to be paid. pub tokens: i64, /// The `PublicKey` that `tokens` should be paid to. pub to: PublicKey, } /// Interface to smart contracts. pub trait PaymentPlan { /// Return Payment if the payment plan requires no additional Witnesses. fn final_payment(&self) -> Option<Payment>; /// Return true if the plan spends exactly `spendable_tokens`. fn verify(&self, spendable_tokens: i64) -> bool; /// Apply a witness to the payment plan to see if the plan can be reduced. /// If so, modify the plan in-place. fn apply_witness(&mut self, witness: &Witness); }
use hacl_star_sys as ffi; use crate::And; pub const KEY_LENGTH: usize = 32; pub const NONCE_LENGTH: usize = 12; pub const BLOCK_LENGTH: usize = 64; pub type ChaCha20<'a> = And<&'a Key, &'a Nonce>; define!{ pub struct Key/key(pub [u8; KEY_LENGTH]); pub struct Nonce/nonce(pub [u8; NONCE_LENGTH]); } impl Key { #[inline] pub fn nonce<'a>(&'a self, n: &'a [u8; NONCE_LENGTH]) -> ChaCha20<'a> { And(self, nonce(n)) } } impl<'a> ChaCha20<'a> { pub fn process(self, buf: &mut [u8]) { unsafe { ffi::chacha20::Hacl_Chacha20_chacha20( buf.as_mut_ptr(), buf.as_ptr() as _, buf.len() as _, (self.0).0.as_ptr() as _, (self.1).0.as_ptr() as _, 0 ) } } pub fn process_ic(self, ctr: u32, input: &[u8], output: &mut [u8]) { assert!(output.len() >= input.len()); unsafe { ffi::chacha20::Hacl_Chacha20_chacha20( output.as_mut_ptr(), input.as_ptr() as _, input.len() as _, (self.0).0.as_ptr() as _, (self.1).0.as_ptr() as _, ctr ); } } pub fn keyblock(self, ctr: u32, block: &mut [u8; BLOCK_LENGTH]) { unsafe { ffi::chacha20::Hacl_Chacha20_chacha20_key_block( block.as_mut_ptr(), (self.0).0.as_ptr() as _, (self.1).0.as_ptr() as _, ctr ); } } }
use std::{ env, env::{VarError, Vars}, net::SocketAddr, }; #[derive(Debug)] pub struct Env {} mod default { pub const ASSET_PATH: &str = "assets"; pub const DEBUG_MODE: &str = "false"; pub const LISTEN_ADDR: &str = "127.0.0.1"; pub const LISTEN_PORT: &str = "3000"; pub const METRIC_LISTEN_PORT: &str = "9402"; pub const METRIC_NAMESPACE: &str = "default_backend"; pub const METRIC_SUBSYSTEM: &str = "http"; } mod environment { pub const ASSET_PATH: &str = "SERVER_ASSET_PATH"; pub const DEBUG_MODE: &str = "SERVER_DEBUG_MODE"; pub const LISTEN_ADDR: &str = "SERVER_LISTEN_ADDR"; pub const LISTEN_PORT: &str = "SERVER_LISTEN_PORT"; pub const METRIC_LISTEN_PORT: &str = "SERVER_METRIC_LISTEN_PORT"; pub const METRIC_NAMESPACE: &str = "SERVER_METRIC_NAMESPACE"; pub const METRIC_SUBSYSTEM: &str = "SERVER_METRIC_SUBSYSTEM"; } impl Env { pub fn is_debug_mode() -> bool { match env::var(environment::DEBUG_MODE) .unwrap_or(default::DEBUG_MODE.into()) .to_lowercase() .as_str() { "1" | "ok" | "okay" | "on" | "true" | "yep" | "yes" => true, _ => false, } } pub fn parse(name: &str) -> Result<String, VarError> { env::var(name) } pub fn parse_asset_path() -> String { env::var(environment::ASSET_PATH).unwrap_or(default::ASSET_PATH.into()) } pub fn parse_metric_address() -> SocketAddr { let addr = match env::var(environment::LISTEN_ADDR) { Ok(addr) => addr, Err(_) => default::LISTEN_ADDR.into(), }; let port = match env::var(environment::METRIC_LISTEN_PORT) { Ok(port) => port, Err(_) => default::METRIC_LISTEN_PORT.into(), }; format!("{}:{}", addr, port).parse().unwrap() } pub fn parse_metric_namespace() -> String { env::var(environment::METRIC_NAMESPACE).unwrap_or(default::METRIC_NAMESPACE.into()) } pub fn parse_metric_subsystem() -> String { env::var(environment::METRIC_SUBSYSTEM).unwrap_or(default::METRIC_SUBSYSTEM.into()) } pub fn parse_service_address() -> SocketAddr { let addr = match env::var(environment::LISTEN_ADDR) { Ok(addr) => addr, Err(_) => default::LISTEN_ADDR.into(), }; let port = match env::var(environment::LISTEN_PORT) { Ok(port) => port, Err(_) => default::LISTEN_PORT.into(), }; format!("{}:{}", addr, port).parse().unwrap() } pub fn vars() -> Vars { env::vars() } }
use engine::Event; pub trait Output { fn receive_event(&mut self, evt: &Event); }
use luminance::shader::program::Program; use super::{ ShaderInterface, UniformType }; use std::collections::HashMap; use regex::Regex; use crate::VertexSemantics; pub trait IsShader { fn program(&self) -> &Program<VertexSemantics, (), ShaderInterface>; } pub struct ShaderSource { pub vertex_shader: String, pub geometry_shader: Option<String>, pub tesselation_shader: Option<String>, pub fragment_shader: String, } pub struct Shader { pub program: Program<VertexSemantics, (), ShaderInterface>, } impl Shader { pub fn from_source(source: ShaderSource) -> Self { let program: Program<VertexSemantics, (), ShaderInterface> = match Program::from_strings(None, &source.vertex_shader, None, &source.fragment_shader) { Ok(program) => program.ignore_warnings(), Err(err) => { error!("{}", err); panic!("Failed to compile shaders!"); } }; Self { program: program, } } } impl IsShader for Shader { fn program(&self) -> &Program<VertexSemantics, (), ShaderInterface> { &self.program } } impl IsShader for &Shader { fn program(&self) -> &Program<VertexSemantics, (), ShaderInterface> { &self.program } }
// u512 division use super::u512; use std::convert::TryInto; /* This is an attempt at Knuth's algorithm D for division. The code is terrible but I'm to lazy to refactor it It passes tests and is fast enough for now */ impl u512 { fn divide_with_remainder(&self, other: &u512) -> (u512, u512) /* (result, remainder) */ { // self/other if other > self { return (u512::zero(), *self); } if *other == u512::zero() { panic!("u512 division by 0!"); } let div_by_small = |u: &mut [u64], small: u64| -> [u64; 9] { let mut result = [0u64; 9]; if small == 0 { panic!("Small div by 0!"); } let mut cur_rem: u128 = *u.last().unwrap() as u128; for i in (0..u.len()).rev() { let cur_q = cur_rem / small as u128; result[i] = cur_q as u64; cur_rem -= cur_q * small as u128; if i >= 1 { cur_rem <<= 64; cur_rem += u[i - 1] as u128; } } u.copy_from_slice(&[cur_rem as u64, (cur_rem >> 64) as u64, 0, 0, 0, 0, 0, 0, 0]); return result; }; let mul_by_small = |digits: &mut [u64], small: u64| { let mut acc: u128 = 0; for digit in digits { acc += *digit as u128 * small as u128; *digit = acc as u64; acc >>= 64; } if acc != 0 { panic!("mul_by_small overflow!"); } }; let shift_left_by = |digits: &mut [u64], shift: u32| { assert!(shift < 64); if shift == 0 { return; } for i in (0..digits.len()).rev() { digits[i] <<= shift; if i != 0 { digits[i] |= digits[i - 1]>> (64 - shift); } } }; let shift_right_by = |digits: &mut [u64], shift: u32| { assert!(shift < 64); if shift == 0 { return; }; for i in 0..digits.len() { digits[i] >>= shift; if i+1 < digits.len() { digits[i] |= digits[i + 1] << (64 - shift); } } }; let is_bigger = |a: &[u64], b: &[u64]| -> bool { for i in (0..usize::max(a.len(), b.len())).rev() { let a_val: u64 = if i < a.len() {a[i]} else {0}; let b_val: u64 = if i < b.len() {b[i]} else {0}; match a_val.cmp(&b_val) { std::cmp::Ordering::Less => return false, std::cmp::Ordering::Greater => return true, _ => {} }; } return false; }; let subs = |a: &mut [u64], b: &[u64]| { assert!(a.len() >= b.len()); let mut borrow = false; for i in 0..a.len() { if borrow { if a[i] != 0 { a[i] -= 1; borrow = false; } else { a[i] = u64::max_value(); } } let sub_val = if i < b.len() {b[i]} else {0}; if a[i] >= sub_val { a[i] -= sub_val; } else { borrow = true; a[i] += u64::max_value() - sub_val + 1; } } assert_eq!(borrow, false); }; let mut u: [u64; 9] = [0u64; 9]; u[0..8].copy_from_slice(&self.data); let m = (0..9).rev().find(|i| u[*i] != 0).unwrap() + 1; let mut v: [u64; 8] = other.data; let n = (0..8).rev().find(|i| v[*i] != 0).unwrap() + 1; if n <= 1 { let result_digits: [u64; 9] = div_by_small(&mut u, v[n-1]); let mut result = u512::zero(); result.data.copy_from_slice(&result_digits[..8]); let mut raminder = u512::zero(); raminder.data.copy_from_slice(&u[..8]); return (result, raminder); } let norm_shift = v[n-1].leading_zeros(); shift_left_by(&mut u, norm_shift); shift_left_by(&mut v, norm_shift); assert!(v[n-1] & (1u64 << 63) != 0); let two_to_64: u128 = 1u128 << 64; let mut result = u512::zero(); for cur_u_highest_index in (n..=m).rev() { let cur_u_lowest_index = cur_u_highest_index - n; let cur_u: &mut [u64] = &mut u[cur_u_lowest_index..=cur_u_highest_index]; assert!(cur_u.len() == n + 1); let first_two_added: u128 = cur_u[cur_u.len() - 1] as u128 * two_to_64 + cur_u[cur_u.len() - 2] as u128; let mut q_guess: u64 = u128::min(first_two_added / v[n - 1] as u128, u64::max_value() as u128).try_into().unwrap(); // One of (q_guess, q_guess - 1, q_guess - 2) is the correct q // Lets try multiplying q_guess times v and see if it is smaller than cur_u let mut vq = [0u64; 9]; vq[..8].copy_from_slice(&v); mul_by_small(&mut vq, q_guess); let vq_len: usize = (0..9).rev().find(|i| vq[*i] != 0).unwrap_or(0) + 1; // While v * q is bigger than cur_u substract v from v * q // This should happen max 2 times let mut counter = 0; while is_bigger(&vq[..vq_len], cur_u) { assert!(counter < 4); subs(&mut vq, &v[..n]); q_guess -= 1; counter += 1; } // Now q_guess is OK result.data[cur_u_lowest_index] = q_guess; // Substract from u and find next quotient digit subs(cur_u, &vq[..vq_len]); } let mut rem: u512 = u512 { data: u[..8].try_into().unwrap() }; shift_right_by(&mut rem.data, norm_shift); return (result, rem); } } impl std::ops::Div for &u512 { type Output = u512; fn div(self, other: &u512) -> u512 { let (result, _remainder) = self.divide_with_remainder(other); return result; } } impl std::ops::DivAssign<&u512> for u512 { fn div_assign(&mut self, other: &u512) { *self = &*self / other; } } impl std::ops::Div for u512 { type Output = u512; fn div(self, other: u512) -> u512 { return &self / &other; } } impl std::ops::Div<&u512> for u512 { type Output = u512; fn div(self, other: &u512) -> u512 { return &self / other; } } impl std::ops::Div<u512> for &u512 { type Output = u512; fn div(self, other: u512) -> u512 { return self / &other; } } impl std::ops::DivAssign<u512> for u512 { fn div_assign(&mut self, other: u512) { *self = &*self / &other; } } impl std::ops::Rem for &u512 { type Output = u512; fn rem(self, modulus: &u512) -> u512 { let (_result, remainder) = self.divide_with_remainder(modulus); return remainder; } } impl std::ops::RemAssign<&u512> for u512 { fn rem_assign(&mut self, other: &u512) { *self = &*self % other; } } impl std::ops::Rem for u512 { type Output = u512; fn rem(self, other: u512) -> u512 { return &self % &other; } } impl std::ops::Rem<&u512> for u512 { type Output = u512; fn rem(self, other: &u512) -> u512 { return &self % other; } } impl std::ops::Rem<u512> for &u512 { type Output = u512; fn rem(self, other: u512) -> u512 { return self % &other; } } impl std::ops::RemAssign<u512> for u512 { fn rem_assign(&mut self, other: u512) { *self = &*self % &other; } } #[cfg(test)] mod tests { use super::super::u512; use crate::test_utils::{TEST_VALUES, BIG_TEST_VALUES}; #[test] fn divide() { let zero = u512::zero(); let one = u512::one(); assert_eq!(zero / one, zero); assert_eq!(one / one, one); for test_val1 in TEST_VALUES.iter() { for test_val2 in TEST_VALUES.iter() { let div_u128: u128 = test_val1 / test_val2; let div_u512: u512 = u512::from(test_val1) / u512::from(test_val2); assert_eq!(div_u512, u512::from(div_u128)); } } } #[test] fn remainder() { let zero = u512::zero(); let one = u512::one(); assert_eq!(zero % one, zero); assert_eq!(one % one, zero); for test_val1 in TEST_VALUES.iter() { for test_val2 in TEST_VALUES.iter() { let remainder_u128: u128 = test_val1 % test_val2; let remainder_u512: u512 = u512::from(test_val1) % u512::from(test_val2); assert_eq!(remainder_u512, u512::from(remainder_u128)); } } } #[test] fn divide_and_remainder_big() { for val_a in BIG_TEST_VALUES { for val_b in BIG_TEST_VALUES { let a_div_b: u512 = val_a / val_b; let a_mod_b: u512 = val_a % val_b; let div_check: u512 = a_div_b * val_b; let mod_check: u512 = val_a - div_check; assert!(div_check <= *val_a); assert!(mod_check < *val_b); assert_eq!(a_mod_b, mod_check); } } } }
struct Solution; impl Solution { pub fn trap(height: Vec<i32>) -> i32 { // 动态编程。 if height.is_empty() { return 0; } let mut ans = 0; let n = height.len(); let mut left_max = vec![0; n]; left_max[0] = height[0]; for i in 1..n { left_max[i] = height[i].max(left_max[i - 1]); } let mut right_max = vec![0; n]; right_max[n - 1] = height[n - 1]; for i in (0..n - 1).rev() { right_max[i] = height[i].max(right_max[i + 1]); } for i in 1..n - 1 { ans += left_max[i].min(right_max[i]) - height[i]; } ans } }
use cgmath::Point3; /// Uses spherical coordinates to represent the cameras location relative to a target. /// https://en.wikipedia.org/wiki/Spherical_coordinate_system /// https://threejs.org/docs/#api/en/math/Spherical pub(crate) struct Camera { pub target: Point3<f32>, /// radius from the target to the camera pub radius: f32, /// polar angle from the y (up) axis pub phi: f32, /// equator angle around the y (up) axis. pub theta: f32, }
use alloc::{sync::Arc, vec::Vec}; use hashbrown::HashMap; use crate::{buffer::Buffer, Renderer, Shader, ShaderBindingType, Texture}; pub struct Material { pub(crate) vertex_shader: Arc<Shader>, pub(crate) fragment_shader: Arc<Shader>, pub(crate) pipeline_layout: wgpu::PipelineLayout, pub(crate) bind_group: wgpu::BindGroup, _textures: HashMap<&'static str, Arc<Texture>>, _uniforms: HashMap<&'static str, Arc<Buffer>>, } impl Material { pub fn new( renderer: &Renderer, textures: HashMap<&'static str, Arc<Texture>>, uniforms: HashMap<&'static str, Arc<Buffer>>, vertex_shader: Arc<Shader>, fragment_shader: Arc<Shader>, ) -> Self { let vs_bindings = vertex_shader.wgpu_bindings(wgpu::ShaderStage::VERTEX); let fs_bindings = fragment_shader.wgpu_bindings(wgpu::ShaderStage::FRAGMENT); // TODO split bind groups by stage.. let bind_group_layout = renderer.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &vs_bindings.into_iter().chain(fs_bindings.into_iter()).collect::<Vec<_>>(), label: None, }); let pipeline_layout = renderer.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { bind_group_layouts: &[&bind_group_layout], }); // TODO wip let sampler = renderer.device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::Repeat, address_mode_v: wgpu::AddressMode::Repeat, address_mode_w: wgpu::AddressMode::Repeat, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Nearest, lod_min_clamp: -100.0, lod_max_clamp: 100.0, compare: wgpu::CompareFunction::Undefined, }); let bindings = vertex_shader .bindings .iter() .chain(fragment_shader.bindings.iter()) .map(|(binding_name, binding)| { let resource = match binding.binding_type { ShaderBindingType::UniformBuffer => { if *binding_name == "Mvp" { renderer.mvp_buf.binding_resource() } else { let buffer = uniforms.get(binding_name); match buffer { Some(x) => x.binding_resource(), None => panic!("No such buffer named {}", binding_name), } } } ShaderBindingType::Texture2D => { let texture = textures.get(binding_name); match texture { Some(x) => wgpu::BindingResource::TextureView(&x.texture_view), None => panic!("No such texture named {}", binding_name), } } ShaderBindingType::Sampler => wgpu::BindingResource::Sampler(&sampler), }; wgpu::Binding { binding: binding.binding, resource, } }) .collect::<Vec<_>>(); let bind_group = renderer.device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &bind_group_layout, bindings: &bindings, label: None, }); Self { vertex_shader, fragment_shader, pipeline_layout, bind_group, _textures: textures, _uniforms: uniforms, } } }
#![feature(test)] extern crate cgmath; extern crate shred; #[macro_use] extern crate shred_derive; extern crate test; use std::ops::{Index, IndexMut}; use cgmath::Vector3; use shred::*; use test::{black_box, Bencher}; #[derive(Debug)] struct VecStorage<T> { data: Vec<T>, } impl<T: Clone> VecStorage<T> { fn new(init: T) -> Self { VecStorage { data: vec![init; NUM_COMPONENTS], } } } impl<T> Default for VecStorage<T> { fn default() -> Self { VecStorage { data: vec![] } } } impl<T> Index<usize> for VecStorage<T> { type Output = T; fn index(&self, index: usize) -> &Self::Output { &self.data[index] } } impl<T> IndexMut<usize> for VecStorage<T> { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.data[index] } } #[derive(Debug)] struct DeltaTime(f32); type Vec3 = Vector3<f32>; #[derive(Clone, Debug)] struct Mass(f32); #[derive(Clone, Debug)] struct Pos(Vec3); #[derive(Clone, Debug)] struct Vel(Vec3); #[derive(Clone, Debug)] struct Force(Vec3); #[derive(Clone, Copy, Debug)] struct Spring { /// the index of the other "entity" connection_to: usize, constant: f32, rest: f32, } type MassStorage = VecStorage<Mass>; type PosStorage = VecStorage<Pos>; type VelStorage = VecStorage<Vel>; type ForceStorage = VecStorage<Force>; type SpringStorage = VecStorage<Spring>; const NUM_COMPONENTS: usize = 200; // -------------- #[derive(SystemData)] struct SpringForceData<'a> { pos: Read<'a, PosStorage>, spring: Read<'a, SpringStorage>, force: Write<'a, ForceStorage>, } struct SpringForce; impl<'a> System<'a> for SpringForce { type SystemData = SpringForceData<'a>; fn run(&mut self, mut data: SpringForceData) { for elem in 0..NUM_COMPONENTS { let pos = data.pos[elem].0; let spring: Spring = data.spring[elem]; let other_pos = data.pos[spring.connection_to].0; let force = pos - other_pos; let len = (force.x * force.x + force.y * force.y + force.z * force.z).sqrt(); let magn = (len - spring.rest).abs() * spring.constant; let mul = -magn / len; let force = force * mul; data.force[elem].0 += force; } } } #[derive(SystemData)] struct IntegrationData<'a> { force: Read<'a, ForceStorage>, mass: Read<'a, MassStorage>, pos: Write<'a, PosStorage>, vel: Write<'a, VelStorage>, time: Option<Read<'a, DeltaTime>>, } struct IntegrationSystem; impl<'a> System<'a> for IntegrationSystem { type SystemData = IntegrationData<'a>; fn run(&mut self, mut data: IntegrationData) { let delta = match data.time { Some(time) => time.0, None => return, }; for elem in 0..NUM_COMPONENTS { let mass = data.mass[elem].0; if mass == 0.0 { // infinite mass continue; } let pos = &mut data.pos[elem].0; let vel = data.vel[elem].0; *pos = vel * delta; let force = data.force[elem].0; let vel = vel + (force / mass) * delta; let damping = (0.9f32).powf(delta); let vel = vel * damping; data.vel[elem] = Vel(vel); } } } #[derive(SystemData)] struct ClearForceAccumData<'a> { force: Write<'a, ForceStorage>, } struct ClearForceAccum; impl<'a> System<'a> for ClearForceAccum { type SystemData = ClearForceAccumData<'a>; fn run(&mut self, mut data: ClearForceAccumData) { for elem in 0..NUM_COMPONENTS { data.force[elem] = Force(Vec3 { x: 0.0, y: 0.0, z: 0.0, }); } } } #[bench] fn basic(b: &mut Bencher) { let mut dispatcher = DispatcherBuilder::new() .with(SpringForce, "spring", &[]) .with(IntegrationSystem, "integration", &[]) .with(ClearForceAccum, "clear_force", &["integration"]) // clear_force is executed after // the integration .build(); let mut res = World::empty(); let mass = VecStorage::new(Mass(10.0)); let mut pos = VecStorage::new(Pos(Vec3::new(0.0, 0.0, 0.0))); let vel = VecStorage::new(Vel(Vec3::new(0.0, 0.0, 0.0))); let force = VecStorage::new(Force(Vec3::new(0.0, 0.0, 0.0))); let spring = VecStorage::new(Spring { constant: 2.0, connection_to: 0, rest: 1.0, }); pos.data[0] = Pos(Vec3::new(-5.0, -5.0, -5.0)); res.insert(DeltaTime(0.05)); res.insert(mass); res.insert(pos); res.insert(vel); res.insert(force); res.insert(spring); b.iter(|| dispatcher.dispatch(&mut res)); } #[bench] fn bench_fetching(b: &mut Bencher) { let mut world = World::empty(); let mass = VecStorage::new(Mass(10.0)); let mut pos = VecStorage::new(Pos(Vec3::new(0.0, 0.0, 0.0))); let vel = VecStorage::new(Vel(Vec3::new(0.0, 0.0, 0.0))); let force = VecStorage::new(Force(Vec3::new(0.0, 0.0, 0.0))); let spring = VecStorage::new(Spring { constant: 2.0, connection_to: 0, rest: 1.0, }); pos.data[0] = Pos(Vec3::new(-5.0, -5.0, -5.0)); world.insert(DeltaTime(0.05)); world.insert(mass); world.insert(pos); world.insert(vel); world.insert(force); world.insert(spring); b.iter(|| { for _ in 0..100 { black_box(world.fetch::<DeltaTime>()); black_box(world.fetch::<VecStorage<Pos>>()); black_box(world.fetch::<VecStorage<Spring>>()); } }) } #[bench] fn bench_indirection_refs(b: &mut Bencher) { use shred::cell::{AtomicRef, AtomicRefCell}; use std::ops::Deref; let cell = AtomicRefCell::new(Box::new(10)); let borrow = cell.borrow(); let refs: Vec<AtomicRef<'_, Box<usize>>> = std::iter::repeat_with(|| AtomicRef::clone(&borrow)) .take(10000) .collect(); b.iter(|| { let sum: usize = refs.iter().map(|v| v.deref().deref()).sum(); black_box(sum); }) } #[bench] fn bench_direct_refs(b: &mut Bencher) { use shred::cell::{AtomicRef, AtomicRefCell}; use std::ops::Deref; let cell = AtomicRefCell::new(Box::new(10)); let mapped_borrow = AtomicRef::map(cell.borrow(), Box::as_ref); let refs: Vec<AtomicRef<'_, usize>> = std::iter::repeat_with(|| AtomicRef::clone(&mapped_borrow)) .take(10000) .collect(); b.iter(|| { let sum: usize = refs.iter().map(|v| v.deref()).sum(); black_box(sum); }) }
extern crate rafy; use rafy::Rafy; fn main() { let content = Rafy::new("https://www.youtube.com/watch?v=DjMkfARvGE8").unwrap(); println!("{}", content.videoid); println!("{}", content.title); println!("{}", content.rating); println!("{}", content.viewcount); }
// Definition for singly-linked list. #[derive(PartialEq, Eq, Clone, Debug)] pub struct ListNode { pub val: i32, pub next: Option<Box<ListNode>>, } impl ListNode { #[inline] fn new(val: i32) -> Self { ListNode { next: None, val } } } pub fn add_two_numbers( l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, ) -> Option<Box<ListNode>> { if l1.is_none() { return l2; } if l2.is_none() { return l1; } let mut head = None; let mut cur_node = &mut head; let mut carry = 0; let mut l1 = l1; let mut l2 = l2; while l1.is_some() || l2.is_some() { let x = l1.take().map_or(0, |mut node| { l1 = node.next.take(); node.val }); let y = l2.take().map_or(0, |mut node| { l2 = node.next.take(); node.val }); let mut sum = x + y + carry; carry = if sum >= 10 { sum -= 10; 1 } else { 0 }; if cur_node.is_none() { head = Some(Box::new(ListNode::new(sum))); cur_node = &mut head; } else { cur_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum))); cur_node = &mut cur_node.as_mut().unwrap().next; } } // 最后可以还有进位没有加入到链表 if carry > 0 { cur_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(1))); } head } #[cfg(test)] mod test { use crate::add_two_numbers::{add_two_numbers, ListNode}; // 传入的 v 是正序的,返回的结果是倒序的。 fn build_list_from_vec(v: Vec<i32>) -> Option<Box<ListNode>> { let mut r = None; for n in v.iter() { // 每个新的节点都插入到链表开头。 let mut node = ListNode::new(*n); node.next = r.take(); r = Some(Box::new(node)); } r } #[test] fn test_add_two_numbers() { let l1 = build_list_from_vec(vec![3, 4, 2]); let l2 = build_list_from_vec(vec![4, 6, 5]); assert_eq!(add_two_numbers(l1, l2), build_list_from_vec(vec![8, 0, 7])); // 一长一短 let l1 = build_list_from_vec(vec![1, 0]); let l2 = build_list_from_vec(vec![2, 1, 0]); assert_eq!(add_two_numbers(l1, l2), build_list_from_vec(vec![2, 2, 0])); // 一个为空 let l1 = build_list_from_vec(vec![]); let l2 = build_list_from_vec(vec![1, 0]); assert_eq!(add_two_numbers(l1, l2), build_list_from_vec(vec![1, 0])); // 运算最后出现进位 let l1 = build_list_from_vec(vec![9, 9]); let l2 = build_list_from_vec(vec![1]); assert_eq!(add_two_numbers(l1, l2), build_list_from_vec(vec![1, 0, 0])); } }
// Copyright 2017-2020 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Substrate is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Substrate. If not, see <http://www.gnu.org/licenses/>. //! Keystore (and session key management) for ed25519 based chains like Polkadot. #![warn(missing_docs)] use parking_lot::RwLock; use sp_application_crypto::{ecdsa, ed25519, sr25519, AppKey, AppPair, AppPublic}; use sp_core::{ crypto::{ CryptoTypePublicPair, ExposeSecret, IsWrappedBy, KeyTypeId, Pair as PairT, Public, SecretString, }, sr25519::{Pair as Sr25519Pair, Public as Sr25519Public}, traits::{BareCryptoStore, Error as TraitError}, vrf::{make_transcript, VRFSignature, VRFTranscriptData}, Encode, }; use std::{ collections::{HashMap, HashSet}, fs::{self, File}, io::{self, Write}, path::PathBuf, sync::Arc, }; /// Keystore pointer pub type KeyStorePtr = Arc<RwLock<Store>>; /// Keystore error. #[derive(Debug, derive_more::Display, derive_more::From)] pub enum Error { /// IO error. Io(io::Error), /// JSON error. Json(serde_json::Error), /// Invalid password. #[display(fmt = "Invalid password")] InvalidPassword, /// Invalid BIP39 phrase #[display(fmt = "Invalid recovery phrase (BIP39) data")] InvalidPhrase, /// Invalid seed #[display(fmt = "Invalid seed")] InvalidSeed, /// Public key type is not supported #[display(fmt = "Key crypto type is not supported")] KeyNotSupported(KeyTypeId), /// Pair not found for public key and KeyTypeId #[display(fmt = "Pair not found for {} public key", "_0")] PairNotFound(String), /// Keystore unavailable #[display(fmt = "Keystore unavailable")] Unavailable, } /// Keystore Result pub type Result<T> = std::result::Result<T, Error>; impl From<Error> for TraitError { fn from(error: Error) -> Self { match error { Error::KeyNotSupported(id) => TraitError::KeyNotSupported(id), Error::PairNotFound(e) => TraitError::PairNotFound(e), Error::InvalidSeed | Error::InvalidPhrase | Error::InvalidPassword => TraitError::ValidationError(error.to_string()), Error::Unavailable => TraitError::Unavailable, Error::Io(e) => TraitError::Other(e.to_string()), Error::Json(e) => TraitError::Other(e.to_string()), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::Io(ref err) => Some(err), Error::Json(ref err) => Some(err), _ => None, } } } /// Key store. /// /// Stores key pairs in a file system store + short lived key pairs in memory. /// /// Every pair that is being generated by a `seed`, will be placed in memory. pub struct Store { path: Option<PathBuf>, /// Map over `(KeyTypeId, Raw public key)` -> `Key phrase/seed` additional: HashMap<(KeyTypeId, Vec<u8>), String>, password: Option<SecretString>, } impl Store { /// Open the store at the given path. /// /// Optionally takes a password that will be used to encrypt/decrypt the keys. pub fn open<T: Into<PathBuf>>(path: T, password: Option<SecretString>) -> Result<KeyStorePtr> { let path = path.into(); fs::create_dir_all(&path)?; let instance = Self { path: Some(path), additional: HashMap::new(), password }; Ok(Arc::new(RwLock::new(instance))) } /// Create a new in-memory store. pub fn new_in_memory() -> KeyStorePtr { Arc::new(RwLock::new(Self { path: None, additional: HashMap::new(), password: None })) } /// Get the key phrase for the given public key and key type from the in-memory store. fn get_additional_pair(&self, public: &[u8], key_type: KeyTypeId) -> Option<&String> { let key = (key_type, public.to_vec()); self.additional.get(&key) } /// Insert the given public/private key pair with the given key type. /// /// Does not place it into the file system store. fn insert_ephemeral_pair<Pair: PairT>(&mut self, pair: &Pair, seed: &str, key_type: KeyTypeId) { let key = (key_type, pair.public().to_raw_vec()); self.additional.insert(key, seed.into()); } /// Insert a new key with anonymous crypto. /// /// Places it into the file system store. fn insert_unknown(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<()> { if let Some(path) = self.key_file_path(public, key_type) { let mut file = File::create(path).map_err(Error::Io)?; serde_json::to_writer(&file, &suri).map_err(Error::Json)?; file.flush().map_err(Error::Io)?; } Ok(()) } /// Insert a new key. /// /// Places it into the file system store. pub fn insert_by_type<Pair: PairT>(&self, key_type: KeyTypeId, suri: &str) -> Result<Pair> { let pair = Pair::from_string(suri, self.password()).map_err(|_| Error::InvalidSeed)?; self.insert_unknown(key_type, suri, pair.public().as_slice()) .map_err(|_| Error::Unavailable)?; Ok(pair) } /// Insert a new key. /// /// Places it into the file system store. pub fn insert<Pair: AppPair>(&self, suri: &str) -> Result<Pair> { self.insert_by_type::<Pair::Generic>(Pair::ID, suri).map(Into::into) } /// Generate a new key. /// /// Places it into the file system store. pub fn generate_by_type<Pair: PairT>(&self, key_type: KeyTypeId) -> Result<Pair> { let (pair, phrase, _) = Pair::generate_with_phrase(self.password()); if let Some(path) = self.key_file_path(pair.public().as_slice(), key_type) { let mut file = File::create(path)?; serde_json::to_writer(&file, &phrase)?; file.flush()?; } Ok(pair) } /// Generate a new key. /// /// Places it into the file system store. pub fn generate<Pair: AppPair>(&self) -> Result<Pair> { self.generate_by_type::<Pair::Generic>(Pair::ID).map(Into::into) } /// Create a new key from seed. /// /// Does not place it into the file system store. pub fn insert_ephemeral_from_seed_by_type<Pair: PairT>( &mut self, seed: &str, key_type: KeyTypeId, ) -> Result<Pair> { let pair = Pair::from_string(seed, None).map_err(|_| Error::InvalidSeed)?; self.insert_ephemeral_pair(&pair, seed, key_type); Ok(pair) } /// Create a new key from seed. /// /// Does not place it into the file system store. pub fn insert_ephemeral_from_seed<Pair: AppPair>(&mut self, seed: &str) -> Result<Pair> { self.insert_ephemeral_from_seed_by_type::<Pair::Generic>(seed, Pair::ID).map(Into::into) } /// Get the key phrase for a given public key and key type. fn key_phrase_by_type(&self, public: &[u8], key_type: KeyTypeId) -> Result<String> { if let Some(phrase) = self.get_additional_pair(public, key_type) { return Ok(phrase.clone()) } let path = self.key_file_path(public, key_type).ok_or_else(|| Error::Unavailable)?; let file = File::open(path)?; serde_json::from_reader(&file).map_err(Into::into) } /// Get a key pair for the given public key and key type. pub fn key_pair_by_type<Pair: PairT>( &self, public: &Pair::Public, key_type: KeyTypeId, ) -> Result<Pair> { let phrase = self.key_phrase_by_type(public.as_slice(), key_type)?; let pair = Pair::from_string(&phrase, self.password()).map_err(|_| Error::InvalidPhrase)?; if &pair.public() == public { Ok(pair) } else { Err(Error::InvalidPassword) } } /// Get a key pair for the given public key. pub fn key_pair<Pair: AppPair>(&self, public: &<Pair as AppKey>::Public) -> Result<Pair> { self.key_pair_by_type::<Pair::Generic>(IsWrappedBy::from_ref(public), Pair::ID) .map(Into::into) } /// Get public keys of all stored keys that match the key type. /// /// This will just use the type of the public key (a list of which to be returned) in order /// to determine the key type. Unless you use a specialized application-type public key, then /// this only give you keys registered under generic cryptography, and will not return keys /// registered under the application type. pub fn public_keys<Public: AppPublic>(&self) -> Result<Vec<Public>> { self.raw_public_keys(Public::ID) .map(|v| v.into_iter().map(|k| Public::from_slice(k.as_slice())).collect()) } /// Returns the file path for the given public key and key type. fn key_file_path(&self, public: &[u8], key_type: KeyTypeId) -> Option<PathBuf> { let mut buf = self.path.as_ref()?.clone(); let key_type = hex::encode(key_type.0); let key = hex::encode(public); buf.push(key_type + key.as_str()); Some(buf) } /// Returns a list of raw public keys filtered by `KeyTypeId` fn raw_public_keys(&self, id: KeyTypeId) -> Result<Vec<Vec<u8>>> { let mut public_keys: Vec<Vec<u8>> = self .additional .keys() .into_iter() .filter_map(|k| if k.0 == id { Some(k.1.clone()) } else { None }) .collect(); if let Some(path) = &self.path { for entry in fs::read_dir(&path)? { let entry = entry?; let path = entry.path(); // skip directories and non-unicode file names (hex is unicode) if let Some(name) = path.file_name().and_then(|n| n.to_str()) { match hex::decode(name) { Ok(ref hex) if hex.len() > 4 => { if &hex[0..4] != &id.0 { continue } let public = hex[4..].to_vec(); public_keys.push(public); }, _ => continue, } } } } Ok(public_keys) } } impl BareCryptoStore for Store { fn keys(&self, id: KeyTypeId) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> { let raw_keys = self.raw_public_keys(id)?; Ok(raw_keys.into_iter().fold(Vec::new(), |mut v, k| { v.push(CryptoTypePublicPair(sr25519::CRYPTO_ID, k.clone())); v.push(CryptoTypePublicPair(ed25519::CRYPTO_ID, k.clone())); v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k)); v })) } fn supported_keys( &self, id: KeyTypeId, keys: Vec<CryptoTypePublicPair>, ) -> std::result::Result<Vec<CryptoTypePublicPair>, TraitError> { let all_keys = self.keys(id)?.into_iter().collect::<HashSet<_>>(); Ok(keys.into_iter().filter(|key| all_keys.contains(key)).collect::<Vec<_>>()) } fn sign_with( &self, id: KeyTypeId, key: &CryptoTypePublicPair, msg: &[u8], ) -> std::result::Result<Vec<u8>, TraitError> { match key.0 { ed25519::CRYPTO_ID => { let pub_key = ed25519::Public::from_slice(key.1.as_slice()); let key_pair: ed25519::Pair = self .key_pair_by_type::<ed25519::Pair>(&pub_key, id) .map_err(|e| TraitError::from(e))?; Ok(key_pair.sign(msg).encode()) }, sr25519::CRYPTO_ID => { let pub_key = sr25519::Public::from_slice(key.1.as_slice()); let key_pair: sr25519::Pair = self .key_pair_by_type::<sr25519::Pair>(&pub_key, id) .map_err(|e| TraitError::from(e))?; Ok(key_pair.sign(msg).encode()) }, ecdsa::CRYPTO_ID => { let pub_key = ecdsa::Public::from_slice(key.1.as_slice()); let key_pair: ecdsa::Pair = self .key_pair_by_type::<ecdsa::Pair>(&pub_key, id) .map_err(|e| TraitError::from(e))?; Ok(key_pair.sign(msg).encode()) }, _ => Err(TraitError::KeyNotSupported(id)), } } fn sr25519_public_keys(&self, key_type: KeyTypeId) -> Vec<sr25519::Public> { self.raw_public_keys(key_type) .map(|v| v.into_iter().map(|k| sr25519::Public::from_slice(k.as_slice())).collect()) .unwrap_or_default() } fn sr25519_generate_new( &mut self, id: KeyTypeId, seed: Option<&str>, ) -> std::result::Result<sr25519::Public, TraitError> { let pair = match seed { Some(seed) => self.insert_ephemeral_from_seed_by_type::<sr25519::Pair>(seed, id), None => self.generate_by_type::<sr25519::Pair>(id), } .map_err(|e| -> TraitError { e.into() })?; Ok(pair.public()) } fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec<ed25519::Public> { self.raw_public_keys(key_type) .map(|v| v.into_iter().map(|k| ed25519::Public::from_slice(k.as_slice())).collect()) .unwrap_or_default() } fn ed25519_generate_new( &mut self, id: KeyTypeId, seed: Option<&str>, ) -> std::result::Result<ed25519::Public, TraitError> { let pair = match seed { Some(seed) => self.insert_ephemeral_from_seed_by_type::<ed25519::Pair>(seed, id), None => self.generate_by_type::<ed25519::Pair>(id), } .map_err(|e| -> TraitError { e.into() })?; Ok(pair.public()) } fn ecdsa_public_keys(&self, key_type: KeyTypeId) -> Vec<ecdsa::Public> { self.raw_public_keys(key_type) .map(|v| v.into_iter().map(|k| ecdsa::Public::from_slice(k.as_slice())).collect()) .unwrap_or_default() } fn ecdsa_generate_new( &mut self, id: KeyTypeId, seed: Option<&str>, ) -> std::result::Result<ecdsa::Public, TraitError> { let pair = match seed { Some(seed) => self.insert_ephemeral_from_seed_by_type::<ecdsa::Pair>(seed, id), None => self.generate_by_type::<ecdsa::Pair>(id), } .map_err(|e| -> TraitError { e.into() })?; Ok(pair.public()) } fn insert_unknown( &mut self, key_type: KeyTypeId, suri: &str, public: &[u8], ) -> std::result::Result<(), ()> { Store::insert_unknown(self, key_type, suri, public).map_err(|_| ()) } fn password(&self) -> Option<&str> { self.password.as_ref().map(|p| p.expose_secret()).map(|p| p.as_str()) } fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool { public_keys.iter().all(|(p, t)| self.key_phrase_by_type(&p, *t).is_ok()) } fn sr25519_vrf_sign( &self, key_type: KeyTypeId, public: &Sr25519Public, transcript_data: VRFTranscriptData, ) -> std::result::Result<VRFSignature, TraitError> { let transcript = make_transcript(transcript_data); let pair = self .key_pair_by_type::<Sr25519Pair>(public, key_type) .map_err(|e| TraitError::PairNotFound(e.to_string()))?; let (inout, proof, _) = pair.as_ref().vrf_sign(transcript); Ok(VRFSignature { output: inout.to_output(), proof }) } } #[cfg(test)] mod tests { use super::*; use sp_core::{crypto::Ss58Codec, testing::SR25519}; use std::str::FromStr; use tempfile::TempDir; #[test] fn basic_store() { let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), None).unwrap(); assert!(store.read().public_keys::<ed25519::AppPublic>().unwrap().is_empty()); let key: ed25519::AppPair = store.write().generate().unwrap(); let key2: ed25519::AppPair = store.read().key_pair(&key.public()).unwrap(); assert_eq!(key.public(), key2.public()); assert_eq!(store.read().public_keys::<ed25519::AppPublic>().unwrap()[0], key.public()); } #[test] fn test_insert_ephemeral_from_seed() { let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), None).unwrap(); let pair: ed25519::AppPair = store .write() .insert_ephemeral_from_seed( "0x3d97c819d68f9bafa7d6e79cb991eebcd77d966c5334c0b94d9e1fa7ad0869dc", ) .unwrap(); assert_eq!( "5DKUrgFqCPV8iAXx9sjy1nyBygQCeiUYRFWurZGhnrn3HJCA", pair.public().to_ss58check() ); drop(store); let store = Store::open(temp_dir.path(), None).unwrap(); // Keys generated from seed should not be persisted! assert!(store.read().key_pair::<ed25519::AppPair>(&pair.public()).is_err()); } #[test] fn password_being_used() { let password = String::from("password"); let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), Some(FromStr::from_str(password.as_str()).unwrap())) .unwrap(); let pair: ed25519::AppPair = store.write().generate().unwrap(); assert_eq!( pair.public(), store.read().key_pair::<ed25519::AppPair>(&pair.public()).unwrap().public(), ); // Without the password the key should not be retrievable let store = Store::open(temp_dir.path(), None).unwrap(); assert!(store.read().key_pair::<ed25519::AppPair>(&pair.public()).is_err()); let store = Store::open(temp_dir.path(), Some(FromStr::from_str(password.as_str()).unwrap())) .unwrap(); assert_eq!( pair.public(), store.read().key_pair::<ed25519::AppPair>(&pair.public()).unwrap().public(), ); } #[test] fn public_keys_are_returned() { let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), None).unwrap(); let mut public_keys = Vec::new(); for i in 0..10 { public_keys.push(store.write().generate::<ed25519::AppPair>().unwrap().public()); public_keys.push( store .write() .insert_ephemeral_from_seed::<ed25519::AppPair>(&format!( "0x3d97c819d68f9bafa7d6e79cb991eebcd7{}d966c5334c0b94d9e1fa7ad0869dc", i )) .unwrap() .public(), ); } // Generate a key of a different type store.write().generate::<sr25519::AppPair>().unwrap(); public_keys.sort(); let mut store_pubs = store.read().public_keys::<ed25519::AppPublic>().unwrap(); store_pubs.sort(); assert_eq!(public_keys, store_pubs); } #[test] fn store_unknown_and_extract_it() { let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), None).unwrap(); let secret_uri = "//Alice"; let key_pair = sr25519::AppPair::from_string(secret_uri, None).expect("Generates key pair"); store .write() .insert_unknown(SR25519, secret_uri, key_pair.public().as_ref()) .expect("Inserts unknown key"); let store_key_pair = store .read() .key_pair_by_type::<sr25519::AppPair>(&key_pair.public(), SR25519) .expect("Gets key pair from keystore"); assert_eq!(key_pair.public(), store_key_pair.public()); } #[test] fn store_ignores_files_with_invalid_name() { let temp_dir = TempDir::new().unwrap(); let store = Store::open(temp_dir.path(), None).unwrap(); let file_name = temp_dir.path().join(hex::encode(&SR25519.0[..2])); fs::write(file_name, "test").expect("Invalid file is written"); assert!(store.read().sr25519_public_keys(SR25519).is_empty(),); } }
use thiserror::Error; use solana_program::program_error::ProgramError; #[derive(Error, Debug, Copy, Clone)] pub enum BackgammonError { #[error("Invalid Instruction")] InvalidInstruction, #[error("Invalid State")] InvalidState, #[error("Unauthorized Action")] UnauthorizedAction, #[error("Invalid Move")] InvalidMove, #[error("Invalid Color")] InvalidColor, #[error("Invalid Point")] InvalidPoint, } impl From<BackgammonError> for ProgramError { fn from(e: BackgammonError) -> Self { ProgramError::Custom(e as u32) } }
$NetBSD: patch-library_core_src_ffi_mod.rs,v 1.1 2023/07/10 12:01:24 he Exp $ NetBSD/riscv64 also has unsigned chars. --- library/core/src/ffi/mod.rs.orig 2023-05-31 19:28:10.000000000 +0000 +++ library/core/src/ffi/mod.rs @@ -132,7 +132,12 @@ mod c_char_definition { ), all( target_os = "netbsd", - any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc") + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "powerpc", + target_arch = "riscv64" + ) ), all( target_os = "vxworks",
#[doc = "Control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ctl](ctl) module"] pub type CTL = crate::Reg<u32, _CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CTL; #[doc = "`read()` method returns [ctl::R](ctl::R) reader structure"] impl crate::Readable for CTL {} #[doc = "`write(|w| ..)` method takes [ctl::W](ctl::W) writer structure"] impl crate::Writable for CTL {} #[doc = "Control"] pub mod ctl; #[doc = "Device region base address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [addr](addr) module"] pub type ADDR = crate::Reg<u32, _ADDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR; #[doc = "`read()` method returns [addr::R](addr::R) reader structure"] impl crate::Readable for ADDR {} #[doc = "`write(|w| ..)` method takes [addr::W](addr::W) writer structure"] impl crate::Writable for ADDR {} #[doc = "Device region base address"] pub mod addr; #[doc = "Device region mask\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [mask](mask) module"] pub type MASK = crate::Reg<u32, _MASK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MASK; #[doc = "`read()` method returns [mask::R](mask::R) reader structure"] impl crate::Readable for MASK {} #[doc = "`write(|w| ..)` method takes [mask::W](mask::W) writer structure"] impl crate::Writable for MASK {} #[doc = "Device region mask"] pub mod mask; #[doc = "Address control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [addr_ctl](addr_ctl) module"] pub type ADDR_CTL = crate::Reg<u32, _ADDR_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_CTL; #[doc = "`read()` method returns [addr_ctl::R](addr_ctl::R) reader structure"] impl crate::Readable for ADDR_CTL {} #[doc = "`write(|w| ..)` method takes [addr_ctl::W](addr_ctl::W) writer structure"] impl crate::Writable for ADDR_CTL {} #[doc = "Address control"] pub mod addr_ctl; #[doc = "Read command control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rd_cmd_ctl](rd_cmd_ctl) module"] pub type RD_CMD_CTL = crate::Reg<u32, _RD_CMD_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RD_CMD_CTL; #[doc = "`read()` method returns [rd_cmd_ctl::R](rd_cmd_ctl::R) reader structure"] impl crate::Readable for RD_CMD_CTL {} #[doc = "`write(|w| ..)` method takes [rd_cmd_ctl::W](rd_cmd_ctl::W) writer structure"] impl crate::Writable for RD_CMD_CTL {} #[doc = "Read command control"] pub mod rd_cmd_ctl; #[doc = "Read address control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rd_addr_ctl](rd_addr_ctl) module"] pub type RD_ADDR_CTL = crate::Reg<u32, _RD_ADDR_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RD_ADDR_CTL; #[doc = "`read()` method returns [rd_addr_ctl::R](rd_addr_ctl::R) reader structure"] impl crate::Readable for RD_ADDR_CTL {} #[doc = "`write(|w| ..)` method takes [rd_addr_ctl::W](rd_addr_ctl::W) writer structure"] impl crate::Writable for RD_ADDR_CTL {} #[doc = "Read address control"] pub mod rd_addr_ctl; #[doc = "Read mode control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rd_mode_ctl](rd_mode_ctl) module"] pub type RD_MODE_CTL = crate::Reg<u32, _RD_MODE_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RD_MODE_CTL; #[doc = "`read()` method returns [rd_mode_ctl::R](rd_mode_ctl::R) reader structure"] impl crate::Readable for RD_MODE_CTL {} #[doc = "`write(|w| ..)` method takes [rd_mode_ctl::W](rd_mode_ctl::W) writer structure"] impl crate::Writable for RD_MODE_CTL {} #[doc = "Read mode control"] pub mod rd_mode_ctl; #[doc = "Read dummy control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rd_dummy_ctl](rd_dummy_ctl) module"] pub type RD_DUMMY_CTL = crate::Reg<u32, _RD_DUMMY_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RD_DUMMY_CTL; #[doc = "`read()` method returns [rd_dummy_ctl::R](rd_dummy_ctl::R) reader structure"] impl crate::Readable for RD_DUMMY_CTL {} #[doc = "`write(|w| ..)` method takes [rd_dummy_ctl::W](rd_dummy_ctl::W) writer structure"] impl crate::Writable for RD_DUMMY_CTL {} #[doc = "Read dummy control"] pub mod rd_dummy_ctl; #[doc = "Read data control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [rd_data_ctl](rd_data_ctl) module"] pub type RD_DATA_CTL = crate::Reg<u32, _RD_DATA_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RD_DATA_CTL; #[doc = "`read()` method returns [rd_data_ctl::R](rd_data_ctl::R) reader structure"] impl crate::Readable for RD_DATA_CTL {} #[doc = "`write(|w| ..)` method takes [rd_data_ctl::W](rd_data_ctl::W) writer structure"] impl crate::Writable for RD_DATA_CTL {} #[doc = "Read data control"] pub mod rd_data_ctl; #[doc = "Write command control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wr_cmd_ctl](wr_cmd_ctl) module"] pub type WR_CMD_CTL = crate::Reg<u32, _WR_CMD_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WR_CMD_CTL; #[doc = "`read()` method returns [wr_cmd_ctl::R](wr_cmd_ctl::R) reader structure"] impl crate::Readable for WR_CMD_CTL {} #[doc = "`write(|w| ..)` method takes [wr_cmd_ctl::W](wr_cmd_ctl::W) writer structure"] impl crate::Writable for WR_CMD_CTL {} #[doc = "Write command control"] pub mod wr_cmd_ctl; #[doc = "Write address control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wr_addr_ctl](wr_addr_ctl) module"] pub type WR_ADDR_CTL = crate::Reg<u32, _WR_ADDR_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WR_ADDR_CTL; #[doc = "`read()` method returns [wr_addr_ctl::R](wr_addr_ctl::R) reader structure"] impl crate::Readable for WR_ADDR_CTL {} #[doc = "`write(|w| ..)` method takes [wr_addr_ctl::W](wr_addr_ctl::W) writer structure"] impl crate::Writable for WR_ADDR_CTL {} #[doc = "Write address control"] pub mod wr_addr_ctl; #[doc = "Write mode control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wr_mode_ctl](wr_mode_ctl) module"] pub type WR_MODE_CTL = crate::Reg<u32, _WR_MODE_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WR_MODE_CTL; #[doc = "`read()` method returns [wr_mode_ctl::R](wr_mode_ctl::R) reader structure"] impl crate::Readable for WR_MODE_CTL {} #[doc = "`write(|w| ..)` method takes [wr_mode_ctl::W](wr_mode_ctl::W) writer structure"] impl crate::Writable for WR_MODE_CTL {} #[doc = "Write mode control"] pub mod wr_mode_ctl; #[doc = "Write dummy control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wr_dummy_ctl](wr_dummy_ctl) module"] pub type WR_DUMMY_CTL = crate::Reg<u32, _WR_DUMMY_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WR_DUMMY_CTL; #[doc = "`read()` method returns [wr_dummy_ctl::R](wr_dummy_ctl::R) reader structure"] impl crate::Readable for WR_DUMMY_CTL {} #[doc = "`write(|w| ..)` method takes [wr_dummy_ctl::W](wr_dummy_ctl::W) writer structure"] impl crate::Writable for WR_DUMMY_CTL {} #[doc = "Write dummy control"] pub mod wr_dummy_ctl; #[doc = "Write data control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [wr_data_ctl](wr_data_ctl) module"] pub type WR_DATA_CTL = crate::Reg<u32, _WR_DATA_CTL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WR_DATA_CTL; #[doc = "`read()` method returns [wr_data_ctl::R](wr_data_ctl::R) reader structure"] impl crate::Readable for WR_DATA_CTL {} #[doc = "`write(|w| ..)` method takes [wr_data_ctl::W](wr_data_ctl::W) writer structure"] impl crate::Writable for WR_DATA_CTL {} #[doc = "Write data control"] pub mod wr_data_ctl;
extern crate bytes; use std::net::SocketAddr; #[derive(Debug)] pub struct Props { pub host: String, pub port: i32 } impl Props { fn to_address(&self) -> SocketAddr { let address = format!("{}:{}", self.host, self.port); address.parse().expect("Unable to parse socket address") } } pub struct Server; impl Server { pub fn serve(props: Props) { let address = props.to_address(); } }
pub fn is_armstrong_number(num: u32) -> bool { // let digits = num // .to_string() // .chars() // .map(|d| d.to_digit(10).unwrap()) // .collect::<Vec<_>>(); // if digits.len() >= 10 { // false // } else { // digits // .iter() // .fold(0, |acc, el| acc + el.pow(digits.len() as u32)) // == num // } let num_str = num.to_string(); match num_str.len() { 0..=9 => { num_str .chars() .filter_map(|c| c.to_digit(10)) .fold(0, |acc, el| acc + el.pow(num_str.len() as u32)) == num } _ => false, } }
use std::collections::{HashMap, HashSet}; use crate::utils::file2vec; pub fn day7(filename:&String){ let contents = file2vec::<String>(filename); let contents:Vec<String> = contents.iter().map(|x| x.to_owned().unwrap()).collect(); let mut contained_in_map: HashMap<String,Vec<String>> = HashMap::new(); let mut contains_map: HashMap<String,Vec<(String, i32)>> = HashMap::new(); for line in contents.iter(){ let curr = parse_line(line); match curr.len() { 1 => (), _ => { for (key, quantity) in curr[1..].iter(){ let containers = contained_in_map.entry(key.to_string()).or_insert(Vec::new()); containers.push(curr[0].0.to_owned()); match contains_map.get_mut(&curr[0].0) { Some(container) => { container.push((key.to_owned(), *quantity)); }, None => { contains_map.insert(curr[0].0.to_owned(), vec![(key.to_owned(), *quantity)]); } } } } } }; let mut stack = vec!["shiny gold".to_string()]; let mut seen = HashSet::new(); let mut count = 0; while stack.len()>0 { match stack.pop() { Some(bag) => { match contained_in_map.get_mut(&bag) { Some(bags) => { for new_bag in bags{ if !seen.contains(new_bag){ seen.insert(new_bag.to_owned()); count += 1; } stack.push(new_bag.as_str().to_owned()); } }, None => () }; }, None => () } }; println!("{} bags can hold shiny gold bags", count); let mut stack = vec![("shiny gold".to_string(),1 as i32, 0 as i32)]; let mut full_count = 0; while stack.len() > 0 { match stack.pop(){ Some(bag) =>{ //parent, let mut sub_count = 0; match contains_map.get(&bag.0) { Some(bags) =>{ for b in bags{ sub_count += b.1*bag.1; stack.push((b.0.to_owned(), b.1*bag.1, bag.1)); } }, None => () } full_count += sub_count; }, None => () } } println!("full count {}", full_count); } fn parse_line(line: &String)-> Vec<(String, i32)>{ // hash map contains <bag: Vec<bag_contained_in, quantity>> let mut map = Vec::new(); line.split(" contain ").enumerate().fold(map, |mut acc, (idx,bag)|{ match idx { 0 => { //the containing bag, store as new value to ad let new_val = bag.trim().split("bag").next().unwrap().trim().to_owned(); acc.push((new_val, 0)); acc }, _ => { // bags contained by new_val bag match bag.trim() { "no other bags." => { acc }, bag_val => { for (sub_bag, quantity) in bag_val.split(",").map(|bags| { let bag_type = bags.trim()[1..].trim().split("bag").next(); (bag_type.unwrap().trim().to_owned(), bags.trim()[..1].parse::<i32>().unwrap_or(-1) ) }){ acc.push((sub_bag.to_owned(), quantity)); } acc } } } } }) }
use diesel::query_dsl::methods::{LimitDsl, OffsetDsl}; use juniper::GraphQLInputObject; #[derive(GraphQLInputObject)] pub struct Pagination { pub take: Option<i32>, pub skip: Option<i32>, } #[allow(clippy::module_name_repetitions)] pub trait PaginateDsl { type Output; fn paginate(self, pagination: Option<Pagination>) -> Self::Output; } impl<T> PaginateDsl for T where T: OffsetDsl, T::Output: LimitDsl, { type Output = <T::Output as LimitDsl>::Output; fn paginate(self, pagination: Option<Pagination>) -> Self::Output { let mut skip = 0; let mut take = 10; if let Some(pagination) = pagination { skip = pagination.skip.unwrap_or(skip); take = pagination.take.unwrap_or(take); } self.offset(skip.into()).limit(take.into()) } }
//! # Structures related to the downloaded game files and the log //! //! #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] pub enum IsoCode { #[serde(rename = "en-US")] EnUS, #[serde(other)] Other, } #[derive(Debug, Serialize, Deserialize)] pub struct DataLoc { #[serde(rename = "isoCode")] pub iso_code: IsoCode, pub keys: Vec<DataKey>, } #[derive(Debug, Serialize, Deserialize)] pub struct DataKey { pub id: u64, pub text: String, } #[derive(Debug, Serialize, Deserialize)] pub struct DataCard { pub grpid: u64, #[serde(rename = "titleId")] pub titleid: u64, pub set: String, #[serde(rename = "isCollectible")] pub is_collectible: bool, #[serde(rename = "isCraftable")] pub is_craftable: bool, #[serde(rename = "CollectorNumber")] pub collector_number: String, }
use std::fs; use std::error::Error; use std::io; struct Operation { opcode: u32, param_mode_1: u32, param_mode_2: u32, param_mode_3: u32, } fn parse_opcode(opcode: i32) -> Operation { let mut args = [0,0,0,0,0]; let arg_len = args.len(); for (i, c) in opcode.to_string().chars().rev().enumerate() { args[arg_len-1-i] = c.to_digit(10).unwrap(); } Operation { opcode: args[3]*10 + args[4], param_mode_1: args[2], param_mode_2: args[1], param_mode_3: args[0] } } fn get_parameter(mode: u32, param: i32, memory: &Vec<i32>) -> i32 { if mode == 0 { return memory[param as usize]; } else if mode == 1 { return param } else { panic!("Invalid mode"); } } pub fn part2() -> Result<(), Box<dyn Error>> { let code: String = fs::read_to_string("src/level5/input.txt")?; let mut opcodes: Vec<i32> = code.trim() .split(",") .map(|x| x.parse().unwrap()) .collect(); let mut i = 0; while i < opcodes.len() { let mem_debug = opcodes.iter().map(|d| d.to_string()).collect::<Vec<String>>(); let offset: usize = mem_debug[..i].iter().map(|x| x.len()).fold(0, |acc, val| acc + val) + i; println!("{}", mem_debug.join(" ")); println!("{}^", " ".repeat(offset)); let operation = parse_opcode(opcodes[i]); // 1 = ADD 1 2 into 3 if operation.opcode == 1 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); let num_3 = opcodes[i+3]; opcodes[num_3 as usize] = num_1 + num_2; i += 4; } // 2 = MULTIPLY 1 2 into 3 else if operation.opcode == 2 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); let num_3 = opcodes[i+3]; opcodes[num_3 as usize] = num_1 * num_2; i += 4; } // 3 = INPUT INTO ADDRESS 1 else if operation.opcode == 3 { let num_1 = opcodes[i+1]; let mut input = String::new(); println!("Input:"); io::stdin().read_line(&mut input)?; let input_value: i32 = input.trim().parse()?; opcodes[num_1 as usize] = input_value; i += 2; } // 4 = OUTPUT ADDRESS 1 else if operation.opcode == 4 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); println!("Output: {}", num_1); i += 2; } // 5 = JUMP TO 2 if 1 != 0 else if operation.opcode == 5 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); println!("IF {} != 0, JUMP TO {}", num_1, num_2); if num_1 != 0 { i = num_2 as usize; } else { i += 3; } } // 6 = JUMP TO 2 if 1 == 0 else if operation.opcode == 6 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); println!("IF {} == 0, JUMP TO {}", num_1, num_2); if num_1 == 0 { i = num_2 as usize; } else { i += 3; } } // 7 = LESS THAN 1 < 2, write 1 to 3 else if operation.opcode == 7 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); let num_3 = opcodes[i+3] as usize; println!("{} < {}", num_1, num_2); if num_1 < num_2 { opcodes[num_3] = 1; } else { opcodes[num_3] = 0; } i += 4; } // 8 = LESS THAN 1 == 2, write 1 to 3 else if operation.opcode == 8 { let num_1 = get_parameter(operation.param_mode_1, opcodes[i+1], &opcodes); let num_2 = get_parameter(operation.param_mode_2, opcodes[i+2], &opcodes); let num_3 = opcodes[i+3] as usize; if num_1 == num_2 { opcodes[num_3] = 1; } else { opcodes[num_3] = 0; } i += 4; } // 99 = HALT else if operation.opcode == 99 { println!("HALT"); println!("{}", opcodes[0]); return Ok(()); } else { // invalid opcode println!("INVALID OPCODE {}", operation.opcode); return Ok(()); } } Ok(()) }
//! Bounding volume hierarchy module. use std::sync::Arc; use crate::aabb::Aabb; use crate::hittable::{HitRecord, Hittable, HittableList}; /// Bounding volume hierarchy node. #[derive(Clone)] pub struct BvhNode { /// Child to the left. pub left: Option<Arc<dyn Hittable + Send + Sync>>, /// Child to the right. pub right: Option<Arc<dyn Hittable + Send + Sync>>, /// Bounding box of node. pub bbox: Aabb, } impl BvhNode { /// Create a new `BvhNode`. pub fn new( left: Option<Arc<dyn Hittable + Send + Sync>>, right: Option<Arc<dyn Hittable + Send + Sync>>, bbox: Aabb, ) -> Self { Self { left, right, bbox } } /// Split the nodes into hierarchies. pub fn bvh_node<R: rand::Rng>( rng: &mut R, list: &mut HittableList, time0: f64, time1: f64, ) -> Self { let left; let right; let axis = match rng.gen_range(0u8, 3) { 0 => Axis::X, 1 => Axis::Y, _ => Axis::Z, }; let object_span = list.objects.len(); match object_span { 0 => panic!("Cannot make a BVH from 0 objects!"), 1 => { left = Some(list.objects.first().unwrap().clone()); right = Some(list.objects.first().unwrap().clone()); } 2 => { if Self::box_compare( list.objects.get(0).unwrap(), list.objects.get(1).unwrap(), axis, ) { left = Some(list.objects.get(0).unwrap().clone()); right = Some(list.objects.get(1).unwrap().clone()); } else { left = Some(list.objects.get(1).unwrap().clone()); right = Some(list.objects.get(0).unwrap().clone()); } } _ => { list.objects.sort_unstable_by(|a, b| { if Self::box_compare(a, b, axis) { core::cmp::Ordering::Greater } else { core::cmp::Ordering::Less } }); let mid = object_span / 2; left = Some(Arc::new(Self::bvh_node( rng, &mut HittableList { objects: list.objects.drain(mid..).collect(), }, time0, time1, ))); right = Some(Arc::new(Self::bvh_node(rng, list, time0, time1))); } } let mut box_left = Aabb::default(); let mut box_right = Aabb::default(); let left_node = match left.clone() { Some(node) => node.bounding_box(time0, time1, &mut box_left), None => false, }; let right_node = match right.clone() { Some(node) => node.bounding_box(time0, time1, &mut box_right), None => false, }; if !left_node || !right_node { eprintln!("No bounding box in bvh_node constructor.\n"); return Self { left: None, right: None, bbox: Aabb::default(), }; } let bbox = Aabb::surrounding_box(&box_left, &box_right); Self { left, right, bbox } } /// Comparator for node bounding boxes. pub fn box_compare( a: &Arc<dyn Hittable + Send + Sync>, b: &Arc<dyn Hittable + Send + Sync>, axis: Axis, ) -> bool { let mut box_a = Aabb::default(); let mut box_b = Aabb::default(); if !(a.bounding_box(0.0, 0.0, &mut box_a)) || !(b.bounding_box(0.0, 0.0, &mut box_b)) { eprintln!("No bounding box in bvh_node constructor.\n"); return false; } match axis { Axis::X => box_a.min().x() < box_b.min().x(), Axis::Y => box_a.min().y() < box_b.min().y(), Axis::Z => box_a.min().z() < box_b.min().z(), } } } /// Cartesian axes. #[derive(Clone, Copy, Debug)] pub enum Axis { /// X-axis. X, /// Y-axis. Y, /// Z-axis. Z, } impl Hittable for BvhNode { fn bounding_box(&self, _t0: f64, _t1: f64, output_box: &mut crate::aabb::Aabb) -> bool { *output_box = self.bbox; true } fn hit(&self, r: &crate::ray::Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { if !self.bbox.hit(r, t_min, t_max) { return false; } let hit_left = match &self.left { Some(node) => node.hit(r, t_min, t_max, rec), None => false, }; let hit_right = match &self.right { Some(node) => node.hit(r, t_min, t_max, rec), None => false, }; hit_left || hit_right } } impl core::default::Default for BvhNode { fn default() -> Self { Self { left: None, right: None, bbox: Aabb::default(), } } }
//! Defines types for registering controllers with runtime. use crate::{operator::Operator, store::Store}; pub mod tasks; use tasks::{controller_tasks, OperatorTask}; pub mod controller; use controller::{Controller, ControllerBuilder}; mod watch; /// Coordinates one or more controllers and the main entrypoint for starting /// the application. /// /// # Warning /// /// This API does not support admissions webhooks yet, please /// use [OperatorRuntime](crate::runtime::OperatorRuntime). pub struct Manager { kubeconfig: kube::Config, controllers: Vec<Controller>, controller_tasks: Vec<OperatorTask>, store: Store, } impl Manager { /// Create a new controller manager. pub fn new(kubeconfig: &kube::Config) -> Self { Manager { controllers: vec![], controller_tasks: vec![], kubeconfig: kubeconfig.clone(), store: Store::new(), } } /// Register a controller with the manager. pub fn register_controller<C: Operator>(&mut self, builder: ControllerBuilder<C>) { let (controller, tasks) = controller_tasks(self.kubeconfig.clone(), builder, self.store.clone()); self.controllers.push(controller); self.controller_tasks.extend(tasks); } /// Start the manager, blocking forever. pub async fn start(self) { use futures::FutureExt; use std::convert::TryFrom; use tasks::launch_watcher; let mut tasks = self.controller_tasks; let client = kube::Client::try_from(self.kubeconfig) .expect("Unable to create kube::Client from kubeconfig."); // TODO: Deduplicate Watchers for controller in self.controllers { tasks.push(launch_watcher(client.clone(), controller.manages).boxed()); for handle in controller.owns { tasks.push(launch_watcher(client.clone(), handle).boxed()); } for handle in controller.watches { tasks.push(launch_watcher(client.clone(), handle).boxed()); } } futures::future::join_all(tasks).await; } }
extern crate aoc2017; use aoc2017::days::day10; fn main() { let input = aoc2017::read_trim("input/day10.txt").unwrap(); let value = day10::part1::parse(256, &input); println!("Day 10 part 1 value: {}", value); let value = day10::part2::parse(&input); println!("Day 10 part 2 value: {}", value); }
#[doc = "Register `ALRMAR` reader"] pub type R = crate::R<ALRMAR_SPEC>; #[doc = "Register `ALRMAR` writer"] pub type W = crate::W<ALRMAR_SPEC>; #[doc = "Field `SU` reader - Second units in BCD format."] pub type SU_R = crate::FieldReader; #[doc = "Field `SU` writer - Second units in BCD format."] pub type SU_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `ST` reader - Second tens in BCD format."] pub type ST_R = crate::FieldReader; #[doc = "Field `ST` writer - Second tens in BCD format."] pub type ST_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `MSK1` reader - Alarm A seconds mask"] pub type MSK1_R = crate::BitReader; #[doc = "Field `MSK1` writer - Alarm A seconds mask"] pub type MSK1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MNU` reader - Minute units in BCD format"] pub type MNU_R = crate::FieldReader; #[doc = "Field `MNU` writer - Minute units in BCD format"] pub type MNU_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `MNT` reader - Minute tens in BCD format"] pub type MNT_R = crate::FieldReader; #[doc = "Field `MNT` writer - Minute tens in BCD format"] pub type MNT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `MSK2` reader - Alarm A minutes mask"] pub type MSK2_R = crate::BitReader; #[doc = "Field `MSK2` writer - Alarm A minutes mask"] pub type MSK2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HU` reader - Hour units in BCD format"] pub type HU_R = crate::FieldReader; #[doc = "Field `HU` writer - Hour units in BCD format"] pub type HU_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `HT` reader - Hour tens in BCD format"] pub type HT_R = crate::FieldReader; #[doc = "Field `HT` writer - Hour tens in BCD format"] pub type HT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PM` reader - AM/PM notation"] pub type PM_R = crate::BitReader; #[doc = "Field `PM` writer - AM/PM notation"] pub type PM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MSK3` reader - Alarm A hours mask"] pub type MSK3_R = crate::BitReader; #[doc = "Field `MSK3` writer - Alarm A hours mask"] pub type MSK3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DU` reader - Date units or day in BCD format"] pub type DU_R = crate::FieldReader; #[doc = "Field `DU` writer - Date units or day in BCD format"] pub type DU_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `DT` reader - Date tens in BCD format"] pub type DT_R = crate::FieldReader; #[doc = "Field `DT` writer - Date tens in BCD format"] pub type DT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WDSEL` reader - Week day selection"] pub type WDSEL_R = crate::BitReader; #[doc = "Field `WDSEL` writer - Week day selection"] pub type WDSEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MSK4` reader - Alarm A date mask"] pub type MSK4_R = crate::BitReader; #[doc = "Field `MSK4` writer - Alarm A date mask"] pub type MSK4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bits 0:3 - Second units in BCD format."] #[inline(always)] pub fn su(&self) -> SU_R { SU_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:6 - Second tens in BCD format."] #[inline(always)] pub fn st(&self) -> ST_R { ST_R::new(((self.bits >> 4) & 7) as u8) } #[doc = "Bit 7 - Alarm A seconds mask"] #[inline(always)] pub fn msk1(&self) -> MSK1_R { MSK1_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bits 8:11 - Minute units in BCD format"] #[inline(always)] pub fn mnu(&self) -> MNU_R { MNU_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 12:14 - Minute tens in BCD format"] #[inline(always)] pub fn mnt(&self) -> MNT_R { MNT_R::new(((self.bits >> 12) & 7) as u8) } #[doc = "Bit 15 - Alarm A minutes mask"] #[inline(always)] pub fn msk2(&self) -> MSK2_R { MSK2_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bits 16:19 - Hour units in BCD format"] #[inline(always)] pub fn hu(&self) -> HU_R { HU_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:21 - Hour tens in BCD format"] #[inline(always)] pub fn ht(&self) -> HT_R { HT_R::new(((self.bits >> 20) & 3) as u8) } #[doc = "Bit 22 - AM/PM notation"] #[inline(always)] pub fn pm(&self) -> PM_R { PM_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Alarm A hours mask"] #[inline(always)] pub fn msk3(&self) -> MSK3_R { MSK3_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bits 24:27 - Date units or day in BCD format"] #[inline(always)] pub fn du(&self) -> DU_R { DU_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:29 - Date tens in BCD format"] #[inline(always)] pub fn dt(&self) -> DT_R { DT_R::new(((self.bits >> 28) & 3) as u8) } #[doc = "Bit 30 - Week day selection"] #[inline(always)] pub fn wdsel(&self) -> WDSEL_R { WDSEL_R::new(((self.bits >> 30) & 1) != 0) } #[doc = "Bit 31 - Alarm A date mask"] #[inline(always)] pub fn msk4(&self) -> MSK4_R { MSK4_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bits 0:3 - Second units in BCD format."] #[inline(always)] #[must_use] pub fn su(&mut self) -> SU_W<ALRMAR_SPEC, 0> { SU_W::new(self) } #[doc = "Bits 4:6 - Second tens in BCD format."] #[inline(always)] #[must_use] pub fn st(&mut self) -> ST_W<ALRMAR_SPEC, 4> { ST_W::new(self) } #[doc = "Bit 7 - Alarm A seconds mask"] #[inline(always)] #[must_use] pub fn msk1(&mut self) -> MSK1_W<ALRMAR_SPEC, 7> { MSK1_W::new(self) } #[doc = "Bits 8:11 - Minute units in BCD format"] #[inline(always)] #[must_use] pub fn mnu(&mut self) -> MNU_W<ALRMAR_SPEC, 8> { MNU_W::new(self) } #[doc = "Bits 12:14 - Minute tens in BCD format"] #[inline(always)] #[must_use] pub fn mnt(&mut self) -> MNT_W<ALRMAR_SPEC, 12> { MNT_W::new(self) } #[doc = "Bit 15 - Alarm A minutes mask"] #[inline(always)] #[must_use] pub fn msk2(&mut self) -> MSK2_W<ALRMAR_SPEC, 15> { MSK2_W::new(self) } #[doc = "Bits 16:19 - Hour units in BCD format"] #[inline(always)] #[must_use] pub fn hu(&mut self) -> HU_W<ALRMAR_SPEC, 16> { HU_W::new(self) } #[doc = "Bits 20:21 - Hour tens in BCD format"] #[inline(always)] #[must_use] pub fn ht(&mut self) -> HT_W<ALRMAR_SPEC, 20> { HT_W::new(self) } #[doc = "Bit 22 - AM/PM notation"] #[inline(always)] #[must_use] pub fn pm(&mut self) -> PM_W<ALRMAR_SPEC, 22> { PM_W::new(self) } #[doc = "Bit 23 - Alarm A hours mask"] #[inline(always)] #[must_use] pub fn msk3(&mut self) -> MSK3_W<ALRMAR_SPEC, 23> { MSK3_W::new(self) } #[doc = "Bits 24:27 - Date units or day in BCD format"] #[inline(always)] #[must_use] pub fn du(&mut self) -> DU_W<ALRMAR_SPEC, 24> { DU_W::new(self) } #[doc = "Bits 28:29 - Date tens in BCD format"] #[inline(always)] #[must_use] pub fn dt(&mut self) -> DT_W<ALRMAR_SPEC, 28> { DT_W::new(self) } #[doc = "Bit 30 - Week day selection"] #[inline(always)] #[must_use] pub fn wdsel(&mut self) -> WDSEL_W<ALRMAR_SPEC, 30> { WDSEL_W::new(self) } #[doc = "Bit 31 - Alarm A date mask"] #[inline(always)] #[must_use] pub fn msk4(&mut self) -> MSK4_W<ALRMAR_SPEC, 31> { MSK4_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "RTC alarm A register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`alrmar::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`alrmar::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ALRMAR_SPEC; impl crate::RegisterSpec for ALRMAR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`alrmar::R`](R) reader structure"] impl crate::Readable for ALRMAR_SPEC {} #[doc = "`write(|w| ..)` method takes [`alrmar::W`](W) writer structure"] impl crate::Writable for ALRMAR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ALRMAR to value 0"] impl crate::Resettable for ALRMAR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use mlvalues; use memory; use mlvalues::{is_block, Value, empty_list}; use alloc; use tag::Tag; use error::Error; pub struct Tuple(Value, usize); impl From<Tuple> for Value { fn from(t: Tuple) -> Value { t.0 } } impl Tuple { pub unsafe fn new(n: usize) -> Tuple { let val = alloc::caml_alloc_tuple(n); Tuple(val, n) } pub fn len(&self) -> usize { self.1 } pub fn value(&self) -> Value { self.0 } pub unsafe fn set(&mut self, i: usize, v: Value) -> Result<(), Error> { if i < self.1 { memory::store_field(self.value(), i, v); Ok(()) } else { Err(Error::OutOfBounds) } } pub unsafe fn get(&self, i: usize) -> Result<Value, Error> { if i < self.1 { Ok(*mlvalues::field(self.value(), i)) } else { Err(Error::OutOfBounds) } } } pub struct Array(Value, usize); impl From<Array> for Value { fn from(t: Array) -> Value { t.0 } } impl From<Value> for Array { fn from(v: Value) -> Array { unsafe { if !is_block(v) { let mut arr = Array::new(1); let _ = arr.set(0, v); arr } else { let length = mlvalues::caml_array_length(v); Array(v, length) } } } } impl Array { pub unsafe fn new(n: usize) -> Array { let val = alloc::caml_alloc(n, Tag::Zero as u8); Array(val, n) } pub fn len(&self) -> usize { self.1 } pub fn value(&self) -> Value { self.0 } pub unsafe fn set(&mut self, i: usize, v: Value) -> Result<(), Error> { if i < self.1 { memory::store_field(self.value(), i, v); Ok(()) } else { Err(Error::OutOfBounds) } } pub unsafe fn get(&self, i: usize) -> Result<Value, Error> { if i < self.1 { Ok(*mlvalues::field(self.value(), i)) } else { Err(Error::OutOfBounds) } } } pub struct List(Value, usize); impl From<List> for Value { fn from(t: List) -> Value { t.0 } } impl List { pub fn new() -> List { List(empty_list(), 0) } pub fn hd(&self) -> Option<Value> { if self.1 == 0 { return None } unsafe { Some(*mlvalues::field(self.0, 0)) } } } pub struct Str(Value, usize); impl From<Str> for Value { fn from(t: Str) -> Value { t.0 } }
pub use lib::bitboard::BitBoard; pub use lib::player::Player; pub use lib::board::Board;
use std::io::BufRead; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; struct Region { name: String, population: i64, south_edge: f64, } fn tally(file: std::fs::File, regions: &mut Vec<Region>) -> Result<()> { // Tally. for maybe_line in std::io::BufReader::new(file).lines() { let line = maybe_line?; let fields: Vec<&str> = line.split("\t").collect(); let latitude = fields[4].parse::<f64>()?; let population = fields[14].parse::<i64>()?; for region in regions.into_iter() { if latitude >= region.south_edge { region.population += population; break; } } } // Report. for region in regions.into_iter() { println!("{}: {}", region.name, region.population); } Ok(()) } fn main() -> Result<()> { let args: Vec<String> = std::env::args().collect(); // dbg!(args); let file = std::fs::File::open(&args[1])?; let mut regions = vec![ Region { name: "North".to_string(), population: 0, south_edge: 0.0, }, Region { name: "South".to_string(), population: 0, south_edge: -90.0, }, ]; tally(file, &mut regions) }
extern crate introsort; fn main() { let mut ss = vec!["Introsort", "or", "introspective", "sort", "is", "a", "hybrid", "sorting", "algorithm", "that", "provides", "both", "fast", "average", "performance", "and", "(asymptotically)", "optimal", "worst-case", "performance"]; introsort::sort(&mut ss[..]); println!("alphabetically"); for s in ss.iter() { println!("\t{}", s); } introsort::sort_by(&mut ss[..], &|a, b| a.len().cmp(&b.len())); println!("\nby length"); for s in ss.iter() { println!("\t{}", s); } }
use crate::components::Token; use crate::root::{AppAnchor, AppRoute, DataState}; use crate::{ data::{MealPlans, MealPlansItem, MealPlansItemRecipesItem}, date::next_seven_days, services::{Error, MealPlansService, RecipeService}, }; use yew::{prelude::*, services::fetch::FetchTask, Properties}; use yew_state::{SharedHandle, SharedState, SharedStateComponent}; pub struct RecipePageComponent { link: ComponentLink<Self>, recipe_service: RecipeService, recipe: Option<RecipeModel>, task: Option<FetchTask>, response: Callback<Result<RecipeModel, Error>>, props: Props, edit_mode: bool, meal_plans_service: MealPlansService, } pub enum Message { OnRecipeFetch(Result<RecipeModel, Error>), OnSave, OnNameChange(String), OnIngredientAmountChange(usize, String), OnIngredientUnitChange(usize, String), OnIngredientNameChange(usize, String), OnIngredientDelete(usize), OnIngredientAdd, OnStepChange(usize, String), OnStepDelete(usize), OnStepAdd, OnSourceUrlAdd, OnSourceUrlChange(String), OnSourceUrlDelete, OnQuantityAdd, OnQuantityAmountChange(String), OnQuantityUnitChange(String), OnQuantityDelete, OnEditMode, OnCancel, PlanRecipe(String), MealPlansResponse(Result<MealPlans, Error>), OpenModal, } #[derive(Clone, PartialEq, Properties)] pub struct Props { pub recipe_id: String, #[prop_or_default] handle: SharedHandle<DataState>, } impl SharedState for Props { type Handle = SharedHandle<DataState>; fn handle(&mut self) -> &mut Self::Handle { &mut self.handle } } impl RecipePageComponent { fn get_recipe(&mut self) { self.task = Some( self.recipe_service .get_recipe_by_id(&self.props.recipe_id, self.response.clone()), ); } fn get_ingredients(&self, recipe: &RecipeModel) -> Html { let ingredients = recipe .ingredients .iter() .map(|ingredient| { let ingredient_amount = if let Some(amount) = ingredient.amount { format!("{} ", amount) } else { "".to_string() }; let ingredient_unit = if let Some(unit) = &ingredient.unit { format!("{} ", unit) } else { "".to_string() }; let value = format!( "{}{}{}", ingredient_amount, ingredient_unit, ingredient.name.clone() ); let icon = ingredient.icon.clone().unwrap_or_else(|| "".to_string()); html! { <div class="ingredient-cell"> <div class="ingredient-item z-depth-1 vegetable"> <img class="fit-picture" src={icon}/> <p>{voca_rs::case::capitalize(&value, &true)}</p> </div> </div> } }) .collect::<Html>(); html! { <div class="ingredients"> {ingredients} </div> } } fn get_ingredients_edit(&self, recipe: &RecipeModel) -> Html { let ingredients = recipe .ingredients .iter() .enumerate() .map(|(index, ingredient)| { let on_ingredient_amount_change_callback = self .link .callback(move |e: InputData| Message::OnIngredientAmountChange(index, e.value)); let on_ingredient_unit_change_callback = self .link .callback(move |e: InputData| Message::OnIngredientUnitChange(index, e.value)); let on_ingredient_name_change_callback = self .link .callback(move |e: InputData| Message::OnIngredientNameChange(index, e.value)); let on_ingredient_delete_callback = self .link .callback(move |_| Message::OnIngredientDelete(index)); let ingredient_amount = if let Some(amount) = ingredient.amount { format!("{}", amount) } else { "".to_string() }; let ingredient_unit = if let Some(unit) = &ingredient.unit { unit.clone() } else { "".to_string() }; html! { <div class="row"> <div class="input-field col s2"> <input disabled={!self.edit_mode} value={ingredient_amount} oninput={on_ingredient_amount_change_callback} id="quantity" type="text" class="validate"/> </div> <div class="input-field col s2"> <input disabled={!self.edit_mode} value={ingredient_unit} oninput={on_ingredient_unit_change_callback} id="unit" type="text" class="validate"/> </div> <div class="input-field col s6"> <input disabled={!self.edit_mode} value={ingredient.name.clone()} oninput={on_ingredient_name_change_callback} autocorrect="off" autocapitalize="none" id="name" type="text" class="validate"/> </div> <div class="input-field col s2"> <button onclick={on_ingredient_delete_callback} class="btn waves-effect waves-light" name="action"> <i class="material-icons left">{"delete"}</i> </button> </div> </div> } }) .collect::<Html>(); let on_ingredient_add_callback = self.link.callback(|_| Message::OnIngredientAdd); html! { <div class="row"> <div class="col s12"> <div class="card horizontal"> <div class="card-stacked"> <div class="card-content"> <form class="col s12"> {ingredients} </form> <div class="row"> <div class="input-field col s12"> <button onclick={on_ingredient_add_callback} class="btn waves-effect waves-light" name="action"> {"ingrédient"} <i class="material-icons left">{"add"}</i> </button> </div> </div> </div> </div> </div> </div> </div> } } fn get_source_url(&self, recipe: &RecipeModel) -> Html { match &recipe.source_url { Some(source_url) => html! { <div class="row"> <a href={source_url.to_string()}>{"source"}</a> </div> }, None => html! {}, } } fn get_source_url_edit(&self, recipe: &RecipeModel) -> Html { let source_url = match &recipe.source_url { Some(source_url) => { let on_source_url_change_callback = self .link .callback(|e: InputData| Message::OnSourceUrlChange(e.value)); let on_source_url_delete_callback = self.link.callback(|_| Message::OnSourceUrlDelete); let delete_source = html! { <div class="input-field col s2"> <button onclick={on_source_url_delete_callback} class="btn waves-effect waves-light" name="action"> <i class="material-icons left">{"delete"}</i> </button> </div> }; html! { <div class="row"> <div class="input-field col s10"> <input disabled={!self.edit_mode} oninput={on_source_url_change_callback} value={source_url} type="text" class="validate"/> </div> {delete_source} </div> } } None => { let on_source_url_add_callback = self.link.callback(|_| Message::OnSourceUrlAdd); html! { <div class="row"> <div class="input-field col s12"> <button onclick={on_source_url_add_callback} class="btn waves-effect waves-light" name="action"> {"source"} <i class="material-icons left">{"add"}</i> </button> </div> </div> } } }; html! { <form class="col s12"> {source_url} </form> } } fn get_instructions_edit(&self, recipe: &RecipeModel) -> Html { let on_step_add_callback = self.link.callback(|_| Message::OnStepAdd); let steps = match &recipe .steps { Some(steps) => steps.iter().enumerate() .map(|(index, step)| { let on_step_change_callback = self .link .callback(move |e: InputData| Message::OnStepChange(index, e.value)); let on_step_delete_callback = self .link .callback(move |_| Message::OnStepDelete(index)); html! { <div class="row"> <div class="input-field col s10"> <textarea oninput={on_step_change_callback} value={step.step.clone()} class="materialize-textarea"></textarea> </div> <div class="input-field col s2"> <button onclick={on_step_delete_callback} class="btn waves-effect waves-light" name="action"> <i class="material-icons left">{"delete"}</i> </button> </div> </div> } }).collect::<Html>(), None => html!{} }; html! { <> <form class="col s12"> {steps} </form> <div class="row"> <div class="input-field col s12"> <button onclick={on_step_add_callback} class="btn waves-effect waves-light"> {"instruction"} <i class="material-icons left">{"add"}</i> </button> </div> </div> </> } } fn get_instructions(&self, recipe: &RecipeModel) -> Html { let steps = match &recipe.steps { Some(steps) => steps .iter() .enumerate() .map(|(index, step)| { let step_index = format!("{}) ", index + 1); html! { <p> {step_index} {step.step.clone()} </p> } }) .collect::<Html>(), None => html! {}, }; html! { <div> {steps} </div> } } fn get_header(&self, recipe: &RecipeModel) -> Html { let quantity = match &recipe.quantity { Some(quantity) => { let value = format!("{} {}", quantity.amount.clone(), quantity.unit.clone()); html! { <h6>{value}</h6> } } None => html! {}, }; html! { <div> <h4>{voca_rs::case::capitalize(&recipe.name, &true)}</h4> {quantity} </div> } } fn get_header_edit(&self, recipe: &RecipeModel) -> Html { let on_name_change_callback = self .link .callback(|e: InputData| Message::OnNameChange(e.value)); let quantity = match &recipe.quantity { Some(quantity) => { let on_quantity_amount_change_callback = self .link .callback(|e: InputData| Message::OnQuantityAmountChange(e.value)); let on_quantity_unit_change_callback = self .link .callback(|e: InputData| Message::OnQuantityUnitChange(e.value)); let on_quantity_delete_callback = self.link.callback(|_| Message::OnQuantityDelete); html! { <div class="row"> <div class="input-field col s3"> <input oninput={on_quantity_amount_change_callback} value={quantity.amount.clone()} type="text" class="validate"/> </div> <div class="input-field col s7"> <input oninput={on_quantity_unit_change_callback} value={quantity.unit.clone()} type="text" class="validate"/> </div> <div class="input-field col s2"> <button onclick={on_quantity_delete_callback} class="btn waves-effect waves-light" name="action"> <i class="material-icons left">{"delete"}</i> </button> </div> </div> } } None => { let on_quantity_add_callback = self.link.callback(|_| Message::OnQuantityAdd); html! { <div class="row"> <div class="input-field col s12"> <button onclick={on_quantity_add_callback} class="btn waves-effect waves-light" name="action"> {"quantité"} <i class="material-icons left">{"add"}</i> </button> </div> </div> } } }; html! { <form class="col s12"> <div class="row"> <div class="input-field col s12"> <input disabled={!self.edit_mode} value={recipe.name.clone()} oninput={on_name_change_callback} type="text" class="validate"/> </div> </div> {quantity} </form> } } fn get_menu(&self, _recipe: &RecipeModel) -> Html { let callback = self.link.callback(|_| Message::OnEditMode); html! { <li> <a onclick={callback}><i class="material-icons">{"edit"}</i></a> </li> } } fn get_edit_menu(&self, _recipe: &RecipeModel) -> Html { let on_save_callback = self.link.callback(|_| Message::OnSave); let on_cancel_edit_mode_callback = self.link.callback(|_| Message::OnCancel); html! { <> <li> <a onclick={on_save_callback}> <i class="material-icons">{"save"}</i> </a> </li> <li> <a onclick=on_cancel_edit_mode_callback> <i class="material-icons">{"close"}</i> </a> </li> </> } } fn get_fab(&self, _recipe: &RecipeModel) -> Html { let callback = self.link.callback(move |_| Message::OpenModal); html! { <a class="btn-floating btn-large red" onclick=callback> <i class="large material-icons">{"event"}</i> </a> } } fn get_fab_edit(&self, _recipe: &RecipeModel) -> Html { html! {} } } impl Component for RecipePageComponent { type Message = Message; type Properties = Props; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { recipe_service: RecipeService::new(), response: link.callback(Message::OnRecipeFetch), recipe: None, task: None, meal_plans_service: MealPlansService::new(), props, link, edit_mode: false, } } fn rendered(&mut self, first_render: bool) { if first_render { self.get_recipe(); self.meal_plans_service .get_meal_plans(self.link.callback(Message::MealPlansResponse)); } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Message::OnRecipeFetch(Ok(recipe)) => { self.recipe = Some(recipe); self.task = None; } Message::OnRecipeFetch(Err(_)) => { self.task = None; } Message::OnSave => { if let Some(recipe) = self.recipe.clone() { self.task = Some(self.recipe_service.update_recipe_by_id( &self.props.recipe_id.clone(), recipe, self.response.clone(), )); } } Message::OnNameChange(name) => { if let Some(recipe) = self.recipe.as_mut() { recipe.name = name; } } Message::OnIngredientAmountChange(index, amount) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(ingredient) = recipe.ingredients.get_mut(index) { ingredient.amount = amount.parse::<f64>().map_or_else(|_| None, Some); } } } Message::OnIngredientUnitChange(index, unit) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(ingredient) = recipe.ingredients.get_mut(index) { ingredient.unit = Some(unit); } } } Message::OnIngredientNameChange(index, name) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(ingredient) = recipe.ingredients.get_mut(index) { ingredient.name = name; } } } Message::OnIngredientAdd => { if let Some(recipe) = self.recipe.as_mut() { recipe.ingredients.push(RecipeIngredientModel { amount: None, unit: None, name: "".to_string(), notes: None, processing: None, substitutions: None, usda_num: None, icon: None, category: None, }); } } Message::OnIngredientDelete(index) => { if let Some(recipe) = self.recipe.as_mut() { recipe.ingredients.remove(index); } } Message::OnStepChange(index, step) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(steps) = recipe.steps.as_mut() { if let Some(selected_step) = steps.get_mut(index) { selected_step.step = step; } } } } Message::OnStepAdd => { if let Some(recipe) = self.recipe.as_mut() { if let Some(steps) = recipe.steps.as_mut() { steps.push(RecipeModelSteps { haccp: None, notes: None, step: "".to_string(), }); } else { recipe.steps = Some(vec![RecipeModelSteps { haccp: None, notes: None, step: "".to_string(), }]); } } } Message::OnStepDelete(index) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(steps) = recipe.steps.as_mut() { steps.remove(index); } } } Message::OnSourceUrlAdd => { if let Some(recipe) = self.recipe.as_mut() { recipe.source_url = Some("".to_string()) } } Message::OnSourceUrlChange(source_url) => { if let Some(recipe) = self.recipe.as_mut() { recipe.source_url = Some(source_url) } } Message::OnSourceUrlDelete => { if let Some(recipe) = self.recipe.as_mut() { recipe.source_url = None } } Message::OnQuantityAdd => { if let Some(recipe) = self.recipe.as_mut() { recipe.quantity = Some(RecipeModelQuantity { amount: 1.0, unit: "personne".to_string(), }) } } Message::OnQuantityAmountChange(quantity_amount) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(quantity) = recipe.quantity.as_mut() { quantity.amount = quantity_amount.parse::<f64>().unwrap_or(1.0); } } } Message::OnQuantityUnitChange(quantity_unit) => { if let Some(recipe) = self.recipe.as_mut() { if let Some(quantity) = recipe.quantity.as_mut() { quantity.unit = quantity_unit; } } } Message::OnQuantityDelete => { if let Some(recipe) = self.recipe.as_mut() { recipe.quantity = None } } Message::OnEditMode => { self.edit_mode = true; } Message::OnCancel => { self.edit_mode = false; } Message::PlanRecipe(meal_date) => { let mut meal_plans = self.props.handle().state().meal_plans.clone(); if let Some(meals_plans_option) = meal_plans.as_mut() { if let Some(meal) = meals_plans_option .iter_mut() .find(|meals| meals.date == meal_date) { meal.recipes.push(MealPlansItemRecipesItem { done: false, id: self.props.recipe_id.clone(), servings: None, }) } else { meals_plans_option.push(MealPlansItem { date: meal_date, recipes: vec![MealPlansItemRecipesItem { done: false, id: self.props.recipe_id.clone(), servings: None, }], }) } } if let Some(meal_plans) = &meal_plans { self.meal_plans_service.update_meal_plans( meal_plans.clone(), self.link.callback(Message::MealPlansResponse), ); } self.props.handle().reduce(move |state| { state.meal_plans = meal_plans; }); close_modal(); } Message::MealPlansResponse(meal_plans) => { let meal_plans = self.meal_plans_service.get_meal_plans.response(meal_plans); self.props .handle .reduce(move |state| state.meal_plans = meal_plans); } Message::OpenModal => open_modal(), } true } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props = props; false } fn view(&self) -> Html { match self.recipe.clone() { Some(recipe) => { let (header, ingredients, instructions, source_url, fab_action, menu_action) = if self.edit_mode { ( self.get_header_edit(&recipe), self.get_ingredients_edit(&recipe), self.get_instructions_edit(&recipe), self.get_source_url_edit(&recipe), self.get_fab_edit(&recipe), self.get_edit_menu(&recipe), ) } else { ( self.get_header(&recipe), self.get_ingredients(&recipe), self.get_instructions(&recipe), self.get_source_url(&recipe), self.get_fab(&recipe), self.get_menu(&recipe), ) }; let next_date = next_seven_days() .iter() .map(|(day_code, day_string)| { let day_code = day_code.clone(); let callback = self.link.callback(move |_| { let day_code = day_code.clone(); Message::PlanRecipe(day_code) }); html! { <li onclick=callback class="waves-effect"> <div class="valign-wrapper">{day_string}</div> </li> } }) .collect::<Html>(); html! { <> <Token/> <div class="navbar-fixed"> <nav> <div class="nav-wrapper"> <ul class="left"> <AppAnchor route=AppRoute::RecipeList> <i class="material-icons">{"chevron_left"}</i> </AppAnchor> </ul> <ul class="right"> {menu_action} </ul> </div> </nav> </div> <div class="fixed-action-btn"> {fab_action} </div> <div id="modal1" class="modal bottom-sheet"> <div class="modal-content"> <ul class="list"> {next_date} </ul> </div> </div> <div class="container planning"> <div class="row"> <div class="col s12"> <div class="card horizontal"> <div class="card-stacked"> <div class="card-content"> {header} <form class="col s12"> {source_url} </form> </div> </div> </div> </div> </div> {ingredients} <div class="row"> <div class="col s12 m6"> <div class="card horizontal"> <div class="card-stacked"> <div class="card-content"> <h5>{"Instructions"}</h5> {instructions} </div> </div> </div> </div> </div> </div> </> } } None => html! { <> <Token/> <div class="navbar-fixed"> <nav> <div class="nav-wrapper"> <ul class="left"> <AppAnchor route=AppRoute::RecipeList> <i class="material-icons">{"chevron_left"}</i> </AppAnchor> </ul> </div> </nav> </div> <div class="loader-page"> <div class="preloader-wrapper active"> <div class="spinner-layer spinner-red-only"> <div class="circle-clipper left"> <div class="circle"></div> </div><div class="gap-patch"> <div class="circle"></div> </div><div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> </div> </> }, } } } pub type RecipePage = SharedStateComponent<RecipePageComponent>; use oikos_api::components::schemas::{ RecipeIngredientModel, RecipeModel, RecipeModelQuantity, RecipeModelSteps, }; use wasm_bindgen::prelude::*; #[wasm_bindgen(inline_js = " export function open_modal() { var elems = document.querySelectorAll('.modal'); var instances = M.Modal.init(elems); var instance = M.Modal.getInstance(elems[0]); instance.open(); }")] extern "C" { fn open_modal(); } #[wasm_bindgen(inline_js = " export function close_modal() { var elems = document.querySelectorAll('.modal'); var instances = M.Modal.init(elems); var instance = M.Modal.getInstance(elems[0]); instance.close(); }")] extern "C" { fn close_modal(); }
#[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct FacetRequest { pub field: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default = "default_top")] pub top: Option<usize>, } fn default_top() -> Option<usize> { Some(10) }
#[doc = "Reader of register INIT_WINDOW_TIMER_CTRL"] pub type R = crate::R<u32, super::INIT_WINDOW_TIMER_CTRL>; #[doc = "Writer for register INIT_WINDOW_TIMER_CTRL"] pub type W = crate::W<u32, super::INIT_WINDOW_TIMER_CTRL>; #[doc = "Register INIT_WINDOW_TIMER_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::INIT_WINDOW_TIMER_CTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `INIT_WINDOW_OFFSET_SEL`"] pub type INIT_WINDOW_OFFSET_SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `INIT_WINDOW_OFFSET_SEL`"] pub struct INIT_WINDOW_OFFSET_SEL_W<'a> { w: &'a mut W, } impl<'a> INIT_WINDOW_OFFSET_SEL_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 } } impl R { #[doc = "Bit 0 - Controls the INIT Window offset source 1 - Pick INIT Window Offset from HW calculated INIT_WINDOW_OFFSET 0 - Pick INIT Window Offset from FW loaded register"] #[inline(always)] pub fn init_window_offset_sel(&self) -> INIT_WINDOW_OFFSET_SEL_R { INIT_WINDOW_OFFSET_SEL_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Controls the INIT Window offset source 1 - Pick INIT Window Offset from HW calculated INIT_WINDOW_OFFSET 0 - Pick INIT Window Offset from FW loaded register"] #[inline(always)] pub fn init_window_offset_sel(&mut self) -> INIT_WINDOW_OFFSET_SEL_W { INIT_WINDOW_OFFSET_SEL_W { w: self } } }
// pub mod owner; pub fn function() { // owner::owner(); let mut greet = String::from("hello"); greet.push_str(", world!"); println!(" {}", greet); }
use super::board::{ Board , BOARD_SIZE }; use super::cell::Cell; use super::cell::Position; /* at a high level, solving is applying a set of strategies, repeatedly in a round-robin-ish way until, either, puzzle is solved or out of options we'll try to provide a hind based solving, at each step, the global logic will select a solving strategy and ask it about a hint to fill in one cell */ /// Information about where from to add/change/remove what. #[allow(dead_code)] pub enum BoardAction { /// At `pos` add `value`. ValueAdd { pos: Position, value: u8 }, /// From `pos`, remove `value`. /// Value may be redundant but it allows transformation /// for both back and forth. ValueRemove { pos: Position, value: u8 }, /// HintAdd { pos: Position, value: u8 }, HintRemove { pos: Position, value: u8 }, } #[allow(dead_code)] pub struct Hint { cell: Cell, pos: Position, } /// Implementors look at the board and try to apply /// their internal logic into finding one more empty /// cell to fill in /// #[allow(dead_code)] pub trait SolveStrategy { fn get_hint(&self, board: &Board ) -> Option< Hint >; fn get_name(&self) -> &String; } // // solving strategy NakedSingle // - https://www.sadmansoftware.com/sudoku/nakedsingle.php // #[allow(dead_code)] pub struct SolveStrategyNakedSingle { name: String, // here there be state for this solving strategy } #[allow(dead_code)] impl SolveStrategyNakedSingle { // helper functions #[allow(unused_variables)] fn is_naked_single(&self, board: &Board, lin: usize, col: usize) -> bool { return false; } } #[allow(dead_code)] impl SolveStrategy for SolveStrategyNakedSingle { #[allow(unused_variables)] fn get_hint(&self, board: &Board ) -> Option< Hint > { for lin in 0..BOARD_SIZE as usize { for col in 0..BOARD_SIZE as usize { let is = SolveStrategyNakedSingle::is_naked_single(self, board, lin, col); } } None } fn get_name(&self) -> &String { &self.name } }
use serde::{Deserialize, Serialize}; use sqlx::FromRow; #[derive(FromRow, Deserialize, Serialize)] pub struct State { pub id: i16, pub name: String, }
use aoc_2020::day_02::*; use std::io::prelude::*; use criterion::{criterion_group, criterion_main, Criterion}; pub fn benchmark(c: &mut Criterion) { let file = std::fs::File::open("input/day-02.txt").expect("Couldn't open input file"); let input: Vec<String> = std::io::BufReader::new(file) .lines() .map(|line| line.unwrap()) .collect(); c.bench_function("Day 02 Part 1", |b| b.iter(|| part1(&input))); c.bench_function("Day 02 Part 2", |b| b.iter(|| part2(&input))); } criterion_group!(benches, benchmark); criterion_main!(benches);
#[doc = "Reader of register NPCTCFG3"] pub type R = crate::R<u32, super::NPCTCFG3>; #[doc = "Writer for register NPCTCFG3"] pub type W = crate::W<u32, super::NPCTCFG3>; #[doc = "Register NPCTCFG3 `reset()`'s with value 0xfcfc_fcfc"] impl crate::ResetValue for super::NPCTCFG3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xfcfc_fcfc } } #[doc = "Reader of field `COMHIZ`"] pub type COMHIZ_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMHIZ`"] pub struct COMHIZ_W<'a> { w: &'a mut W, } impl<'a> COMHIZ_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24); self.w } } #[doc = "Reader of field `COMHLD`"] pub type COMHLD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMHLD`"] pub struct COMHLD_W<'a> { w: &'a mut W, } impl<'a> COMHLD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `COMWAIT`"] pub type COMWAIT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMWAIT`"] pub struct COMWAIT_W<'a> { w: &'a mut W, } impl<'a> COMWAIT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of field `COMSET`"] pub type COMSET_R = crate::R<u8, u8>; #[doc = "Write proxy for field `COMSET`"] pub struct COMSET_W<'a> { w: &'a mut W, } impl<'a> COMSET_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } impl R { #[doc = "Bits 24:31 - Common memory data bus HiZ time"] #[inline(always)] pub fn comhiz(&self) -> COMHIZ_R { COMHIZ_R::new(((self.bits >> 24) & 0xff) as u8) } #[doc = "Bits 16:23 - Common memory hold time"] #[inline(always)] pub fn comhld(&self) -> COMHLD_R { COMHLD_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 8:15 - Common memory wait time"] #[inline(always)] pub fn comwait(&self) -> COMWAIT_R { COMWAIT_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 0:7 - Common memory setup time"] #[inline(always)] pub fn comset(&self) -> COMSET_R { COMSET_R::new((self.bits & 0xff) as u8) } } impl W { #[doc = "Bits 24:31 - Common memory data bus HiZ time"] #[inline(always)] pub fn comhiz(&mut self) -> COMHIZ_W { COMHIZ_W { w: self } } #[doc = "Bits 16:23 - Common memory hold time"] #[inline(always)] pub fn comhld(&mut self) -> COMHLD_W { COMHLD_W { w: self } } #[doc = "Bits 8:15 - Common memory wait time"] #[inline(always)] pub fn comwait(&mut self) -> COMWAIT_W { COMWAIT_W { w: self } } #[doc = "Bits 0:7 - Common memory setup time"] #[inline(always)] pub fn comset(&mut self) -> COMSET_W { COMSET_W { w: self } } }
use std::error; fn main() { sample(); result(); } type Result<T> = std::result::Result<T, Box<dyn error::Error>>; fn double(num: &str) -> Result<i32> { let n = num.parse::<i32>()?; Ok(n * 2) } fn sample() { let tuple: Vec<_> = vec![(1, "foo"), (2, "bar"), (3, "baz")]; assert_eq!(tuple[1].0, 2); assert_eq!(tuple[1].1, "bar"); } fn result() { // let tc: Vec<_>; let nums = vec![ ("7", true, Ok(14)), ("tofu", false, Err("hello")), ("12", true, Ok(24)), ]; for num in nums { let res = double(num.0); assert_eq!(res.is_ok(), num.1); } }
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `RXP` reader - Rx-Packet available"] pub type RXP_R = crate::BitReader<RXP_A>; #[doc = "Rx-Packet available\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RXP_A { #[doc = "0: Rx buffer empty"] Empty = 0, #[doc = "1: Rx buffer not empty"] NotEmpty = 1, } impl From<RXP_A> for bool { #[inline(always)] fn from(variant: RXP_A) -> Self { variant as u8 != 0 } } impl RXP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXP_A { match self.bits { false => RXP_A::Empty, true => RXP_A::NotEmpty, } } #[doc = "Rx buffer empty"] #[inline(always)] pub fn is_empty(&self) -> bool { *self == RXP_A::Empty } #[doc = "Rx buffer not empty"] #[inline(always)] pub fn is_not_empty(&self) -> bool { *self == RXP_A::NotEmpty } } #[doc = "Field `TXP` reader - Tx-Packet space available"] pub type TXP_R = crate::BitReader<TXP_A>; #[doc = "Tx-Packet space available\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TXP_A { #[doc = "0: Tx buffer full"] Full = 0, #[doc = "1: Tx buffer not full"] NotFull = 1, } impl From<TXP_A> for bool { #[inline(always)] fn from(variant: TXP_A) -> Self { variant as u8 != 0 } } impl TXP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXP_A { match self.bits { false => TXP_A::Full, true => TXP_A::NotFull, } } #[doc = "Tx buffer full"] #[inline(always)] pub fn is_full(&self) -> bool { *self == TXP_A::Full } #[doc = "Tx buffer not full"] #[inline(always)] pub fn is_not_full(&self) -> bool { *self == TXP_A::NotFull } } #[doc = "Field `DXP` reader - Duplex Packet"] pub type DXP_R = crate::BitReader<DXP_A>; #[doc = "Duplex Packet\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DXP_A { #[doc = "0: Duplex packet unavailable: no space for transmission and/or no data received"] Unavailable = 0, #[doc = "1: Duplex packet available: space for transmission and data received"] Available = 1, } impl From<DXP_A> for bool { #[inline(always)] fn from(variant: DXP_A) -> Self { variant as u8 != 0 } } impl DXP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DXP_A { match self.bits { false => DXP_A::Unavailable, true => DXP_A::Available, } } #[doc = "Duplex packet unavailable: no space for transmission and/or no data received"] #[inline(always)] pub fn is_unavailable(&self) -> bool { *self == DXP_A::Unavailable } #[doc = "Duplex packet available: space for transmission and data received"] #[inline(always)] pub fn is_available(&self) -> bool { *self == DXP_A::Available } } #[doc = "Field `EOT` reader - End Of Transfer"] pub type EOT_R = crate::BitReader<EOT_A>; #[doc = "End Of Transfer\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EOT_A { #[doc = "0: Transfer ongoing or not started"] NotCompleted = 0, #[doc = "1: Transfer complete"] Completed = 1, } impl From<EOT_A> for bool { #[inline(always)] fn from(variant: EOT_A) -> Self { variant as u8 != 0 } } impl EOT_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EOT_A { match self.bits { false => EOT_A::NotCompleted, true => EOT_A::Completed, } } #[doc = "Transfer ongoing or not started"] #[inline(always)] pub fn is_not_completed(&self) -> bool { *self == EOT_A::NotCompleted } #[doc = "Transfer complete"] #[inline(always)] pub fn is_completed(&self) -> bool { *self == EOT_A::Completed } } #[doc = "Field `TXTF` reader - Transmission Transfer Filled"] pub type TXTF_R = crate::BitReader<TXTF_A>; #[doc = "Transmission Transfer Filled\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TXTF_A { #[doc = "0: Transmission buffer incomplete"] NotCompleted = 0, #[doc = "1: Transmission buffer filled with at least one transfer"] Completed = 1, } impl From<TXTF_A> for bool { #[inline(always)] fn from(variant: TXTF_A) -> Self { variant as u8 != 0 } } impl TXTF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXTF_A { match self.bits { false => TXTF_A::NotCompleted, true => TXTF_A::Completed, } } #[doc = "Transmission buffer incomplete"] #[inline(always)] pub fn is_not_completed(&self) -> bool { *self == TXTF_A::NotCompleted } #[doc = "Transmission buffer filled with at least one transfer"] #[inline(always)] pub fn is_completed(&self) -> bool { *self == TXTF_A::Completed } } #[doc = "Field `UDR` reader - Underrun at slave transmission mode"] pub type UDR_R = crate::BitReader<UDR_A>; #[doc = "Underrun at slave transmission mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum UDR_A { #[doc = "0: No underrun occurred"] NoUnderrun = 0, #[doc = "1: Underrun occurred"] Underrun = 1, } impl From<UDR_A> for bool { #[inline(always)] fn from(variant: UDR_A) -> Self { variant as u8 != 0 } } impl UDR_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UDR_A { match self.bits { false => UDR_A::NoUnderrun, true => UDR_A::Underrun, } } #[doc = "No underrun occurred"] #[inline(always)] pub fn is_no_underrun(&self) -> bool { *self == UDR_A::NoUnderrun } #[doc = "Underrun occurred"] #[inline(always)] pub fn is_underrun(&self) -> bool { *self == UDR_A::Underrun } } #[doc = "Field `OVR` reader - Overrun"] pub type OVR_R = crate::BitReader<OVR_A>; #[doc = "Overrun\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OVR_A { #[doc = "0: No overrun occurred"] NoOverrun = 0, #[doc = "1: Overrun occurred"] Overrun = 1, } impl From<OVR_A> for bool { #[inline(always)] fn from(variant: OVR_A) -> Self { variant as u8 != 0 } } impl OVR_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OVR_A { match self.bits { false => OVR_A::NoOverrun, true => OVR_A::Overrun, } } #[doc = "No overrun occurred"] #[inline(always)] pub fn is_no_overrun(&self) -> bool { *self == OVR_A::NoOverrun } #[doc = "Overrun occurred"] #[inline(always)] pub fn is_overrun(&self) -> bool { *self == OVR_A::Overrun } } #[doc = "Field `CRCE` reader - CRC Error"] pub type CRCE_R = crate::BitReader<CRCE_A>; #[doc = "CRC Error\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CRCE_A { #[doc = "0: No CRC error detected"] NoError = 0, #[doc = "1: CRC error detected"] Error = 1, } impl From<CRCE_A> for bool { #[inline(always)] fn from(variant: CRCE_A) -> Self { variant as u8 != 0 } } impl CRCE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CRCE_A { match self.bits { false => CRCE_A::NoError, true => CRCE_A::Error, } } #[doc = "No CRC error detected"] #[inline(always)] pub fn is_no_error(&self) -> bool { *self == CRCE_A::NoError } #[doc = "CRC error detected"] #[inline(always)] pub fn is_error(&self) -> bool { *self == CRCE_A::Error } } #[doc = "Field `TIFRE` reader - TI frame format error"] pub type TIFRE_R = crate::BitReader<TIFRE_A>; #[doc = "TI frame format error\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIFRE_A { #[doc = "0: TI frame format error detected"] NoError = 0, #[doc = "1: TI frame format error detected"] Error = 1, } impl From<TIFRE_A> for bool { #[inline(always)] fn from(variant: TIFRE_A) -> Self { variant as u8 != 0 } } impl TIFRE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIFRE_A { match self.bits { false => TIFRE_A::NoError, true => TIFRE_A::Error, } } #[doc = "TI frame format error detected"] #[inline(always)] pub fn is_no_error(&self) -> bool { *self == TIFRE_A::NoError } #[doc = "TI frame format error detected"] #[inline(always)] pub fn is_error(&self) -> bool { *self == TIFRE_A::Error } } #[doc = "Field `MODF` reader - Mode Fault"] pub type MODF_R = crate::BitReader<MODF_A>; #[doc = "Mode Fault\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MODF_A { #[doc = "0: No mode fault detected"] NoFault = 0, #[doc = "1: Mode fault detected"] Fault = 1, } impl From<MODF_A> for bool { #[inline(always)] fn from(variant: MODF_A) -> Self { variant as u8 != 0 } } impl MODF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MODF_A { match self.bits { false => MODF_A::NoFault, true => MODF_A::Fault, } } #[doc = "No mode fault detected"] #[inline(always)] pub fn is_no_fault(&self) -> bool { *self == MODF_A::NoFault } #[doc = "Mode fault detected"] #[inline(always)] pub fn is_fault(&self) -> bool { *self == MODF_A::Fault } } #[doc = "Field `TSERF` reader - Additional number of SPI data to be transacted was reload"] pub type TSERF_R = crate::BitReader<TSERF_A>; #[doc = "Additional number of SPI data to be transacted was reload\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TSERF_A { #[doc = "0: Additional number of SPI data to be transacted not yet loaded"] NotLoaded = 0, #[doc = "1: Additional number of SPI data to be transacted was reloaded"] Loaded = 1, } impl From<TSERF_A> for bool { #[inline(always)] fn from(variant: TSERF_A) -> Self { variant as u8 != 0 } } impl TSERF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TSERF_A { match self.bits { false => TSERF_A::NotLoaded, true => TSERF_A::Loaded, } } #[doc = "Additional number of SPI data to be transacted not yet loaded"] #[inline(always)] pub fn is_not_loaded(&self) -> bool { *self == TSERF_A::NotLoaded } #[doc = "Additional number of SPI data to be transacted was reloaded"] #[inline(always)] pub fn is_loaded(&self) -> bool { *self == TSERF_A::Loaded } } #[doc = "Field `SUSP` reader - SUSPend"] pub type SUSP_R = crate::BitReader<SUSP_A>; #[doc = "SUSPend\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SUSP_A { #[doc = "0: Master not suspended"] NotSuspended = 0, #[doc = "1: Master suspended"] Suspended = 1, } impl From<SUSP_A> for bool { #[inline(always)] fn from(variant: SUSP_A) -> Self { variant as u8 != 0 } } impl SUSP_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SUSP_A { match self.bits { false => SUSP_A::NotSuspended, true => SUSP_A::Suspended, } } #[doc = "Master not suspended"] #[inline(always)] pub fn is_not_suspended(&self) -> bool { *self == SUSP_A::NotSuspended } #[doc = "Master suspended"] #[inline(always)] pub fn is_suspended(&self) -> bool { *self == SUSP_A::Suspended } } #[doc = "Field `TXC` reader - TxFIFO transmission complete"] pub type TXC_R = crate::BitReader<TXC_A>; #[doc = "TxFIFO transmission complete\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TXC_A { #[doc = "0: Transmission ongoing"] Ongoing = 0, #[doc = "1: Transmission completed"] Completed = 1, } impl From<TXC_A> for bool { #[inline(always)] fn from(variant: TXC_A) -> Self { variant as u8 != 0 } } impl TXC_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXC_A { match self.bits { false => TXC_A::Ongoing, true => TXC_A::Completed, } } #[doc = "Transmission ongoing"] #[inline(always)] pub fn is_ongoing(&self) -> bool { *self == TXC_A::Ongoing } #[doc = "Transmission completed"] #[inline(always)] pub fn is_completed(&self) -> bool { *self == TXC_A::Completed } } #[doc = "Field `RXPLVL` reader - RxFIFO Packing LeVeL"] pub type RXPLVL_R = crate::FieldReader<RXPLVL_A>; #[doc = "RxFIFO Packing LeVeL\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum RXPLVL_A { #[doc = "0: Zero frames beyond packing ratio available"] ZeroFrames = 0, #[doc = "1: One frame beyond packing ratio available"] OneFrame = 1, #[doc = "2: Two frame beyond packing ratio available"] TwoFrames = 2, #[doc = "3: Three frame beyond packing ratio available"] ThreeFrames = 3, } impl From<RXPLVL_A> for u8 { #[inline(always)] fn from(variant: RXPLVL_A) -> Self { variant as _ } } impl crate::FieldSpec for RXPLVL_A { type Ux = u8; } impl RXPLVL_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXPLVL_A { match self.bits { 0 => RXPLVL_A::ZeroFrames, 1 => RXPLVL_A::OneFrame, 2 => RXPLVL_A::TwoFrames, 3 => RXPLVL_A::ThreeFrames, _ => unreachable!(), } } #[doc = "Zero frames beyond packing ratio available"] #[inline(always)] pub fn is_zero_frames(&self) -> bool { *self == RXPLVL_A::ZeroFrames } #[doc = "One frame beyond packing ratio available"] #[inline(always)] pub fn is_one_frame(&self) -> bool { *self == RXPLVL_A::OneFrame } #[doc = "Two frame beyond packing ratio available"] #[inline(always)] pub fn is_two_frames(&self) -> bool { *self == RXPLVL_A::TwoFrames } #[doc = "Three frame beyond packing ratio available"] #[inline(always)] pub fn is_three_frames(&self) -> bool { *self == RXPLVL_A::ThreeFrames } } #[doc = "Field `RXWNE` reader - RxFIFO Word Not Empty"] pub type RXWNE_R = crate::BitReader<RXWNE_A>; #[doc = "RxFIFO Word Not Empty\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RXWNE_A { #[doc = "0: Less than 32-bit data frame received"] LessThan32 = 0, #[doc = "1: At least 32-bit data frame received"] AtLeast32 = 1, } impl From<RXWNE_A> for bool { #[inline(always)] fn from(variant: RXWNE_A) -> Self { variant as u8 != 0 } } impl RXWNE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXWNE_A { match self.bits { false => RXWNE_A::LessThan32, true => RXWNE_A::AtLeast32, } } #[doc = "Less than 32-bit data frame received"] #[inline(always)] pub fn is_less_than32(&self) -> bool { *self == RXWNE_A::LessThan32 } #[doc = "At least 32-bit data frame received"] #[inline(always)] pub fn is_at_least32(&self) -> bool { *self == RXWNE_A::AtLeast32 } } #[doc = "Field `CTSIZE` reader - Number of data frames remaining in current TSIZE session"] pub type CTSIZE_R = crate::FieldReader<u16>; impl R { #[doc = "Bit 0 - Rx-Packet available"] #[inline(always)] pub fn rxp(&self) -> RXP_R { RXP_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Tx-Packet space available"] #[inline(always)] pub fn txp(&self) -> TXP_R { TXP_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Duplex Packet"] #[inline(always)] pub fn dxp(&self) -> DXP_R { DXP_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - End Of Transfer"] #[inline(always)] pub fn eot(&self) -> EOT_R { EOT_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Transmission Transfer Filled"] #[inline(always)] pub fn txtf(&self) -> TXTF_R { TXTF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Underrun at slave transmission mode"] #[inline(always)] pub fn udr(&self) -> UDR_R { UDR_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Overrun"] #[inline(always)] pub fn ovr(&self) -> OVR_R { OVR_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - CRC Error"] #[inline(always)] pub fn crce(&self) -> CRCE_R { CRCE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - TI frame format error"] #[inline(always)] pub fn tifre(&self) -> TIFRE_R { TIFRE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Mode Fault"] #[inline(always)] pub fn modf(&self) -> MODF_R { MODF_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Additional number of SPI data to be transacted was reload"] #[inline(always)] pub fn tserf(&self) -> TSERF_R { TSERF_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - SUSPend"] #[inline(always)] pub fn susp(&self) -> SUSP_R { SUSP_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - TxFIFO transmission complete"] #[inline(always)] pub fn txc(&self) -> TXC_R { TXC_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bits 13:14 - RxFIFO Packing LeVeL"] #[inline(always)] pub fn rxplvl(&self) -> RXPLVL_R { RXPLVL_R::new(((self.bits >> 13) & 3) as u8) } #[doc = "Bit 15 - RxFIFO Word Not Empty"] #[inline(always)] pub fn rxwne(&self) -> RXWNE_R { RXWNE_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bits 16:31 - Number of data frames remaining in current TSIZE session"] #[inline(always)] pub fn ctsize(&self) -> CTSIZE_R { CTSIZE_R::new(((self.bits >> 16) & 0xffff) as u16) } } #[doc = "Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SR_SPEC; impl crate::RegisterSpec for SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`sr::R`](R) reader structure"] impl crate::Readable for SR_SPEC {} #[doc = "`reset()` method sets SR to value 0x1002"] impl crate::Resettable for SR_SPEC { const RESET_VALUE: Self::Ux = 0x1002; }
use crate::engine::board; use crate::engine::enums; pub fn main_heuristic(board: &board::Board, player: enums::Player) -> i16 { if board.state == enums::State::End { let tiles = count_tiles(board, player); if tiles > 0 { return 30000; } else if tiles == 0 { return 0; } else if tiles < 0 { return -30000; } } let count_weight = 1; let location_weight = 3; (count_tiles(board, player) * count_weight) + (evaluate_locations(board, player) * location_weight) } pub fn count_tiles(board: &board::Board, player: enums::Player) -> i16 { let black_count: i16 = board.black_bitboard.count_ones() as i16; let white_count: i16 = board.white_bitboard.count_ones() as i16; if player == enums::Player::White { (white_count - black_count) as i16 } else { (black_count - white_count) as i16 } } // returns an into from -100 to 100 rating the overall position of the board. pub fn evaluate_locations(board: &board::Board, player: enums::Player) -> i16{ // TODO add ability to consider c squares as positive if they are next to an owned corner square. let player_pieces; let opponent_pieces; if player == enums::Player::White { player_pieces = board.white_bitboard; opponent_pieces = board.black_bitboard; } else { player_pieces = board.black_bitboard; opponent_pieces = board.white_bitboard; } let corner_bitmask = 0b1000000100000000000000000000000000000000000000000000000010000001; let c_square_bitmask = 0b0100001010000001000000000000000000000000000000001000000101000010; let x_square_bitmask = 0b0000000001000010000000000000000000000000000000000100001000000000; let center_square_bitmask = 0b0000000000000000000000000001100000011000000000000000000000000000; let edge_square_bitmask = 0b0011110000000000100000011000000110000001100000010000000000111100; let corner_weight = 2; let c_weight: i64 = -1; let x_weight: i64 = -2; let center_weight = 0; let edge_weight = 1; let corner_value = corner_weight * (corner_bitmask & player_pieces).count_ones() as i64; let c_value = c_weight * (c_square_bitmask & player_pieces).count_ones() as i64; let x_value = x_weight * (x_square_bitmask & player_pieces).count_ones() as i64; let center_value = center_weight * (center_square_bitmask & player_pieces).count_ones() as i64; let edge_value = edge_weight * (edge_square_bitmask & player_pieces).count_ones() as i64; let o_corner_value = -((corner_weight * (corner_bitmask & opponent_pieces).count_ones() as i64) as i64); let o_c_value = -(c_weight * (c_square_bitmask & opponent_pieces).count_ones() as i64); let o_x_value = -(x_weight * (x_square_bitmask & opponent_pieces).count_ones() as i64); let o_center_value = -((center_weight * (center_square_bitmask & opponent_pieces).count_ones() as i64) as i64); let o_edge_value = -((edge_weight * (edge_square_bitmask & opponent_pieces).count_ones() as i64) as i64); (corner_value + c_value + x_value + center_value + edge_value + o_c_value + o_center_value + o_corner_value + o_edge_value + o_x_value) as i16 } // check for tempo in frontiers // check for parity // check for stability // // #[test] // fn test_heuristic() { // let board = board::Board::new(); // let player = enums::Player::Black; // // println!("{}", board); // evaluate_locations(&board, player); // }
#![allow(dead_code)] // 标准库中常见的 trait // Display Debug pub fn learn_display_debug() { use std::fmt::{Display, Formatter, Result}; #[derive(Debug)] struct T { field1: i32, field2: i32, } impl Display for T { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{{ field1: {}, field2: {} }}", self.field1, self.field2) } } let var = T { field1: 1, field2: 2, }; println!("{}", var); println!("{:?}", var); println!("{:#?}", var); } // 只有实现了 Display trait 的类型,才能用 {} 格式控制打印出来 // 只有实现了 Debug trait 的类型,才能用 {:?} {:#?} 格式控制打印出来 // {} {:?} {:#?} 的区别如下 // Display 假定了这个类型可以用 utf-8 格式的字符串表示,它是准备给最终用户看的 // 并不是所有类型都应该或者能够实现这个 trait。这个 trait 的 fmt 应该如何格式化 // 字符串,完全取决于程序员自己,编译器不提供自动 derive 的功能 // 标准库中还有一个常用 trait 叫作 std::string::ToString,对于所有实现了 // Display trait 的类型,都自动实现了这个 ToString trait // 它包含了一个方法 to_string(&self) -> String 任何一个实现了 Display // trait 的类型,我们都可以对它调用 to_string() 方法格式化出一个字符串 // Debug 则是主要为了调试使用,建议所有的作为 API 的"公开"类型都应该实现 // 这个 trait,以方便调试。它打印出来的字符串不是以"美观易读"为标准 // 编译器提供了自动 derive 的功能 // PartialOrd / Ord / PartialEq / Eq // 因为 NaN 的存在,浮点数是不具备"total order(全序关系)"的 // 对于集合 X 中的元素 a, b, c, // * 如果 a < b 则一定有 !(a > b);反之, 若 a > b,则一定有 !(a < b),称为反对称性 // * 如果 a < b 且 b < c 则 a < c,称为传递性 // * 对于 X 中的所有元素,都存在 a < b 或 a > b 或者 a == b, 三者必居其一,称为完全性 // 偏序: 如果集合 X 中的元素只具备上述前两条特征 // 全序: 同时具备以上所有特征 pub fn learn_float() { let nan = std::f32::NAN; let x = 1.0f32; println!("{}", nan < x); // false println!("{}", nan > x); // false println!("{}", nan == x); // false } // Rust 设计了两个 trait 来描述这样的状态: // 一个是 std::cmp::PartialOrd,表示"偏序" // 一个是 std::cmp::Ord,表示"全序" // PartialEq 和 Eq 两个 trait 也就可以理解了 // 它们的作用是比较相等关系,与排序关系非常类似 // 偏等 全等 // Sized // 这个 trait 定义在 std::marker 模块中,它没有任何的成员方法 // 它有#[lang = "sized"] 属性,说明它与普通 trait 不同,编译器对它有特殊的处理 // 用户也不能针对自己的类型 impl 这个 trait // 一个类型是否满足 Sized 约束是完全由编译器推导的,用户无权指定 // 我们知道,在 C/C++ 这一类的语言中,大部分变量、参数、返回值都应该 // 是编译阶段固定大小的。在 Rust 中,但凡编译阶段能确定大小的类型, // 都满足 Sized 约束。那还有什么类型是不满足 Sized 约束的呢? // 比如 C 语言里的不定长数组(Variable-length Array)。 // 不定长数组的长度在编译阶段是未知的,是在执行阶段才确定下来的 // Rust 里面也有类似的类型[T]。 在 Rust 中 VLA 类型已经通过了 RFC 设计, // 只是暂时还没有实现而已。不定长类型在使用的时候有一些限制, // 比如不能用它作为函数的返回类型,而必须将这个类型藏到指针背后才可以 // 但它作为一个类型,依然是有意义的,我们可以为它添加成员方法, // 用它实例化泛型参数,等等 // Rust 中对于动态大小类型专门有一个名词 Dynamic Sized Type。 // 我们后面将会看到的[T], str 以及 dyn Trait 都是 DST // Default // Rust 里面并没有 C++ 里面的"构造函数"的概念 // 大家可以看到,它只提供了类似 C 语言的各种复合类型各自的初始化语法 // 主要原因在于,相比普通函数,构造函数本身并没有提供什么额外的抽象能力 // 所以 Rust 里面推荐使用普通的静态函数作为类型的"构造器" // 对于那种无参数、无错误处理的简单情况,标准库中提供了 Default trait // 来做这个统一抽象 // 它只包含一个"静态函数" default() 返回 Self 类型 // 标准库中很多类型都实现了这个 trait,它相当于提供了一个类型的默认值 // 在 Rust 中,单词 new 并不是一个关键字。所以我们可以看到,很多类型中都使用了 // new 作为函数名,用于命名那种最常用的创建新对象的情况。因为这些 new 函数差别甚大, // 所以并没有一个 trait 来对这些 new 函数做一个统一抽象 // 总结 // 除了上面介绍的之外,trait 还有许多用处: // 1 trait 可以携带泛型参数 // 2 trait 可以用在泛型参数的约束中 // 3 trait 可以为一组类型 impl,也可以单独为某一个具体类型 impl,而且它们可以同时存在 // 4 trait 可以为某个 trait impl,而不是为某个具体类型 impl // 5 trait 可以包含关联类型,而且还可以包含类型构造器,实现高阶类型的某些功能 // 6 trait 可以实现泛型代码的静态分派,也可以通过 trait object 实现动态分派 // 0 trait 可以不包含任何方法,用于给类型做标签(marker)以此来描述类型的一些重要特性 // 0 trait 可以包含常量 // trait 这个概念在 Rust 语言中扮演了非常重要的角色,承担了各种各样的功能,在写代码的时候会经常用到
pub mod watch_face; pub use watch_face::{WatchFace, WatchFaceResources}; // some trait, ScreenExt: Drawable // on_focus // off_focus // // update(Self::Resources) // // (use eg::ContainsPoint trait) // handle_event(Event) -> Forward/SomeAction (like switch to ScreenFoo) // touch/gesture // button press // enum Screen { WatchFace(..), ... }
use common::*; use gl; use gl::types::*; use glw::gl_context::GLContext; use glw::shader::Shader; use glw::texture::BufferTexture; use glw::texture::TextureUnit; use id_allocator::IdAllocator; use nalgebra::{Pnt3, Vec3}; use state::EntityId; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[deriving(Show, Copy, Clone, PartialEq, Eq, Hash)] pub enum TerrainType { Grass, Dirt, Stone, } pub struct TerrainPiece { pub vertices: [Pnt3<GLfloat>, ..3], pub normal: Vec3<GLfloat>, pub typ: GLuint, pub id: EntityId, } pub struct TerrainBuffers { id_to_index: HashMap<EntityId, uint>, index_to_id: Vec<EntityId>, empty_array: GLuint, length: uint, // Each position is buffered as 3 separate floats due to image format restrictions. vertex_positions: BufferTexture<GLfloat>, // Each normal component is buffered separately floats due to image format restrictions. normals: BufferTexture<GLfloat>, types: BufferTexture<GLuint>, } impl TerrainBuffers { pub fn new( gl: &GLContext, ) -> TerrainBuffers { TerrainBuffers { id_to_index: HashMap::new(), index_to_id: Vec::new(), empty_array: unsafe { let mut empty_array = 0; gl::GenVertexArrays(1, &mut empty_array); empty_array }, length: 0, // multiply by 3 because there are 3 R32F components vertex_positions: BufferTexture::new(gl, gl::R32F, 3 * MAX_WORLD_SIZE * VERTICES_PER_TRIANGLE), normals: BufferTexture::new(gl, gl::R32F, 3 * MAX_WORLD_SIZE), types: BufferTexture::new(gl, gl::R32UI, MAX_WORLD_SIZE), } } pub fn bind( &self, gl: &mut GLContext, texture_unit_alloc: &mut IdAllocator<TextureUnit>, shader: Rc<RefCell<Shader>>, ) { let bind = |name, id| { let unit = texture_unit_alloc.allocate(); gl::ActiveTexture(unit.gl_id()); gl::BindTexture(gl::TEXTURE_BUFFER, id); shader.borrow_mut().with_uniform_location(gl, name, |loc| { gl::Uniform1i(loc, unit.glsl_id as GLint); }); }; bind("positions", self.vertex_positions.texture.gl_id); if USE_LIGHTING { bind("normals", self.normals.texture.gl_id); } bind("terrain_types", self.types.texture.gl_id); } pub fn push( &mut self, id: EntityId, terrain: &TerrainPiece, ) { self.id_to_index.insert(id, self.index_to_id.len()); self.index_to_id.push(id); self.length += 3; self.vertex_positions.buffer.push([ terrain.vertices[0].x, terrain.vertices[0].y, terrain.vertices[0].z, terrain.vertices[1].x, terrain.vertices[1].y, terrain.vertices[1].z, terrain.vertices[2].x, terrain.vertices[2].y, terrain.vertices[2].z, ]); if USE_LIGHTING { self.normals.buffer.push([terrain.normal.x, terrain.normal.y, terrain.normal.z]); } self.types.buffer.push(&[terrain.typ as GLuint]); } // Note: `id` must be present in the buffers. pub fn swap_remove(&mut self, id: EntityId) { let idx = *self.id_to_index.find(&id).unwrap(); let swapped_id = self.index_to_id[self.index_to_id.len() - 1]; self.index_to_id.swap_remove(idx).unwrap(); self.id_to_index.remove(&id); if id != swapped_id { self.id_to_index.insert(swapped_id, idx); } self.length -= 3; self.vertex_positions.buffer.swap_remove(idx * 3 * VERTICES_PER_TRIANGLE, 3 * VERTICES_PER_TRIANGLE); if USE_LIGHTING { self.normals.buffer.swap_remove(3 * idx, 3); } self.types.buffer.swap_remove(idx, 1); } pub fn draw(&self, _gl: &GLContext) { gl::BindVertexArray(self.empty_array); gl::DrawArrays(gl::TRIANGLES, 0, self.length as GLint); } }
use std::{env, io}; use objdump::Elf; use std::process::exit; use crate::simulator::Simulator; use std::io::{Error, BufReader, BufRead}; use std::fs::File; use crate::cache::{CacheOp, Storage, CacheConfig}; mod memory; mod simulator; mod register; mod instruction; mod action; mod statistic; mod cache; fn lab2_pipeline(args: &[String]) { if args.len() < 1 { eprintln!("unknown filename"); exit(1); } let mut simulator = Simulator::new(); simulator.load_from_elf(args[0].as_str()); if args.len() == 1 { loop { let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(_) => { match &input[..] { "regs\n" => simulator.regs.println(), "s\n" => { simulator.run(); } "mem\n" => { let mut input_text = String::new(); io::stdin() .read_line(&mut input_text) .expect("failed to read from stdin"); let trimmed = input_text.trim(); match u64::from_str_radix(trimmed, 16) { Ok(i) => simulator.memory.println(i, 4), Err(..) => println!("this was not a valid address: {}", trimmed), } } _ => println!("unknown command") } }, Err(_) => { break }, } } } while simulator.run() {} args.iter().for_each(|s| { let res = simulator.elf.symbol_entries.iter() .filter(|x| { x.0.contains(s) }).next(); match res { None => { println!("cannot find {}", s); }, Some((s, start, size)) => { println!("{} 0x{:x} {}", s, start, size); simulator.memory.println(*start, *size as usize); }, } }); simulator.stat.println(); } fn lab3_run(cache: &mut Box<dyn Storage>, filename: &String) -> cache::StorageStats { let file = File::open(filename.as_str()).unwrap(); let reader = BufReader::new(file); for line in reader.lines() { let l = line.unwrap(); let mut iter = l.split_whitespace(); let op = match iter.next().unwrap() { "r" => CacheOp::Read, "w" => CacheOp::Write, _ => { panic!("unknown op") } }; let addr_s = iter.next().unwrap(); let addr: u64 = if addr_s.starts_with("0x") { u64::from_str_radix(addr_s.trim_start_matches("0x"), 16).unwrap() } else { addr_s.parse::<u64>().unwrap() }; cache.access(addr, op); } cache.stats() } fn lab3_cache(args: &[String]) { if args.len() < 1 { eprintln!("unknown filename"); exit(1); } let mut cache = cache::new_3_levels(); let cache::StorageStats { num_access, time, .. } = lab3_run(&mut cache, &args[0]); cache.output_stats(); println!("AMAT: {}", time as f32 / num_access as f32); } fn lab3_cache1(args: &[String]) { if args.len() < 1 { eprintln!("unknown filename"); exit(1); } let line_size: &'static [u64] = &[32, 64, 128, 256, 512, 1024, 2048, 4096]; let cache_size: &'static [u64] = &[32, 128, 512, 2048, 8192, 32768]; let associativity: &'static [u64] = &[1, 2, 4, 8, 16, 32]; for c in cache_size { for l in line_size { let mut cache = cache::new_1_levels(CacheConfig { name: "L1", write_through: false, write_allocate: true, capacity: c * 1024, associativity: 8, line_size: *l, latency: 3, }); let result = lab3_run(&mut cache, &args[0]); print!("{}\t", result.num_miss as f32 / result.num_access as f32) } println!() } println!(); for c in cache_size { for a in associativity { let mut cache = cache::new_1_levels(CacheConfig { name: "L1", write_through: false, write_allocate: true, capacity: c * 1024, associativity: *a, line_size: 512, latency: 3, }); let result = lab3_run(&mut cache, &args[0]); print!("{}\t", result.num_miss as f32 / result.num_access as f32) } println!() } println!(); for b1 in &[true, false] { for b2 in &[true, false] { let mut cache = cache::new_1_levels(CacheConfig { name: "L1", write_through: *b2, write_allocate: *b1, capacity: 2 * 1024 * 1024, associativity: 8, line_size: 512, latency: 3, }); let result = lab3_run(&mut cache, &args[0]); print!("{}\t", result.time) } println!() } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("Usage: {} [pipeline|cache|cache1]", args[0]); exit(1) } match args[1].as_str() { "cache" => lab3_cache(&args[2..]), "cache1" => lab3_cache1(&args[2..]), "pipeline" => lab2_pipeline(&args[2..]), _ => { eprintln!("Usage: {} [pipeline|cache]", args[0]); exit(1); }, } }
use iota_client::{Client}; #[tokio::main] async fn main() { let balance = Balance{ }; balance.balance().await; } struct Balance {} impl Balance { async fn balance(&self) { let iota = Client::builder() .with_node("https://chrysalis-nodes.iota.org") .unwrap() .with_node_sync_disabled() .finish() .await .unwrap(); let address = "iota1qrepert94y80wyx6j07n2zgldfy2509hpugkx3apvdga0uux780xz3xtcyf"; let response = iota.get_address().balance(&address).await.unwrap(); let balance: u64 = response.balance; #[derive(Debug)] struct Information { balance: u64, address: String } let balance_address = Information { balance, address: response.address }; println!("{:?}", balance_address) } }
use std::io; fn main(){ println!("Enter something"); let mut input_string = String::new(); io::stdin().read_line(&mut input_string).expect("Failed to read input"); let integer_input:i32 = input_string.trim().parse().unwrap();//converting string into mentioned datatype println!("You entered {}",integer_input); }
pub fn binary_tree() { println!("Here's a binary tree!") }
use criterion::{black_box, Criterion}; use common::storage_trait::StorageTrait; use common::testutil::get_random_vec_of_byte_vec; use heapstore::storage_manager::StorageManager; use heapstore::testutil::bench_sm_insert; pub fn sm_ins_bench(c: &mut Criterion) { let to_insert = get_random_vec_of_byte_vec(1000, 80, 100); let sm = StorageManager::new_test_sm(); c.bench_function("sm insert 1k", |b| { b.iter(|| bench_sm_insert(&sm, black_box(&to_insert))) }); }
mod regs; pub use self::regs::{ Register, Scale, Disp, RegSize, parse_reg, parse_512bit_reg, parse_256bit_reg, parse_128bit_reg, parse_64bit_reg, parse_32bit_reg, parse_16bit_reg, parse_8bit_reg, parse_mmx_reg, parse_x87_reg, parse_vec_reg, parse_long_ptr_reg, parse_scale, parse_const }; mod mem; pub use self::mem::{ Mem, parse_mem }; mod fault; pub use self::fault::{ Fault }; mod access; pub use self::access::{ Access, parse_z0, parse_i, parse_mi, parse_mr, parse_rm, parse_rr, parse_rrvv, parse_rvm, parse_rvmvv };
use serde::de::{self, Visitor}; use crate::de::{Deserializer, Error}; pub struct MapAccess<'a, 'b> { de: &'a mut Deserializer<'b>, first: bool, } impl<'a, 'b> MapAccess<'a, 'b> { pub(crate) fn new(de: &'a mut Deserializer<'b>) -> Self { MapAccess { de, first: true } } } impl<'a, 'de> de::MapAccess<'de> for MapAccess<'a, 'de> { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> where K: de::DeserializeSeed<'de>, { let peek = match self .de .parse_whitespace() .ok_or(Error::EofWhileParsingObject)? { b'}' => return Ok(None), b',' if !self.first => { self.de.eat_char(); self.de.parse_whitespace() } b => { if self.first { self.first = false; Some(b) } else { return Err(Error::ExpectedObjectCommaOrEnd); } } }; match peek.ok_or(Error::EofWhileParsingValue)? { b'"' => seed.deserialize(MapKey { de: &mut *self.de }).map(Some), b'}' => Err(Error::TrailingComma), _ => Err(Error::KeyMustBeAString), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> where V: de::DeserializeSeed<'de>, { self.de.parse_object_colon()?; seed.deserialize(&mut *self.de) } } struct MapKey<'a, 'b> { de: &'a mut Deserializer<'b>, } impl<'de, 'a> de::Deserializer<'de> for MapKey<'a, 'de> { type Error = Error; fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_bool<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_i8<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_i16<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_i32<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_i64<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_u8<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_u16<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_u32<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_u64<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_f32<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_f64<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_char<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.de.deserialize_str(visitor) } fn deserialize_string<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_option<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_unit<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_unit_struct<V>( self, _name: &'static str, _visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_newtype_struct<V>( self, _name: &'static str, _visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_seq<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_tuple_struct<V>( self, _name: &'static str, _len: usize, _visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], _visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], _visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { unreachable!() } }
use bevy::{ecs::entity::EntityMap, prelude::*, utils::HashSet}; use thiserror::Error; use crate::{ de::PrefabDeserializer, loader::PrefabLoader, registry::{ ComponentDescriptorRegistry, ComponentEntityMapperRegistry, PrefabDescriptorRegistry, }, Prefab, PrefabConstruct, PrefabError, PrefabErrorTag, PrefabNotInstantiatedTag, PrefabTransformOverride, PrefabTypeUuid, }; /////////////////////////////////////////////////////////////////////////////// #[derive(Error, Debug)] pub enum PrefabSpawnError { #[error("prefab not found")] MissingPrefab(Handle<Prefab>), } /////////////////////////////////////////////////////////////////////////////// struct Instantiate(Entity, Handle<Prefab>); fn enqueue_prefab_not_instantiated(world: &mut World, queue: &mut Vec<Instantiate>) { for (entity, handle, _) in world .query::<(Entity, &Handle<Prefab>, &PrefabNotInstantiatedTag)>() .iter(world) { queue.push(Instantiate(entity, handle.clone_weak())); } } fn prefab_spawner( world: &mut World, prefabs: &Assets<Prefab>, prefabs_queue: &mut Vec<Instantiate>, component_entity_mapper: &ComponentEntityMapperRegistry, component_registry: &ComponentDescriptorRegistry, ) { let mut blacklist = HashSet::default(); loop { while let Some(Instantiate(root_entity, source_prefab)) = prefabs_queue.pop() { // TODO: we can not know when a nested prefab finished loading or not, that causes a lot of issues // TODO: remove PrefabNotInstantiatedTag and add PrefabMissing let prefab = match prefabs.get(&source_prefab) { Some(prefab) => prefab, None => { blacklist.insert(root_entity); continue; } }; // validate prefab type with the expected type, sadly this can't be done during // de-serialization because the prefab might not be available at that time, // so as a consequence the exact source of error will be hard to determine let mut root = world.entity_mut(root_entity); if let Some(PrefabTypeUuid(uuid)) = root.get() { let source = prefab.data.0.type_uuid(); if source != *uuid { // fail without loading prefab root.remove::<PrefabNotInstantiatedTag>(); root.insert(PrefabErrorTag(PrefabError::WrongExpectedSourcePrefab)); error!( "prefab expected type `{}` but got source of type `{}`", uuid, source ); continue; } } let mut prefab_to_instance = EntityMap::default(); // copy prefab entities over for archetype in prefab.world.archetypes().iter() { for prefab_entity in archetype.entities() { if prefab.root_entity == *prefab_entity { // root entity prefab_to_instance.insert(*prefab_entity, root_entity); // TODO: cache copy functions by archetype, because the prefab won't change unless reloaded // or during selected editor operations the archetypes order will predictable for component_id in archetype.components() { let component_info = prefab.world.components().get_info(component_id).unwrap(); if let Some(descriptor) = component_registry.find_by_type(component_info.type_id().unwrap()) { // copy prefab from his world over the current active world // but don't override any component, a bit slower but needed since the (descriptor.copy_without_overriding)( &prefab.world, world, *prefab_entity, root_entity, ); } else { // hard error, must be fixed by user panic!( "prefab component `{}` not registered", component_info.name() ); } } } else { // default entity let instance_entity = *prefab_to_instance .entry(*prefab_entity) .or_insert_with(|| world.spawn().id()); for component_id in archetype.components() { let component_info = prefab.world.components().get_info(component_id).unwrap(); if let Some(descriptor) = component_registry.find_by_type(component_info.type_id().unwrap()) { // copy prefab from his world over the current active world (descriptor.copy)( &prefab.world, world, *prefab_entity, instance_entity, ); } else { // hard error, must be fixed by user panic!( "prefab component `{}` not registered", component_info.name() ); } } } } } for instance_entity in prefab_to_instance.values() { let mut instance = world.entity_mut(instance_entity); // map entities components to instance space component_entity_mapper .map_entity_components(&mut instance, &prefab_to_instance) .unwrap(); // parent all root prefab entities under the instance root if instance.get::<Parent>().is_none() { instance.insert(Parent(root_entity)); } } let mut root = world.entity_mut(root_entity); // clear not instantiated tag root.remove::<PrefabNotInstantiatedTag>(); // override prefab transformations with instance's transform let mut transform = prefab.transform.clone(); if let Some(transform_overrides) = root.remove::<PrefabTransformOverride>() { if let Some(translation) = transform_overrides.translation { transform.translation = translation; } if let Some(rotation) = transform_overrides.rotation { transform.rotation = rotation; } if let Some(scale) = transform_overrides.scale { transform.scale = scale; } } // TODO: `Children` added where because of a bug on bevy's `Commands`, once is fixed he should be removed root.insert_bundle((GlobalTransform::default(), transform, Children::default())); // apply overrides and run construct function if let Some(prefab_construct) = root.get::<PrefabConstruct>() { // prefab doesn't require a valid source (fully procedural) (prefab_construct.0)(world, root_entity, &prefab_to_instance).unwrap(); } else { prefab .data .0 .apply_overrides_and_construct_instance(world, root_entity, &prefab_to_instance) .unwrap(); } } enqueue_prefab_not_instantiated(world, prefabs_queue); // TODO: very hacky and expensive, we don't know when a prefab was finished loading prefabs_queue.retain(|Instantiate(x, _)| !blacklist.contains(x)); // Nothing left to spawn if prefabs_queue.is_empty() { break; } } } pub(crate) fn prefab_commit_startup_system(world: &mut World) { // commits to registered prefab and components on startup let prefab_registry = world.remove_resource::<PrefabDescriptorRegistry>().unwrap(); let component_registry = world .remove_resource::<ComponentDescriptorRegistry>() .unwrap(); let component_entity_mapper = world .remove_resource::<ComponentEntityMapperRegistry>() .unwrap(); let prefab_deserializer = PrefabDeserializer::new(component_entity_mapper, component_registry, prefab_registry); world.insert_resource(prefab_deserializer); // create prefab loader let loader = PrefabLoader::from_world(world); world .get_resource::<AssetServer>() .unwrap() .add_loader(loader); } pub fn prefab_managing_system(world: &mut World) { let mut prefabs_queue = vec![]; // Avoid extra working or using resource scope every frame if none prefabs enqueue_prefab_not_instantiated(world, &mut prefabs_queue); if prefabs_queue.is_empty() { return; } let prefab_registry = world.get_resource::<PrefabDeserializer>().unwrap().clone(); world.resource_scope(|world, prefabs: Mut<Assets<Prefab>>| { prefab_spawner( world, &*prefabs, &mut prefabs_queue, &prefab_registry.inner.component_entity_mapper, &prefab_registry.inner.component_registry, ) }); }
#[cfg(feature = "parsec")] use parsec::{self, Entity}; use std::iter::repeat; use std::mem; use super::{TrieLayer, Trie, TrieIter}; use super::shift::*; #[derive(Clone)] pub struct BitSet { layer2: u64, layer1: Vec<u64>, layer0: Vec<u64>, } impl BitSet { pub fn new() -> BitSet { BitSet { layer2: 0, layer1: Vec::new(), layer0: Vec::new(), } } #[inline] fn valid_range(max: u32) { if (1 << 19 - 1) < max { panic!("Expected index to be less then {}, found {}", 1 << 19 - 1, max); } } // create a new BitSet with 0..max set pub fn all_set(max: u32) -> BitSet { let mut new = Self::new(); // this is slow, but works for i in 0..max { new.add(i); } new } pub fn reserve(max: u32) -> BitSet { let mut value = BitSet::new(); value.extend(max); value } fn extend(&mut self, bit: u32) { Self::valid_range(bit); let p0 = bit.offset::<Shift1>(); let p1 = bit.offset::<Shift2>(); if self.layer1.len() <= p1 { let count = p1 - self.layer1.len() + 1; self.layer1.extend(repeat(0).take(count)); } if self.layer0.len() <= p0 { let count = p0 - self.layer0.len() + 1; self.layer0.extend(repeat(0).take(count)); } } #[inline] pub fn add(&mut self, bit: u32) -> bool { let p0 = bit.offset::<Shift1>(); let p1 = bit.offset::<Shift2>(); if p0 >= self.layer0.len() { self.extend(bit); } self.layer2 |= 1 << bit.row::<Shift2>(); self.layer1[p1] |= 1 << bit.row::<Shift1>(); let mask = 1 << bit.row::<Shift0>(); let was_set = (self.layer0[p0] & mask) != 0; self.layer0[p0] |= mask; was_set } #[inline] pub fn remove(&mut self, bit: u32) -> bool { let p0 = bit.offset::<Shift1>(); if p0 > self.layer0.len() { return false; } let mask = 1 << bit.row::<Shift0>(); let was_set = (self.layer0[p0] & mask) != 0; self.layer0[p0] &= !mask; if self.layer0[p0] == 0 { let p1 = bit.offset::<Shift2>(); self.layer1[p1] &= !(1 << bit.row::<Shift1>()); if self.layer1[p1] == 0 { self.layer2 &= !(1 << bit.row::<Shift2>()); } } was_set } #[inline] pub fn contains(&self, bit: u32) -> bool { let p0 = bit.offset::<Shift1>(); if p0 >= self.layer0.len() { return false; } let mask = 1 << bit.row::<Shift0>(); (self.layer0[p0] & mask) != 0 } } impl<'a> IntoIterator for &'a BitSet { type Item = (u32, ()); type IntoIter = TrieIter<Self>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a> Trie for &'a BitSet { type L2 = SetLayer2<'a>; type L1 = SetLayer1<'a>; type L0 = SetLayer0; type Value = (); type Row = u32; fn top(self) -> SetLayer2<'a> { SetLayer2 { layer2: self.layer2, layer1: &self.layer1[..], layer0: &self.layer0[..], } } } pub struct SetLayer2<'a> { layer2: u64, layer1: &'a [u64], layer0: &'a [u64], } impl<'a> TrieLayer for SetLayer2<'a> { type Value = SetLayer1<'a>; fn mask(&self) -> u64 { self.layer2 } unsafe fn get(&self, idx: usize) -> SetLayer1<'a> { let l = idx * 64; SetLayer1 { layer1: self.layer1[idx], layer0: &self.layer0[l..], } } } pub struct SetLayer1<'a> { layer1: u64, layer0: &'a [u64], } impl<'a> TrieLayer for SetLayer1<'a> { type Value = SetLayer0; fn mask(&self) -> u64 { self.layer1 } unsafe fn get(&self, idx: usize) -> SetLayer0 { SetLayer0 { layer0: self.layer0[idx] } } } pub struct SetLayer0 { layer0: u64, } impl TrieLayer for SetLayer0 { type Value = (); fn mask(&self) -> u64 { self.layer0 } unsafe fn get(&self, _: usize) -> () { () } } pub struct VecMap<T> { set: BitSet, values: Vec<T>, } impl<T> VecMap<T> { pub fn new() -> VecMap<T> { VecMap { set: BitSet::new(), values: Vec::new(), } } fn extend(&mut self, bit: u32) { unsafe { self.values.reserve(bit as usize + 1); self.values.set_len(bit as usize + 1); } } pub fn insert(&mut self, bit: u32, mut value: T) -> Option<T> { use std::{ptr, mem}; if self.set.contains(bit) { mem::swap(&mut self.values[bit as usize], &mut value); Some(value) } else { self.set.add(bit); if self.values.len() <= bit as usize { self.extend(bit); } unsafe { ptr::write(&mut self.values[bit as usize], value); } None } } #[inline] pub fn get(&self, bit: u32) -> Option<&T> { if self.set.contains(bit) { unsafe { Some(self.values.get_unchecked(bit as usize)) } } else { None } } #[inline] pub fn get_mut(&mut self, bit: u32) -> Option<&mut T> { if self.set.contains(bit) { unsafe { Some(self.values.get_unchecked_mut(bit as usize)) } } else { None } } pub fn delete(&mut self, bit: u32) -> Option<T> { use std::ptr; if self.set.remove(bit) { Some(unsafe { ptr::read(&self.values[bit as usize]) }) } else { None } } } impl<T> Drop for VecMap<T> { fn drop(&mut self) { use std::mem; for (i, v) in self.values.drain(..).enumerate() { // if v was not in the set the data is invalid // and we must forget it instead of dropping it if !self.set.remove(i as u32) { mem::forget(v); } } } } #[cfg(feature = "parsec")] impl<T> parsec::StorageBase for VecMap<T> { fn del(&mut self, e: Entity) { VecMap::delete(self, e.get_id() as u32); } } #[cfg(feature = "parsec")] impl<T> parsec::Storage<T> for VecMap<T> { fn new() -> Self { VecMap::new() } fn get(&self, e: Entity) -> Option<&T> { VecMap::get(self, e.get_id() as u32) } fn get_mut(&mut self, e: Entity) -> Option<&mut T> { VecMap::get_mut(self, e.get_id() as u32) } fn add(&mut self, e: Entity, v: T) { VecMap::insert(self, e.get_id() as u32, v); } fn sub(&mut self, e: Entity) -> Option<T> { VecMap::delete(self, e.get_id() as u32) } } impl<'a, T: 'a> IntoIterator for &'a VecMap<T> { type Item = (u32, (&'a T,)); type IntoIter = TrieIter<Self>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, T> Trie for &'a VecMap<T> { type L2 = SliceMapLayer2<'a, T>; type L1 = SliceMapLayer1<'a, T>; type L0 = SliceMapLayer0<'a, T>; type Value = (&'a T,); type Row = u32; fn top(self) -> SliceMapLayer2<'a, T> { SliceMapLayer2 { layer2: self.set.layer2, layer1: &self.set.layer1[..], layer0: &self.set.layer0[..], values: &self.values[..], } } } impl<'a, T> Trie for &'a mut VecMap<T> { type L2 = SliceMapMutLayer2<'a, T>; type L1 = SliceMapMutLayer1<'a, T>; type L0 = SliceMapMutLayer0<'a, T>; type Value = (&'a mut T,); type Row = u32; fn top(self) -> SliceMapMutLayer2<'a, T> { SliceMapMutLayer2 { layer2: self.set.layer2, layer1: &self.set.layer1[..], layer0: &self.set.layer0[..], values: &mut self.values[..], } } } #[derive(Clone)] pub struct SliceMap<'a, T: 'a> { set: BitSet, values: &'a [T], } impl<'a, T> SliceMap<'a, T> { pub fn new(slice: &'a [T]) -> SliceMap<'a, T> { assert!(slice.len() < 1 << 18); SliceMap { set: BitSet::all_set(slice.len() as u32), values: slice, } } // get a value from the map if it exists pub fn get(&self, bit: u32) -> Option<&T> { if self.set.contains(bit) { Some(&self.values[bit as usize]) } else { None } } // remove element N from the set // since this only holds a reference // the value itself is not dropped pub fn remove(&mut self, bit: u32) -> bool { self.set.remove(bit) } } impl<'a, T> Trie for &'a SliceMap<'a, T> { type L2 = SliceMapLayer2<'a, T>; type L1 = SliceMapLayer1<'a, T>; type L0 = SliceMapLayer0<'a, T>; type Value = (&'a T,); type Row = u32; fn top(self) -> SliceMapLayer2<'a, T> { SliceMapLayer2 { layer2: self.set.layer2, layer1: &self.set.layer1[..], layer0: &self.set.layer0[..], values: &self.values[..], } } } pub struct SliceMutMap<'a, T: 'a> { set: BitSet, values: &'a mut [T], } impl<'a, T> SliceMutMap<'a, T> { pub fn new(slice: &'a mut [T]) -> SliceMutMap<'a, T> { assert!(slice.len() < 1 << 18); SliceMutMap { set: BitSet::all_set(slice.len() as u32), values: slice, } } // get a value from the map if it exists pub fn get(&self, bit: u32) -> Option<&T> { if self.set.contains(bit) { Some(&self.values[bit as usize]) } else { None } } // get a value from the map if it exists pub fn get_mut(&mut self, bit: u32) -> Option<&mut T> { if self.set.contains(bit) { Some(&mut self.values[bit as usize]) } else { None } } // remove element N from the set // since this only holds a reference // the value itself is not dropped pub fn remove(&mut self, bit: u32) -> bool { self.set.remove(bit) } } impl<'a, T> Trie for &'a mut SliceMutMap<'a, T> { type L2 = SliceMapMutLayer2<'a, T>; type L1 = SliceMapMutLayer1<'a, T>; type L0 = SliceMapMutLayer0<'a, T>; type Value = (&'a mut T,); type Row = u32; fn top(self) -> SliceMapMutLayer2<'a, T> { SliceMapMutLayer2 { layer2: self.set.layer2, layer1: &self.set.layer1[..], layer0: &self.set.layer0[..], values: &mut self.values[..], } } } pub struct SliceMapLayer2<'a, T: 'a> { layer2: u64, layer1: &'a [u64], layer0: &'a [u64], values: &'a [T], } impl<'a, T: 'a> TrieLayer for SliceMapLayer2<'a, T> { type Value = SliceMapLayer1<'a, T>; fn mask(&self) -> u64 { self.layer2 } unsafe fn get(&self, idx: usize) -> SliceMapLayer1<'a, T> { let l = idx * 64; let v = idx * 64 * 64; SliceMapLayer1 { layer1: self.layer1[idx], layer0: &self.layer0[l..], values: &self.values[v..], } } } pub struct SliceMapLayer1<'a, T: 'a> { layer1: u64, layer0: &'a [u64], values: &'a [T], } impl<'a, T: 'a> TrieLayer for SliceMapLayer1<'a, T> { type Value = SliceMapLayer0<'a, T>; fn mask(&self) -> u64 { self.layer1 } unsafe fn get(&self, idx: usize) -> SliceMapLayer0<'a, T> { let l = idx * 64; SliceMapLayer0 { layer0: self.layer0[idx], values: &self.values[l..], } } } pub struct SliceMapLayer0<'a, T: 'a> { layer0: u64, values: &'a [T], } impl<'a, T: 'a> TrieLayer for SliceMapLayer0<'a, T> { type Value = (&'a T,); fn mask(&self) -> u64 { self.layer0 } unsafe fn get(&self, idx: usize) -> (&'a T,) { (&self.values.get_unchecked(idx),) } } pub struct SliceMapMutLayer2<'a, T: 'a> { layer2: u64, layer1: &'a [u64], layer0: &'a [u64], values: &'a mut [T], } impl<'a, T: 'a> TrieLayer for SliceMapMutLayer2<'a, T> { type Value = SliceMapMutLayer1<'a, T>; fn mask(&self) -> u64 { self.layer2 } #[allow(mutable_transmutes)] unsafe fn get(&self, idx: usize) -> SliceMapMutLayer1<'a, T> { let l = idx * 64; let v = idx * 64 * 64; let x: &mut [T] = mem::transmute(&self.values[v..]); SliceMapMutLayer1 { layer1: self.layer1[idx], layer0: &self.layer0[l..], values: x, } } } pub struct SliceMapMutLayer1<'a, T: 'a> { layer1: u64, layer0: &'a [u64], values: &'a mut [T], } impl<'a, T: 'a> TrieLayer for SliceMapMutLayer1<'a, T> { type Value = SliceMapMutLayer0<'a, T>; fn mask(&self) -> u64 { self.layer1 } #[allow(mutable_transmutes)] unsafe fn get(&self, idx: usize) -> SliceMapMutLayer0<'a, T> { let l = idx * 64; let x: &mut [T] = mem::transmute(&self.values[l..]); SliceMapMutLayer0 { layer0: self.layer0[idx], values: x, } } } pub struct SliceMapMutLayer0<'a, T: 'a> { layer0: u64, values: &'a mut [T], } impl<'a, T: 'a> TrieLayer for SliceMapMutLayer0<'a, T> { type Value = (&'a mut T,); fn mask(&self) -> u64 { self.layer0 } #[allow(mutable_transmutes)] unsafe fn get(&self, idx: usize) -> (&'a mut T,) { let x: &mut T = mem::transmute(self.values.get_unchecked(idx)); (x,) } } #[cfg(test)] mod set_test { use super::BitSet; #[test] fn insert() { let mut c = BitSet::new(); for i in 0..1_000 { assert!(!c.add(i)); assert!(c.add(i)); } for i in 0..1_000 { assert!(c.contains(i)); } } #[test] fn insert_100k() { let mut c = BitSet::new(); for i in 0..100_000 { assert!(!c.add(i)); assert!(c.add(i)); } for i in 0..100_000 { assert!(c.contains(i)); } } #[test] fn remove() { let mut c = BitSet::new(); for i in 0..1_000 { assert!(!c.add(i)); } for i in 0..1_000 { assert!(c.contains(i)); assert!(c.remove(i)); assert!(!c.contains(i)); assert!(!c.remove(i)); } } } #[cfg(test)] mod map_test { use super::VecMap; #[test] fn insert() { let mut c = VecMap::new(); for i in 0..1_000 { c.insert(i, i); } for i in 0..1_000 { assert_eq!(c.get(i).unwrap(), &i); } } #[test] fn insert_100k() { let mut c = VecMap::new(); for i in 0..100_000 { c.insert(i, i); } for i in 0..100_000 { assert_eq!(c.get(i).unwrap(), &i); } } #[test] fn delete() { let mut c = VecMap::new(); for i in 0..1_000 { c.insert(i, i); } for i in 0..1_000 { assert_eq!(c.get(i).unwrap(), &i); } for i in 0..1_000 { c.delete(i); } for i in 0..1_000 { assert!(c.get(i).is_none()); } } #[test] fn test_gen() { let mut c = VecMap::new(); for i in 0..1_000i32 { c.insert(i as u32, i); c.insert(i as u32, -i); } for i in 0..1_000i32 { assert_eq!(c.get(i as u32).unwrap(), &-i); } } #[test] fn insert_same_key() { let mut c = VecMap::new(); for i in 0..10_000 { c.insert(0, i); assert_eq!(c.get(0).unwrap(), &i); } } #[should_panic] #[test] fn wrap() { let mut c = VecMap::new(); c.insert(1 << 19, 7); } }
use crate::*; #[derive(PartialEq, Clone, Copy, Debug)] pub enum IntegerBits { Eight, Sixteen, ThirtyTwo, SixtyFour, OneTwentyEight, Arch, } #[derive(PartialEq, Clone, Copy, Debug)] pub enum FloatBits { ThirtyTwo, SixtyFour, } #[derive(PartialEq, Clone, Debug)] pub enum Type { String, SignedInteger(IntegerBits), Float(FloatBits), Bool, UnsignedInteger(IntegerBits), Function(Vec<Type>), // curried type decl, last entry is return type Generic { name: String }, // generic/polymorphic type params Tuple(Vec<Type>), Unknown, } impl Type { pub(crate) fn arity(&self) -> Either<FunctionArity, TupleArity> { match self { Type::Tuple(ref tup) => Either::Right(tup.len()), Type::Function(ref types) => { let r#type_arity = types .iter() .last() .expect("fn item had no return type") .arity(); let r#type_arity = match r#type_arity { Either::Left(..) => panic!("return type had function erity; internal error"), Either::Right(num) => num, }; let num_types = types.len() - 1; Either::Left((num_types, r#type_arity)) } _ => Either::Right(1), } } pub(crate) fn to_rust_string(&self) -> String { match &self { Type::String => "String", Type::SignedInteger(IntegerBits::Eight) => "i8", Type::SignedInteger(IntegerBits::Sixteen) => "i16", Type::SignedInteger(IntegerBits::ThirtyTwo) => "i32", Type::SignedInteger(IntegerBits::SixtyFour) => "i64", Type::SignedInteger(IntegerBits::OneTwentyEight) => "i128", Type::UnsignedInteger(IntegerBits::Eight) => "u8", Type::UnsignedInteger(IntegerBits::Sixteen) => "u16", Type::UnsignedInteger(IntegerBits::ThirtyTwo) => "u32", Type::UnsignedInteger(IntegerBits::SixtyFour) => "u64", Type::UnsignedInteger(IntegerBits::OneTwentyEight) => "u128", Type::Float(FloatBits::ThirtyTwo) => "f32", Type::Float(FloatBits::SixtyFour) => "f64", Type::UnsignedInteger(IntegerBits::Arch) => "usize", Type::SignedInteger(IntegerBits::Arch) => "isize", Type::Bool => "bool", _ => todo!("Exhaustive type rendering"), } .into() } fn from_string(a: &str) -> Type { match a { "String" => Type::String, "i8" => Type::SignedInteger(IntegerBits::Eight), "i16" => Type::SignedInteger(IntegerBits::Sixteen), "i32" => Type::SignedInteger(IntegerBits::ThirtyTwo), "i64" => Type::SignedInteger(IntegerBits::SixtyFour), "i128" => Type::SignedInteger(IntegerBits::OneTwentyEight), "u8" => Type::UnsignedInteger(IntegerBits::Eight), "u16" => Type::UnsignedInteger(IntegerBits::Sixteen), "u32" => Type::UnsignedInteger(IntegerBits::ThirtyTwo), "u64" => Type::UnsignedInteger(IntegerBits::SixtyFour), "u128" => Type::UnsignedInteger(IntegerBits::OneTwentyEight), "f32" => Type::Float(FloatBits::ThirtyTwo), "f64" => Type::Float(FloatBits::SixtyFour), "usize" => Type::UnsignedInteger(IntegerBits::Arch), "isize" => Type::SignedInteger(IntegerBits::Arch), "bool" => Type::Bool, other => Type::Generic { name: other.to_string(), }, /* TODO rest of types */ } } pub(crate) fn from_vec_string(args: Vec<Vec<&str>>) -> Type { let args = args .into_iter() .map(|y| { if y.len() == 1 { Type::from_string(y[0]) } else { // TODO handle parsing nested tuple types Type::Tuple( y.into_iter() .map(|x| Type::from_string(x)) .collect::<Vec<_>>(), ) } }) .collect::<Vec<_>>(); if args.len() == 1 { // then this is not a fn type args[0].clone() } else { Type::Function(args) } } }
use std::{ collections::HashMap, fmt::{Display, Formatter}, iter::FromIterator, }; // Generic expression evaluation automaton and expression formatting support #[derive(Clone, Debug)] pub enum EvaluationError<T> { NoResults, TooManyResults, OperatorFailed(T), } pub trait Operator<T> { type Err; fn execute(&self, stack: &mut Vec<T>) -> Result<(), Self::Err>; } #[derive(Clone, Copy, Debug)] enum Element<O> { Operator(O), Variable(usize), } #[derive(Clone, Debug)] pub struct Expression<O> { elements: Vec<Element<O>>, symbols: Vec<String>, } impl<O> Expression<O> { pub fn evaluate<T>( &self, mut bindings: impl FnMut(usize) -> T, ) -> Result<T, EvaluationError<O::Err>> where O: Operator<T>, { let mut stack = Vec::new(); for element in self.elements.iter() { match element { Element::Variable(index) => stack.push(bindings(*index)), Element::Operator(op) => op .execute(&mut stack) .map_err(EvaluationError::OperatorFailed)?, } } match stack.pop() { Some(result) if stack.is_empty() => Ok(result), Some(_) => Err(EvaluationError::TooManyResults), None => Err(EvaluationError::NoResults), } } pub fn symbols(&self) -> &[String] { &self.symbols } pub fn formatted(&self) -> Result<String, EvaluationError<O::Err>> where O: Operator<Formatted>, { self.evaluate(|index| Formatted(self.symbols[index].clone())) .map(|formatted| formatted.0) } } #[derive(Clone, Debug)] pub struct Formatted(pub String); impl Display for Formatted { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl<O> Display for Expression<O> where O: Operator<Formatted>, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self.formatted() { Ok(result) => write!(f, "{}", result), Err(_) => write!(f, "<malformed expression>"), } } } // Generic parts of the parsing machinery #[derive(Clone, Copy, Debug)] pub enum Token<'a, O> { LBrace, RBrace, Operator(O), Variable(&'a str), Malformed(&'a str), } pub type Symbol<'a, O> = (&'a str, bool, Token<'a, O>); #[derive(Debug)] pub struct Tokens<'a, O> { source: &'a str, symbols: &'a [Symbol<'a, O>], } impl<'a, O> Tokens<'a, O> { pub fn new(source: &'a str, symbols: &'a [Symbol<'a, O>]) -> Self { Self { source, symbols } } } impl<'a, O: Clone> Iterator for Tokens<'a, O> { type Item = Token<'a, O>; fn next(&mut self) -> Option<Self::Item> { self.source = self.source.trim_start(); let symbol = self.symbols.iter().find_map(|(symbol, word, token)| { if self.source.starts_with(symbol) { let end = symbol.len(); if *word { match &self.source[end..].chars().next() { Some(c) if !c.is_whitespace() => return None, _ => (), } } Some((token, end)) } else { None } }); if let Some((token, end)) = symbol { self.source = &self.source[end..]; Some(token.clone()) } else { match self.source.chars().next() { Some(c) if c.is_alphabetic() => { let end = self .source .char_indices() .find_map(|(i, c)| Some(i).filter(|_| !c.is_alphanumeric())) .unwrap_or_else(|| self.source.len()); let result = &self.source[0..end]; self.source = &self.source[end..]; Some(Token::Variable(result)) } Some(c) => { let end = c.len_utf8(); let result = &self.source[0..end]; self.source = &self.source[end..]; Some(Token::Malformed(result)) } None => None, } } } } pub trait WithPriority { type Priority; fn priority(&self) -> Self::Priority; } impl<'a, O> FromIterator<Token<'a, O>> for Result<Expression<O>, Token<'a, O>> where O: WithPriority, O::Priority: Ord, { fn from_iter<T: IntoIterator<Item = Token<'a, O>>>(tokens: T) -> Self { let mut token_stack = Vec::new(); let mut indices = HashMap::new(); let mut symbols = Vec::new(); let mut elements = Vec::new(); 'outer: for token in tokens { match token { Token::Malformed(_) => return Err(token), Token::LBrace => token_stack.push(token), Token::RBrace => { // Flush all operators to the matching LBrace while let Some(token) = token_stack.pop() { match token { Token::LBrace => continue 'outer, Token::Operator(op) => elements.push(Element::Operator(op)), _ => return Err(token), } } } Token::Variable(name) => { let index = indices.len(); let symbol = name.to_string(); let index = *indices.entry(symbol.clone()).or_insert_with(|| { symbols.push(symbol); index }); elements.push(Element::Variable(index)); } Token::Operator(ref op) => { while let Some(token) = token_stack.pop() { match token { Token::Operator(pop) if op.priority() < pop.priority() => { elements.push(Element::Operator(pop)); } Token::Operator(pop) => { token_stack.push(Token::Operator(pop)); break; } _ => { token_stack.push(token); break; } } } token_stack.push(token); } } } // Handle leftovers while let Some(token) = token_stack.pop() { match token { Token::Operator(op) => elements.push(Element::Operator(op)), _ => return Err(token), } } Ok(Expression { elements, symbols }) } } // Definition of Boolean operators #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Boolean { Or, Xor, And, Not, } impl Display for Boolean { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let s = match self { Self::Or => "∨", Self::And => "∧", Self::Not => "¬", Self::Xor => "⩛", }; write!(f, "{}", s) } } impl WithPriority for Boolean { type Priority = u8; fn priority(&self) -> u8 { match self { Self::Or => 0, Self::Xor => 1, Self::And => 2, Self::Not => 3, } } } #[derive(Clone, Debug)] pub enum BooleanError { StackUnderflow, } impl Operator<bool> for Boolean { type Err = BooleanError; fn execute(&self, stack: &mut Vec<bool>) -> Result<(), Self::Err> { let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow); let result = match self { Boolean::Or => pop()? | pop()?, Boolean::And => pop()? & pop()?, Boolean::Xor => pop()? ^ pop()?, Boolean::Not => !pop()?, }; stack.push(result); Ok(()) } } impl Operator<Formatted> for Boolean { type Err = BooleanError; fn execute(&self, stack: &mut Vec<Formatted>) -> Result<(), Self::Err> { let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow); let result = match self { Boolean::Not => format!("{}{}", Boolean::Not, pop()?), binary_operator => { // The stack orders the operands backwards, so to format them // properly, we have to count with the reversed popping order let b = pop()?; let a = pop()?; format!("({} {} {})", a, binary_operator, b) } }; stack.push(Formatted(result)); Ok(()) } } impl Boolean { // It is important for the tokens to be ordered by their parsing priority (if // some operator was a prefix of another operator, the prefix must come later) const SYMBOLS: [Symbol<'static, Boolean>; 18] = [ ("(", false, Token::LBrace), (")", false, Token::RBrace), ("|", false, Token::Operator(Boolean::Or)), ("∨", false, Token::Operator(Boolean::Or)), ("or", true, Token::Operator(Boolean::Or)), ("OR", true, Token::Operator(Boolean::Or)), ("&", false, Token::Operator(Boolean::And)), ("∧", false, Token::Operator(Boolean::And)), ("and", true, Token::Operator(Boolean::And)), ("AND", true, Token::Operator(Boolean::And)), ("!", false, Token::Operator(Boolean::Not)), ("¬", false, Token::Operator(Boolean::Not)), ("not", true, Token::Operator(Boolean::Not)), ("NOT", true, Token::Operator(Boolean::Not)), ("^", false, Token::Operator(Boolean::Xor)), ("⩛", false, Token::Operator(Boolean::Xor)), ("xor", true, Token::Operator(Boolean::Xor)), ("XOR", true, Token::Operator(Boolean::Xor)), ]; pub fn tokenize(s: &str) -> Tokens<'_, Boolean> { Tokens::new(s, &Self::SYMBOLS) } pub fn parse<'a>(s: &'a str) -> Result<Expression<Boolean>, Token<'a, Boolean>> { Self::tokenize(s).collect() } } // Finally the table printing fn print_truth_table(s: &str) -> Result<(), std::borrow::Cow<'_, str>> { let expression = Boolean::parse(s).map_err(|e| format!("Parsing failed at token {:?}", e))?; let formatted = expression .formatted() .map_err(|_| "Malformed expression detected.")?; let var_count = expression.symbols().len(); if var_count > 64 { return Err("Too many variables to list.".into()); } let column_widths = { // Print header and compute the widths of columns let mut widths = Vec::with_capacity(var_count); for symbol in expression.symbols() { print!("{} ", symbol); widths.push(symbol.chars().count() + 2); // Include spacing } println!("{}", formatted); let width = widths.iter().sum::<usize>() + formatted.chars().count(); (0..width).for_each(|_| print!("-")); println!(); widths }; // Choose the bit extraction order for the more traditional table ordering let var_value = |input, index| (input >> (var_count - 1 - index)) & 1 ^ 1; // Use counter to enumerate all bit combinations for var_values in 0u64..(1 << var_count) { for (var_index, width) in column_widths.iter().enumerate() { let value = var_value(var_values, var_index); print!("{:<width$}", value, width = width); } match expression.evaluate(|var_index| var_value(var_values, var_index) == 1) { Ok(result) => println!("{}", if result { "1" } else { "0" }), Err(e) => println!("{:?}", e), } } println!(); Ok(()) } fn main() { loop { let input = { println!("Enter the expression to parse (or nothing to quit):"); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); println!(); input }; if input.trim().is_empty() { break; } if let Err(e) = print_truth_table(&input) { eprintln!("{}\n", e); } } }
// This file is part of Substrate. // Copyright (C) 2017-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use super::*; use assert_matches::assert_matches; use futures::prelude::*; use sc_network::config::Role; use sc_network::{self, PeerId}; use sp_utils::mpsc::tracing_unbounded; use std::thread; use substrate_test_runtime_client::runtime::Block; struct Status { pub peers: usize, pub is_syncing: bool, pub is_dev: bool, pub peer_id: PeerId, } impl Default for Status { fn default() -> Status { Status { peer_id: PeerId::random(), peers: 0, is_syncing: false, is_dev: false } } } fn api<T: Into<Option<Status>>>(sync: T) -> System<Block> { let status = sync.into().unwrap_or_default(); let should_have_peers = !status.is_dev; let (tx, rx) = tracing_unbounded("rpc_system_tests"); thread::spawn(move || { futures::executor::block_on(rx.for_each(move |request| { match request { Request::Health(sender) => { let _ = sender.send(Health { peers: status.peers, is_syncing: status.is_syncing, should_have_peers, }); }, Request::LocalPeerId(sender) => { let _ = sender.send("QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".to_string()); }, Request::LocalListenAddresses(sender) => { let _ = sender.send(vec![ "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".to_string(), "/ip4/127.0.0.1/tcp/30334/ws/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".to_string(), ]); }, Request::Peers(sender) => { let mut peers = vec![]; for _peer in 0..status.peers { peers.push(PeerInfo { peer_id: status.peer_id.to_base58(), roles: format!("{}", Role::Full), best_hash: Default::default(), best_number: 1, }); } let _ = sender.send(peers); }, Request::NetworkState(sender) => { let _ = sender.send( serde_json::to_value(&sc_network::network_state::NetworkState { peer_id: String::new(), listened_addresses: Default::default(), external_addresses: Default::default(), connected_peers: Default::default(), not_connected_peers: Default::default(), peerset: serde_json::Value::Null, }) .unwrap(), ); }, Request::NetworkAddReservedPeer(peer, sender) => { let _ = match sc_network::config::parse_str_addr(&peer) { Ok(_) => sender.send(Ok(())), Err(s) => sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))), }; }, Request::NetworkRemoveReservedPeer(peer, sender) => { let _ = match peer.parse::<PeerId>() { Ok(_) => sender.send(Ok(())), Err(s) => sender.send(Err(error::Error::MalformattedPeerArg(s.to_string()))), }; }, Request::NodeRoles(sender) => { let _ = sender.send(vec![NodeRole::Authority]); }, }; future::ready(()) })) }); System::new( SystemInfo { impl_name: "testclient".into(), impl_version: "0.2.0".into(), chain_name: "testchain".into(), properties: Default::default(), chain_type: Default::default(), }, tx, sc_rpc_api::DenyUnsafe::No, ) } fn wait_receiver<T>(rx: Receiver<T>) -> T { let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); runtime.block_on(rx).unwrap() } #[test] fn system_name_works() { assert_eq!(api(None).system_name().unwrap(), "testclient".to_owned(),); } #[test] fn system_version_works() { assert_eq!(api(None).system_version().unwrap(), "0.2.0".to_owned(),); } #[test] fn system_chain_works() { assert_eq!(api(None).system_chain().unwrap(), "testchain".to_owned(),); } #[test] fn system_properties_works() { assert_eq!(api(None).system_properties().unwrap(), serde_json::map::Map::new(),); } #[test] fn system_type_works() { assert_eq!(api(None).system_type().unwrap(), Default::default(),); } #[test] fn system_health() { assert_matches!( wait_receiver(api(None).system_health()), Health { peers: 0, is_syncing: false, should_have_peers: true } ); assert_matches!( wait_receiver( api(Status { peer_id: PeerId::random(), peers: 5, is_syncing: true, is_dev: true }) .system_health() ), Health { peers: 5, is_syncing: true, should_have_peers: false } ); assert_eq!( wait_receiver( api(Status { peer_id: PeerId::random(), peers: 5, is_syncing: false, is_dev: false }) .system_health() ), Health { peers: 5, is_syncing: false, should_have_peers: true } ); assert_eq!( wait_receiver( api(Status { peer_id: PeerId::random(), peers: 0, is_syncing: false, is_dev: true }) .system_health() ), Health { peers: 0, is_syncing: false, should_have_peers: false } ); } #[test] fn system_local_peer_id_works() { assert_eq!( wait_receiver(api(None).system_local_peer_id()), "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV".to_owned(), ); } #[test] fn system_local_listen_addresses_works() { assert_eq!( wait_receiver(api(None).system_local_listen_addresses()), vec![ "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV" .to_string(), "/ip4/127.0.0.1/tcp/30334/ws/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV" .to_string(), ] ); } #[test] fn system_peers() { let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); let peer_id = PeerId::random(); let req = api(Status { peer_id: peer_id.clone(), peers: 1, is_syncing: false, is_dev: true }) .system_peers(); let res = runtime.block_on(req).unwrap(); assert_eq!( res, vec![PeerInfo { peer_id: peer_id.to_base58(), roles: "FULL".into(), best_hash: Default::default(), best_number: 1u64, }] ); } #[test] fn system_network_state() { let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); let req = api(None).system_network_state(); let res = runtime.block_on(req).unwrap(); assert_eq!( serde_json::from_value::<sc_network::network_state::NetworkState>(res).unwrap(), sc_network::network_state::NetworkState { peer_id: String::new(), listened_addresses: Default::default(), external_addresses: Default::default(), connected_peers: Default::default(), not_connected_peers: Default::default(), peerset: serde_json::Value::Null, } ); } #[test] fn system_node_roles() { assert_eq!(wait_receiver(api(None).system_node_roles()), vec![NodeRole::Authority]); } #[test] fn system_network_add_reserved() { let good_peer_id = "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"; let bad_peer_id = "/ip4/198.51.100.19/tcp/30333"; let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); let good_fut = api(None).system_add_reserved_peer(good_peer_id.into()); let bad_fut = api(None).system_add_reserved_peer(bad_peer_id.into()); assert_eq!(runtime.block_on(good_fut), Ok(())); assert!(runtime.block_on(bad_fut).is_err()); } #[test] fn system_network_remove_reserved() { let good_peer_id = "QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"; let bad_peer_id = "/ip4/198.51.100.19/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV"; let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); let good_fut = api(None).system_remove_reserved_peer(good_peer_id.into()); let bad_fut = api(None).system_remove_reserved_peer(bad_peer_id.into()); assert_eq!(runtime.block_on(good_fut), Ok(())); assert!(runtime.block_on(bad_fut).is_err()); }
use super::super::super::super::super::{awesome, btn, color_picker, modeless, text}; use super::super::state::{Modal, Modeless}; use super::Msg; use crate::{ block::{self, BlockId}, model::{self}, resource::Data, Color, Resource, }; use kagura::prelude::*; use wasm_bindgen::JsCast; pub fn render( block_field: &block::Field, resource: &Resource, is_grabbed: bool, boxblock: &block::table_object::Boxblock, boxblock_id: &BlockId, ) -> Html { let [xw, yw, zw] = boxblock.size().clone(); let color = boxblock.color(); modeless::body( Attributes::new().class("scroll-v"), Events::new().on_mousemove(move |e| { if !is_grabbed { e.stop_propagation(); } Msg::NoOp }), vec![Html::div( Attributes::new() .class("editormodeless") .class("pure-form") .class("linear-v"), Events::new(), vec![Html::div( Attributes::new().class("container-a").class("keyvalue"), Events::new(), vec![ text::span("X幅"), set_size_input(boxblock_id, xw, move |xw| [xw, yw, zw]), text::span("Y幅"), set_size_input(boxblock_id, yw, move |yw| [xw, yw, zw]), text::span("Z幅"), set_size_input(boxblock_id, zw, move |zw| [xw, yw, zw]), text::span("選択色"), Html::div( Attributes::new() .class("cell") .class("cell-medium") .style("background-color", color.to_string()), Events::new(), vec![], ), Html::div( Attributes::new().class("keyvalue-banner").class("linear-v"), Events::new(), vec![ table_color(boxblock_id, color.alpha, 3), table_color(boxblock_id, color.alpha, 5), table_color(boxblock_id, color.alpha, 7), ], ), ], )], )], ) } fn set_size_input( boxblock_id: &BlockId, s: f32, on_input: impl FnOnce(f32) -> [f32; 3] + 'static, ) -> Html { Html::input( Attributes::new() .type_("number") .value(s.to_string()) .string("step", "0.1"), Events::new().on_input({ let boxblock_id = boxblock_id.clone(); move |s| { s.parse() .map(|s| Msg::SetBoxblockSize(boxblock_id, on_input(s))) .unwrap_or(Msg::NoOp) } }), vec![], ) } fn table_color(boxblock_id: &BlockId, alpha: u8, idx: usize) -> Html { color_picker::idx(idx, Msg::NoOp, { let boxblock_id = boxblock_id.clone(); move |mut color| { color.alpha = alpha; Msg::SetBoxblockColor(boxblock_id, color) } }) }
#[doc = "Register `HMONR` reader"] pub type R = crate::R<HMONR_SPEC>; #[doc = "Field `HITMON` reader - cache hit monitor counter"] pub type HITMON_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - cache hit monitor counter"] #[inline(always)] pub fn hitmon(&self) -> HITMON_R { HITMON_R::new(self.bits) } } #[doc = "ICACHE hit monitor register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hmonr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HMONR_SPEC; impl crate::RegisterSpec for HMONR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hmonr::R`](R) reader structure"] impl crate::Readable for HMONR_SPEC {} #[doc = "`reset()` method sets HMONR to value 0"] impl crate::Resettable for HMONR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod chat { tonic::include_proto!("chat"); } use chat::{chat_server::Chat, Empty, Message, Reply, User}; use std::{collections::HashMap, sync::Arc}; use tokio::sync::{mpsc, RwLock}; use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; type SenderId = i32; #[derive(Debug, Default)] struct Connections { senders: HashMap<SenderId, mpsc::Sender<Message>>, } impl Connections { async fn broadcast(&self, msg: Message) { for (sender_id, tx) in &self.senders { match tx.send(msg.clone()).await { Ok(_) => {} Err(_) => { println!("[Broadcast] SendError: to {}, {:?}", sender_id, msg) } } } } } #[derive(Debug, Default)] pub struct ChatService { connections: Arc<RwLock<Connections>>, } #[tonic::async_trait] impl Chat for ChatService { type UserJoinStream = ReceiverStream<Result<Message, Status>>; /* When a user joins, his transmission is saved in hashmap, whenever */ async fn user_join(&self, request: Request<chat::User>) -> Result<Response<Self::UserJoinStream>, Status> { let sender_id = request.into_inner().id; if self.connections.read().await.senders.get(&sender_id).is_some() { return Err(Status::already_exists("user with id exists")); } let (tx, mut rx) = mpsc::channel(1); self.connections.write().await.senders.insert(sender_id, tx); /* saving transmitter of every user */ let connections_clone = self.connections.clone(); let (stream_tx, stream_rx) = mpsc::channel(1); tokio::spawn(async move { while let Some(msg) = rx.recv().await { match stream_tx.send(Ok(msg)).await { Ok(_) => {} Err(_) => { // If sending failed, then remove the user from shared data println!("[Remote] stream tx sending error. Remote {}", &sender_id); connections_clone.write().await.senders.remove(&sender_id); } } } }); let result = Ok(Response::new(ReceiverStream::new(stream_rx))); result } async fn send_message(&self, request: Request<Message>) -> Result<Response<Empty>, Status> { let Message { id, content } = request.into_inner(); if self.connections.read().await.senders.get(&id).is_none() { return Err(Status::not_found("user with id does not exist")); } let msg = Message { id, content }; self.connections.read().await.broadcast(msg).await; Ok(Response::new(Empty {})) } async fn say_hello(&self, request: Request<User>) -> Result<Response<Reply>, Status> { let User { name, .. } = request.into_inner(); Ok(Response::new(Reply { hi: format!("Hello {}!", name), })) } }
use anyhow::Result; use async_std::sync::{Arc, Mutex, RwLock, RwLockReadGuard}; use blake2_rfc::blake2b::Blake2b; use ed25519_dalek::{PublicKey, SecretKey}; use futures::channel::mpsc; use futures::sink::SinkExt; use hypercore::{storage_disk, Feed}; use hypercore_replicator::discovery_key; use log::*; use rand::rngs::{OsRng, StdRng}; use rand::SeedableRng; use rand_core::RngCore; use random_access_disk::RandomAccessDisk; use random_access_storage::RandomAccess; use std::collections::hash_map::Values; use std::convert::TryInto; use std::fmt::Debug; use std::path::{Path, PathBuf}; use crate::feed_map::FeedMap; const MASTER_KEY_FILENAME: &str = "master_key"; const NAMESPACE: &str = "corestore"; /// A hypercore public key pub type Key = [u8; 32]; /// A feed name pub type Name = Vec<u8>; /// A feed that can be shared between threads pub type ArcFeed = Arc<Mutex<Feed>>; /// Corestore events #[derive(Debug, Clone)] pub enum Event { /// A new feed has been opened Feed(Arc<Mutex<Feed>>), } #[derive(Clone)] pub struct Corestore { inner: Arc<RwLock<InnerCorestore>>, } /// A store for hypercore feeds. impl Corestore { /// Open a corestore from disk pub async fn open<P>(storage_path: P) -> Result<Self> where P: AsRef<Path>, { let inner = InnerCorestore::open(storage_path).await?; Ok(Self { inner: Arc::new(RwLock::new(inner)), }) } /// Subscribe to events from this corestore pub async fn subscribe(&mut self) -> mpsc::Receiver<Event> { self.inner.write().await.subscribe().await } /// Get a feed by its public key pub async fn get_by_key(&mut self, key: Key) -> Result<ArcFeed> { self.inner.write().await.get_by_key(key).await } /// Get or create a writable feed by name pub async fn get_by_name<T>(&mut self, name: T) -> Result<ArcFeed> where T: AsRef<str>, { self.inner.write().await.get_by_name(name).await } /// Get a feed by its discovery key /// /// This only works if the feed is found on disk pub async fn get_by_dkey(&mut self, dkey: Key) -> Result<Option<ArcFeed>> { self.inner.write().await.get_by_dkey(dkey).await } /// Iterate over all feeds. /// /// Note: A lock on the corestore is kept until the iterator is dropped, /// so don't use this across `await`s. /// /// Example: /// ``` /// # #[async_std::main] /// # async fn main() -> anyhow::Result<()> { /// let corestore = corestore::Corestore::open("/tmp/foo").await?; /// for feed in &corestore.feeds().await { /// // Do somethings with feed. /// // Don't await things here! /// // Instead, clone the feed if you need to keep a reference. /// } /// # Ok(()) /// # } /// ``` pub async fn feeds(&self) -> FeedsIterator<'_> { let inner = self.inner.read().await; FeedsIterator::new(inner) } } /// An iterator over feeds in a corestore. /// /// Note: Because this is tied to a read lock, the iterator is only /// available on a reference to the iterator. See [Corestore::feeds]. pub struct FeedsIterator<'a> { inner: RwLockReadGuard<'a, InnerCorestore>, } impl<'a, 'b: 'a> IntoIterator for &'b FeedsIterator<'a> { type Item = &'a ArcFeed; type IntoIter = Values<'a, u64, ArcFeed>; fn into_iter(self) -> Values<'a, u64, ArcFeed> { self.inner.feeds() } } impl<'a> FeedsIterator<'a> { fn new(inner: RwLockReadGuard<'a, InnerCorestore>) -> Self { Self { inner } } } struct InnerCorestore { master_key: Key, feeds: FeedMap, #[allow(dead_code)] name: String, storage_path: PathBuf, subscribers: Vec<mpsc::Sender<Event>>, } impl InnerCorestore { /// Open a corestore from disk pub async fn open<P>(storage_path: P) -> Result<Self> where P: AsRef<Path>, { let storage_path = storage_path.as_ref().to_path_buf(); Self::with_storage_path(storage_path).await } async fn with_storage_path(path: PathBuf) -> Result<Self> { let master_key_path = path.join(MASTER_KEY_FILENAME); let mut master_key_storage = random_access_disk(master_key_path).await?; let master_key: Key = match master_key_storage.read(0, 32).await { Ok(key) => key.try_into().unwrap(), Err(_) => { let key = generate_key(); // TODO: Map err, not unwrap. master_key_storage.write(0, &key[..32]).await.unwrap(); key } }; Ok(Self { master_key, feeds: FeedMap::new(), name: "default".into(), storage_path: path, subscribers: vec![], }) } async fn emit(&mut self, event: Event) { for sender in self.subscribers.iter_mut() { sender.send(event.clone()).await.unwrap(); } } /// Subscribe to events from this corestore pub async fn subscribe(&mut self) -> mpsc::Receiver<Event> { let (send, recv) = mpsc::channel(100); self.subscribers.push(send); recv } /// Get a feed by its public key pub async fn get_by_key(&mut self, key: Key) -> Result<ArcFeed> { self.open_feed(Some(key), None).await } /// Get or create a writable feed by name pub async fn get_by_name<T>(&mut self, name: T) -> Result<ArcFeed> where T: AsRef<str>, { let name = name.as_ref().as_bytes().to_vec(); self.open_feed(None, Some(name)).await } /// Get a feed by its discovery key /// /// This only works if the feed is found on disk pub async fn get_by_dkey(&mut self, dkey: Key) -> Result<Option<ArcFeed>> { if let Some(feed) = self.feeds.get_dkey(&dkey) { return Ok(Some(feed.clone())); } // Check if the feed exists on disk. let key = { let mut key_storage = self.feed_storage(&dkey, "key").await?; key_storage.read(0, 32).await }; let feed = match key { Ok(key) => Some(self.get_by_key(key.try_into().unwrap()).await?), Err(_) => None, }; Ok(feed) } /// Iterate over all feeds /// /// Returns an iterator of `ArcFeed`s pub fn feeds(&self) -> Values<u64, ArcFeed> { self.feeds.iter() } async fn open_feed(&mut self, key: Option<Key>, name: Option<Name>) -> Result<ArcFeed> { if let Some(feed) = key.as_ref().map(|k| self.feeds.get_key(&k)).flatten() { return Ok((*feed).clone()); } if let Some(feed) = name.as_ref().map(|n| self.feeds.get_name(&n)).flatten() { return Ok((*feed).clone()); } debug!( "open feed key {:?} name {:?} dkey {:?}", key.as_ref().map(|k| hex::encode(k)), name, key.as_ref().map(|k| hex::encode(discovery_key(k))) ); // When opening a feed by key without a name, check if a name exists. let name = match (&key, name) { (_, Some(name)) => Some(name), (None, None) => None, (Some(key), None) => { let dkey = discovery_key(&key[..]); self.read_name(&dkey).await? } }; let (public_key, secret_key, generated_name) = match (key, name) { (_, Some(name)) => self.generate_key_pair(Some(name)), (None, None) => self.generate_key_pair(None), (Some(key), None) => (pubkey_from_bytes(&key)?, None, None), }; let dkey = discovery_key(public_key.as_bytes()); if let Some(name) = &generated_name { self.write_name_if_empty(&dkey, name).await?; } let dir = self.feed_path(&dkey); let feed_storage = storage_disk(&dir).await?; let builder = Feed::builder(public_key.clone(), feed_storage); let builder = if let Some(secret_key) = secret_key { builder.secret_key(secret_key) } else { builder }; let feed = builder.build().await?; debug!( "open feed, key: {}", hex::encode(feed.public_key().as_bytes()) ); let arc_feed = self.feeds.insert(feed, generated_name); self.emit(Event::Feed(arc_feed.clone())).await; Ok(arc_feed) } fn feed_path(&self, dkey: &Key) -> PathBuf { let hdkey = hex::encode(dkey); let mut path = self.storage_path.clone(); path.push(&hdkey[..2]); path.push(&hdkey[2..4]); path.push(&hdkey); path } async fn feed_storage(&self, dkey: &Key, name: &str) -> Result<RandomAccessDisk> { let mut path = self.feed_path(dkey); path.push(name); random_access_disk(path).await } async fn name_storage(&self, dkey: &Key) -> Result<RandomAccessDisk> { self.feed_storage(&dkey, "name").await } async fn read_name(&self, dkey: &Key) -> Result<Option<Name>> { let mut name_storage = self.name_storage(dkey).await?; let len = name_storage.len().await.unwrap_or(0); if len > 0 { // TODO: Map error. let name = name_storage.read(0, len).await.unwrap(); Ok(Some(name)) } else { Ok(None) } } async fn write_name_if_empty(&self, dkey: &Key, name: &Name) -> Result<bool> { let mut name_storage = self.name_storage(dkey).await?; let len = name_storage.len().await.unwrap_or(0); if len > 0 { Ok(false) } else { // TODO: Map error. name_storage.write(0, name).await.unwrap(); Ok(true) } } fn derive_secret(&self, namespace: &Name, name: &Name) -> Key { derive_key(&self.master_key, namespace, name) } fn generate_key_pair( &self, name: Option<Name>, ) -> (PublicKey, Option<SecretKey>, Option<Name>) { let name = name.or_else(|| Some(generate_key().to_vec())).unwrap(); let seed = self.derive_secret(&NAMESPACE.as_bytes().to_vec(), &name); let secret_key = SecretKey::from_bytes(&seed).unwrap(); let public_key: PublicKey = (&secret_key).into(); (public_key, Some(secret_key), Some(name)) } } fn pubkey_from_bytes(bytes: &Key) -> Result<PublicKey> { PublicKey::from_bytes(bytes).map_err(|e| e.into()) } fn derive_key(master_key: &[u8], ns: &[u8], name: &[u8]) -> Key { let mut hasher = Blake2b::with_key(32, master_key); hasher.update(ns); hasher.update(name); hasher.finalize().as_bytes().try_into().unwrap() } fn generate_key() -> Key { let mut rng = StdRng::from_rng(OsRng::default()).unwrap(); let mut key = [0u8; 32]; rng.fill_bytes(&mut key); key } // TODO: Make this a callback (for e.g. inmemory). async fn random_access_disk(path: PathBuf) -> Result<RandomAccessDisk> { RandomAccessDisk::open(path).await }
fn main() { // Examples for various data representation // Decimal 98_222 // Hex 0xff // Octal 0o77 // Binary 0b1111_0000 // Byte (u8 only) b'A // two data type subsets: scalar and compound // compiler can usually infer what type we want to use based on the value and how we use it // One type to another type using parse let guess = String::new(); let guess: u32 = "42".parse().expect("Not a number!"); // If we don’t add the type annotation here, Rust will display the error // signed variant can store numbers from -(2**(n - 1)) to 2**(n - 1) - 1 // Unsigned variants can store numbers from 0 to 2**(n - 1) let x = 1; // integer types default to i32 // the isize and usize types depend on the kind of computer your program is running on: // 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture let x = 2.0; // f64 float type by default let y: f32 = 3.0; // explicit f32 type assigning // The f32 type is a single-precision float, and f64 has double precision let t = true; // auto annotation let f: bool = false; // with explicit type annotation let c = 'z'; // char literals are specified with single quotes, as opposed to string literals, which use double quotes let z = 'ℤ'; // Char type as four bytes // and represents a Unicode Scalar Value, which means it can represent a lot more than just ASCII let heart_eyed_cat = '😻'; let tup: (i32, f64, u8) = (500, 6.4, 1); // A tuple is a general way of grouping together some number of other values with a variety of types into one compound type. Tuples have a fixed length. let (x, y, z) = tup; // can use pattern matching to destructure a tuple value let five_hundred = tup.0; // can access a tuple element directly by using a period (.) followed by // the index of the value we want to access // every element of an array must have the same type and arrays in Rust have a fixed length let a = [0, 1, 2, 3, 4]; let a[isize; 5] = [0, 1, 2, 3, 4]; // write an array’s type by using square brackets including the type of each element, a semicolon, and then the number of elements in the array let a = [3; 5]; // This is the same as writing let a = [3, 3, 3, 3, 3]; let first_a = a[0]; // access elements of an array using indexing, }
use nix::unistd::{execvp, fork, ForkResult, Pid}; use std::convert::Infallible; use std::env; use std::ffi::CString; use std::process; fn tracee() -> Infallible { let args: Vec<CString> = env::args() // Skip the path of this file. .skip(1) .map(|a| CString::new(a).expect("Invalid string argument.")) .collect(); let executable = match args.first() { Some(e) => e, None => { println!("Usage: listen <executable> [args]"); process::exit(1) } }; println!("I'll be traced."); execvp(&executable, &args[..]).expect("Couldn't execute given command.") } fn tracer(pid: Pid) { println!("Tracing {}", pid); } fn main() { match unsafe { fork() }.expect("Could not fork.") { ForkResult::Parent { child } => { tracer(child); } ForkResult::Child => { tracee(); } }; }
use cranelift::codegen::write_function; use cranelift::prelude::*; use cranelift_module::{FuncId, Linkage, Module}; use cranelift_preopt::optimize; use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder}; use jetski::SchemeExpression; use jetski::{jit::Tag, parser::parse_datum, ErrorKind, Object, Result}; use rustyline::{error::ReadlineError, Editor}; use std::collections::HashMap; #[derive(Debug)] struct Environment { data: HashMap<i64, (i8, i64)>, } impl Environment { pub fn new() -> Self { Environment { data: HashMap::new(), } } pub fn define(&mut self, _key_tag: i8, key_val: i64, val_tag: i8, val_val: i64) { self.data.insert(key_val, (val_tag, val_val)); } pub fn lookup(&self, tag: i8, val: i64) -> (i8, i64) { println!("looking up {:?}", (self, tag, val)); self.data[&val] } } type TopLevelFunction = fn(&Environment) -> (Tag, i64); fn compile_top_level( module: &mut Module<SimpleJITBackend>, expr: &Object, ) -> Result<TopLevelFunction> { let fn_id = compile_function(module, &Object::nil(), expr, "main")?; let fn_code = module.get_finalized_function(fn_id); let fn_ptr = unsafe { std::mem::transmute::<_, TopLevelFunction>(fn_code) }; Ok(fn_ptr) } fn compile_function( module: &mut Module<SimpleJITBackend>, params: &Object, body: &Object, name: &str, ) -> Result<FuncId> { let mut ctx = module.make_context(); let mut func_ctx = FunctionBuilderContext::new(); let signature = make_dynamic_signature(module, params.list_len().unwrap()); let func = module .declare_function(name, Linkage::Local, &signature) .unwrap(); ctx.func.signature = signature; ctx.func.name = ExternalName::user(0, func.as_u32()); { let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx); let ebb = bcx.create_ebb(); bcx.switch_to_block(ebb); bcx.append_ebb_params_for_function_params(ebb); let env = bcx.ebb_params(ebb)[0]; let mut compiler = Compiler::new(module, &mut bcx); compiler.new_variable("env", 0, types::I64, Some(env)); let (tag, val) = compiler.compile_expression(body)?; bcx.ins().return_(&[tag, val]); bcx.seal_all_blocks(); bcx.finalize(); } optimize(&mut ctx, module.isa()).unwrap(); let mut s = String::new(); write_function(&mut s, &ctx.func, None).unwrap(); println!("{}", s); module.define_function(func, &mut ctx).unwrap(); module.clear_context(&mut ctx); module.finalize_definitions(); Ok(func) } struct Compiler<'a, 'b> { module: &'a mut Module<SimpleJITBackend>, builder: &'a mut FunctionBuilder<'b>, variables: HashMap<&'static str, Variable>, //builtins: HashMap<&'static str, Function>, } impl<'a, 'b> Compiler<'a, 'b> { fn new(module: &'a mut Module<SimpleJITBackend>, builder: &'a mut FunctionBuilder<'b>) -> Self { Compiler { module, builder, variables: HashMap::new(), //builtins: HashMap::new() } } fn new_variable(&mut self, name: &'static str, idx: usize, typ: Type, init: Option<Value>) { let var = Variable::new(idx); self.builder.declare_var(var, typ); if let Some(val) = init { self.builder.def_var(var, val); } self.variables.insert(name, var); } fn use_variable(&mut self, name: &'static str) -> Value { self.builder.use_var(self.variables[name]) } fn compile_expression(&mut self, expr: &Object) -> Result<(Value, Value)> { if is_self_evaluating(expr) { self.compile_self_evaluating(expr) } else if is_variable(expr) { self.compile_variable(expr) } else if is_hardcoded(expr) { self.compile_hardcoded(expr) } else if is_definition(expr) { self.compile_definition(expr) } else if is_lambda(expr) { self.compile_lambda(expr) } else if is_application(expr) { self.compile_application(expr) } else { Err(ErrorKind::UnknownExpressionType(expr.clone()).into()) } } fn compile_self_evaluating(&mut self, expr: &Object) -> Result<(Value, Value)> { if expr.is_integer() { Ok(self.make_integer(expr.try_as_integer().unwrap())) } else if expr.is_float() { Ok(self.make_float(expr.try_as_float().unwrap())) } else { unimplemented!() } } fn compile_variable(&mut self, expr: &Object) -> Result<(Value, Value)> { let (tag, val) = self.make_symbol(expr.symbol_name().unwrap()); let mut sig = self.module.make_signature(); sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(types::I8)); sig.params.push(AbiParam::new(types::I64)); sig.returns.push(AbiParam::new(types::I8)); sig.returns.push(AbiParam::new(types::I64)); let lookup_decl = self .module .declare_function("lookup", Linkage::Import, &sig) .unwrap(); let lookup = self .module .declare_func_in_func(lookup_decl, self.builder.func); let env = self.use_variable("env"); let call = self.builder.ins().call(lookup, &[env, tag, val]); let results = self.builder.inst_results(call); Ok((results[0], results[1])) } fn compile_hardcoded(&mut self, expr: &Object) -> Result<(Value, Value)> { let lhs = self.compile_expression(expr.get_ref(1).unwrap())?; let rhs = self.compile_expression(expr.get_ref(2).unwrap())?; let result = match expr.get_ref(0).and_then(Object::symbol_name) { Some("+") => self.builder.ins().iadd(lhs.1, rhs.1), Some("-") => self.builder.ins().isub(lhs.1, rhs.1), Some("*") => self.builder.ins().imul(lhs.1, rhs.1), Some("/") => self.builder.ins().sdiv(lhs.1, rhs.1), _ => unreachable!(), }; Ok(self.cast_integer(result)) } fn compile_definition(&mut self, expr: &Object) -> Result<(Value, Value)> { let (var_tag, var_val) = self.make_symbol(definition_variable(expr).symbol_name().unwrap()); let (val_tag, val_val) = self.compile_expression(definition_value(expr))?; let mut sig = self.module.make_signature(); sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(types::I8)); sig.params.push(AbiParam::new(types::I64)); sig.params.push(AbiParam::new(types::I8)); sig.params.push(AbiParam::new(types::I64)); let define_decl = self .module .declare_function("define", Linkage::Import, &sig) .unwrap(); let define = self .module .declare_func_in_func(define_decl, self.builder.func); let env = self.use_variable("env"); self.builder .ins() .call(define, &[env, var_tag, var_val, val_tag, val_val]); Ok(self.make_undef()) } fn compile_lambda(&mut self, expr: &Object) -> Result<(Value, Value)> { let func_id = compile_function( self.module, lambda_params(&expr), lambda_body(&expr), "lambda", )?; let func_ref = self.module.declare_func_in_func(func_id, self.builder.func); let addr = self.builder.ins().func_addr(types::I64, func_ref); // TODO: automatically detect pointer size of target Ok(self.cast_function(addr)) } fn compile_application(&mut self, expr: &Object) -> Result<(Value, Value)> { let signature = make_dynamic_signature(self.module, get_operands(expr).len()); let sig = self.builder.func.import_signature(signature); let env = self.use_variable("env"); let proc = self.compile_expression(get_operator(expr))?; let args = self.compile_args(env, get_operands(expr))?; // TODO: check if proc is a function // TODO: check that signatures match let call = self.builder.ins().call_indirect(sig, proc.1, &args); let results = self.builder.inst_results(call); Ok((results[0], results[1])) } fn compile_args(&mut self, env: Value, args: &[Object]) -> Result<Vec<Value>> { let mut compiled_args = vec![]; compiled_args.push(env); for op in args { let (tag, val) = self.compile_expression(op)?; compiled_args.push(tag); compiled_args.push(val); } Ok(compiled_args) } fn make_undef(&mut self) -> (Value, Value) { let tag = self.builder.ins().iconst(types::I8, Tag::Undef as i64); let val = self.builder.ins().iconst(types::I64, 0); (tag, val) } fn make_integer(&mut self, value: i64) -> (Value, Value) { let tag = self.builder.ins().iconst(types::I8, Tag::Integer as i64); let val = self.builder.ins().iconst(types::I64, value); (tag, val) } fn cast_integer(&mut self, val: Value) -> (Value, Value) { let tag = self.builder.ins().iconst(types::I8, Tag::Integer as i64); (tag, val) } fn make_float(&mut self, value: f64) -> (Value, Value) { let tag = self.builder.ins().iconst(types::I8, Tag::Float as i64); let val = self.builder.ins().iconst(types::I64, unsafe { std::mem::transmute::<f64, i64>(value) }); (tag, val) } fn make_symbol(&mut self, name: &str) -> (Value, Value) { // TODO: get pointer or something that uniquely identifies the symbol // temporary workaround: use first character let tag = self.builder.ins().iconst(types::I8, Tag::Symbol as i64); let val = self .builder .ins() .iconst(types::I64, name.chars().next().unwrap() as i64); (tag, val) } fn cast_function(&mut self, func: Value) -> (Value, Value) { let tag = self.builder.ins().iconst(types::I8, Tag::Function as i64); (tag, func) } } fn make_dynamic_signature(module: &mut Module<SimpleJITBackend>, nargs: usize) -> Signature { let mut signature = module.make_signature(); // every function takes as first argument the current environment signature.params.push(AbiParam::new(types::I64)); for _ in 0..nargs { signature.params.push(AbiParam::new(types::I8)); signature.params.push(AbiParam::new(types::I64)); } signature.returns.push(AbiParam::new(types::I8)); signature.returns.push(AbiParam::new(types::I64)); signature } fn is_self_evaluating(expr: &Object) -> bool { expr.is_number() || expr.is_string() } fn is_variable(expr: &Object) -> bool { expr.is_symbol() } fn is_hardcoded(expr: &Object) -> bool { expr.car() .and_then(Object::symbol_name) .map(|name| ["+", "-", "*", "/"].contains(&name)) .unwrap_or(false) } fn is_definition(expr: &Object) -> bool { expr.car() .and_then(Object::symbol_name) .map(|name| name == "define") .unwrap_or(false) } fn definition_variable(expr: &Object) -> &Object { expr.get_ref(1).unwrap() } fn definition_value(expr: &Object) -> &Object { expr.get_ref(2).unwrap() } fn is_lambda(expr: &Object) -> bool { expr.car() .and_then(Object::symbol_name) .map(|name| name == "lambda") .unwrap_or(false) } fn lambda_params(expr: &Object) -> &Object { expr.get_ref(1).unwrap() } fn lambda_body(expr: &Object) -> &Object { expr.get_ref(2).unwrap() } fn is_application(expr: &Object) -> bool { expr.is_list() } fn get_operator(expr: &Object) -> &Object { expr.car().unwrap() } fn get_operands(_expr: &Object) -> &[Object] { //&expr.try_as_slice().unwrap()[1..] unimplemented!() } fn main() -> Result<()> { //use llvm_sys::execution_engine:: //ee = LLVMEng let global_environment = Environment::new(); let mut editor = Editor::<()>::new(); loop { match editor.readline("ready> ") { Ok(line) => { editor.add_history_entry(line.clone()); let expression = parse_datum(&line)?; // TODO: I'm not sure if we should reuse the module or create a new one every time. // Since functions cannot be dropped from modules, reusing would require // unique function names. I'm not sure if/how functions from different modules // can call each other, which is a requirement of recreating... let mut jb = SimpleJITBuilder::new(); jb.symbol("lookup", Environment::lookup as *const _); jb.symbol("define", Environment::define as *const _); let mut module = Module::new(jb); let top_fn = compile_top_level(&mut module, &expression)?; let result: Object = top_fn(&global_environment).into(); println!("{:?}", result); } Err(ReadlineError::Eof) => return Ok(()), Err(e) => eprintln!("{}", e.to_string()), } } }
#![allow(unused_imports)] use { crate::{ config::CONFIG, models::{ monitor::Monitor, rect::*, window_type::WindowType, windowwrapper::*, HandleState, }, state::State, wm, xlibwrapper::action, xlibwrapper::core::*, xlibwrapper::util::*, xlibwrapper::xlibmodels::*, }, reducer::*, std::cell::RefCell, std::rc::Rc, }; impl Reducer<action::ConfigurationRequest> for State { fn reduce(&mut self, action: action::ConfigurationRequest) { debug!( "ConfigurationRequest for window: {} - {:?}", action.win, action.win_changes ); let mon_id = match wm::get_mon_by_window(&self, action.win) { Some(mon_id) => mon_id, None => { self.lib .configure_window(action.win, action.value_mask as i64, action.win_changes); return; } }; let mon = self .monitors .get_mut(&mon_id) .expect("ConfigurationRequest - monitor - get_mut"); if mon.contains_window(action.win) { let ws = mon.get_ws_by_window(action.win).unwrap(); let ww = mon .remove_window_non_current(action.win, ws) .expect("ConfigurationRequest - monitor - remove_window"); self.lib.configure_window( action.win, action.value_mask as i64, WindowChanges { x: ww.window_rect.get_position().x, y: ww.window_rect.get_position().y, width: ww.window_rect.get_size().width, height: ww.window_rect.get_size().height, ..action.win_changes }, ); mon.add_window_non_current(ww.window(), ww, ws); } } }
use hydroflow::{assert_graphvis_snapshots, hydroflow_syntax}; use multiplatform_test::multiplatform_test; #[multiplatform_test] pub fn test_reduce_tick() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<u32>(); let (result_send, mut result_recv) = hydroflow::util::unbounded_channel::<u32>(); let mut df = hydroflow::hydroflow_syntax! { source_stream(items_recv) -> reduce::<'tick>(|acc: &mut u32, next: u32| *acc += next) -> for_each(|v| result_send.send(v).unwrap()); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); items_send.send(1).unwrap(); items_send.send(2).unwrap(); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[3], &*hydroflow::util::collect_ready::<Vec<_>, _>(&mut result_recv) ); items_send.send(3).unwrap(); items_send.send(4).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[7], &*hydroflow::util::collect_ready::<Vec<_>, _>(&mut result_recv) ); } #[multiplatform_test] pub fn test_reduce_static() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<u32>(); let (result_send, mut result_recv) = hydroflow::util::unbounded_channel::<u32>(); let mut df = hydroflow::hydroflow_syntax! { source_stream(items_recv) -> reduce::<'static>(|acc: &mut u32, next: u32| *acc += next) -> for_each(|v| result_send.send(v).unwrap()); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); items_send.send(1).unwrap(); items_send.send(2).unwrap(); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[3], &*hydroflow::util::collect_ready::<Vec<_>, _>(&mut result_recv) ); items_send.send(3).unwrap(); items_send.send(4).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); assert_eq!( &[10], &*hydroflow::util::collect_ready::<Vec<_>, _>(&mut result_recv) ); } #[multiplatform_test] pub fn test_reduce_sum() { let (items_send, items_recv) = hydroflow::util::unbounded_channel::<usize>(); let mut df = hydroflow_syntax! { source_stream(items_recv) -> reduce(|a: &mut _, b| *a += b) -> for_each(|v| print!("{:?}", v)); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); print!("\nA: "); items_send.send(9).unwrap(); items_send.send(2).unwrap(); items_send.send(5).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); print!("\nB: "); items_send.send(9).unwrap(); items_send.send(5).unwrap(); items_send.send(2).unwrap(); items_send.send(0).unwrap(); items_send.send(3).unwrap(); df.run_tick(); assert_eq!((3, 0), (df.current_tick(), df.current_stratum())); println!(); } /// This tests graph reachability along with an accumulation (in this case sum of vertex ids). /// This is to test fixed-point being reched before the accumulation running. #[multiplatform_test] pub fn test_reduce() { // An edge in the input data = a pair of `usize` vertex IDs. let (pairs_send, pairs_recv) = hydroflow::util::unbounded_channel::<(usize, usize)>(); let mut df = hydroflow_syntax! { reached_vertices = union() -> map(|v| (v, ())); source_iter(vec![0]) -> [0]reached_vertices; my_join_tee = join() -> map(|(_src, ((), dst))| dst) -> tee(); reached_vertices -> [0]my_join_tee; source_stream(pairs_recv) -> [1]my_join_tee; my_join_tee[0] -> [1]reached_vertices; my_join_tee[1] -> reduce(|a: &mut _, b| *a += b) -> for_each(|sum| println!("{}", sum)); }; assert_graphvis_snapshots!(df); assert_eq!((0, 0), (df.current_tick(), df.current_stratum())); df.run_tick(); assert_eq!((1, 0), (df.current_tick(), df.current_stratum())); println!("A"); pairs_send.send((0, 1)).unwrap(); pairs_send.send((2, 4)).unwrap(); pairs_send.send((3, 4)).unwrap(); pairs_send.send((1, 2)).unwrap(); df.run_tick(); assert_eq!((2, 0), (df.current_tick(), df.current_stratum())); println!("B"); pairs_send.send((0, 3)).unwrap(); pairs_send.send((0, 3)).unwrap(); df.run_tick(); assert_eq!((3, 0), (df.current_tick(), df.current_stratum())); }
enum Foo { Bar, } fn abc(x: &Foo) { let mut p = x; while let Foo::Bar = *p { p = x; } } fn main() {} /* thread 'rustc' panicked at 'no entry found for key', prusti-viper/src/encoder/procedure_encoder.rs:5876:10 stack backtrace: 0: rust_begin_unwind at /rustc/8007b506ac5da629f223b755f5a5391edd5f6d01/library/std/src/panicking.rs:517:5 1: core::panicking::panic_fmt at /rustc/8007b506ac5da629f223b755f5a5391edd5f6d01/library/core/src/panicking.rs:93:14 2: core::option::expect_failed at /rustc/8007b506ac5da629f223b755f5a5391edd5f6d01/library/core/src/option.rs:1618:5 3: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::construct_vir_reborrowing_dag 4: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_expiration_of_loans 5: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_blocks_group 6: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_loop 7: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_blocks_group 8: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode 9: prusti_viper::encoder::encoder::Encoder::encode_procedure 10: prusti_viper::encoder::encoder::Encoder::process_encoding_queue 11: prusti_viper::verifier::Verifier::verify 12: prusti_driver::verifier::verify 13: <prusti_driver::callbacks::PrustiCompilerCalls as rustc_driver::Callbacks>::after_analysis 14: rustc_interface::queries::<impl rustc_interface::interface::Compiler>::enter 15: rustc_span::with_source_map 16: rustc_interface::interface::create_compiler_and_run 17: scoped_tls::ScopedKey<T>::set */
use crate::lc3::{consts::Register, LC3}; use std::io::{self, Read}; /// Implementations of the trap routines in the LC3 architecture. /// /// Every method has the same type: `fn(&mut LC3)`, which makes it easy to create function dispatch /// tables for trap codes. pub fn puts(vm: &mut LC3) { // build up a string by looking for 16 bit integers until we hit the null terminator. The // starting location of the string is whatever is at the r0 register let start_pos = vm.registers[Register::R0 as usize] as usize; let end_pos = vm .memory .iter() .skip(start_pos) .position(|x| *x == 0) .unwrap(); print!( "{}", String::from_utf16_lossy(&vm.memory[start_pos..end_pos]) ); } pub fn getc(vm: &mut LC3) { // Get the next character from stdin and convert it to a 16 bit integer so we can store it // in the R0 register let c = io::stdin() .bytes() .next() .and_then(|result| result.ok()) .map(u16::from) .unwrap_or(0); vm.registers[Register::R0 as usize] = c; } pub fn out(vm: &mut LC3) { let r0 = vm.registers[Register::R0 as usize]; let character = String::from_utf16_lossy(&[r0]); print!("{}", character); } pub fn r#in(vm: &mut LC3) { print!("Enter a character: "); let raw_c = io::stdin() .bytes() .next() // We use the `and_then` call because there is no native cast from a u8 to a u16, so we // have to promote the type from a `Result` type and do a primitive cast from u8 -> // u16. .and_then(|result| result.ok()) .map(u16::from) .unwrap_or(0); let character = String::from_utf16_lossy(&[raw_c]); println!("{}", character); vm.registers[Register::R0 as usize] = raw_c; } pub fn putsp(vm: &mut LC3) { let start_pos = vm.registers[Register::R0 as usize] as usize; let end_pos = vm .memory .iter() .skip(start_pos) .position(|x| *x == 0) .unwrap(); for &c in &vm.registers[start_pos..end_pos] { let char1 = vec![(c & 0xFF) as u8]; let s = String::from_utf8_lossy(char1.as_slice()); print!("{}", s); let char2 = vec![(c >> 8) as u8]; let s = String::from_utf8_lossy(char2.as_slice()); print!("{}", s); } } pub fn halt(vm: &mut LC3) { print!("HALT"); vm.running = false; }
/* Copyright (C) 2018-2019 de4dot@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use super::super::*; #[cfg(not(feature = "std"))] use alloc::vec::Vec; pub(crate) fn get_tests() -> Vec<(u32, &'static str, Instruction)> { let mut v = Vec::with_capacity(INFOS16.len() + INFOS32.len() + INFOS64.len()); for &(hex_bytes, instr) in &*INFOS16 { v.push((16, hex_bytes, instr)); } for &(hex_bytes, instr) in &*INFOS32 { v.push((32, hex_bytes, instr)); } for &(hex_bytes, instr) in &*INFOS64 { v.push((64, hex_bytes, instr)); } v } #[cfg(any(feature = "gas", feature = "intel", feature = "masm", feature = "nasm"))] pub(crate) fn get_infos(bitness: u32) -> &'static Vec<(&'static str, Instruction)> { match bitness { 16 => &*INFOS16, 32 => &*INFOS32, 64 => &*INFOS64, _ => unreachable!(), } } fn c16(mut instruction: Instruction) -> Instruction { instruction.set_code_size(CodeSize::Code16); instruction } fn c32(mut instruction: Instruction) -> Instruction { instruction.set_code_size(CodeSize::Code32); instruction } fn c64(mut instruction: Instruction) -> Instruction { instruction.set_code_size(CodeSize::Code64); instruction } lazy_static! { static ref INFOS16: Vec<(&'static str, Instruction)> = { #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array = [ ("0F", c16(Instruction::with_reg(Code::Popw_CS, Register::CS))), ("9B D9 30", c16(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 D9 30", c16(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B 66 D9 30", c16(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 66 D9 30", c16(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B D9 38", c16(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 D9 38", c16(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B DB E0", c16(Instruction::with(Code::Feni))), ("9B DB E1", c16(Instruction::with(Code::Fdisi))), ("9B DB E2", c16(Instruction::with(Code::Fclex))), ("9B DB E3", c16(Instruction::with(Code::Finit))), ("9B DB E4", c16(Instruction::with(Code::Fsetpm))), ("9B DD 30", c16(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 DD 30", c16(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B 66 DD 30", c16(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 66 DD 30", c16(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B DD 38", c16(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::None)))), ("9B 64 DD 38", c16(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::BX, Register::SI, 1, 0, 0, false, Register::FS)))), ("9B DF E0", c16(Instruction::with_reg(Code::Fstsw_AX, Register::AX))), ("9B DF E1", c16(Instruction::with_reg(Code::Fstdw_AX, Register::AX))), ("9B DF E2", c16(Instruction::with_reg(Code::Fstsg_AX, Register::AX))), ]; #[cfg(not(feature = "db"))] let array_db: [(&'static str, Instruction); 0] = []; #[cfg(feature = "db")] #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array_db = [ ("77", c16(Instruction::with_declare_byte_1(0x77))), ("77 A9", c16(Instruction::with_declare_byte_2(0x77, 0xA9))), ("77 A9 CE", c16(Instruction::with_declare_byte_3(0x77, 0xA9, 0xCE))), ("77 A9 CE 9D", c16(Instruction::with_declare_byte_4(0x77, 0xA9, 0xCE, 0x9D))), ("77 A9 CE 9D 55", c16(Instruction::with_declare_byte_5(0x77, 0xA9, 0xCE, 0x9D, 0x55))), ("77 A9 CE 9D 55 05", c16(Instruction::with_declare_byte_6(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05))), ("77 A9 CE 9D 55 05 42", c16(Instruction::with_declare_byte_7(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42))), ("77 A9 CE 9D 55 05 42 6C", c16(Instruction::with_declare_byte_8(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C))), ("77 A9 CE 9D 55 05 42 6C 86", c16(Instruction::with_declare_byte_9(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86))), ("77 A9 CE 9D 55 05 42 6C 86 32", c16(Instruction::with_declare_byte_10(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE", c16(Instruction::with_declare_byte_11(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F", c16(Instruction::with_declare_byte_12(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34", c16(Instruction::with_declare_byte_13(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27", c16(Instruction::with_declare_byte_14(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA", c16(Instruction::with_declare_byte_15(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA 08", c16(Instruction::with_declare_byte_16(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA, 0x08))), ("A977", c16(Instruction::with_declare_word_1(0x77A9))), ("A977 9DCE", c16(Instruction::with_declare_word_2(0x77A9, 0xCE9D))), ("A977 9DCE 0555", c16(Instruction::with_declare_word_3(0x77A9, 0xCE9D, 0x5505))), ("A977 9DCE 0555 6C42", c16(Instruction::with_declare_word_4(0x77A9, 0xCE9D, 0x5505, 0x426C))), ("A977 9DCE 0555 6C42 3286", c16(Instruction::with_declare_word_5(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632))), ("A977 9DCE 0555 6C42 3286 4FFE", c16(Instruction::with_declare_word_6(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F))), ("A977 9DCE 0555 6C42 3286 4FFE 2734", c16(Instruction::with_declare_word_7(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427))), ("A977 9DCE 0555 6C42 3286 4FFE 2734 08AA", c16(Instruction::with_declare_word_8(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427, 0xAA08))), ("9DCEA977", c16(Instruction::with_declare_dword_1(0x77A9_CE9D))), ("9DCEA977 6C420555", c16(Instruction::with_declare_dword_2(0x77A9_CE9D, 0x5505_426C))), ("9DCEA977 6C420555 4FFE3286", c16(Instruction::with_declare_dword_3(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F))), ("9DCEA977 6C420555 4FFE3286 08AA2734", c16(Instruction::with_declare_dword_4(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F, 0x3427_AA08))), ("6C4205559DCEA977", c16(Instruction::with_declare_qword_1(0x77A9_CE9D_5505_426C))), ("6C4205559DCEA977 08AA27344FFE3286", c16(Instruction::with_declare_qword_2(0x77A9_CE9D_5505_426C, 0x8632_FE4F_3427_AA08))), ]; array.iter().cloned().chain(array_db.iter().cloned()).collect() }; } lazy_static! { static ref INFOS32: Vec<(&'static str, Instruction)> = { #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array = [ ("66 0F", c32(Instruction::with_reg(Code::Popw_CS, Register::CS))), ("9B 66 D9 30", c32(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 66 D9 30", c32(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B D9 30", c32(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 D9 30", c32(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B D9 38", c32(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 D9 38", c32(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DB E0", c32(Instruction::with(Code::Feni))), ("9B DB E1", c32(Instruction::with(Code::Fdisi))), ("9B DB E2", c32(Instruction::with(Code::Fclex))), ("9B DB E3", c32(Instruction::with(Code::Finit))), ("9B DB E4", c32(Instruction::with(Code::Fsetpm))), ("9B 66 DD 30", c32(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 66 DD 30", c32(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DD 30", c32(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 DD 30", c32(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DD 38", c32(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 DD 38", c32(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::EAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DF E0", c32(Instruction::with_reg(Code::Fstsw_AX, Register::AX))), ("9B DF E1", c32(Instruction::with_reg(Code::Fstdw_AX, Register::AX))), ("9B DF E2", c32(Instruction::with_reg(Code::Fstsg_AX, Register::AX))), ]; #[cfg(not(feature = "db"))] let array_db: [(&'static str, Instruction); 0] = []; #[cfg(feature = "db")] #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array_db = [ ("77", c32(Instruction::with_declare_byte_1(0x77))), ("77 A9", c32(Instruction::with_declare_byte_2(0x77, 0xA9))), ("77 A9 CE", c32(Instruction::with_declare_byte_3(0x77, 0xA9, 0xCE))), ("77 A9 CE 9D", c32(Instruction::with_declare_byte_4(0x77, 0xA9, 0xCE, 0x9D))), ("77 A9 CE 9D 55", c32(Instruction::with_declare_byte_5(0x77, 0xA9, 0xCE, 0x9D, 0x55))), ("77 A9 CE 9D 55 05", c32(Instruction::with_declare_byte_6(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05))), ("77 A9 CE 9D 55 05 42", c32(Instruction::with_declare_byte_7(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42))), ("77 A9 CE 9D 55 05 42 6C", c32(Instruction::with_declare_byte_8(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C))), ("77 A9 CE 9D 55 05 42 6C 86", c32(Instruction::with_declare_byte_9(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86))), ("77 A9 CE 9D 55 05 42 6C 86 32", c32(Instruction::with_declare_byte_10(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE", c32(Instruction::with_declare_byte_11(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F", c32(Instruction::with_declare_byte_12(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34", c32(Instruction::with_declare_byte_13(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27", c32(Instruction::with_declare_byte_14(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA", c32(Instruction::with_declare_byte_15(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA 08", c32(Instruction::with_declare_byte_16(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA, 0x08))), ("A977", c32(Instruction::with_declare_word_1(0x77A9))), ("A977 9DCE", c32(Instruction::with_declare_word_2(0x77A9, 0xCE9D))), ("A977 9DCE 0555", c32(Instruction::with_declare_word_3(0x77A9, 0xCE9D, 0x5505))), ("A977 9DCE 0555 6C42", c32(Instruction::with_declare_word_4(0x77A9, 0xCE9D, 0x5505, 0x426C))), ("A977 9DCE 0555 6C42 3286", c32(Instruction::with_declare_word_5(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632))), ("A977 9DCE 0555 6C42 3286 4FFE", c32(Instruction::with_declare_word_6(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F))), ("A977 9DCE 0555 6C42 3286 4FFE 2734", c32(Instruction::with_declare_word_7(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427))), ("A977 9DCE 0555 6C42 3286 4FFE 2734 08AA", c32(Instruction::with_declare_word_8(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427, 0xAA08))), ("9DCEA977", c32(Instruction::with_declare_dword_1(0x77A9_CE9D))), ("9DCEA977 6C420555", c32(Instruction::with_declare_dword_2(0x77A9_CE9D, 0x5505_426C))), ("9DCEA977 6C420555 4FFE3286", c32(Instruction::with_declare_dword_3(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F))), ("9DCEA977 6C420555 4FFE3286 08AA2734", c32(Instruction::with_declare_dword_4(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F, 0x3427_AA08))), ("6C4205559DCEA977", c32(Instruction::with_declare_qword_1(0x77A9_CE9D_5505_426C))), ("6C4205559DCEA977 08AA27344FFE3286", c32(Instruction::with_declare_qword_2(0x77A9_CE9D_5505_426C, 0x8632_FE4F_3427_AA08))), ]; array.iter().cloned().chain(array_db.iter().cloned()).collect() }; } lazy_static! { static ref INFOS64: Vec<(&'static str, Instruction)> = { #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array = [ ("9B 66 D9 30", c64(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 66 D9 30", c64(Instruction::with_mem(Code::Fstenv_m14byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B D9 30", c64(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 D9 30", c64(Instruction::with_mem(Code::Fstenv_m28byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B D9 38", c64(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 D9 38", c64(Instruction::with_mem(Code::Fstcw_m2byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DB E0", c64(Instruction::with(Code::Feni))), ("9B DB E1", c64(Instruction::with(Code::Fdisi))), ("9B DB E2", c64(Instruction::with(Code::Fclex))), ("9B DB E3", c64(Instruction::with(Code::Finit))), ("9B DB E4", c64(Instruction::with(Code::Fsetpm))), ("9B 66 DD 30", c64(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 66 DD 30", c64(Instruction::with_mem(Code::Fsave_m94byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DD 30", c64(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 DD 30", c64(Instruction::with_mem(Code::Fsave_m108byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DD 38", c64(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::None)))), ("9B 64 DD 38", c64(Instruction::with_mem(Code::Fstsw_m2byte, MemoryOperand::new(Register::RAX, Register::None, 1, 0, 0, false, Register::FS)))), ("9B DF E0", c64(Instruction::with_reg(Code::Fstsw_AX, Register::AX))), ]; #[cfg(not(feature = "db"))] let array_db: [(&'static str, Instruction); 0] = []; #[cfg(feature = "db")] #[cfg_attr(feature = "cargo-fmt", rustfmt::skip)] let array_db = [ ("77", c64(Instruction::with_declare_byte_1(0x77))), ("77 A9", c64(Instruction::with_declare_byte_2(0x77, 0xA9))), ("77 A9 CE", c64(Instruction::with_declare_byte_3(0x77, 0xA9, 0xCE))), ("77 A9 CE 9D", c64(Instruction::with_declare_byte_4(0x77, 0xA9, 0xCE, 0x9D))), ("77 A9 CE 9D 55", c64(Instruction::with_declare_byte_5(0x77, 0xA9, 0xCE, 0x9D, 0x55))), ("77 A9 CE 9D 55 05", c64(Instruction::with_declare_byte_6(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05))), ("77 A9 CE 9D 55 05 42", c64(Instruction::with_declare_byte_7(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42))), ("77 A9 CE 9D 55 05 42 6C", c64(Instruction::with_declare_byte_8(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C))), ("77 A9 CE 9D 55 05 42 6C 86", c64(Instruction::with_declare_byte_9(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86))), ("77 A9 CE 9D 55 05 42 6C 86 32", c64(Instruction::with_declare_byte_10(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE", c64(Instruction::with_declare_byte_11(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F", c64(Instruction::with_declare_byte_12(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34", c64(Instruction::with_declare_byte_13(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27", c64(Instruction::with_declare_byte_14(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA", c64(Instruction::with_declare_byte_15(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA))), ("77 A9 CE 9D 55 05 42 6C 86 32 FE 4F 34 27 AA 08", c64(Instruction::with_declare_byte_16(0x77, 0xA9, 0xCE, 0x9D, 0x55, 0x05, 0x42, 0x6C, 0x86, 0x32, 0xFE, 0x4F, 0x34, 0x27, 0xAA, 0x08))), ("A977", c64(Instruction::with_declare_word_1(0x77A9))), ("A977 9DCE", c64(Instruction::with_declare_word_2(0x77A9, 0xCE9D))), ("A977 9DCE 0555", c64(Instruction::with_declare_word_3(0x77A9, 0xCE9D, 0x5505))), ("A977 9DCE 0555 6C42", c64(Instruction::with_declare_word_4(0x77A9, 0xCE9D, 0x5505, 0x426C))), ("A977 9DCE 0555 6C42 3286", c64(Instruction::with_declare_word_5(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632))), ("A977 9DCE 0555 6C42 3286 4FFE", c64(Instruction::with_declare_word_6(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F))), ("A977 9DCE 0555 6C42 3286 4FFE 2734", c64(Instruction::with_declare_word_7(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427))), ("A977 9DCE 0555 6C42 3286 4FFE 2734 08AA", c64(Instruction::with_declare_word_8(0x77A9, 0xCE9D, 0x5505, 0x426C, 0x8632, 0xFE4F, 0x3427, 0xAA08))), ("9DCEA977", c64(Instruction::with_declare_dword_1(0x77A9_CE9D))), ("9DCEA977 6C420555", c64(Instruction::with_declare_dword_2(0x77A9_CE9D, 0x5505_426C))), ("9DCEA977 6C420555 4FFE3286", c64(Instruction::with_declare_dword_3(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F))), ("9DCEA977 6C420555 4FFE3286 08AA2734", c64(Instruction::with_declare_dword_4(0x77A9_CE9D, 0x5505_426C, 0x8632_FE4F, 0x3427_AA08))), ("6C4205559DCEA977", c64(Instruction::with_declare_qword_1(0x77A9_CE9D_5505_426C))), ("6C4205559DCEA977 08AA27344FFE3286", c64(Instruction::with_declare_qword_2(0x77A9_CE9D_5505_426C, 0x8632_FE4F_3427_AA08))), ]; array.iter().cloned().chain(array_db.iter().cloned()).collect() }; }