text
stringlengths
8
4.13M
mod models; mod parser; mod pretty_printer; use crate::parser::get_functions; use crate::pretty_printer::print_script; use colored::*; use structopt::StructOpt; /// Run or list the contents of a script #[derive(StructOpt)] struct Cli { /// The path to the script to describe or run. #[structopt(parse(from_os_str))] script: std::path::PathBuf, /// The name of the function to run. This will not run the function, it will just validate that it exists. function: Option<String>, /// Optional params for the function. We're not processing them yet (e.g. validating) but /// they need to be permitted as a param to runsh. #[allow(dead_code)] params: Vec<String>, } fn main() { let args = Cli::from_args(); match get_functions(&args.script) { Ok(script) => match &args.function { Some(function_to_run) => { match script .functions .iter() .find(|&n| &n.name == function_to_run) { Some(_) => { // Found a valid function. We're going to return a non-0 exit code // so the script knows that it can go ahead and run the function. std::process::exit(78); } None => { println!("{}", "Function does not exist!\n".red()); print_script(script); } } } None => { print_script(script); } }, Err(_) => { let script = &args.script.into_os_string().into_string().unwrap(); println!( "{} {}", "Unable to get functions from".red(), script.green() ); } } }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // This should resolve fine. Prior to fix, the last import // was being tried too early, and marked as unrsolved before // the glob import had a chance to be resolved. mod bar { pub use self::middle::*; mod middle { pub use self::baz::Baz; mod baz { pub enum Baz { Baz1, Baz2 } } } } mod foo { use bar::Baz::{Baz1, Baz2}; } fn main() {}
extern crate core; use self::core::ptr; use std::sync::Arc; use std::sync::atomic::Ordering; use super::buffer::{Buffer, value_ptr}; use super::concurrent_queue::ConcurrentQueue; /// A bounded queue allowing a single producer and a single consumer. pub struct SpscConcurrentQueue<T> { buffer: Buffer<T> } impl<T> SpscConcurrentQueue<T> { /// Creates a single producer single consumer queue with the specified /// capacity. /// /// # Examples /// /// ``` /// use cosmo::collection::{ConcurrentQueue, SpscConcurrentQueue}; /// let q = SpscConcurrentQueue::<u64>::with_capacity(1024); /// assert_eq!(1024, q.capacity()); /// ``` pub fn with_capacity(initial_capacity: usize) -> Arc<SpscConcurrentQueue<T>> { Arc::new(SpscConcurrentQueue { buffer: Buffer::with_capacity(initial_capacity) }) } } impl<T: Clone> SpscConcurrentQueue<T> { /// Tries to peek a value from the queue. The value needs to be Clone /// since the value in the queue can't be moved out. /// /// If the queue is not empty, the method returns `Some(v)`, where `v` is /// the value at the head of the queue. If the queue is empty, it returns /// `None`. /// /// # Examples /// /// ``` /// use cosmo::collection::{ConcurrentQueue, SpscConcurrentQueue}; /// let queue = SpscConcurrentQueue::<u64>::with_capacity(16); /// match queue.peek() { /// Some(v) => println!("Peeked value {}", v), /// None => println!("Queue is empty") /// } /// ``` pub fn peek(&self) -> Option<T> { let index = self.buffer.head.load(Ordering::Relaxed); unsafe { let item = self.buffer.item(index); if item.is_defined.load(Ordering::Acquire) { Some((&*value_ptr(item)).clone()) } else { None } } } } impl<T> ConcurrentQueue<T> for SpscConcurrentQueue<T> { /// Puts an item in the queue. This method only reads and modifies the /// `tail` index, thus avoiding cache line ping-ponging. /// /// # Examples /// /// ``` /// use cosmo::collection::{ConcurrentQueue, SpscConcurrentQueue}; /// let q = SpscConcurrentQueue::<u64>::with_capacity(1024); /// assert_eq!(None, q.offer(10)); /// ``` fn offer(&self, val: T) -> Option<T> { let index = self.buffer.tail.load(Ordering::Relaxed); unsafe { let item = self.buffer.item(index); if item.is_defined.load(Ordering::Acquire) { return Some(val) } self.buffer.tail.store(index + 1, Ordering::Relaxed); ptr::write(value_ptr(item), val); item.is_defined.store(true, Ordering::Release); None } } /// Takes an item from the queue. This method only reads and modifies the /// `head` index. /// /// # Example /// /// ``` /// use cosmo::collection::{ConcurrentQueue, SpscConcurrentQueue}; /// let q = SpscConcurrentQueue::<u64>::with_capacity(1024); /// q.offer(10); /// assert_eq!(Some(10), q.poll()); /// ``` fn poll(&self) -> Option<T> { let index = self.buffer.head.load(Ordering::Relaxed); unsafe { let item = self.buffer.item(index); if !item.is_defined.load(Ordering::Acquire) { return None; } self.buffer.head.store(index + 1, Ordering::Relaxed); let res = ptr::read(value_ptr(item)); item.is_defined.store(false, Ordering::Release); Some(res) } } /// Returns the capacity of the queue. fn capacity(&self) -> usize { self.buffer.capacity } /// Returns how many items are in the queue. fn size(&self) -> usize { self.buffer.size() } } #[cfg(test)] mod test { use super::core::mem; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; use std::thread; use super::SpscConcurrentQueue; use super::super::concurrent_queue::ConcurrentQueue; #[test] fn capacity_is_next_power_of_two() { assert_eq!(16, SpscConcurrentQueue::<i32>::with_capacity(10).capacity()); } #[test] fn adds_and_removes_a_value() { let q = SpscConcurrentQueue::<i32>::with_capacity(2); assert_eq!(None, q.offer(34)); assert_eq!(Some(34), q.poll()); } #[test] fn gets_full() { let q = SpscConcurrentQueue::<i32>::with_capacity(2); assert_eq!(None, q.offer(1)); assert_eq!(None, q.offer(2)); assert_eq!(Some(3), q.offer(3)); assert!(q.is_full()); } #[test] fn gets_empty() { let q = SpscConcurrentQueue::<i32>::with_capacity(2); assert_eq!(None, q.poll()); assert!(q.is_empty()); } #[test] fn peeks_a_value() { let q = SpscConcurrentQueue::<i32>::with_capacity(2); assert_eq!(None, q.offer(34)); assert_eq!(Some(34), q.peek()); assert_eq!(Some(34), q.poll()); assert_eq!(None, q.poll()); } #[derive(Debug)] struct Payload { value: u64, dropped: Arc<AtomicBool> } impl Clone for Payload { fn clone(&self) -> Payload { let is_dropped = self.dropped.load(Ordering::Relaxed); Payload { value: self.value, dropped: Arc::new(AtomicBool::new(is_dropped)) } } } impl Drop for Payload { fn drop(&mut self) { self.dropped.store(true, Ordering::Relaxed); } } impl PartialEq<Payload> for Payload { fn eq(&self, other: &Payload) -> bool { self.value == other.value } } #[test] fn items_are_moved() { let q = SpscConcurrentQueue::<Payload>::with_capacity(2); let dropped = Arc::new(AtomicBool::new(false)); let p1 = Payload { value: 67, dropped: dropped.clone() }; assert!(q.is_empty()); assert_eq!(None, q.offer(p1)); let p2 = q.poll().unwrap(); assert_eq!(67, p2.value); assert!(!dropped.load(Ordering::Relaxed)); mem::drop(p2); assert!(dropped.load(Ordering::Relaxed)); } #[test] fn peeked_items_are_cloned() { let q = SpscConcurrentQueue::<Payload>::with_capacity(2); let dropped = Arc::new(AtomicBool::new(false)); let p1 = Payload { value: 67, dropped: dropped.clone() }; assert!(q.is_empty()); assert_eq!(None, q.offer(p1)); let p2 = q.peek().unwrap(); let dropped2 = p2.dropped.clone(); assert_eq!(67, p2.value); assert!(!dropped.load(Ordering::Relaxed)); assert!(!dropped2.load(Ordering::Relaxed)); mem::drop(p2); assert!(!dropped.load(Ordering::Relaxed)); assert!(dropped2.load(Ordering::Relaxed)); } #[test] fn lost_items_are_dropped() { let q = SpscConcurrentQueue::<Payload>::with_capacity(2); let dropped = Arc::new(AtomicBool::new(false)); let p = Payload { value: 67, dropped: dropped.clone() }; assert_eq!(None, q.offer(p)); assert_eq!(1, q.size()); assert!(!dropped.load(Ordering::Relaxed)); mem::drop(q); assert!(dropped.load(Ordering::Relaxed)); } #[test] fn two_threads_can_add_and_remove() { const REPETITIONS: u64 = 10 * 1000 * 1000; let q = SpscConcurrentQueue::<u64>::with_capacity(1024); let barrier = Arc::new(Barrier::new(2)); let cb = barrier.clone(); let cq = q.clone(); let c = thread::spawn(move|| { cb.wait(); for i in 0..REPETITIONS { let mut opt: Option<u64>; while { opt = cq.poll(); opt.is_none() } { thread::yield_now(); } assert_eq!(i, opt.unwrap()); } }); let pc = barrier.clone(); let pq = q.clone(); let p = thread::spawn(move|| { pc.wait(); for i in 0..REPETITIONS { while pq.offer(i).is_some() { thread::yield_now(); } } }); c.join().unwrap(); p.join().unwrap(); } }
use async_graphql::{Context, FieldResult, Object}; use crud_crait::CRUD; use dataset::Dataset; use sqlx::MySqlPool; use user::User; pub struct QueryRoot; #[Object] impl QueryRoot { async fn users(&self, ctx: &Context<'_>) -> FieldResult<Vec<User>> { let pool = ctx.data_unchecked::<MySqlPool>(); let users = User::find_all(pool).await?; println!("users: {:?}", users); Ok(users) } async fn datasets(&self, ctx: &Context<'_>) -> FieldResult<Vec<Dataset>> { let pool = ctx.data_unchecked::<MySqlPool>(); // let datasets = Dataset::find_all(pool).await?; //println!("datasets: {:?}", datasets); Ok(vec![]) } }
use super::circular_unit::CircularUnit; use super::status::Status; pub trait LivingUnit: CircularUnit { fn life(&self) -> i32; fn max_life(&self) -> i32; fn statuses(&self) -> &Vec<Status>; } #[macro_export] macro_rules! living_unit_impl( ($t:ty) => ( impl LivingUnit for $t { fn life(&self) -> i32 { self.life() } fn max_life(&self) -> i32 { self.max_life() } fn statuses(&self) -> &Vec<Status> { &self.statuses() } } ) );
#[macro_use] extern crate bencher; extern crate image; extern crate color_thief; use std::path::Path; use bencher::Bencher; use color_thief::ColorFormat; fn get_image_buffer(img: image::DynamicImage) -> Vec<u8> { match img { image::DynamicImage::ImageRgb8(buffer) => buffer.to_vec(), _ => unreachable!(), } } fn q1(bencher: &mut Bencher) { let img = image::open(&Path::new("images/photo1.jpg")).unwrap(); let pixels = get_image_buffer(img); bencher.iter(|| color_thief::get_palette(&pixels, ColorFormat::Rgb, 1, 10)) } fn q10(bencher: &mut Bencher) { let img = image::open(&Path::new("images/photo1.jpg")).unwrap(); let pixels = get_image_buffer(img); bencher.iter(|| color_thief::get_palette(&pixels, ColorFormat::Rgb, 10, 10)) } benchmark_group!(benches, q1, q10); benchmark_main!(benches);
use std::collections::HashMap; fn can_hold_shiny_gold(bag_map : &HashMap<String, Vec<(u64, String)>>, bag : &str) -> bool { for (_count, bag_type) in &bag_map[bag] { if bag_type == "shiny gold" { return true; } if can_hold_shiny_gold(bag_map, &bag_type) { return true; } } return false; } fn how_many_bags_must_a_bag_hold(bag_map : &HashMap<String, Vec<(u64, String)>>, bag :&str) -> u64 { return bag_map[bag].iter() .map(|(count, bag_type)| { count * how_many_bags_must_a_bag_hold(bag_map, &bag_type) }) .sum::<u64>() + 1; // +1 for itself } fn main() { let mut bag_map = HashMap::new(); for line in aoc::read_lines_as_vec("./day7.txt") { let mut v = line.split(" bags contain "); let color = v.next().unwrap().to_string(); let contents : Vec<_> = v.next().unwrap().split(',') .map(|content| content.trim_matches(|c| c == ' ' || c == '.')) .map(|content| content.splitn(2, ' ')) // Split out the # from the type of bag // Parse the # and type into a tuple (count, type) .map(|mut split_result| (split_result.next().unwrap().parse::<u64>().unwrap_or(0), split_result.next().unwrap().split(" bag").nth(0).unwrap().to_string())) .filter(|(count, _)| count > &0) .collect(); bag_map.insert(color, contents); } let total1 = bag_map.iter().filter(|(bag_type, _contents)| can_hold_shiny_gold(&bag_map, &bag_type)).count(); println!("Total1: {}", total1); let total2 = how_many_bags_must_a_bag_hold(&bag_map, "shiny gold"); println!("Total2: {}", total2 - 1); // -1 to not include the shiny gold bag itself }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_catalog::plan::DataSourcePlan; use common_catalog::plan::Projection; use common_catalog::plan::PushDownInfo; use common_catalog::table_context::TableContext; use common_exception::ErrorCode; use common_exception::Result; use common_expression::DataSchema; use common_expression::DataSchemaRefExt; use common_expression::Expr; use common_expression::RemoteExpr; use common_expression::TableSchemaRef; use common_expression::TopKSorter; use common_functions::BUILTIN_FUNCTIONS; use common_pipeline_core::Pipeline; use storages_common_index::Index; use storages_common_index::RangeIndex; use super::ParquetTable; use crate::deserialize_transform::ParquetDeserializeTransform; use crate::deserialize_transform::ParquetPrewhereInfo; use crate::parquet_reader::ParquetReader; use crate::parquet_source::AsyncParquetSource; use crate::parquet_source::SyncParquetSource; impl ParquetTable { pub fn create_reader(&self, projection: Projection) -> Result<Arc<ParquetReader>> { ParquetReader::create(self.operator.clone(), self.arrow_schema.clone(), projection) } fn build_filter(filter: &RemoteExpr<String>, schema: &DataSchema) -> Expr { filter .as_expr(&BUILTIN_FUNCTIONS) .project_column_ref(|name| schema.index_of(name).unwrap()) } #[inline] pub(super) fn do_read_data( &self, ctx: Arc<dyn TableContext>, plan: &DataSourcePlan, pipeline: &mut Pipeline, ) -> Result<()> { let table_schema: TableSchemaRef = self.table_info.schema(); let source_projection = PushDownInfo::projection_of_push_downs(&table_schema, &plan.push_downs); // The front of the src_fields are prewhere columns (if exist). // The back of the src_fields are remain columns. let mut src_fields = Vec::with_capacity(source_projection.len()); // The schema of the data block `read_data` output. let output_schema: Arc<DataSchema> = Arc::new(plan.schema().into()); // Build the reader for parquet source. let source_reader = ParquetReader::create( self.operator.clone(), self.arrow_schema.clone(), source_projection, )?; // build top k information let top_k = plan .push_downs .as_ref() .map(|p| p.top_k(&table_schema, None, RangeIndex::supported_type)) .unwrap_or_default(); // Build prewhere info. let mut push_down_prewhere = PushDownInfo::prewhere_of_push_downs(&plan.push_downs); let top_k = if let Some((prewhere, top_k)) = push_down_prewhere.as_mut().zip(top_k) { // If there is a top k, we need to add the top k columns to the prewhere columns. if let RemoteExpr::<String>::ColumnRef { id, .. } = &plan.push_downs.as_ref().unwrap().order_by[0].0 { let index = table_schema.index_of(id)?; prewhere.remain_columns.remove_col(index); prewhere.prewhere_columns.add_col(index); Some((id.clone(), top_k)) } else { None } } else { None }; // Build remain reader. // If there is no prewhere filter, remain reader is the same as source reader (no prewhere phase, deserialize directly). let remain_reader = if let Some(p) = &push_down_prewhere { ParquetReader::create( self.operator.clone(), self.arrow_schema.clone(), p.remain_columns.clone(), )? } else { source_reader.clone() }; let prewhere_info = push_down_prewhere .map(|p| { let reader = ParquetReader::create( self.operator.clone(), self.arrow_schema.clone(), p.prewhere_columns, )?; src_fields.extend_from_slice(reader.output_schema.fields()); let filter = Self::build_filter(&p.filter, &reader.output_schema); let top_k = top_k.map(|(name, top_k)| { ( reader.output_schema.index_of(&name).unwrap(), TopKSorter::new(top_k.limit, top_k.asc), ) }); let func_ctx = ctx.get_function_context()?; Ok::<_, ErrorCode>(ParquetPrewhereInfo { func_ctx, reader, filter, top_k, }) }) .transpose()?; src_fields.extend_from_slice(remain_reader.output_schema.fields()); let src_schema = DataSchemaRefExt::create(src_fields); let max_threads = ctx.get_settings().get_max_threads()? as usize; // Add source pipe. if self.operator.info().can_blocking() { pipeline.add_source( |output| SyncParquetSource::create(ctx.clone(), output, source_reader.clone()), max_threads, )?; } else { let max_io_requests = std::cmp::max( max_threads, ctx.get_settings().get_max_storage_io_requests()? as usize, ); pipeline.add_source( |output| AsyncParquetSource::create(ctx.clone(), output, source_reader.clone()), max_io_requests, )?; pipeline.resize(std::cmp::min(max_threads, max_io_requests))?; } pipeline.add_transform(|input, output| { ParquetDeserializeTransform::create( ctx.clone(), input, output, src_schema.clone(), output_schema.clone(), prewhere_info.clone(), remain_reader.clone(), ) }) } }
use serde::Deserialize; use crate::apis::flight_provider::raw_models::airport_instance_country_raw::AirportInstanceCountryRaw; use crate::apis::flight_provider::raw_models::airport_instance_region_raw::AirportInstanceRegionRaw; #[derive(Deserialize, Debug)] pub struct AirportInstancePositionRaw { pub latitude: Option<f64>, pub longitude: Option<f64>, pub altitude: Option<f64>, pub country: Option<AirportInstanceCountryRaw>, pub region: Option<AirportInstanceRegionRaw>, }
//! SQL metadata tables (originally from [queryrouterd]) //! //! TODO: figure out how to generate these keywords automatically from DataFusion / sqlparser-rs //! //! [queryrouterd]: https://github.com/influxdata/idpe/blob/85aa7a52b40f173cc4d79ac02b3a4a13e82333c4/queryrouter/internal/server/flightsql_info.go#L4 pub(crate) const SQL_INFO_SQL_KEYWORDS: &[&str] = &[ // SQL-92 Reserved Words "absolute", "action", "add", "all", "allocate", "alter", "and", "any", "are", "as", "asc", "assertion", "at", "authorization", "avg", "begin", "between", "bit", "bit_length", "both", "by", "cascade", "cascaded", "case", "cast", "catalog", "char", "char_length", "character", "character_length", "check", "close", "coalesce", "collate", "collation", "column", "commit", "connect", "connection", "constraint", "constraints", "continue", "convert", "corresponding", "count", "create", "cross", "current", "current_date", "current_time", "current_timestamp", "current_user", "cursor", "date", "day", "deallocate", "dec", "decimal", "declare", "default", "deferrable", "deferred", "delete", "desc", "describe", "descriptor", "diagnostics", "disconnect", "distinct", "domain", "double", "drop", "else", "end", "end-exec", "escape", "except", "exception", "exec", "execute", "exists", "external", "extract", "false", "fetch", "first", "float", "for", "foreign", "found", "from", "full", "get", "global", "go", "goto", "grant", "group", "having", "hour", "identity", "immediate", "in", "indicator", "initially", "inner", "input", "insensitive", "insert", "int", "integer", "intersect", "interval", "into", "is", "isolation", "join", "key", "language", "last", "leading", "left", "level", "like", "local", "lower", "match", "max", "min", "minute", "module", "month", "names", "national", "natural", "nchar", "next", "no", "not", "null", "nullif", "numeric", "octet_length", "of", "on", "only", "open", "option", "or", "order", "outer", "output", "overlaps", "pad", "partial", "position", "precision", "prepare", "preserve", "primary", "prior", "privileges", "procedure", "public", "read", "real", "references", "relative", "restrict", "revoke", "right", "rollback", "rows", "schema", "scroll", "second", "section", "select", "session", "session_user", "set", "size", "smallint", "some", "space", "sql", "sqlcode", "sqlerror", "sqlstate", "substring", "sum", "system_user", "table", "temporary", "then", "time", "timestamp", "timezone_hour", "timezone_minute", "to", "trailing", "transaction", "translate", "translation", "trim", "true", "union", "unique", "unknown", "update", "upper", "usage", "user", "using", "value", "values", "varchar", "varying", "view", "when", "whenever", "where", "with", "work", "write", "year", "zone", ]; pub(crate) const SQL_INFO_NUMERIC_FUNCTIONS: &[&str] = &[ "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "ln", "log", "log10", "log2", "pow", "power", "round", "signum", "sin", "sqrt", "tan", "trunc", ]; pub(crate) const SQL_INFO_STRING_FUNCTIONS: &[&str] = &[ "arrow_typeof", "ascii", "bit_length", "btrim", "char_length", "character_length", "chr", "concat", "concat_ws", "digest", "from_unixtime", "initcap", "left", "length", "lower", "lpad", "ltrim", "md5", "octet_length", "random", "regexp_match", "regexp_replace", "repeat", "replace", "reverse", "right", "rpad", "rtrim", "sha224", "sha256", "sha384", "sha512", "split_part", "starts_with", "strpos", "substr", "to_hex", "translate", "trim", "upper", "uuid", ]; pub(crate) const SQL_INFO_DATE_TIME_FUNCTIONS: &[&str] = &[ "current_date", "current_time", "date_bin", "date_part", "date_trunc", "datepart", "datetrunc", "from_unixtime", "now", "to_timestamp", "to_timestamp_micros", "to_timestamp_millis", "to_timestamp_seconds", ]; pub(crate) const SQL_INFO_SYSTEM_FUNCTIONS: &[&str] = &["array", "arrow_typeof", "struct"];
/* This is about the simplest program that can successfully send a message. */ fn main() { let po: port[int] = port(); let ch: chan[int] = chan(po); ch <| 42; let r; po |> r; log_err r; }
// Copyright 2016-2018 Austin Bonander <austin.bonander@gmail.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use safemem; use std::cmp; use self::impl_::RawBuf; pub struct StdBuf { buf: RawBuf, pos: usize, end: usize, } impl StdBuf { pub fn with_capacity(cap: usize) -> Self { StdBuf { buf: RawBuf::with_capacity(cap), pos: 0, end: 0, } } pub fn capacity(&self) -> usize { self.buf.capacity() } pub fn len(&self) -> usize { self.end - self.pos } pub fn usable_space(&self) -> usize { self.capacity() - self.end } pub fn reserve(&mut self, additional: usize) -> bool { self.check_cursors(); let usable_space = self.usable_space(); // there's already enough space if usable_space >= additional { return false } // attempt to reserve additional capacity in-place if self.buf.reserve_in_place(additional - usable_space) { return false; } // don't copy the contents of the buffer as they're irrelevant now if self.pos == self.end { let capacity = self.buf.capacity(); // free the existing memory self.buf = RawBuf::with_capacity(0); self.buf = RawBuf::with_capacity(capacity + additional); return true; } self.buf.reserve(additional - usable_space) } pub fn make_room(&mut self) { self.check_cursors(); // no room at the head of the buffer if self.pos == 0 { return; } // simply move the bytes down to the beginning let len = self.len(); safemem::copy_over(unsafe { self.buf.as_mut_slice() }, self.pos, 0, len); self.pos = 0; self.end = len; } pub fn buf(&self) -> &[u8] { unsafe { &self.buf.as_slice()[self.pos .. self.end] } } pub fn buf_mut(&mut self) -> &mut [u8] { unsafe { &mut self.buf.as_mut_slice()[self.pos .. self.end] } } pub unsafe fn write_buf(&mut self) -> &mut [u8] { &mut self.buf.as_mut_slice()[self.end ..] } pub unsafe fn bytes_written(&mut self, amt: usize) { self.end = cmp::min(self.end + amt, self.capacity()); } pub fn consume(&mut self, amt: usize) { self.pos = cmp::min(self.pos + amt, self.end); self.check_cursors(); } pub fn check_cursors(&mut self) -> bool { if self.pos == self.end { self.pos = 0; self.end = 0; true } else { false } } } #[cfg(not(feature = "nightly"))] mod impl_ { use std::mem; pub struct RawBuf { buf: Box<[u8]>, } impl RawBuf { pub fn with_capacity(capacity: usize) -> Self { let mut buf = Vec::with_capacity(capacity); let true_cap = buf.capacity(); unsafe { buf.set_len(true_cap); } RawBuf { buf: buf.into_boxed_slice(), } } pub fn capacity(&self) -> usize { self.buf.len() } pub fn reserve(&mut self, additional: usize) -> bool { let mut buf = mem::replace(&mut self.buf, Box::new([])).into_vec(); let old_ptr = self.buf.as_ptr(); buf.reserve_exact(additional); unsafe { let new_cap = buf.capacity(); buf.set_len(new_cap); } self.buf = buf.into_boxed_slice(); old_ptr == self.buf.as_ptr() } pub fn reserve_in_place(&mut self, _additional: usize) -> bool { // `Vec` does not support this return false; } pub unsafe fn as_slice(&self) -> &[u8] { &self.buf } pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.buf } } } #[cfg(feature = "nightly")] mod impl_ { extern crate alloc; use self::alloc::raw_vec::RawVec; use std::slice; pub struct RawBuf { buf: RawVec<u8>, } impl RawBuf { pub fn with_capacity(capacity: usize) -> Self { RawBuf { buf: RawVec::with_capacity(capacity) } } pub fn capacity(&self) -> usize { self.buf.cap() } pub fn reserve(&mut self, additional: usize) -> bool { let cap = self.capacity(); let old_ptr = self.buf.ptr(); self.buf.reserve_exact(cap, additional); old_ptr != self.buf.ptr() } pub fn reserve_in_place(&mut self, additional: usize) -> bool { let cap = self.capacity(); self.buf.reserve_in_place(cap, additional) } pub unsafe fn as_slice(&self) -> &[u8] { slice::from_raw_parts(self.buf.ptr(), self.buf.cap()) } pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] { slice::from_raw_parts_mut(self.buf.ptr(), self.buf.cap()) } } } #[test] fn read_into_full() { use Buffer; let mut buffer = Buffer::with_capacity(1); assert_eq!(buffer.capacity(), 1); let mut bytes = &[1u8, 2][..]; // Result<usize, io::Error> does not impl PartialEq assert_eq!(buffer.read_from(&mut bytes).unwrap(), 1); assert_eq!(buffer.read_from(&mut bytes).unwrap(), 0); }
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:lifetimes.rs // ignore-stage1 #![feature(use_extern_macros)] extern crate lifetimes; use lifetimes::*; lifetimes_bang! { fn bang<'a>() -> &'a u8 { &0 } } #[lifetimes_attr] fn attr<'a>() -> &'a u8 { &1 } #[derive(Lifetimes)] pub struct Lifetimes<'a> { pub field: &'a u8, } fn main() { assert_eq!(bang::<'static>(), &0); assert_eq!(attr::<'static>(), &1); let l1 = Lifetimes { field: &0 }; let l2 = m::Lifetimes { field: &1 }; }
use { super::{ Connection as Sway, ConnectionBuilder as SwayBuilder, Event, EventType, }, crate::modules::Module, gtk::{ Box as WidgetBox, BoxExt, Button, ButtonExt, ContainerExt, Orientation, ReliefStyle, StyleContextExt, Widget, WidgetExt, }, }; #[derive(Clone)] pub struct Workspaces { button_box: WidgetBox, } impl Workspaces { pub fn new(builder: &mut SwayBuilder) -> Workspaces { // make a box to put workspace buttons in let button_box = WidgetBox::new(Orientation::Horizontal, 0); button_box.set_homogeneous(false); button_box.show(); button_box.set_widget_name("workspaces"); let me = Workspaces { button_box }; builder.subscribe( &[EventType::Workspace], { let me = me.clone(); move |conn, event| match event { Event::Workspace(_) => me.refresh(&conn), _ => { } } } ); me.refresh(builder); me } pub fn refresh(&self, sway: &Sway) { self.button_box.foreach(|button| { self.button_box.remove(button); }); let workspaces = match sway.get_workspaces() { Ok(ws) => ws, Err(_) => return }; for ws in workspaces { let button = Button::with_label(&ws.name); button.set_relief(ReliefStyle::None); button.set_can_focus(false); button.show(); let sctx = button.get_style_context(); if ws.focused { sctx.add_class("focused"); } else if ws.urgent { sctx.add_class("urgent"); } if ws.visible { sctx.add_class("visible"); } button.connect_clicked({ let sway = sway.clone(); let name = ws.name.clone(); move |_| { if let Err(e) = sway.run_commands(&format!("workspace {}", name)) { eprintln!("Error switching workspace: {}", e); } } }); self.button_box.pack_start(&button, false, false, 0); self.button_box.reorder_child(&button, ws.num + 1); } } } impl Module for Workspaces { fn get_widget(&self) -> Widget { use glib::object::Cast; self.button_box.clone().upcast() } }
fn main() { let a: char = 'a'; println!("karakter a: {}", a); }
//! A [futures] friendly [inotify] wrapper for [fibers] crate. //! //! [futures]: https://crates.io/crates/futures //! [fibers]: https://crates.io/crates/fibers //! [inotify]: https://en.wikipedia.org/wiki/Inotify //! //! # Examples //! //! Watches `/tmp` directory: //! //! ``` //! # extern crate fibers; //! # extern crate fibers_inotify; //! # extern crate futures; //! use fibers::{Executor, InPlaceExecutor, Spawn}; //! use fibers_inotify::{InotifyService, WatchMask}; //! use futures::{Future, Stream}; //! //! # fn main() { //! let inotify_service = InotifyService::new(); //! let inotify_handle = inotify_service.handle(); //! //! let mut executor = InPlaceExecutor::new().unwrap(); //! executor.spawn(inotify_service.map_err(|e| panic!("{}", e))); //! //! executor.spawn( //! inotify_handle //! .watch("/tmp/", WatchMask::CREATE | WatchMask::DELETE) //! .for_each(|event| Ok(println!("# EVENT: {:?}", event))) //! .map_err(|e| panic!("{}", e)), //! ); //! //! executor.run_once().unwrap(); //! # } //! ``` #![warn(missing_docs)] extern crate fibers; extern crate futures; extern crate inotify; extern crate inotify_sys; extern crate libc; extern crate mio; #[macro_use] extern crate trackable; #[doc(no_inline)] pub use inotify::{EventMask, WatchMask}; pub use error::{Error, ErrorKind}; pub use internal_inotify::InotifyEvent; pub use service::{InotifyService, InotifyServiceHandle}; pub use watcher::{Watcher, WatcherEvent}; mod error; mod internal_inotify; mod mio_ext; mod service; mod watcher; /// This crate specific `Result` type. pub type Result<T> = std::result::Result<T, Error>; #[cfg(test)] mod test { use std::thread; use std::time::Duration; use fibers::{Executor, InPlaceExecutor, Spawn}; use futures::{Future, Stream}; use super::*; #[test] fn it_works() { let service = InotifyService::new(); let inotify = service.handle(); let mut executor = InPlaceExecutor::new().unwrap(); executor.spawn(service.map_err(|e| panic!("{}", e))); executor.spawn( inotify .watch("/tmp/", WatchMask::all()) .for_each(|_event| Ok(())) .map_err(|e| panic!("{}", e)), ); executor.spawn( inotify .watch("/tmp/", WatchMask::CREATE) .for_each(|_event| Ok(())) .map_err(|e| panic!("{}", e)), ); for _ in 0..500 { executor.run_once().unwrap(); thread::sleep(Duration::from_millis(1)); } } }
use consts::{ CODE_ALPHABET, ENCODING_BASE, GRID_ROWS, LATITUDE_MAX, LONGITUDE_MAX, PAIR_CODE_LENGTH, }; use interface::encode; use geo::Point; pub fn code_value(chr: char) -> usize { // We assume this function is only called by other functions that have // already ensured that the characters in the passed-in code are all valid // and have all been "treated" (upper-cased, padding and '+' stripped) CODE_ALPHABET.iter().position(|&x| x == chr).unwrap() } pub fn normalize_longitude(value: f64) -> f64 { let mut result: f64 = value; while result >= LONGITUDE_MAX { result -= LONGITUDE_MAX * 2f64; } while result < -LONGITUDE_MAX { result += LONGITUDE_MAX * 2f64; } result } pub fn clip_latitude(latitude_degrees: f64) -> f64 { latitude_degrees.min(LATITUDE_MAX).max(-LATITUDE_MAX) } pub fn compute_latitude_precision(code_length: usize) -> f64 { if code_length <= PAIR_CODE_LENGTH { return (ENCODING_BASE as f64).powf((code_length as f64 / -2f64 + 2f64).floor()); } (ENCODING_BASE as f64).powf(-3f64) / GRID_ROWS.pow((code_length - PAIR_CODE_LENGTH) as u32) as f64 } pub fn prefix_by_reference(pt: Point<f64>, code_length: usize) -> String { let precision = compute_latitude_precision(code_length); let mut code = encode( Point::new( (pt.lng() / precision).floor() * precision, (pt.lat() / precision).floor() * precision, ), PAIR_CODE_LENGTH, ); code.drain(code_length..); code }
use pcap::{Device, Capture}; use futures::executor::block_on; async fn capture_1() { let interface_1 = Device::lookup().unwrap(); let mut cap1 = Capture::from_device(interface_1) .unwrap() .promisc(true) .snaplen(5000) .open().unwrap(); // tokio::block_on(cap1.next()) while let Ok(packet) = cap1.next().await { println!("Received packet on Capture 1! {:?}", packet); } } async fn capture_2() { let interface_2 = Device::lookup().unwrap(); let mut cap2 = Capture::from_device(interface_2) .unwrap() .promisc(true) .snaplen(5000) .open().unwrap(); while let Ok(packet) = cap2.next().await { println!("Received packet on Capture 2! {:?}", packet); } } #[tokio::main] async fn main() { let f1 = capture_1(); let f2 = capture_2(); futures::join!(f1, f2).await }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qcalendarwidget.h // dst-file: /src/widgets/qcalendarwidget.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qwidget::*; // 773 use std::ops::Deref; use super::super::core::qdatetime::*; // 771 use super::super::core::qsize::*; // 771 use super::super::gui::qtextformat::*; // 771 use super::super::core::qobjectdefs::*; // 771 // use super::qmap::*; // 775 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QCalendarWidget_Class_Size() -> c_int; // proto: void QCalendarWidget::showPreviousYear(); fn C_ZN15QCalendarWidget16showPreviousYearEv(qthis: u64 /* *mut c_void*/); // proto: QDate QCalendarWidget::maximumDate(); fn C_ZNK15QCalendarWidget11maximumDateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::showPreviousMonth(); fn C_ZN15QCalendarWidget17showPreviousMonthEv(qthis: u64 /* *mut c_void*/); // proto: void QCalendarWidget::showSelectedDate(); fn C_ZN15QCalendarWidget16showSelectedDateEv(qthis: u64 /* *mut c_void*/); // proto: QSize QCalendarWidget::minimumSizeHint(); fn C_ZNK15QCalendarWidget15minimumSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::setDateEditAcceptDelay(int delay); fn C_ZN15QCalendarWidget22setDateEditAcceptDelayEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QCalendarWidget::setGridVisible(bool show); fn C_ZN15QCalendarWidget14setGridVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QCalendarWidget::~QCalendarWidget(); fn C_ZN15QCalendarWidgetD2Ev(qthis: u64 /* *mut c_void*/); // proto: QSize QCalendarWidget::sizeHint(); fn C_ZNK15QCalendarWidget8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QCalendarWidget::monthShown(); fn C_ZNK15QCalendarWidget10monthShownEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QCalendarWidget::setSelectedDate(const QDate & date); fn C_ZN15QCalendarWidget15setSelectedDateERK5QDate(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QCalendarWidget::QCalendarWidget(QWidget * parent); fn C_ZN15QCalendarWidgetC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: const QMetaObject * QCalendarWidget::metaObject(); fn C_ZNK15QCalendarWidget10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::setNavigationBarVisible(bool visible); fn C_ZN15QCalendarWidget23setNavigationBarVisibleEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QCalendarWidget::isNavigationBarVisible(); fn C_ZNK15QCalendarWidget22isNavigationBarVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QTextCharFormat QCalendarWidget::dateTextFormat(const QDate & date); fn C_ZNK15QCalendarWidget14dateTextFormatERK5QDate(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QCalendarWidget::setMinimumDate(const QDate & date); fn C_ZN15QCalendarWidget14setMinimumDateERK5QDate(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: int QCalendarWidget::dateEditAcceptDelay(); fn C_ZNK15QCalendarWidget19dateEditAcceptDelayEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: QDate QCalendarWidget::minimumDate(); fn C_ZNK15QCalendarWidget11minimumDateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QCalendarWidget::isDateEditEnabled(); fn C_ZNK15QCalendarWidget17isDateEditEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QMap<QDate, QTextCharFormat> QCalendarWidget::dateTextFormat(); fn C_ZNK15QCalendarWidget14dateTextFormatEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::setDateEditEnabled(bool enable); fn C_ZN15QCalendarWidget18setDateEditEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: void QCalendarWidget::setDateTextFormat(const QDate & date, const QTextCharFormat & format); fn C_ZN15QCalendarWidget17setDateTextFormatERK5QDateRK15QTextCharFormat(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: void QCalendarWidget::showNextMonth(); fn C_ZN15QCalendarWidget13showNextMonthEv(qthis: u64 /* *mut c_void*/); // proto: void QCalendarWidget::setDateRange(const QDate & min, const QDate & max); fn C_ZN15QCalendarWidget12setDateRangeERK5QDateS2_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: QDate QCalendarWidget::selectedDate(); fn C_ZNK15QCalendarWidget12selectedDateEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::setHeaderTextFormat(const QTextCharFormat & format); fn C_ZN15QCalendarWidget19setHeaderTextFormatERK15QTextCharFormat(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: bool QCalendarWidget::isGridVisible(); fn C_ZNK15QCalendarWidget13isGridVisibleEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: int QCalendarWidget::yearShown(); fn C_ZNK15QCalendarWidget9yearShownEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QCalendarWidget::setMaximumDate(const QDate & date); fn C_ZN15QCalendarWidget14setMaximumDateERK5QDate(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QTextCharFormat QCalendarWidget::headerTextFormat(); fn C_ZNK15QCalendarWidget16headerTextFormatEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QCalendarWidget::setCurrentPage(int year, int month); fn C_ZN15QCalendarWidget14setCurrentPageEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QCalendarWidget::showToday(); fn C_ZN15QCalendarWidget9showTodayEv(qthis: u64 /* *mut c_void*/); // proto: void QCalendarWidget::showNextYear(); fn C_ZN15QCalendarWidget12showNextYearEv(qthis: u64 /* *mut c_void*/); fn QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget7clickedERK5QDate(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget16selectionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget9activatedERK5QDate(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget18currentPageChangedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QCalendarWidget)=1 #[derive(Default)] pub struct QCalendarWidget { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _activated: QCalendarWidget_activated_signal, pub _clicked: QCalendarWidget_clicked_signal, pub _currentPageChanged: QCalendarWidget_currentPageChanged_signal, pub _selectionChanged: QCalendarWidget_selectionChanged_signal, } impl /*struct*/ QCalendarWidget { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QCalendarWidget { return QCalendarWidget{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QCalendarWidget { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QCalendarWidget { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: void QCalendarWidget::showPreviousYear(); impl /*struct*/ QCalendarWidget { pub fn showPreviousYear<RetType, T: QCalendarWidget_showPreviousYear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showPreviousYear(self); // return 1; } } pub trait QCalendarWidget_showPreviousYear<RetType> { fn showPreviousYear(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showPreviousYear(); impl<'a> /*trait*/ QCalendarWidget_showPreviousYear<()> for () { fn showPreviousYear(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget16showPreviousYearEv()}; unsafe {C_ZN15QCalendarWidget16showPreviousYearEv(rsthis.qclsinst)}; // return 1; } } // proto: QDate QCalendarWidget::maximumDate(); impl /*struct*/ QCalendarWidget { pub fn maximumDate<RetType, T: QCalendarWidget_maximumDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.maximumDate(self); // return 1; } } pub trait QCalendarWidget_maximumDate<RetType> { fn maximumDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QDate QCalendarWidget::maximumDate(); impl<'a> /*trait*/ QCalendarWidget_maximumDate<QDate> for () { fn maximumDate(self , rsthis: & QCalendarWidget) -> QDate { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget11maximumDateEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget11maximumDateEv(rsthis.qclsinst)}; let mut ret1 = QDate::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::showPreviousMonth(); impl /*struct*/ QCalendarWidget { pub fn showPreviousMonth<RetType, T: QCalendarWidget_showPreviousMonth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showPreviousMonth(self); // return 1; } } pub trait QCalendarWidget_showPreviousMonth<RetType> { fn showPreviousMonth(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showPreviousMonth(); impl<'a> /*trait*/ QCalendarWidget_showPreviousMonth<()> for () { fn showPreviousMonth(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget17showPreviousMonthEv()}; unsafe {C_ZN15QCalendarWidget17showPreviousMonthEv(rsthis.qclsinst)}; // return 1; } } // proto: void QCalendarWidget::showSelectedDate(); impl /*struct*/ QCalendarWidget { pub fn showSelectedDate<RetType, T: QCalendarWidget_showSelectedDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showSelectedDate(self); // return 1; } } pub trait QCalendarWidget_showSelectedDate<RetType> { fn showSelectedDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showSelectedDate(); impl<'a> /*trait*/ QCalendarWidget_showSelectedDate<()> for () { fn showSelectedDate(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget16showSelectedDateEv()}; unsafe {C_ZN15QCalendarWidget16showSelectedDateEv(rsthis.qclsinst)}; // return 1; } } // proto: QSize QCalendarWidget::minimumSizeHint(); impl /*struct*/ QCalendarWidget { pub fn minimumSizeHint<RetType, T: QCalendarWidget_minimumSizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSizeHint(self); // return 1; } } pub trait QCalendarWidget_minimumSizeHint<RetType> { fn minimumSizeHint(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QSize QCalendarWidget::minimumSizeHint(); impl<'a> /*trait*/ QCalendarWidget_minimumSizeHint<QSize> for () { fn minimumSizeHint(self , rsthis: & QCalendarWidget) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget15minimumSizeHintEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget15minimumSizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::setDateEditAcceptDelay(int delay); impl /*struct*/ QCalendarWidget { pub fn setDateEditAcceptDelay<RetType, T: QCalendarWidget_setDateEditAcceptDelay<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDateEditAcceptDelay(self); // return 1; } } pub trait QCalendarWidget_setDateEditAcceptDelay<RetType> { fn setDateEditAcceptDelay(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setDateEditAcceptDelay(int delay); impl<'a> /*trait*/ QCalendarWidget_setDateEditAcceptDelay<()> for (i32) { fn setDateEditAcceptDelay(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget22setDateEditAcceptDelayEi()}; let arg0 = self as c_int; unsafe {C_ZN15QCalendarWidget22setDateEditAcceptDelayEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QCalendarWidget::setGridVisible(bool show); impl /*struct*/ QCalendarWidget { pub fn setGridVisible<RetType, T: QCalendarWidget_setGridVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setGridVisible(self); // return 1; } } pub trait QCalendarWidget_setGridVisible<RetType> { fn setGridVisible(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setGridVisible(bool show); impl<'a> /*trait*/ QCalendarWidget_setGridVisible<()> for (i8) { fn setGridVisible(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget14setGridVisibleEb()}; let arg0 = self as c_char; unsafe {C_ZN15QCalendarWidget14setGridVisibleEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QCalendarWidget::~QCalendarWidget(); impl /*struct*/ QCalendarWidget { pub fn free<RetType, T: QCalendarWidget_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QCalendarWidget_free<RetType> { fn free(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::~QCalendarWidget(); impl<'a> /*trait*/ QCalendarWidget_free<()> for () { fn free(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidgetD2Ev()}; unsafe {C_ZN15QCalendarWidgetD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QSize QCalendarWidget::sizeHint(); impl /*struct*/ QCalendarWidget { pub fn sizeHint<RetType, T: QCalendarWidget_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QCalendarWidget_sizeHint<RetType> { fn sizeHint(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QSize QCalendarWidget::sizeHint(); impl<'a> /*trait*/ QCalendarWidget_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QCalendarWidget) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget8sizeHintEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QCalendarWidget::monthShown(); impl /*struct*/ QCalendarWidget { pub fn monthShown<RetType, T: QCalendarWidget_monthShown<RetType>>(& self, overload_args: T) -> RetType { return overload_args.monthShown(self); // return 1; } } pub trait QCalendarWidget_monthShown<RetType> { fn monthShown(self , rsthis: & QCalendarWidget) -> RetType; } // proto: int QCalendarWidget::monthShown(); impl<'a> /*trait*/ QCalendarWidget_monthShown<i32> for () { fn monthShown(self , rsthis: & QCalendarWidget) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget10monthShownEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget10monthShownEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QCalendarWidget::setSelectedDate(const QDate & date); impl /*struct*/ QCalendarWidget { pub fn setSelectedDate<RetType, T: QCalendarWidget_setSelectedDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSelectedDate(self); // return 1; } } pub trait QCalendarWidget_setSelectedDate<RetType> { fn setSelectedDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setSelectedDate(const QDate & date); impl<'a> /*trait*/ QCalendarWidget_setSelectedDate<()> for (&'a QDate) { fn setSelectedDate(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget15setSelectedDateERK5QDate()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget15setSelectedDateERK5QDate(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QCalendarWidget::QCalendarWidget(QWidget * parent); impl /*struct*/ QCalendarWidget { pub fn new<T: QCalendarWidget_new>(value: T) -> QCalendarWidget { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QCalendarWidget_new { fn new(self) -> QCalendarWidget; } // proto: void QCalendarWidget::QCalendarWidget(QWidget * parent); impl<'a> /*trait*/ QCalendarWidget_new for (Option<&'a QWidget>) { fn new(self) -> QCalendarWidget { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidgetC2EP7QWidget()}; let ctysz: c_int = unsafe{QCalendarWidget_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN15QCalendarWidgetC2EP7QWidget(arg0)}; let rsthis = QCalendarWidget{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QCalendarWidget::metaObject(); impl /*struct*/ QCalendarWidget { pub fn metaObject<RetType, T: QCalendarWidget_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QCalendarWidget_metaObject<RetType> { fn metaObject(self , rsthis: & QCalendarWidget) -> RetType; } // proto: const QMetaObject * QCalendarWidget::metaObject(); impl<'a> /*trait*/ QCalendarWidget_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QCalendarWidget) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget10metaObjectEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::setNavigationBarVisible(bool visible); impl /*struct*/ QCalendarWidget { pub fn setNavigationBarVisible<RetType, T: QCalendarWidget_setNavigationBarVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setNavigationBarVisible(self); // return 1; } } pub trait QCalendarWidget_setNavigationBarVisible<RetType> { fn setNavigationBarVisible(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setNavigationBarVisible(bool visible); impl<'a> /*trait*/ QCalendarWidget_setNavigationBarVisible<()> for (i8) { fn setNavigationBarVisible(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget23setNavigationBarVisibleEb()}; let arg0 = self as c_char; unsafe {C_ZN15QCalendarWidget23setNavigationBarVisibleEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QCalendarWidget::isNavigationBarVisible(); impl /*struct*/ QCalendarWidget { pub fn isNavigationBarVisible<RetType, T: QCalendarWidget_isNavigationBarVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isNavigationBarVisible(self); // return 1; } } pub trait QCalendarWidget_isNavigationBarVisible<RetType> { fn isNavigationBarVisible(self , rsthis: & QCalendarWidget) -> RetType; } // proto: bool QCalendarWidget::isNavigationBarVisible(); impl<'a> /*trait*/ QCalendarWidget_isNavigationBarVisible<i8> for () { fn isNavigationBarVisible(self , rsthis: & QCalendarWidget) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget22isNavigationBarVisibleEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget22isNavigationBarVisibleEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QTextCharFormat QCalendarWidget::dateTextFormat(const QDate & date); impl /*struct*/ QCalendarWidget { pub fn dateTextFormat<RetType, T: QCalendarWidget_dateTextFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dateTextFormat(self); // return 1; } } pub trait QCalendarWidget_dateTextFormat<RetType> { fn dateTextFormat(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QTextCharFormat QCalendarWidget::dateTextFormat(const QDate & date); impl<'a> /*trait*/ QCalendarWidget_dateTextFormat<QTextCharFormat> for (&'a QDate) { fn dateTextFormat(self , rsthis: & QCalendarWidget) -> QTextCharFormat { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget14dateTextFormatERK5QDate()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {C_ZNK15QCalendarWidget14dateTextFormatERK5QDate(rsthis.qclsinst, arg0)}; let mut ret1 = QTextCharFormat::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::setMinimumDate(const QDate & date); impl /*struct*/ QCalendarWidget { pub fn setMinimumDate<RetType, T: QCalendarWidget_setMinimumDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMinimumDate(self); // return 1; } } pub trait QCalendarWidget_setMinimumDate<RetType> { fn setMinimumDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setMinimumDate(const QDate & date); impl<'a> /*trait*/ QCalendarWidget_setMinimumDate<()> for (&'a QDate) { fn setMinimumDate(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget14setMinimumDateERK5QDate()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget14setMinimumDateERK5QDate(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QCalendarWidget::dateEditAcceptDelay(); impl /*struct*/ QCalendarWidget { pub fn dateEditAcceptDelay<RetType, T: QCalendarWidget_dateEditAcceptDelay<RetType>>(& self, overload_args: T) -> RetType { return overload_args.dateEditAcceptDelay(self); // return 1; } } pub trait QCalendarWidget_dateEditAcceptDelay<RetType> { fn dateEditAcceptDelay(self , rsthis: & QCalendarWidget) -> RetType; } // proto: int QCalendarWidget::dateEditAcceptDelay(); impl<'a> /*trait*/ QCalendarWidget_dateEditAcceptDelay<i32> for () { fn dateEditAcceptDelay(self , rsthis: & QCalendarWidget) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget19dateEditAcceptDelayEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget19dateEditAcceptDelayEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: QDate QCalendarWidget::minimumDate(); impl /*struct*/ QCalendarWidget { pub fn minimumDate<RetType, T: QCalendarWidget_minimumDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumDate(self); // return 1; } } pub trait QCalendarWidget_minimumDate<RetType> { fn minimumDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QDate QCalendarWidget::minimumDate(); impl<'a> /*trait*/ QCalendarWidget_minimumDate<QDate> for () { fn minimumDate(self , rsthis: & QCalendarWidget) -> QDate { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget11minimumDateEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget11minimumDateEv(rsthis.qclsinst)}; let mut ret1 = QDate::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QCalendarWidget::isDateEditEnabled(); impl /*struct*/ QCalendarWidget { pub fn isDateEditEnabled<RetType, T: QCalendarWidget_isDateEditEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isDateEditEnabled(self); // return 1; } } pub trait QCalendarWidget_isDateEditEnabled<RetType> { fn isDateEditEnabled(self , rsthis: & QCalendarWidget) -> RetType; } // proto: bool QCalendarWidget::isDateEditEnabled(); impl<'a> /*trait*/ QCalendarWidget_isDateEditEnabled<i8> for () { fn isDateEditEnabled(self , rsthis: & QCalendarWidget) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget17isDateEditEnabledEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget17isDateEditEnabledEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QMap<QDate, QTextCharFormat> QCalendarWidget::dateTextFormat(); impl<'a> /*trait*/ QCalendarWidget_dateTextFormat<u64> for () { fn dateTextFormat(self , rsthis: & QCalendarWidget) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget14dateTextFormatEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget14dateTextFormatEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: void QCalendarWidget::setDateEditEnabled(bool enable); impl /*struct*/ QCalendarWidget { pub fn setDateEditEnabled<RetType, T: QCalendarWidget_setDateEditEnabled<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDateEditEnabled(self); // return 1; } } pub trait QCalendarWidget_setDateEditEnabled<RetType> { fn setDateEditEnabled(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setDateEditEnabled(bool enable); impl<'a> /*trait*/ QCalendarWidget_setDateEditEnabled<()> for (i8) { fn setDateEditEnabled(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget18setDateEditEnabledEb()}; let arg0 = self as c_char; unsafe {C_ZN15QCalendarWidget18setDateEditEnabledEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QCalendarWidget::setDateTextFormat(const QDate & date, const QTextCharFormat & format); impl /*struct*/ QCalendarWidget { pub fn setDateTextFormat<RetType, T: QCalendarWidget_setDateTextFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDateTextFormat(self); // return 1; } } pub trait QCalendarWidget_setDateTextFormat<RetType> { fn setDateTextFormat(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setDateTextFormat(const QDate & date, const QTextCharFormat & format); impl<'a> /*trait*/ QCalendarWidget_setDateTextFormat<()> for (&'a QDate, &'a QTextCharFormat) { fn setDateTextFormat(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget17setDateTextFormatERK5QDateRK15QTextCharFormat()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget17setDateTextFormatERK5QDateRK15QTextCharFormat(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QCalendarWidget::showNextMonth(); impl /*struct*/ QCalendarWidget { pub fn showNextMonth<RetType, T: QCalendarWidget_showNextMonth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showNextMonth(self); // return 1; } } pub trait QCalendarWidget_showNextMonth<RetType> { fn showNextMonth(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showNextMonth(); impl<'a> /*trait*/ QCalendarWidget_showNextMonth<()> for () { fn showNextMonth(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget13showNextMonthEv()}; unsafe {C_ZN15QCalendarWidget13showNextMonthEv(rsthis.qclsinst)}; // return 1; } } // proto: void QCalendarWidget::setDateRange(const QDate & min, const QDate & max); impl /*struct*/ QCalendarWidget { pub fn setDateRange<RetType, T: QCalendarWidget_setDateRange<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setDateRange(self); // return 1; } } pub trait QCalendarWidget_setDateRange<RetType> { fn setDateRange(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setDateRange(const QDate & min, const QDate & max); impl<'a> /*trait*/ QCalendarWidget_setDateRange<()> for (&'a QDate, &'a QDate) { fn setDateRange(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget12setDateRangeERK5QDateS2_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget12setDateRangeERK5QDateS2_(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QDate QCalendarWidget::selectedDate(); impl /*struct*/ QCalendarWidget { pub fn selectedDate<RetType, T: QCalendarWidget_selectedDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.selectedDate(self); // return 1; } } pub trait QCalendarWidget_selectedDate<RetType> { fn selectedDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QDate QCalendarWidget::selectedDate(); impl<'a> /*trait*/ QCalendarWidget_selectedDate<QDate> for () { fn selectedDate(self , rsthis: & QCalendarWidget) -> QDate { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget12selectedDateEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget12selectedDateEv(rsthis.qclsinst)}; let mut ret1 = QDate::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::setHeaderTextFormat(const QTextCharFormat & format); impl /*struct*/ QCalendarWidget { pub fn setHeaderTextFormat<RetType, T: QCalendarWidget_setHeaderTextFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setHeaderTextFormat(self); // return 1; } } pub trait QCalendarWidget_setHeaderTextFormat<RetType> { fn setHeaderTextFormat(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setHeaderTextFormat(const QTextCharFormat & format); impl<'a> /*trait*/ QCalendarWidget_setHeaderTextFormat<()> for (&'a QTextCharFormat) { fn setHeaderTextFormat(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget19setHeaderTextFormatERK15QTextCharFormat()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget19setHeaderTextFormatERK15QTextCharFormat(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QCalendarWidget::isGridVisible(); impl /*struct*/ QCalendarWidget { pub fn isGridVisible<RetType, T: QCalendarWidget_isGridVisible<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isGridVisible(self); // return 1; } } pub trait QCalendarWidget_isGridVisible<RetType> { fn isGridVisible(self , rsthis: & QCalendarWidget) -> RetType; } // proto: bool QCalendarWidget::isGridVisible(); impl<'a> /*trait*/ QCalendarWidget_isGridVisible<i8> for () { fn isGridVisible(self , rsthis: & QCalendarWidget) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget13isGridVisibleEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget13isGridVisibleEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: int QCalendarWidget::yearShown(); impl /*struct*/ QCalendarWidget { pub fn yearShown<RetType, T: QCalendarWidget_yearShown<RetType>>(& self, overload_args: T) -> RetType { return overload_args.yearShown(self); // return 1; } } pub trait QCalendarWidget_yearShown<RetType> { fn yearShown(self , rsthis: & QCalendarWidget) -> RetType; } // proto: int QCalendarWidget::yearShown(); impl<'a> /*trait*/ QCalendarWidget_yearShown<i32> for () { fn yearShown(self , rsthis: & QCalendarWidget) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget9yearShownEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget9yearShownEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QCalendarWidget::setMaximumDate(const QDate & date); impl /*struct*/ QCalendarWidget { pub fn setMaximumDate<RetType, T: QCalendarWidget_setMaximumDate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setMaximumDate(self); // return 1; } } pub trait QCalendarWidget_setMaximumDate<RetType> { fn setMaximumDate(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setMaximumDate(const QDate & date); impl<'a> /*trait*/ QCalendarWidget_setMaximumDate<()> for (&'a QDate) { fn setMaximumDate(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget14setMaximumDateERK5QDate()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN15QCalendarWidget14setMaximumDateERK5QDate(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QTextCharFormat QCalendarWidget::headerTextFormat(); impl /*struct*/ QCalendarWidget { pub fn headerTextFormat<RetType, T: QCalendarWidget_headerTextFormat<RetType>>(& self, overload_args: T) -> RetType { return overload_args.headerTextFormat(self); // return 1; } } pub trait QCalendarWidget_headerTextFormat<RetType> { fn headerTextFormat(self , rsthis: & QCalendarWidget) -> RetType; } // proto: QTextCharFormat QCalendarWidget::headerTextFormat(); impl<'a> /*trait*/ QCalendarWidget_headerTextFormat<QTextCharFormat> for () { fn headerTextFormat(self , rsthis: & QCalendarWidget) -> QTextCharFormat { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK15QCalendarWidget16headerTextFormatEv()}; let mut ret = unsafe {C_ZNK15QCalendarWidget16headerTextFormatEv(rsthis.qclsinst)}; let mut ret1 = QTextCharFormat::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QCalendarWidget::setCurrentPage(int year, int month); impl /*struct*/ QCalendarWidget { pub fn setCurrentPage<RetType, T: QCalendarWidget_setCurrentPage<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCurrentPage(self); // return 1; } } pub trait QCalendarWidget_setCurrentPage<RetType> { fn setCurrentPage(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::setCurrentPage(int year, int month); impl<'a> /*trait*/ QCalendarWidget_setCurrentPage<()> for (i32, i32) { fn setCurrentPage(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget14setCurrentPageEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN15QCalendarWidget14setCurrentPageEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QCalendarWidget::showToday(); impl /*struct*/ QCalendarWidget { pub fn showToday<RetType, T: QCalendarWidget_showToday<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showToday(self); // return 1; } } pub trait QCalendarWidget_showToday<RetType> { fn showToday(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showToday(); impl<'a> /*trait*/ QCalendarWidget_showToday<()> for () { fn showToday(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget9showTodayEv()}; unsafe {C_ZN15QCalendarWidget9showTodayEv(rsthis.qclsinst)}; // return 1; } } // proto: void QCalendarWidget::showNextYear(); impl /*struct*/ QCalendarWidget { pub fn showNextYear<RetType, T: QCalendarWidget_showNextYear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.showNextYear(self); // return 1; } } pub trait QCalendarWidget_showNextYear<RetType> { fn showNextYear(self , rsthis: & QCalendarWidget) -> RetType; } // proto: void QCalendarWidget::showNextYear(); impl<'a> /*trait*/ QCalendarWidget_showNextYear<()> for () { fn showNextYear(self , rsthis: & QCalendarWidget) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN15QCalendarWidget12showNextYearEv()}; unsafe {C_ZN15QCalendarWidget12showNextYearEv(rsthis.qclsinst)}; // return 1; } } #[derive(Default)] // for QCalendarWidget_activated pub struct QCalendarWidget_activated_signal{poi:u64} impl /* struct */ QCalendarWidget { pub fn activated(&self) -> QCalendarWidget_activated_signal { return QCalendarWidget_activated_signal{poi:self.qclsinst}; } } impl /* struct */ QCalendarWidget_activated_signal { pub fn connect<T: QCalendarWidget_activated_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QCalendarWidget_activated_signal_connect { fn connect(self, sigthis: QCalendarWidget_activated_signal); } #[derive(Default)] // for QCalendarWidget_clicked pub struct QCalendarWidget_clicked_signal{poi:u64} impl /* struct */ QCalendarWidget { pub fn clicked(&self) -> QCalendarWidget_clicked_signal { return QCalendarWidget_clicked_signal{poi:self.qclsinst}; } } impl /* struct */ QCalendarWidget_clicked_signal { pub fn connect<T: QCalendarWidget_clicked_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QCalendarWidget_clicked_signal_connect { fn connect(self, sigthis: QCalendarWidget_clicked_signal); } #[derive(Default)] // for QCalendarWidget_currentPageChanged pub struct QCalendarWidget_currentPageChanged_signal{poi:u64} impl /* struct */ QCalendarWidget { pub fn currentPageChanged(&self) -> QCalendarWidget_currentPageChanged_signal { return QCalendarWidget_currentPageChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QCalendarWidget_currentPageChanged_signal { pub fn connect<T: QCalendarWidget_currentPageChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QCalendarWidget_currentPageChanged_signal_connect { fn connect(self, sigthis: QCalendarWidget_currentPageChanged_signal); } #[derive(Default)] // for QCalendarWidget_selectionChanged pub struct QCalendarWidget_selectionChanged_signal{poi:u64} impl /* struct */ QCalendarWidget { pub fn selectionChanged(&self) -> QCalendarWidget_selectionChanged_signal { return QCalendarWidget_selectionChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QCalendarWidget_selectionChanged_signal { pub fn connect<T: QCalendarWidget_selectionChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QCalendarWidget_selectionChanged_signal_connect { fn connect(self, sigthis: QCalendarWidget_selectionChanged_signal); } // clicked(const class QDate &) extern fn QCalendarWidget_clicked_signal_connect_cb_0(rsfptr:fn(QDate), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QDate::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QCalendarWidget_clicked_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QDate)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QDate::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QCalendarWidget_clicked_signal_connect for fn(QDate) { fn connect(self, sigthis: QCalendarWidget_clicked_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_clicked_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget7clickedERK5QDate(arg0, arg1, arg2)}; } } impl /* trait */ QCalendarWidget_clicked_signal_connect for Box<Fn(QDate)> { fn connect(self, sigthis: QCalendarWidget_clicked_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_clicked_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget7clickedERK5QDate(arg0, arg1, arg2)}; } } // selectionChanged() extern fn QCalendarWidget_selectionChanged_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QCalendarWidget_selectionChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QCalendarWidget_selectionChanged_signal_connect for fn() { fn connect(self, sigthis: QCalendarWidget_selectionChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_selectionChanged_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget16selectionChangedEv(arg0, arg1, arg2)}; } } impl /* trait */ QCalendarWidget_selectionChanged_signal_connect for Box<Fn()> { fn connect(self, sigthis: QCalendarWidget_selectionChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_selectionChanged_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget16selectionChangedEv(arg0, arg1, arg2)}; } } // activated(const class QDate &) extern fn QCalendarWidget_activated_signal_connect_cb_2(rsfptr:fn(QDate), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QDate::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QCalendarWidget_activated_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QDate)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QDate::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QCalendarWidget_activated_signal_connect for fn(QDate) { fn connect(self, sigthis: QCalendarWidget_activated_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_activated_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget9activatedERK5QDate(arg0, arg1, arg2)}; } } impl /* trait */ QCalendarWidget_activated_signal_connect for Box<Fn(QDate)> { fn connect(self, sigthis: QCalendarWidget_activated_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_activated_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget9activatedERK5QDate(arg0, arg1, arg2)}; } } // currentPageChanged(int, int) extern fn QCalendarWidget_currentPageChanged_signal_connect_cb_3(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as i32; let rsarg1 = arg1 as i32; rsfptr(rsarg0,rsarg1); } extern fn QCalendarWidget_currentPageChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as i32; let rsarg1 = arg1 as i32; // rsfptr(rsarg0,rsarg1); unsafe{(*rsfptr_raw)(rsarg0,rsarg1)}; } impl /* trait */ QCalendarWidget_currentPageChanged_signal_connect for fn(i32, i32) { fn connect(self, sigthis: QCalendarWidget_currentPageChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_currentPageChanged_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget18currentPageChangedEii(arg0, arg1, arg2)}; } } impl /* trait */ QCalendarWidget_currentPageChanged_signal_connect for Box<Fn(i32, i32)> { fn connect(self, sigthis: QCalendarWidget_currentPageChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QCalendarWidget_currentPageChanged_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QCalendarWidget_SlotProxy_connect__ZN15QCalendarWidget18currentPageChangedEii(arg0, arg1, arg2)}; } } // <= body block end
use crate::prelude::*; #[repr(C)] #[derive(Debug, Default)] pub struct VkSurfaceCapabilitiesKHR { pub minImageCount: u32, pub maxImageCount: u32, pub currentExtent: VkExtent2D, pub minImageExtent: VkExtent2D, pub maxImageExtent: VkExtent2D, pub maxImageArrayLayers: u32, pub supportedTransforms: VkSurfaceTransformFlagBitsKHR, pub currentTransform: VkSurfaceTransformFlagBitsKHR, pub supportedCompositeAlpha: VkCompositeAlphaFlagBitsKHR, pub supportedUsageFlagBits: VkImageUsageFlagBits, }
// spell-checker:ignore numer denom use super::{ try_bigint_to_f64, PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyType, PyTypeRef, }; use crate::{ class::PyClassImpl, common::{float_ops, hash}, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{ ArgBytesLike, OptionalArg, OptionalOption, PyArithmeticValue::{self, *}, PyComparisonValue, }, protocol::PyNumberMethods, types::{AsNumber, Callable, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, }; use malachite_bigint::{BigInt, ToBigInt}; use num_complex::Complex64; use num_traits::{Signed, ToPrimitive, Zero}; use rustpython_common::int::float_to_ratio; use rustpython_format::FormatSpec; #[pyclass(module = false, name = "float")] #[derive(Debug, Copy, Clone, PartialEq)] pub struct PyFloat { value: f64, } impl PyFloat { pub fn to_f64(&self) -> f64 { self.value } } impl PyPayload for PyFloat { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.float_type } } impl ToPyObject for f64 { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_float(self).into() } } impl ToPyObject for f32 { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_float(f64::from(self)).into() } } impl From<f64> for PyFloat { fn from(value: f64) -> Self { PyFloat { value } } } pub(crate) fn to_op_float(obj: &PyObject, vm: &VirtualMachine) -> PyResult<Option<f64>> { let v = if let Some(float) = obj.payload_if_subclass::<PyFloat>(vm) { Some(float.value) } else if let Some(int) = obj.payload_if_subclass::<PyInt>(vm) { Some(try_bigint_to_f64(int.as_bigint(), vm)?) } else { None }; Ok(v) } macro_rules! impl_try_from_object_float { ($($t:ty),*) => { $(impl TryFromObject for $t { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { PyRef::<PyFloat>::try_from_object(vm, obj).map(|f| f.to_f64() as $t) } })* }; } impl_try_from_object_float!(f32, f64); fn inner_div(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::div(v1, v2) .ok_or_else(|| vm.new_zero_division_error("float division by zero".to_owned())) } fn inner_mod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::mod_(v1, v2) .ok_or_else(|| vm.new_zero_division_error("float mod by zero".to_owned())) } pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> { match value.to_bigint() { Some(int) => Ok(int), None => { if value.is_infinite() { Err(vm.new_overflow_error( "OverflowError: cannot convert float infinity to integer".to_owned(), )) } else if value.is_nan() { Err(vm .new_value_error("ValueError: cannot convert float NaN to integer".to_owned())) } else { // unreachable unless BigInt has a bug unreachable!( "A finite float value failed to be converted to bigint: {}", value ) } } } } fn inner_floordiv(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::floordiv(v1, v2) .ok_or_else(|| vm.new_zero_division_error("float floordiv by zero".to_owned())) } fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { float_ops::divmod(v1, v2).ok_or_else(|| vm.new_zero_division_error("float divmod()".to_owned())) } pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v1.is_zero() && v2.is_sign_negative() { let msg = format!("{v1} cannot be raised to a negative power"); Err(vm.new_zero_division_error(msg)) } else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON { let v1 = Complex64::new(v1, 0.); let v2 = Complex64::new(v2, 0.); Ok(v1.powc(v2).to_pyobject(vm)) } else { Ok(v1.powf(v2).to_pyobject(vm)) } } impl Constructor for PyFloat { type Args = OptionalArg<PyObjectRef>; fn py_new(cls: PyTypeRef, arg: Self::Args, vm: &VirtualMachine) -> PyResult { let float_val = match arg { OptionalArg::Missing => 0.0, OptionalArg::Present(val) => { if cls.is(vm.ctx.types.float_type) && val.class().is(vm.ctx.types.float_type) { return Ok(val); } if let Some(f) = val.try_float_opt(vm) { f?.value } else { float_from_string(val, vm)? } } }; PyFloat::from(float_val) .into_ref_with_type(vm, cls) .map(Into::into) } } fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> { let (bytearray, buffer, buffer_lock); let b = if let Some(s) = val.payload_if_subclass::<PyStr>(vm) { s.as_str().trim().as_bytes() } else if let Some(bytes) = val.payload_if_subclass::<PyBytes>(vm) { bytes.as_bytes() } else if let Some(buf) = val.payload_if_subclass::<PyByteArray>(vm) { bytearray = buf.borrow_buf(); &*bytearray } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, &val) { buffer = b; buffer_lock = buffer.borrow_buf(); &*buffer_lock } else { return Err(vm.new_type_error(format!( "float() argument must be a string or a number, not '{}'", val.class().name() ))); }; crate::literal::float::parse_bytes(b).ok_or_else(|| { val.repr(vm) .map(|repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) .unwrap_or_else(|e| e) }) } #[pyclass( flags(BASETYPE), with(Comparable, Hashable, Constructor, AsNumber, Representable) )] impl PyFloat { #[pymethod(magic)] fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { FormatSpec::parse(spec.as_str()) .and_then(|format_spec| format_spec.format_float(self.value)) .map_err(|err| err.into_pyexception(vm)) } #[pystaticmethod(magic)] fn getformat(spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { if !matches!(spec.as_str(), "double" | "float") { return Err(vm.new_value_error( "__getformat__() argument 1 must be 'double' or 'float'".to_owned(), )); } const BIG_ENDIAN: bool = cfg!(target_endian = "big"); Ok(if BIG_ENDIAN { "IEEE, big-endian" } else { "IEEE, little-endian" } .to_owned()) } #[pymethod(magic)] fn abs(&self) -> f64 { self.value.abs() } #[inline] fn simple_op<F>( &self, other: PyObjectRef, op: F, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<f64>> where F: Fn(f64, f64) -> PyResult<f64>, { to_op_float(&other, vm)?.map_or_else( || Ok(NotImplemented), |other| Ok(Implemented(op(self.value, other)?)), ) } #[inline] fn complex_op<F>(&self, other: PyObjectRef, op: F, vm: &VirtualMachine) -> PyResult where F: Fn(f64, f64) -> PyResult, { to_op_float(&other, vm)?.map_or_else( || Ok(vm.ctx.not_implemented()), |other| op(self.value, other), ) } #[inline] fn tuple_op<F>( &self, other: PyObjectRef, op: F, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<(f64, f64)>> where F: Fn(f64, f64) -> PyResult<(f64, f64)>, { to_op_float(&other, vm)?.map_or_else( || Ok(NotImplemented), |other| Ok(Implemented(op(self.value, other)?)), ) } #[pymethod(name = "__radd__")] #[pymethod(magic)] fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| Ok(a + b), vm) } #[pymethod(magic)] fn bool(&self) -> bool { self.value != 0.0 } #[pymethod(magic)] fn divmod( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<(f64, f64)>> { self.tuple_op(other, |a, b| inner_divmod(a, b, vm), vm) } #[pymethod(magic)] fn rdivmod( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<(f64, f64)>> { self.tuple_op(other, |a, b| inner_divmod(b, a, vm), vm) } #[pymethod(magic)] fn floordiv( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_floordiv(a, b, vm), vm) } #[pymethod(magic)] fn rfloordiv( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_floordiv(b, a, vm), vm) } #[pymethod(name = "__mod__")] fn mod_(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_mod(a, b, vm), vm) } #[pymethod(magic)] fn rmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_mod(b, a, vm), vm) } #[pymethod(magic)] fn pos(&self) -> f64 { self.value } #[pymethod(magic)] fn neg(&self) -> f64 { -self.value } #[pymethod(magic)] fn pow( &self, other: PyObjectRef, mod_val: OptionalOption<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { if mod_val.flatten().is_some() { Err(vm.new_type_error("floating point pow() does not accept a 3rd argument".to_owned())) } else { self.complex_op(other, |a, b| float_pow(a, b, vm), vm) } } #[pymethod(magic)] fn rpow(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.complex_op(other, |a, b| float_pow(b, a, vm), vm) } #[pymethod(magic)] fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| Ok(a - b), vm) } #[pymethod(magic)] fn rsub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| Ok(b - a), vm) } #[pymethod(magic)] fn truediv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_div(a, b, vm), vm) } #[pymethod(magic)] fn rtruediv( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| inner_div(b, a, vm), vm) } #[pymethod(name = "__rmul__")] #[pymethod(magic)] fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> { self.simple_op(other, |a, b| Ok(a * b), vm) } #[pymethod(magic)] fn trunc(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value, vm) } #[pymethod(magic)] fn floor(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value.floor(), vm) } #[pymethod(magic)] fn ceil(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value.ceil(), vm) } #[pymethod(magic)] fn round(&self, ndigits: OptionalOption<PyIntRef>, vm: &VirtualMachine) -> PyResult { let ndigits = ndigits.flatten(); let value = if let Some(ndigits) = ndigits { let ndigits = ndigits.as_bigint(); let ndigits = match ndigits.to_i32() { Some(n) => n, None if ndigits.is_positive() => i32::MAX, None => i32::MIN, }; let float = float_ops::round_float_digits(self.value, ndigits).ok_or_else(|| { vm.new_overflow_error("overflow occurred during round".to_owned()) })?; vm.ctx.new_float(float).into() } else { let fract = self.value.fract(); let value = if (fract.abs() - 0.5).abs() < f64::EPSILON { if self.value.trunc() % 2.0 == 0.0 { self.value - fract } else { self.value + fract } } else { self.value.round() }; let int = try_to_bigint(value, vm)?; vm.ctx.new_int(int).into() }; Ok(value) } #[pymethod(magic)] fn int(&self, vm: &VirtualMachine) -> PyResult<BigInt> { self.trunc(vm) } #[pymethod(magic)] fn float(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pygetset] fn real(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pygetset] fn imag(&self) -> f64 { 0.0f64 } #[pymethod] fn conjugate(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod] fn is_integer(&self) -> bool { crate::literal::float::is_integer(self.value) } #[pymethod] fn as_integer_ratio(&self, vm: &VirtualMachine) -> PyResult<(PyIntRef, PyIntRef)> { let value = self.value; float_to_ratio(value) .map(|(numer, denom)| (vm.ctx.new_bigint(&numer), vm.ctx.new_bigint(&denom))) .ok_or_else(|| { if value.is_infinite() { vm.new_overflow_error("cannot convert Infinity to integer ratio".to_owned()) } else if value.is_nan() { vm.new_value_error("cannot convert NaN to integer ratio".to_owned()) } else { unreachable!("finite float must able to convert to integer ratio") } }) } #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult { let result = crate::literal::float::from_hex(string.as_str().trim()).ok_or_else(|| { vm.new_value_error("invalid hexadecimal floating-point string".to_owned()) })?; PyType::call(&cls, vec![vm.ctx.new_float(result).into()].into(), vm) } #[pymethod] fn hex(&self) -> String { crate::literal::float::to_hex(self.value) } #[pymethod(magic)] fn getnewargs(&self, vm: &VirtualMachine) -> PyObjectRef { (self.value,).to_pyobject(vm) } } impl Comparable for PyFloat { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let ret = if let Some(other) = other.payload_if_subclass::<PyFloat>(vm) { zelf.value .partial_cmp(&other.value) .map_or_else(|| op == PyComparisonOp::Ne, |ord| op.eval_ord(ord)) } else if let Some(other) = other.payload_if_subclass::<PyInt>(vm) { let a = zelf.to_f64(); let b = other.as_bigint(); match op { PyComparisonOp::Lt => float_ops::lt_int(a, b), PyComparisonOp::Le => { if let (Some(a_int), Some(b_float)) = (a.to_bigint(), b.to_f64()) { a <= b_float && a_int <= *b } else { float_ops::lt_int(a, b) } } PyComparisonOp::Eq => float_ops::eq_int(a, b), PyComparisonOp::Ne => !float_ops::eq_int(a, b), PyComparisonOp::Ge => { if let (Some(a_int), Some(b_float)) = (a.to_bigint(), b.to_f64()) { a >= b_float && a_int >= *b } else { float_ops::gt_int(a, b) } } PyComparisonOp::Gt => float_ops::gt_int(a, b), } } else { return Ok(NotImplemented); }; Ok(Implemented(ret)) } } impl Hashable for PyFloat { #[inline] fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> { Ok(hash::hash_float(zelf.to_f64()).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()))) } } impl AsNumber for PyFloat { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { add: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a + b, vm)), subtract: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a - b, vm)), multiply: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a * b, vm)), remainder: Some(|a, b, vm| PyFloat::number_op(a, b, inner_mod, vm)), divmod: Some(|a, b, vm| PyFloat::number_op(a, b, inner_divmod, vm)), power: Some(|a, b, c, vm| { if vm.is_none(c) { PyFloat::number_op(a, b, float_pow, vm) } else { Err(vm.new_type_error(String::from( "pow() 3rd argument not allowed unless all arguments are integers", ))) } }), negative: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; (-value).to_pyresult(vm) }), positive: Some(|num, vm| PyFloat::number_downcast_exact(num, vm).to_pyresult(vm)), absolute: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; value.abs().to_pyresult(vm) }), boolean: Some(|num, _vm| Ok(PyFloat::number_downcast(num).value.is_zero())), int: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; try_to_bigint(value, vm).map(|x| PyInt::from(x).into_pyobject(vm)) }), float: Some(|num, vm| Ok(PyFloat::number_downcast_exact(num, vm).into())), floor_divide: Some(|a, b, vm| PyFloat::number_op(a, b, inner_floordiv, vm)), true_divide: Some(|a, b, vm| PyFloat::number_op(a, b, inner_div, vm)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } #[inline] fn clone_exact(zelf: &Py<Self>, vm: &VirtualMachine) -> PyRef<Self> { vm.ctx.new_float(zelf.value) } } impl Representable for PyFloat { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(crate::literal::float::to_string(zelf.value)) } } impl PyFloat { fn number_op<F, R>(a: &PyObject, b: &PyObject, op: F, vm: &VirtualMachine) -> PyResult where F: FnOnce(f64, f64, &VirtualMachine) -> R, R: ToPyResult, { if let (Some(a), Some(b)) = (to_op_float(a, vm)?, to_op_float(b, vm)?) { op(a, b, vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } } } // Retrieve inner float value: #[cfg(feature = "serde")] pub(crate) fn get_value(obj: &PyObject) -> f64 { obj.payload::<PyFloat>().unwrap().value } #[rustfmt::skip] // to avoid line splitting pub fn init(context: &Context) { PyFloat::extend_class(context, context.types.float_type); }
fn main() { let base_path = dg2core::base_path(); }
pub mod metrics; pub mod model; pub mod metric; pub mod trainer;
pub fn min_operations(boxes: String) -> Vec<i32> { let boxes = boxes.chars().collect::<Vec<char>>(); let mut ops = 0; let mut count = 0; let mut result: Vec<i32> = vec![0; boxes.len()]; for i in 0..boxes.len() { result[i] += ops; count += if boxes[i] == '1' { 1 } else { 0 }; ops += count; } ops = 0; count = 0; for i in (0..boxes.len()).rev() { result[i] += ops; count += if boxes[i] == '1' { 1 } else { 0 }; ops += count; } result } #[cfg(test)] mod min_operations_tests { fn min_operations_test_one() {} }
//! The vast majority of the code is taken from https://github.com/markschl/seq_io/blob/master/src/fastq.rs use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use crate::errors::{ErrorPosition, ParseError}; use crate::parser::record::SequenceRecord; use crate::parser::utils::{ fill_buf, find_line_ending, grow_to, trim_cr, FastxReader, Format, LineEnding, Position, BUFSIZE, }; use memchr::memchr; /// Represents the position of a record within a buffer #[derive(Debug, Clone, Default)] pub struct BufferPosition { pub(crate) start: usize, pub(crate) end: usize, pub(crate) seq: usize, pub(crate) sep: usize, pub(crate) qual: usize, } impl BufferPosition { #[inline] pub(crate) fn is_new(&self) -> bool { self.end == 0 } #[inline] pub(crate) fn len(&self) -> u64 { (self.end + 1 - self.start) as u64 } #[inline] pub(crate) fn id<'a>(&'a self, buffer: &'a [u8]) -> &'a [u8] { trim_cr(&buffer[self.start + 1..self.seq - 1]) } #[inline] pub(crate) fn seq<'a>(&'a self, buffer: &'a [u8]) -> &'a [u8] { trim_cr(&buffer[self.seq..self.sep - 1]) } #[inline] pub(crate) fn qual<'a>(&'a self, buffer: &'a [u8]) -> &'a [u8] { trim_cr(&buffer[self.qual..self.end]) } #[inline] pub(crate) fn num_bases<'a>(&'a self, buffer: &'a [u8]) -> usize { self.seq(buffer).len() } #[inline] fn find_line_ending<'a>(&'a self, buffer: &'a [u8]) -> Option<LineEnding> { find_line_ending(self.all(buffer)) } #[inline] pub(crate) fn all<'a>(&self, buffer: &'a [u8]) -> &'a [u8] { &buffer[self.start..self.end] } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] enum SearchPosition { Id, Sequence, Separator, Quality, } /// Parser for FASTQ files. /// Only use this directly if you know your file is FASTQ and that it is not compressed as /// it does not handle decompression. /// If you are unsure, it's better to use [parse_fastx_file](fn.parse_fastx_file.html). pub struct Reader<R: io::Read> { buf_reader: buffer_redux::BufReader<R>, buf_pos: BufferPosition, search_pos: SearchPosition, position: Position, finished: bool, line_ending: Option<LineEnding>, } impl<R> Reader<R> where R: io::Read, { /// Creates a new reader with the default buffer size of 64 KiB /// /// # Example: /// /// ``` /// use needletail::parser::{FastqReader, FastxReader}; /// let fastq = b"@id\nACGT\n+\nIIII"; /// /// let mut reader = FastqReader::new(&fastq[..]); /// let record = reader.next().unwrap().unwrap(); /// assert_eq!(record.id(), b"id") /// ``` pub fn new(reader: R) -> Reader<R> { Reader::with_capacity(reader, BUFSIZE) } /// Creates a new reader with a given buffer capacity. The minimum allowed /// capacity is 3. pub fn with_capacity(reader: R, capacity: usize) -> Reader<R> { assert!(capacity >= 3); Reader { buf_reader: buffer_redux::BufReader::with_capacity(capacity, reader), buf_pos: BufferPosition::default(), search_pos: SearchPosition::Id, position: Position::new(1, 0), finished: false, line_ending: None, } } } impl Reader<File> { /// Creates a reader from a file path. /// /// # Example: /// /// ```no_run /// use needletail::parser::{FastxReader, FastqReader}; /// /// let mut reader = FastqReader::from_path("seqs.fastq").unwrap(); /// /// // (... do something with the reader) /// ``` pub fn from_path<P: AsRef<Path>>(path: P) -> io::Result<Reader<File>> { File::open(path).map(Reader::new) } } impl<R> Reader<R> where R: io::Read, { #[inline] fn get_buf(&self) -> &[u8] { self.buf_reader.buffer() } // TODO: avoid duplication with find_incomplete. // TODO: having a single fn and adding branches introduce a noticeable slowdown /// Reads the current record and returns true if found. /// Returns false if incomplete because end of buffer reached, /// meaning that the last record may be incomplete. /// Updates self.search_pos. fn find(&mut self) -> Result<bool, ParseError> { self.buf_pos.seq = match self.find_line(self.buf_pos.start) { Some(p) => p, None => { self.search_pos = SearchPosition::Id; return Ok(false); } }; self.buf_pos.sep = match self.find_line(self.buf_pos.seq) { Some(p) => p, None => { self.search_pos = SearchPosition::Sequence; return Ok(false); } }; self.buf_pos.qual = match self.find_line(self.buf_pos.sep) { Some(p) => p, None => { self.search_pos = SearchPosition::Separator; return Ok(false); } }; self.buf_pos.end = match self.find_line(self.buf_pos.qual) { Some(p) => p - 1, None => { self.search_pos = SearchPosition::Quality; return Ok(false); } }; self.validate()?; Ok(true) } // Resumes reading an incomplete record without // re-searching positions that were already found. // The resulting position may still be incomplete (-> false). fn find_incomplete(&mut self) -> Result<bool, ParseError> { if self.search_pos == SearchPosition::Id { self.buf_pos.seq = match self.find_line(self.buf_pos.start) { Some(p) => p, None => { self.search_pos = SearchPosition::Id; return Ok(false); } }; } if self.search_pos <= SearchPosition::Sequence { self.buf_pos.sep = match self.find_line(self.buf_pos.seq) { Some(p) => p, None => { self.search_pos = SearchPosition::Sequence; return Ok(false); } }; } if self.search_pos <= SearchPosition::Separator { self.buf_pos.qual = match self.find_line(self.buf_pos.sep) { Some(p) => p, None => { self.search_pos = SearchPosition::Separator; return Ok(false); } }; } if self.search_pos <= SearchPosition::Quality { self.buf_pos.end = match self.find_line(self.buf_pos.qual) { Some(p) => p - 1, None => { self.search_pos = SearchPosition::Quality; return Ok(false); } }; } self.search_pos = SearchPosition::Id; self.validate()?; Ok(true) } /// Verify that the record is valid: /// - starts with @ /// - separator line starts with - /// - quality and sequence have the same length fn validate(&mut self) -> Result<(), ParseError> { let start_byte = self.get_buf()[self.buf_pos.start]; if start_byte != b'@' { self.finished = true; return Err(ParseError::new_invalid_start( start_byte, self.get_error_pos(0, false), Format::Fastq, )); } let sep_byte = self.get_buf()[self.buf_pos.sep]; if sep_byte != b'+' { self.finished = true; return Err(ParseError::new_invalid_separator( sep_byte, self.get_error_pos(2, true), )); } let buf = self.get_buf(); // We assume we only have ASCII in sequence and quality let seq_len = self.buf_pos.seq(buf).len(); let qual_len = self.buf_pos.qual(buf).len(); // TODO: we don't do that every time because it's a ~90% performance penalty. // TODO: mention it on the README // And we can further validate quality chars // and the vast majority of files don't have this issue // let qual_len = self // .buf_pos // .qual(&buf) // .iter() // .filter(|c| *c >= &b'!' && *c <= &b'~') // .count(); if seq_len != qual_len { self.finished = true; return Err(ParseError::new_unequal_length( seq_len, qual_len, self.get_error_pos(0, true), )); } Ok(()) } fn get_error_pos(&self, line_offset: u64, parse_id: bool) -> ErrorPosition { let id = if parse_id && self.buf_pos.seq - self.buf_pos.start > 1 { let id = self .buf_pos .id(self.get_buf()) .split(|b| *b == b' ') .next() .unwrap(); Some(String::from_utf8_lossy(id).into()) } else { None }; ErrorPosition { line: self.position.line() + line_offset, id, } } #[inline] fn find_line(&self, search_start: usize) -> Option<usize> { memchr(b'\n', &self.get_buf()[search_start..]).map(|pos| search_start + pos + 1) } /// Called when we couldn't find a complete record. /// We might be at EOF, buffer might be too small or we need to refill it fn next_complete(&mut self) -> Result<bool, ParseError> { loop { if self.get_buf().len() < self.buf_reader.capacity() { // EOF reached, there will be no next record return self.check_end(); } if self.buf_pos.start == 0 { // first record already incomplete -> buffer too small self.grow(); } else { // not the first record -> buffer may be big enough but we need to make some space self.make_room(); } fill_buf(&mut self.buf_reader)?; if self.find_incomplete()? { return Ok(true); } } } /// Checks for EOF. /// If there is one last record that can be sent, return `true` otherwise `false`. fn check_end(&mut self) -> Result<bool, ParseError> { self.finished = true; if self.search_pos == SearchPosition::Quality { // no line ending at end of last record self.buf_pos.end = self.get_buf().len(); self.validate()?; return Ok(true); } // It allows some blank lines at the end of the file let rest = &self.get_buf()[self.buf_pos.start..]; if rest.split(|c| *c == b'\n').all(|l| trim_cr(l).is_empty()) { return Ok(false); } Err(ParseError::new_unexpected_end( self.get_error_pos(self.search_pos as u64, self.search_pos > SearchPosition::Id), Format::Fastq, )) } // Grow the internal buffer. Used if the original buffer is not big // enough for a record fn grow(&mut self) { let cap = self.buf_reader.capacity(); let new_size = grow_to(cap); let additional = new_size - cap; self.buf_reader.reserve(additional); } // Consume bytes from records we've seen and move incomplete bytes to start of buffer fn make_room(&mut self) { let consumed = self.buf_pos.start; self.buf_reader.consume(consumed); self.buf_reader.make_room(); self.buf_pos.start = 0; if self.search_pos >= SearchPosition::Sequence { self.buf_pos.seq -= consumed; } if self.search_pos >= SearchPosition::Separator { self.buf_pos.sep -= consumed; } if self.search_pos >= SearchPosition::Quality { self.buf_pos.qual -= consumed; } } } impl<R: io::Read + Send> FastxReader for Reader<R> { fn next(&mut self) -> Option<Result<SequenceRecord, ParseError>> { // No more records to read if self.finished { return None; } // Empty buffer, let's fill it if self.get_buf().is_empty() { // If we get an ParseError when reading or get back 0 bytes, we're done match fill_buf(&mut self.buf_reader) { Ok(n) => { if n == 0 { self.finished = true; return None; } } Err(e) => { return Some(Err(e.into())); } }; } // If we already did look at a record, let's setup for the next one if !self.buf_pos.is_new() { self.position.byte += self.buf_pos.len(); self.position.line += 4; self.buf_pos.start = self.buf_pos.end + 1; } // Can we identify all the positions of each element of the next record? let complete = match self.find() { Ok(f) => f, Err(e) => { return Some(Err(e)); } }; // If it's not complete, try to fetch more from the buffer until we have it in full if !complete { // Did we get a record? let got_record = match self.next_complete() { Ok(f) => f, Err(e) => { return Some(Err(e)); } }; if !got_record { return None; } } if self.line_ending.is_none() { self.line_ending = self.buf_pos.find_line_ending(self.get_buf()); } // We got one! Some(Ok(SequenceRecord::new_fastq( self.get_buf(), &self.buf_pos, &self.position, self.line_ending, ))) } fn position(&self) -> &Position { &self.position } fn line_ending(&self) -> Option<LineEnding> { self.line_ending } } #[cfg(test)] mod test { use std::io::Cursor; use super::Reader; use crate::errors::ParseErrorKind; use crate::parser::utils::LineEnding; use crate::FastxReader; fn seq(s: &[u8]) -> Cursor<&[u8]> { Cursor::new(&s[..]) } #[test] fn test_simple_fastq() { // Test both line endings let sequences = vec![ ( "@test\nAGCT\n+test\n~~a!\n@test2\nTGCA\n+test\nWUI9", LineEnding::Unix, ), ( "@test\r\nAGCT\r\n+test\r\n~~a!\r\n@test2\r\nTGCA\r\n+test\r\nWUI9", LineEnding::Windows, ), ]; for (sequence, line_ending) in sequences { let mut i = 0; let mut reader = Reader::new(seq(sequence.as_bytes())); while let Some(record) = reader.next() { let rec = record.unwrap(); match i { 0 => { assert_eq!(&rec.id(), b"test"); assert_eq!(&rec.raw_seq(), b"AGCT"); assert_eq!(&rec.qual().unwrap(), b"~~a!"); assert_eq!(reader.line_ending().unwrap(), line_ending); } 1 => { assert_eq!(&rec.id(), b"test2"); assert_eq!(&rec.raw_seq(), b"TGCA"); assert_eq!(&rec.qual().unwrap(), b"WUI9"); assert_eq!(reader.line_ending().unwrap(), line_ending); } _ => unreachable!("Too many records"), } i += 1; } assert_eq!(i, 2); } } #[test] fn test_eof_in_qual() { let mut reader = Reader::new(seq(b"@test\nACGT\n+\nIII")); let rec = reader.next().unwrap(); assert!(rec.is_err()); let e = rec.unwrap_err(); // Not a eof error due to the way the validate is implemented assert_eq!(e.kind, ParseErrorKind::UnequalLengths); } #[test] fn test_eof_in_seq() { let mut reader = Reader::new(seq(b"@test\nAGCT\n+test\n~~a!\n@test2\nTGCA")); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let rec2 = reader.next().unwrap(); assert!(rec2.is_err()); let e = rec2.unwrap_err(); assert_eq!(e.kind, ParseErrorKind::UnexpectedEnd); } #[test] fn test_extra_empty_newlines_at_end_are_ok() { let mut reader = Reader::new(seq(b"@test\nAGCT\n+test\n~~a!\n\n")); let rec = reader.next().unwrap(); assert!(rec.is_ok()); assert!(reader.next().is_none()); } #[test] fn test_extra_non_empty_newlines_at_end_are_not_ok() { let mut reader = Reader::new(seq(b"@test\nAGCT\n+test\n~~a!\n\n@TEST\nA\n+TEST\n~")); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let rec2 = reader.next().unwrap(); let e = rec2.unwrap_err(); assert_eq!(e.kind, ParseErrorKind::InvalidStart); } #[test] fn test_empty_records() { let mut reader = Reader::new(seq(b"@\n\n+\n\n@test2\nTGCA\n+test2\n~~~~\n")); let mut i = 0; while let Some(record) = reader.next() { let rec = record.unwrap(); match i { 0 => { assert_eq!(&rec.id(), b""); assert_eq!(&rec.raw_seq(), b""); assert_eq!(&rec.qual().unwrap(), b""); assert_eq!(rec.all(), b"@\n\n+\n"); } 1 => { assert_eq!(&rec.id(), b"test2"); assert_eq!(&rec.raw_seq(), b"TGCA"); assert_eq!(&rec.qual().unwrap(), b"~~~~"); assert_eq!(rec.all(), b"@test2\nTGCA\n+test2\n~~~~"); } _ => unreachable!("Too many records"), } i += 1 } assert_eq!(i, 2); } #[test] fn test_weird_ncbi_file() { let test = b"@NCBI actually has files like this\nACGTACGATCGTACGTAGCTGCTAGCTAGCATGCATGACACACACGTACGATCGTACGTAGCTGCTAGCTAGCATGCATGACACAC\n+\n00000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n@NCBI actually has files like this\n\n+\n\n@NCBI actually has files like this\nACGTACGATCGTACGTAGCTGCTAGCTAGCATGCATGACACACACGTACGATCGTACGTAGCTGCTAGCTAGCATGCATGACACAC\n+\n00000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; let mut reader = Reader::new(seq(test)); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let r = rec.unwrap(); assert_eq!(r.start_line_number(), 1); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let r = rec.unwrap(); assert_eq!(r.start_line_number(), 5); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let r = rec.unwrap(); assert_eq!(r.start_line_number(), 9); } #[test] fn test_mismatched_lengths() { let mut reader = Reader::new(seq(b"@test\nAGCT\n+\nIII\n@TEST\nA\n+\nI")); let rec = reader.next().unwrap(); assert!(rec.is_err()); let e = rec.unwrap_err(); assert_eq!(e.kind, ParseErrorKind::UnequalLengths); } // https://github.com/onecodex/needletail/pull/36 #[test] fn test_bad_headers() { let mut reader = Reader::from_path("tests/data/bad_header.fastq").unwrap(); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let rec2 = reader.next().unwrap(); let e = rec2.unwrap_err(); // Ideally this would not be UnexpectedEnd since we know it's an invalid record // but that's for another day assert_eq!(e.kind, ParseErrorKind::UnexpectedEnd); } // https://github.com/onecodex/needletail/pull/39 #[test] fn test_fastq_with_random_tsv_inside() { let mut reader = Reader::from_path("tests/data/random_tsv.fq").unwrap(); let rec = reader.next().unwrap(); assert!(rec.is_ok()); let rec2 = reader.next().unwrap(); let e = rec2.unwrap_err(); // It errors when it tries to validate the separator line that needs to start with `+` assert_eq!(e.kind, ParseErrorKind::InvalidSeparator); } }
use projecteuler::helper; fn main() { helper::check_bench(|| { solve(); }); assert_eq!(solve(), 1533776805); dbg!(solve()); } //What is the distance from T_n to T_{n+1}? /* Well, obviously: T_{n+1}-T_n = n+1 */ //what is the distance from P_n to P_{n+1}? /* P_{n+1}-P_n = (n+1)(3n+3-1)/2 - n(3n-1)/2 P_{n+1}-P_n = ((n+1)(3n+3-1) - n(3n-1))/2 (n+1)(3n+3-1) - n(3n-1) (n+1)(3n+2) - n(3n-1) 3n²+2n+3n+2 - 3n²+n 2n+3n+2+n 6n+2 P_{n+1}-P_n = (6n+2)/2 P_{n+1}-P_n = 3n+1 */ //What is the distance from H_n to H_{n-1} /* By guessing H_{n+1}-H_n = 4n+1 */ fn solve() -> usize { //since every triangle number is a hexagonal number, we can ignore the triangle numbers let mut p_i = 165; let mut h_i = 143; let mut p = 40755usize; let mut h = p; p += 3 * p_i + 1; p_i += 1; while !(p == h) { if p <= h { p += 3 * p_i + 1; p_i += 1; } else { h += 4 * h_i + 1; h_i += 1; } } p }
#[cfg(test)] mod v8facade_error_handling_tests { use javascript_eval_native::v8facade::{Output, V8Facade}; #[test] fn it_gets_error_with_bad_function_call() { let eval = V8Facade::new(); let result = eval.call("what", vec![]).unwrap(); if let Output::Error(e) = result { assert_eq!("", e.stack_trace); assert_eq!( "Couldn't resolve function `what`, V8 returned: 'undefined'", e.exception ); } else { assert!(false, "I guess no error was thrown..."); } } #[test] fn it_gets_error_when_provided_bad_javascript_for_eval() { let eval = V8Facade::new(); let result = eval .run("fucktion () { return \"Hello World!\"; }") .unwrap(); if let Output::Error(e) = result { assert_eq!("", e.stack_trace); assert_eq!("There was an issue compiling the provided script: SyntaxError: Unexpected token '{'", e.exception); } else { assert!(false, "I guess no error was throw..."); } } }
pub(crate) fn main() { println!("Welcome to the Game! by zul wasaya using RUST language"); println!("using github repo rustfirst"); println!("testing github repo") }
extern crate hyper; extern crate regex; extern crate idna; #[macro_use] extern crate log; extern crate fern; pub mod tldextract; use tldextract::extract::TldExtract; fn setupLogging() { let logger_config = fern::DispatchConfig { format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| { // This is a fairly simple format, though it's possible to do more complicated ones. // This closure can contain any code, as long as it produces a String message. format!("[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(), level, msg) }), output: vec![fern::OutputConfig::stdout(), fern::OutputConfig::file("output.log")], level: log::LogLevelFilter::Trace, }; } #[test] fn multi_level_sub_domain_two_part_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://news.forums.bbc.co.uk"); assert_eq!(domain, "bbc".to_owned()); assert_eq!(subdomain, "news.forums".to_owned()); assert_eq!(suffix, "co.uk".to_owned()); } #[test] fn single_level_sub_domain_simple_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://www.google.com"); assert_eq!(domain, "google".to_owned()); assert_eq!(subdomain, "www".to_owned()); assert_eq!(suffix, "com".to_owned()); } #[test] fn no_sub_domain_simple_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://google.com"); assert_eq!(domain, "google".to_owned()); assert_eq!(subdomain, "".to_owned()); assert_eq!(suffix, "com".to_owned()); } #[test] fn https_no_sub_domain_simple_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("https://google.com"); assert_eq!(domain, "google".to_owned()); assert_eq!(subdomain, "".to_owned()); assert_eq!(suffix, "com".to_owned()); } #[test] fn no_sub_domain_not_a_valid_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://google.notavalidsuffix"); assert_eq!(domain, "notavalidsuffix".to_owned()); assert_eq!(subdomain, "google".to_owned()); assert_eq!(suffix, "".to_owned()); } #[test] fn ip_url() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://127.0.0.1:8080/deployed/"); assert_eq!(domain, "127.0.0.1".to_owned()); assert_eq!(subdomain, "".to_owned()); assert_eq!(suffix, "".to_owned()); } #[test] fn http_single_level_sub_domain_two_part_suffix() { let mut TldExtractor = TldExtract::new(None, None); let (subdomain, domain, suffix) = TldExtractor.extract("http://www.worldbank.org.kg/"); assert_eq!(domain, "worldbank".to_owned()); assert_eq!(subdomain, "www".to_owned()); assert_eq!(suffix, "org.kg".to_owned()); }
//! Bundles commonly used items - meant for internal crate usage only. pub(crate) use crate::connection::Transaction; pub(crate) use crate::params::{named_params, params, RowExt, TryIntoSql, TryIntoSqlInt}; pub(crate) use rusqlite::OptionalExtension;
use std::{env, fmt::Write}; use awto::{ protobuf::{ProtobufField, ProtobufMessage, ProtobufMethod, ProtobufService}, schema::{Model, Role}, }; use heck::SnakeCase; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use crate::util::{is_ty_vec, strip_ty_option}; const COMPILED_PROTO_FILE: &str = "app.proto"; const COMPILED_RUST_FILE: &str = "app.rs"; #[cfg(feature = "async")] pub fn compile_protobuf( models: Vec<Model>, services: Vec<ProtobufService>, ) -> Result<(), Box<dyn std::error::Error>> { use tokio::fs; use tokio::io::AsyncWriteExt; let app_config = A::app_config(); let out_dir = env::var("OUT_DIR").unwrap(); if !app_config.compile_protobuf { return Ok(()); } let compiler = ProtobufCompiler::new(models, services); let proto = compiler.compile_file(); let proto_path = format!("{}/{}", out_dir, COMPILED_PROTO_FILE); fs::write(&proto_path, proto + "\n").await?; tonic_build::configure().compile(&[&proto_path], &[&out_dir])?; let generated_code = compiler.compile_generated_code(); if !generated_code.is_empty() { let rs_path = format!("{}/{}", out_dir, COMPILED_RUST_FILE); let mut schema_file = fs::OpenOptions::new().append(true).open(&rs_path).await?; schema_file.write(generated_code.as_bytes()).await?; schema_file.sync_all().await?; } Ok(()) } #[cfg(not(feature = "async"))] pub fn compile_protobuf( models: Vec<Model>, services: Vec<ProtobufService>, ) -> Result<(), Box<dyn std::error::Error>> { use std::fs; use std::io::Write; let out_dir = env::var("OUT_DIR").unwrap(); let compiler = ProtobufCompiler::new(models, services); let proto = compiler.compile_file(); let proto_path = format!("{}/{}", out_dir, COMPILED_PROTO_FILE); fs::write(&proto_path, proto + "\n")?; tonic_build::configure().compile(&[&proto_path], &[&out_dir])?; let generated_code = compiler.compile_generated_code(); if !generated_code.is_empty() { let rs_path = format!("{}/{}", out_dir, COMPILED_RUST_FILE); let mut schema_file = fs::OpenOptions::new().append(true).open(&rs_path)?; write!(schema_file, "{}", generated_code)?; schema_file.sync_all()?; } Ok(()) } /// Compiles a protobuf schema from a slice of [`ProtobufMessage`]s and [`ProtobufService`]s. /// /// # Examples /// /// ``` /// # use awto_compile::protobuf::ProtobufCompiler; /// # use awto::tests_cfg::*; /// # use awto::protobuf::IntoProtobufService; /// let compiler = ProtobufCompiler::new( /// MODELS.to_vec(), /// vec![ProductService::protobuf_service()], /// ); /// let protobuf_file = compiler.compile_file(); /// /// assert_eq!(protobuf_file, r#"syntax = "proto3"; /// /// package app; /// /// import "google/protobuf/timestamp.proto"; /// /// message Product { /// string id = 1; /// google.protobuf.Timestamp created_at = 2; /// google.protobuf.Timestamp updated_at = 3; /// string name = 4; /// int64 price = 5; /// optional string description = 6; /// } /// /// message ProductId { /// string id = 1; /// } /// /// message ProductList { /// repeated Product products = 1; /// } /// /// message NewProduct { /// string name = 1; /// optional int64 price = 2; /// optional string description = 3; /// } /// /// service ProductService { /// rpc FindProduct(ProductId) returns (ProductList); /// }"#); /// ``` pub struct ProtobufCompiler { models: Vec<Model>, services: Vec<ProtobufService>, } impl ProtobufCompiler { /// Creates a new instance of [`ProtobufCompiler`]. pub fn new(models: Vec<Model>, services: Vec<ProtobufService>) -> ProtobufCompiler { ProtobufCompiler { models, services } } /// Compiles a protobuf file. pub fn compile_file(&self) -> String { let mut proto = String::new(); write!(proto, "{}", self.write_protobuf_header()).unwrap(); writeln!(proto).unwrap(); for message in self.all_protobuf_messages() { writeln!(proto, "{}", self.write_protobuf_message(message)).unwrap(); } for service in &self.services { writeln!(proto, "{}", self.write_protobuf_service(service)).unwrap(); } proto.trim().to_string() } /// Compiles generated Rust code from schemas and services. pub fn compile_generated_code(&self) -> String { let mut code = String::new(); write!( code, r#" pub enum TryFromProtoError {{ InvalidUuid, MissingField(String), }} impl ::std::fmt::Display for TryFromProtoError {{ fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {{ match self {{ Self::InvalidUuid => write!(f, "invalid uuid"), Self::MissingField(field) => write!(f, "missing field '{{}}'", field), }} }} }} "# ) .unwrap(); for (model, _) in self.protobuf_messages() { let ident = format_ident!("{}", model.name); let mut from_rust_fields = Vec::new(); let mut from_proto_fields = Vec::new(); for field in &model.fields { let field_ident = format_ident!("{}", field.name); let field_ident_string = &field.name; let ty = strip_ty_option(&field.ty); match ty { "chrono::NaiveDateTime" | "NaiveDateTime" | "chrono::DateTime<chrono::FixedOffset>" | "chrono::DateTime<FixedOffset>" | "DateTime<chrono::FixedOffset>" | "DateTime<FixedOffset>" => { from_rust_fields.push(quote!( #field_ident: Some(::prost_types::Timestamp { nanos: val.#field_ident.timestamp_nanos() as i32, seconds: val.#field_ident.timestamp(), }) )); from_proto_fields.push(quote!( #field_ident: { let unwrapped_value = val.#field_ident.ok_or_else(|| TryFromProtoError::MissingField(#field_ident_string.to_string()))?; ::chrono::DateTime::from_utc( ::chrono::naive::NaiveDateTime::from_timestamp( unwrapped_value.seconds, unwrapped_value.nanos as u32 ), ::chrono::FixedOffset::east(0), ) } )); } "uuid::Uuid" | "Uuid" => { from_rust_fields.push(quote!( #field_ident: val.#field_ident.to_string() )); from_proto_fields.push(quote!( #field_ident: ::uuid::Uuid::parse_str(&val.#field_ident).map_err(|_| TryFromProtoError::InvalidUuid)? )); } _ => { if is_ty_vec(ty) { from_rust_fields.push(quote!(#field_ident: val.#field_ident.into_iter().map(|v| v.into()).collect())); from_proto_fields.push(quote!(#field_ident: val.#field_ident.into_iter().map(|v| ::std::convert::TryFrom::try_from(v)).collect::<Result<_, _>>()?)); } else { from_rust_fields.push(quote!(#field_ident: val.#field_ident.into())); from_proto_fields.push(quote!(#field_ident: val.#field_ident.into())); } } } } let expanded = quote!( impl ::std::convert::TryFrom<#ident> for ::schema::#ident { type Error = TryFromProtoError; #[allow(unused_variables)] fn try_from(val: #ident) -> Result<Self, Self::Error> { Ok(Self { #( #from_proto_fields, )* }) } } impl ::std::convert::From<::schema::#ident> for #ident { #[allow(unused_variables)] fn from(val: ::schema::#ident) -> Self { Self { #( #from_rust_fields, )* } } } ); write!(code, "{}", expanded.to_string()).unwrap(); } for service in &self.services { let ident = format_ident!("{}", service.name); let service_path: TokenStream = service.module_path.parse().unwrap(); let service_server_name = format_ident!("{}_server", service.name.to_snake_case()); let mut methods = Vec::new(); for method in &service.methods { let name_ident = format_ident!("{}", method.name.to_snake_case()); let param_ident = format_ident!("{}", method.param.name); let returns_ident = format_ident!("{}", method.returns.name); let expanded_call_method = if method.returns_result { if method.is_async { quote!(self.#name_ident(param).await?) } else { quote!(self.#name_ident(param)?) } } else if method.is_async { quote!(self.#name_ident(param).await) } else { quote!(self.#name_ident(param)) }; methods.push(quote!( async fn #name_ident( &self, request: ::tonic::Request<#param_ident>, ) -> Result<::tonic::Response<#returns_ident>, ::tonic::Status> { let inner = request.into_inner(); let param = ::std::convert::TryInto::try_into(inner).map_err(|err: TryFromProtoError| ::tonic::Status::invalid_argument(err.to_string()))?; let value = #expanded_call_method; Ok(::tonic::Response::new(value.into())) } )); } let expanded = quote!( #[::tonic::async_trait] impl #service_server_name::#ident for #service_path::#ident { #( #methods )* } ); write!(code, "{}", expanded.to_string()).unwrap(); } code.trim().to_string() } fn protobuf_messages(&self) -> Vec<(&Model, &ProtobufMessage)> { self.models.iter().fold(Vec::new(), |mut acc, model| { let roles = model .roles .iter() .filter_map(|role| match role { Role::ProtobufMessage(protobuf_message) => Some((model, protobuf_message)), _ => None, }) .collect::<Vec<_>>(); acc.extend(roles); acc }) } fn all_protobuf_messages(&self) -> Vec<&ProtobufMessage> { self.protobuf_messages() .iter() .map(|(_, protobuf_message)| *protobuf_message) .collect() } fn write_protobuf_header(&self) -> String { let mut proto = String::new(); writeln!(proto, r#"syntax = "proto3";"#).unwrap(); writeln!(proto).unwrap(); writeln!(proto, r#"package app;"#).unwrap(); writeln!(proto).unwrap(); writeln!(proto, r#"import "google/protobuf/timestamp.proto";"#).unwrap(); proto } fn write_protobuf_message(&self, message: &ProtobufMessage) -> String { let mut proto = String::new(); writeln!(proto, "message {} {{", message.name).unwrap(); for (i, field) in message.fields.iter().enumerate() { writeln!(proto, " {}", self.write_protobuf_field(field, i)).unwrap(); } writeln!(proto, "}}").unwrap(); proto } fn write_protobuf_field(&self, field: &ProtobufField, index: usize) -> String { let mut proto = String::new(); if !field.required { write!(proto, "optional ").unwrap(); } write!( proto, "{ty} {name} = {num};", ty = field.ty, name = field.name, num = index + 1 ) .unwrap(); proto } fn write_protobuf_service(&self, service: &ProtobufService) -> String { let mut proto = String::new(); writeln!(proto, "service {} {{", service.name).unwrap(); for method in &service.methods { write!(proto, " {}", self.write_protobuf_method(method)).unwrap(); } writeln!(proto, "}}").unwrap(); proto } fn write_protobuf_method(&self, method: &ProtobufMethod) -> String { let mut proto = String::new(); writeln!( proto, "rpc {name}({param}) returns ({returns});", name = method.name, param = method.param.name, returns = method.returns.name, ) .unwrap(); proto } }
use nalgebra::{UnitQuaternion, Quaternion}; use crate::traits::{required::{SliceExt, QuatExt}, extra::F32Compat}; ////////// F32 /////////////////////////// impl F32Compat for Quaternion<f32> { fn write_to_vf32(&self, target: &mut [f32]) { target.copy_from_slice(self.as_slice()); } } impl SliceExt<f32> for Quaternion<f32>{ fn as_slice(&self) -> &[f32] { self.coords.as_slice() } fn as_slice_mut(&mut self) -> &mut [f32] { self.coords.as_mut_slice() } } impl QuatExt<f32> for Quaternion<f32> { fn identity() -> Self { Quaternion::identity() } } impl F32Compat for UnitQuaternion<f32> { fn write_to_vf32(&self, target: &mut [f32]) { target.copy_from_slice(self.as_slice()); } } impl SliceExt<f32> for UnitQuaternion<f32>{ fn as_slice(&self) -> &[f32] { self.coords.as_slice() } fn as_slice_mut(&mut self) -> &mut [f32] { self.as_mut_unchecked().coords.as_mut_slice() //self.coords.as_mut_slice() } } impl QuatExt<f32> for UnitQuaternion<f32> { fn identity() -> Self { UnitQuaternion::identity() } } ////////// F64 /////////////////////////// impl F32Compat for Quaternion<f64>{ fn write_to_vf32(&self, target: &mut [f32]) { //can't memcpy since it needs a cast target[0] = self.coords.x as f32; target[1] = self.coords.y as f32; target[2] = self.coords.z as f32; target[3] = self.coords.w as f32; } } impl SliceExt<f64> for Quaternion<f64>{ fn as_slice(&self) -> &[f64] { self.coords.as_slice() } fn as_slice_mut(&mut self) -> &mut [f64] { self.coords.as_mut_slice() } } impl QuatExt<f64> for Quaternion<f64>{ fn identity() -> Self { //The storage order is [ i, j, k, w ] while the arguments for this functions are in the order (w, i, j, k). nalgebra::Quaternion::new(1.0, 0.0, 0.0, 0.0) } } impl F32Compat for UnitQuaternion<f64>{ fn write_to_vf32(&self, target: &mut [f32]) { //can't memcpy since it needs a cast target[0] = self.coords.x as f32; target[1] = self.coords.y as f32; target[2] = self.coords.z as f32; target[3] = self.coords.w as f32; } } impl SliceExt<f64> for UnitQuaternion<f64>{ fn as_slice(&self) -> &[f64] { self.coords.as_slice() } fn as_slice_mut(&mut self) -> &mut [f64] { self.as_mut_unchecked().coords.as_mut_slice() } } impl QuatExt<f64> for UnitQuaternion<f64>{ fn identity() -> Self { //The storage order is [ i, j, k, w ] while the arguments for this functions are in the order (w, i, j, k). Self::new_unchecked(Quaternion::new(1.0, 0.0, 0.0, 0.0)) } }
use std::io; fn main() { let mut buf = String::new(); let stdin = io::stdin(); stdin .read_line(&mut buf) .expect("Failed to read first line."); let nums: Vec<u32> = buf .split_whitespace() .map(|num| num.parse().unwrap()) .collect(); for _ in 0..nums[0] { buf.clear(); stdin .read_line(&mut buf) .expect("Failed to read matrix row."); for _ in 0..nums[2] { for x in buf.trim().chars() { for _ in 0..nums[3] { print!("{}", x); } } println!(""); } } }
use ::units::Unit; fn fetch_unit(path : &String) -> Unit { Unit::from_file(path.to_string()).unwrap() } pub fn command(args : Vec<String>) { let res = exec(args); println!("{}", res); } fn exec(args : Vec<String>) -> String { match args[1].as_ref() { "precision" => Unit::precision(&fetch_unit(&args[2])).json(), "threat" => Unit::threat(&fetch_unit(&args[2])).json(), "penetration" => Unit::penetration(&fetch_unit(&args[2])).json(), "ranged-threat" => Unit::ranged_threat(&fetch_unit(&args[2])).json(), "ranged-penetration" => Unit::ranged_penetration(&fetch_unit(&args[2])).json(), "combat-threat" => Unit::combat_threat(&fetch_unit(&args[2])).json(), "combat-penetration" => Unit::combat_penetration(&fetch_unit(&args[2])).json(), "effective-threat" => Unit::effective_threat(&fetch_unit(&args[2])).json(), "effective-penetration" => Unit::effective_penetration(&fetch_unit(&args[2])).json(), "ekl" => Unit::ekl(&fetch_unit(&args[2])).json(), "unsaved" => Unit::unsaved(&fetch_unit(&args[2]), &fetch_unit(&args[3])).json(), "damage" => Unit::damage(&fetch_unit(&args[2]), &fetch_unit(&args[3])).json(), "fight" => Unit::fight(&fetch_unit(&args[2]), &fetch_unit(&args[3])).json(), "top-threat-efficiency" => Unit::top_threat_efficiency(args).json(), "top-penetration-efficiency" => Unit::top_penetration_efficiency(args).json(), "top-ranged-threat-efficiency" => Unit::top_ranged_threat_efficiency(args).json(), "top-ranged-penetration-efficiency" => Unit::top_ranged_penetration_efficiency(args).json(), "top-combat-threat-efficiency" => Unit::top_combat_threat_efficiency(args).json(), "top-combat-penetration-efficiency" => Unit::top_combat_penetration_efficiency(args).json(), _ => format!("Unknown command: {}\n", args[1]), } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::vec::Vec; pub const BITS_PER_BYTE: usize = 8; pub const BYTES_PER_LONG: usize = 8; // only for 64-bit architectures pub fn CPUSetSize(num: usize) -> usize { let bytes = (num + BITS_PER_BYTE - 1) / BITS_PER_BYTE; let longs = (bytes + BYTES_PER_LONG - 1) / BYTES_PER_LONG; return longs * BYTES_PER_LONG } const ONES: [u8; 256] = [ 0x00, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x03, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x01, 0x02, 0x02, 0x03, 0x02, 0x03, 0x03, 0x04, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x02, 0x03, 0x03, 0x04, 0x03, 0x04, 0x04, 0x05, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x05, 0x06, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x04, 0x05, 0x05, 0x06, 0x05, 0x06, 0x06, 0x07, 0x05, 0x06, 0x06, 0x07, 0x06, 0x07, 0x07, 0x08, ]; #[derive(Default, Debug)] pub struct CPUSet(pub Vec<u8>); impl CPUSet { // NewCPUSet returns a CPUSet for the given number of CPUs which initially // contains no CPUs. pub fn New(num: usize) -> Self { return Self(vec![0; CPUSetSize(num)]) } // NewFullCPUSet returns a CPUSet for the given number of CPUs, all of which // are present in the set. pub fn NewFullCPUSet(num: usize) -> Self { let mut set = Self::New(num); for i in 0..num / BITS_PER_BYTE { set.0[i] = 0xff; } let idx = num / BITS_PER_BYTE; let rem = num % BITS_PER_BYTE; if rem != 0 { set.0[idx] = (1 << rem) - 1; } return set } // Size returns the size of 'c' in bytes. pub fn Size(&self) -> usize { return self.0.len() } // NumCPUs returns how many cpus are set in the CPUSet. pub fn NumCPUs(&self) -> usize { let mut res = 0; for v in &self.0 { res += ONES[*v as usize] as usize } return res } // Copy returns a copy of the CPUSet. pub fn Copy(&self) -> Self { let mut dup = Vec::with_capacity(self.0.len()); for v in &self.0 { dup.push(*v) } return Self(dup) } // Set sets the bit corresponding to cpu. pub fn Set(&mut self, cpu: usize) { self.0[cpu / BITS_PER_BYTE] |= 1 << (cpu % BITS_PER_BYTE) } // ClearAbove clears bits corresponding to cpu and all higher cpus. pub fn ClearAbove(&mut self, cpu: usize) { let i = cpu / BITS_PER_BYTE; if i >= self.0.len() { return; } self.0[i] &= !(0xff << (cpu % BITS_PER_BYTE)); for v in i + 1..self.0.len() { self.0[v] = 0; } } // ForEachCPU iterates over the CPUSet and calls fn with the cpu index if // it's set. pub fn ForEachCPU(&self, mut f: impl FnMut(usize)) { for i in 0..self.0.len() * BITS_PER_BYTE { let bit = 1 << (i & (BITS_PER_BYTE - 1)); if (self.0[i / BITS_PER_BYTE] as usize) & bit == bit { f(i) } } } }
use utopia_core::widgets::Widget; use crate::{context::ImageContext, primitive::ImagePrimitive}; #[derive(Debug)] pub struct Image<Img> { _src: std::marker::PhantomData<Img>, } impl<Img> Image<Img> { pub fn new() -> Self { Image { _src: std::marker::PhantomData, } } } impl<Img: Clone> Widget<Img> for Image<Img> { type Primitive = ImagePrimitive<Img>; type Context = ImageContext<Img>; type Event = (); type Reaction = (); fn draw( &self, origin: utopia_core::math::Vector2, size: utopia_core::math::Size, data: &Img, ) -> Self::Primitive { ImagePrimitive { position: origin, size, src: data.clone(), } } fn layout( &mut self, bc: &utopia_core::BoxConstraints, context: &Self::Context, data: &Img, ) -> utopia_core::math::Size { let size = (context.measure)(data); bc.constrain(size) } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Security_Authentication_Identity")] pub mod Identity;
//! This module holds the definitions of //! AB_JTM related wrappers. use libc::time_t; use data_structs::AB_JTM; use jalali_bindings::*; use std::mem; impl AB_JTM { /// This function initializes the struct. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// jalali::AB_JTM::new(); /// /// ``` pub fn new() -> Self { AB_JTM { ab_sec: 0, ab_min: 0, ab_hour: 0, ab_days: 0, } } /// This function initializes the struct based on the number of seconds passed since UTC Epoch. /// /// # Arguments /// /// * `secs` - A 64 bit integer representing number of seconds passed since UTC Epoch. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// jalali::AB_JTM::from_secs(719425800); /// /// ``` pub fn from_secs(secs: i64) -> Self { let mut result; unsafe { result = mem::uninitialized(); jalali_create_time_from_secs(secs as time_t, &mut result); } result } /// This function initializes the struct based on the number of seconds passed since UTC Epoch. /// /// # Examples /// /// ``` /// extern crate jalali; /// /// let j = jalali::AB_JTM::from_secs(719425800); /// /// assert_eq!(j.to_secs(), 719425800); /// ``` pub fn to_secs(&self) -> i64 { unsafe { jalali_create_secs_from_time(self) } } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Access control register"] pub acr: ACR, _reserved1: [u8; 4usize], #[doc = "0x08 - Flash key register"] pub keyr: KEYR, #[doc = "0x0c - Option byte key register"] pub optkeyr: OPTKEYR, #[doc = "0x10 - Status register"] pub sr: SR, #[doc = "0x14 - Flash control register"] pub cr: CR, #[doc = "0x18 - Flash ECC register"] pub eccr: ECCR, _reserved6: [u8; 4usize], #[doc = "0x20 - Flash option register"] pub optr: OPTR, #[doc = "0x24 - Flash PCROP zone A Start address register"] pub pcrop1asr: PCROP1ASR, #[doc = "0x28 - Flash PCROP zone A End address register"] pub pcrop1aer: PCROP1AER, #[doc = "0x2c - Flash WRP area A address register"] pub wrp1ar: WRP1AR, #[doc = "0x30 - Flash WRP area B address register"] pub wrp1br: WRP1BR, #[doc = "0x34 - Flash PCROP zone B Start address register"] pub pcrop1bsr: PCROP1BSR, #[doc = "0x38 - Flash PCROP zone B End address register"] pub pcrop1ber: PCROP1BER, _reserved13: [u8; 68usize], #[doc = "0x80 - Flash Security register"] pub secr: SECR, } #[doc = "Access control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [acr](acr) module"] pub type ACR = crate::Reg<u32, _ACR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ACR; #[doc = "`read()` method returns [acr::R](acr::R) reader structure"] impl crate::Readable for ACR {} #[doc = "`write(|w| ..)` method takes [acr::W](acr::W) writer structure"] impl crate::Writable for ACR {} #[doc = "Access control register"] pub mod acr; #[doc = "Flash key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [keyr](keyr) module"] pub type KEYR = crate::Reg<u32, _KEYR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _KEYR; #[doc = "`write(|w| ..)` method takes [keyr::W](keyr::W) writer structure"] impl crate::Writable for KEYR {} #[doc = "Flash key register"] pub mod keyr; #[doc = "Option byte key register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optkeyr](optkeyr) module"] pub type OPTKEYR = crate::Reg<u32, _OPTKEYR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OPTKEYR; #[doc = "`write(|w| ..)` method takes [optkeyr::W](optkeyr::W) writer structure"] impl crate::Writable for OPTKEYR {} #[doc = "Option byte key register"] pub mod optkeyr; #[doc = "Status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sr](sr) module"] pub type SR = crate::Reg<u32, _SR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SR; #[doc = "`read()` method returns [sr::R](sr::R) reader structure"] impl crate::Readable for SR {} #[doc = "`write(|w| ..)` method takes [sr::W](sr::W) writer structure"] impl crate::Writable for SR {} #[doc = "Status register"] pub mod sr; #[doc = "Flash control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"] pub type CR = crate::Reg<u32, _CR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _CR; #[doc = "`read()` method returns [cr::R](cr::R) reader structure"] impl crate::Readable for CR {} #[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"] impl crate::Writable for CR {} #[doc = "Flash control register"] pub mod cr; #[doc = "Flash ECC register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [eccr](eccr) module"] pub type ECCR = crate::Reg<u32, _ECCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ECCR; #[doc = "`read()` method returns [eccr::R](eccr::R) reader structure"] impl crate::Readable for ECCR {} #[doc = "`write(|w| ..)` method takes [eccr::W](eccr::W) writer structure"] impl crate::Writable for ECCR {} #[doc = "Flash ECC register"] pub mod eccr; #[doc = "Flash option register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [optr](optr) module"] pub type OPTR = crate::Reg<u32, _OPTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _OPTR; #[doc = "`read()` method returns [optr::R](optr::R) reader structure"] impl crate::Readable for OPTR {} #[doc = "`write(|w| ..)` method takes [optr::W](optr::W) writer structure"] impl crate::Writable for OPTR {} #[doc = "Flash option register"] pub mod optr; #[doc = "Flash PCROP zone A Start address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1asr](pcrop1asr) module"] pub type PCROP1ASR = crate::Reg<u32, _PCROP1ASR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PCROP1ASR; #[doc = "`read()` method returns [pcrop1asr::R](pcrop1asr::R) reader structure"] impl crate::Readable for PCROP1ASR {} #[doc = "Flash PCROP zone A Start address register"] pub mod pcrop1asr; #[doc = "Flash PCROP zone A End address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1aer](pcrop1aer) module"] pub type PCROP1AER = crate::Reg<u32, _PCROP1AER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PCROP1AER; #[doc = "`read()` method returns [pcrop1aer::R](pcrop1aer::R) reader structure"] impl crate::Readable for PCROP1AER {} #[doc = "Flash PCROP zone A End address register"] pub mod pcrop1aer; #[doc = "Flash WRP area A address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrp1ar](wrp1ar) module"] pub type WRP1AR = crate::Reg<u32, _WRP1AR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WRP1AR; #[doc = "`read()` method returns [wrp1ar::R](wrp1ar::R) reader structure"] impl crate::Readable for WRP1AR {} #[doc = "Flash WRP area A address register"] pub mod wrp1ar; #[doc = "Flash WRP area B address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [wrp1br](wrp1br) module"] pub type WRP1BR = crate::Reg<u32, _WRP1BR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _WRP1BR; #[doc = "`read()` method returns [wrp1br::R](wrp1br::R) reader structure"] impl crate::Readable for WRP1BR {} #[doc = "Flash WRP area B address register"] pub mod wrp1br; #[doc = "Flash PCROP zone B Start address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1bsr](pcrop1bsr) module"] pub type PCROP1BSR = crate::Reg<u32, _PCROP1BSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PCROP1BSR; #[doc = "`read()` method returns [pcrop1bsr::R](pcrop1bsr::R) reader structure"] impl crate::Readable for PCROP1BSR {} #[doc = "Flash PCROP zone B Start address register"] pub mod pcrop1bsr; #[doc = "Flash PCROP zone B End address register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pcrop1ber](pcrop1ber) module"] pub type PCROP1BER = crate::Reg<u32, _PCROP1BER>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PCROP1BER; #[doc = "`read()` method returns [pcrop1ber::R](pcrop1ber::R) reader structure"] impl crate::Readable for PCROP1BER {} #[doc = "Flash PCROP zone B End address register"] pub mod pcrop1ber; #[doc = "Flash Security register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [secr](secr) module"] pub type SECR = crate::Reg<u32, _SECR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SECR; #[doc = "`read()` method returns [secr::R](secr::R) reader structure"] impl crate::Readable for SECR {} #[doc = "Flash Security register"] pub mod secr;
use sqlx::error::DatabaseError; use sqlx::sqlite::{SqliteConnectOptions, SqliteError}; use sqlx::ConnectOptions; use sqlx::TypeInfo; use sqlx::{sqlite::Sqlite, Column, Executor}; use sqlx_test::new; use std::env; #[sqlx_macros::test] async fn it_describes_simple() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let info = conn.describe("SELECT * FROM tweet").await?; let columns = info.columns(); assert_eq!(columns[0].name(), "id"); assert_eq!(columns[1].name(), "text"); assert_eq!(columns[2].name(), "is_sent"); assert_eq!(columns[3].name(), "owner_id"); assert_eq!(columns[0].ordinal(), 0); assert_eq!(columns[1].ordinal(), 1); assert_eq!(columns[2].ordinal(), 2); assert_eq!(columns[3].ordinal(), 3); assert_eq!(info.nullable(0), Some(false)); assert_eq!(info.nullable(1), Some(false)); assert_eq!(info.nullable(2), Some(false)); assert_eq!(info.nullable(3), Some(true)); // owner_id assert_eq!(columns[0].type_info().name(), "INTEGER"); assert_eq!(columns[1].type_info().name(), "TEXT"); assert_eq!(columns[2].type_info().name(), "BOOLEAN"); assert_eq!(columns[3].type_info().name(), "INTEGER"); Ok(()) } #[sqlx_macros::test] async fn it_describes_variables() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; // without any context, we resolve to NULL let info = conn.describe("SELECT ?1").await?; assert_eq!(info.columns()[0].type_info().name(), "NULL"); assert_eq!(info.nullable(0), Some(true)); // nothing prevents the value from being bound to null // context can be provided by using CAST(_ as _) let info = conn.describe("SELECT CAST(?1 AS REAL)").await?; assert_eq!(info.columns()[0].type_info().name(), "REAL"); assert_eq!(info.nullable(0), Some(true)); // nothing prevents the value from being bound to null Ok(()) } #[sqlx_macros::test] async fn it_describes_expression() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let d = conn .describe("SELECT 1 + 10, 5.12 * 2, 'Hello', x'deadbeef', null") .await?; let columns = d.columns(); assert_eq!(columns[0].type_info().name(), "INTEGER"); assert_eq!(columns[0].name(), "1 + 10"); assert_eq!(d.nullable(0), Some(false)); // literal constant assert_eq!(columns[1].type_info().name(), "REAL"); assert_eq!(columns[1].name(), "5.12 * 2"); assert_eq!(d.nullable(1), Some(false)); // literal constant assert_eq!(columns[2].type_info().name(), "TEXT"); assert_eq!(columns[2].name(), "'Hello'"); assert_eq!(d.nullable(2), Some(false)); // literal constant assert_eq!(columns[3].type_info().name(), "BLOB"); assert_eq!(columns[3].name(), "x'deadbeef'"); assert_eq!(d.nullable(3), Some(false)); // literal constant assert_eq!(columns[4].type_info().name(), "NULL"); assert_eq!(columns[4].name(), "null"); assert_eq!(d.nullable(4), Some(true)); // literal null Ok(()) } #[sqlx_macros::test] async fn it_describes_expression_from_empty_table() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; conn.execute("CREATE TEMP TABLE _temp_empty ( name TEXT NOT NULL, a INT )") .await?; let d = conn .describe("SELECT COUNT(*), a + 1, name, 5.12, 'Hello' FROM _temp_empty") .await?; assert_eq!(d.columns()[0].type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(false)); // COUNT(*) assert_eq!(d.columns()[1].type_info().name(), "INTEGER"); assert_eq!(d.nullable(1), Some(true)); // `a+1` is nullable, because a is nullable assert_eq!(d.columns()[2].type_info().name(), "TEXT"); assert_eq!(d.nullable(2), Some(true)); // `name` is not nullable, but the query can be null due to zero rows assert_eq!(d.columns()[3].type_info().name(), "REAL"); assert_eq!(d.nullable(3), Some(false)); // literal constant assert_eq!(d.columns()[4].type_info().name(), "TEXT"); assert_eq!(d.nullable(4), Some(false)); // literal constant Ok(()) } #[sqlx_macros::test] async fn it_describes_expression_from_empty_table_with_star() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; conn.execute("CREATE TEMP TABLE _temp_empty ( name TEXT, a INT )") .await?; let d = conn .describe("SELECT *, 5, 'Hello' FROM _temp_empty") .await?; assert_eq!(d.columns()[0].type_info().name(), "TEXT"); assert_eq!(d.columns()[1].type_info().name(), "INTEGER"); assert_eq!(d.columns()[2].type_info().name(), "INTEGER"); assert_eq!(d.columns()[3].type_info().name(), "TEXT"); Ok(()) } #[sqlx_macros::test] async fn it_describes_insert() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let d = conn .describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello')") .await?; assert_eq!(d.columns().len(), 0); let d = conn .describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello'); SELECT last_insert_rowid();") .await?; assert_eq!(d.columns().len(), 1); assert_eq!(d.columns()[0].type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(false)); Ok(()) } #[sqlx_macros::test] async fn it_describes_insert_with_read_only() -> anyhow::Result<()> { sqlx_test::setup_if_needed(); let mut options: SqliteConnectOptions = env::var("DATABASE_URL")?.parse().unwrap(); options = options.read_only(true); let mut conn = options.connect().await?; let d = conn .describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello')") .await?; assert_eq!(d.columns().len(), 0); Ok(()) } #[sqlx_macros::test] async fn it_describes_insert_with_returning() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let d = conn .describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello') RETURNING *") .await?; assert_eq!(d.columns().len(), 4); assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.column(1).type_info().name(), "TEXT"); Ok(()) } #[sqlx_macros::test] async fn it_describes_bad_statement() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let err = conn.describe("SELECT 1 FROM not_found").await.unwrap_err(); let err = err .as_database_error() .unwrap() .downcast_ref::<SqliteError>(); assert_eq!(err.message(), "no such table: not_found"); assert_eq!(err.code().as_deref(), Some("1")); Ok(()) } #[sqlx_macros::test] async fn it_describes_left_join() -> anyhow::Result<()> { let mut conn = new::<Sqlite>().await?; let d = conn.describe("select accounts.id from accounts").await?; assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(false)); let d = conn .describe("select tweet.id from accounts left join tweet on owner_id = accounts.id") .await?; assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(true)); let d = conn .describe( "select tweet.id, accounts.id from accounts left join tweet on owner_id = accounts.id", ) .await?; assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(true)); assert_eq!(d.column(1).type_info().name(), "INTEGER"); assert_eq!(d.nullable(1), Some(false)); let d = conn .describe( "select tweet.id, accounts.id from accounts inner join tweet on owner_id = accounts.id", ) .await?; assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(false)); assert_eq!(d.column(1).type_info().name(), "INTEGER"); assert_eq!(d.nullable(1), Some(false)); let d = conn .describe( "select tweet.id, accounts.id from accounts left join tweet on tweet.id = accounts.id", ) .await?; assert_eq!(d.column(0).type_info().name(), "INTEGER"); assert_eq!(d.nullable(0), Some(true)); assert_eq!(d.column(1).type_info().name(), "INTEGER"); assert_eq!(d.nullable(1), Some(false)); Ok(()) } #[sqlx_macros::test] async fn it_describes_literal_subquery() -> anyhow::Result<()> { async fn assert_literal_described( conn: &mut sqlx::SqliteConnection, query: &str, ) -> anyhow::Result<()> { let info = conn.describe(query).await?; assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query); assert_eq!(info.nullable(0), Some(false), "{}", query); assert_eq!(info.column(1).type_info().name(), "NULL", "{}", query); assert_eq!(info.nullable(1), Some(true), "{}", query); Ok(()) } let mut conn = new::<Sqlite>().await?; assert_literal_described(&mut conn, "SELECT 'a', NULL").await?; assert_literal_described(&mut conn, "SELECT * FROM (SELECT 'a', NULL)").await?; assert_literal_described( &mut conn, "WITH cte AS (SELECT 'a', NULL) SELECT * FROM cte", ) .await?; assert_literal_described( &mut conn, "WITH cte AS MATERIALIZED (SELECT 'a', NULL) SELECT * FROM cte", ) .await?; assert_literal_described( &mut conn, "WITH RECURSIVE cte(a,b) AS (SELECT 'a', NULL UNION ALL SELECT a||a, NULL FROM cte WHERE length(a)<3) SELECT * FROM cte", ) .await?; Ok(()) } #[sqlx_macros::test] async fn it_describes_table_subquery() -> anyhow::Result<()> { async fn assert_tweet_described( conn: &mut sqlx::SqliteConnection, query: &str, ) -> anyhow::Result<()> { let info = conn.describe(query).await?; let columns = info.columns(); assert_eq!(columns[0].name(), "id", "{}", query); assert_eq!(columns[1].name(), "text", "{}", query); assert_eq!(columns[2].name(), "is_sent", "{}", query); assert_eq!(columns[3].name(), "owner_id", "{}", query); assert_eq!(columns[0].ordinal(), 0, "{}", query); assert_eq!(columns[1].ordinal(), 1, "{}", query); assert_eq!(columns[2].ordinal(), 2, "{}", query); assert_eq!(columns[3].ordinal(), 3, "{}", query); assert_eq!(info.nullable(0), Some(false), "{}", query); assert_eq!(info.nullable(1), Some(false), "{}", query); assert_eq!(info.nullable(2), Some(false), "{}", query); assert_eq!(info.nullable(3), Some(true), "{}", query); assert_eq!(columns[0].type_info().name(), "INTEGER", "{}", query); assert_eq!(columns[1].type_info().name(), "TEXT", "{}", query); assert_eq!(columns[2].type_info().name(), "BOOLEAN", "{}", query); assert_eq!(columns[3].type_info().name(), "INTEGER", "{}", query); Ok(()) } let mut conn = new::<Sqlite>().await?; assert_tweet_described(&mut conn, "SELECT * FROM tweet").await?; assert_tweet_described(&mut conn, "SELECT * FROM (SELECT * FROM tweet)").await?; assert_tweet_described( &mut conn, "WITH cte AS (SELECT * FROM tweet) SELECT * FROM cte", ) .await?; assert_tweet_described( &mut conn, "WITH cte AS MATERIALIZED (SELECT * FROM tweet) SELECT * FROM cte", ) .await?; Ok(()) } #[sqlx_macros::test] async fn it_describes_union() -> anyhow::Result<()> { async fn assert_union_described( conn: &mut sqlx::SqliteConnection, query: &str, ) -> anyhow::Result<()> { let info = conn.describe(query).await?; assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query); assert_eq!(info.nullable(0), Some(false), "{}", query); assert_eq!(info.column(1).type_info().name(), "TEXT", "{}", query); assert_eq!(info.nullable(1), Some(true), "{}", query); assert_eq!(info.column(2).type_info().name(), "INTEGER", "{}", query); assert_eq!(info.nullable(2), Some(true), "{}", query); //TODO: mixed type columns not handled correctly //assert_eq!(info.column(3).type_info().name(), "NULL", "{}", query); //assert_eq!(info.nullable(3), Some(false), "{}", query); Ok(()) } let mut conn = new::<Sqlite>().await?; assert_union_described( &mut conn, "SELECT 'txt','a',null,'b' UNION ALL SELECT 'int',NULL,1,2 ", ) .await?; //TODO: insert into temp-table not merging datatype/nullable of all operations - currently keeping last-writer //assert_union_described(&mut conn, "SELECT 'txt','a',null,'b' UNION SELECT 'int',NULL,1,2 ").await?; Ok(()) }
//mod print; //mod vars; //mod types; //mod ifs; //mod loops; //mod boolean; //mod hi; fn main() { //print::run(); //vars::run(); //types::run(); //ifs::run(); //loops::run(); //boolean::run(); //hi::run(); }
use proconio::{input, marker::Chars}; const M: u64 = 998244353; macro_rules! add { ($a: expr, $b: expr) => { $a = ($a + $b) % M; }; } fn main() { input! { s: Chars, }; let mut dp = vec![0_u64; s.len() + 1]; dp[0] = 1; for &ch in &s { let mut next = vec![0; s.len() + 1]; if ch == '(' { for i in 0..s.len() { next[i + 1] = dp[i]; } } else if ch == ')' { for i in 0..s.len() { next[i] = dp[i + 1]; } } else { // ? -> ( for i in 0..s.len() { next[i + 1] = dp[i]; } // ? -> ) for i in 0..s.len() { add!(next[i], dp[i + 1]); } } dp = next; } println!("{}", dp[0]); }
use crate::{ event::log_schema, sinks::util::{ encoding::{EncodingConfig, EncodingConfiguration}, tcp::TcpSink, Encoding, UriSerde, }, tls::{MaybeTlsSettings, TlsSettings}, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use bytes::Bytes; use futures01::{stream::iter_ok, Sink}; use serde::{Deserialize, Serialize}; use syslog::{Facility, Formatter3164, LogFormat, Severity}; #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] pub struct PapertrailConfig { endpoint: UriSerde, encoding: EncodingConfig<Encoding>, } inventory::submit! { SinkDescription::new_without_default::<PapertrailConfig>("papertrail") } #[typetag::serde(name = "papertrail")] impl SinkConfig for PapertrailConfig { fn build(&self, cx: SinkContext) -> crate::Result<(super::RouterSink, super::Healthcheck)> { let host = self .endpoint .host() .map(str::to_string) .ok_or_else(|| "A host is required for endpoints".to_string())?; let port = self .endpoint .port_u16() .ok_or_else(|| "A port is required for endpoints".to_string())?; let sink = TcpSink::new( host, port, cx.resolver(), MaybeTlsSettings::Tls(TlsSettings::default()), ); let healthcheck = sink.healthcheck(); let pid = std::process::id(); let encoding = self.encoding.clone(); let sink = sink.with_flat_map(move |e| iter_ok(encode_event(e, pid, &encoding))); Ok((Box::new(sink), Box::new(healthcheck))) } fn input_type(&self) -> DataType { DataType::Log } fn sink_type(&self) -> &'static str { "papertrail" } } fn encode_event( mut event: crate::Event, pid: u32, encoding: &EncodingConfig<Encoding>, ) -> Option<Bytes> { encoding.apply_rules(&mut event); let host = if let Some(host) = event.as_mut_log().remove(log_schema().host_key()) { Some(host.to_string_lossy()) } else { None }; let formatter = Formatter3164 { facility: Facility::LOG_USER, hostname: host, process: "vector".into(), pid: pid as i32, }; let mut s: Vec<u8> = Vec::new(); let log = event.into_log(); let message = match encoding.codec() { Encoding::Json => serde_json::to_string(&log).unwrap(), Encoding::Text => log .get(&log_schema().message_key()) .map(|v| v.to_string_lossy()) .unwrap_or_default(), }; formatter .format(&mut s, Severity::LOG_INFO, message) .unwrap(); s.push(b'\n'); Some(Bytes::from(s)) }
use crate::input_error::InputError; pub struct Passport { value_map: std::collections::HashMap<String, String>, } impl Passport { pub fn new(key_value_row: &str) -> Result<Passport, InputError> { let mut value_map = std::collections::HashMap::<String, String>::new(); let key_value_pairs = key_value_row .split(" ") .map(|p| p.split(":")); for mut pair in key_value_pairs { let key = match pair.next() { Some(k) => k, None => return Err(InputError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Bad key:value pair"))), }; let value = match pair.next() { Some(v) => v, None => return Err(InputError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, "Bad key:value pair"))), }; value_map.insert(String::from(key), String::from(value)); } return Ok(Passport { value_map: value_map }); } pub fn is_valid(&self, apply_validators: bool) -> bool { let required_field_keys = Passport::required_field_keys(); let validators = Passport::field_validators(); if required_field_keys.iter().all(|k| self.value_map.contains_key(k)) { if apply_validators { return self.value_map.iter() .all(|(k, v)| !validators.contains_key(k) || validators[k](v)); } else { return true; } } return false; } fn required_field_keys() -> Vec<String> { return vec!( String::from("byr"), String::from("iyr"), String::from("eyr"), String::from("hgt"), String::from("hcl"), String::from("ecl"), String::from("pid"), ); } fn field_validators() -> std::collections::HashMap::<String, fn(&String) -> bool> { let mut map = std::collections::HashMap::<String, fn(&String) -> bool>::new(); map.insert(String::from("byr"), Passport::birth_year_valid); map.insert(String::from("iyr"), Passport::issue_year_valid); map.insert(String::from("eyr"), Passport::expiration_year_valid); map.insert(String::from("hgt"), Passport::height_valid); map.insert(String::from("hcl"), Passport::hair_color_valid); map.insert(String::from("ecl"), Passport::eye_color_valid); map.insert(String::from("pid"), Passport::passport_id_valid); return map; } fn birth_year_valid(year: &String) -> bool { //byr (Birth Year) - four digits; at least 1920 and at most 2002. return match year.parse::<usize>() { Ok(y) => y >= 1920 && y <= 2002, Err(_) => false, } } fn issue_year_valid(year: &String) -> bool { //iyr (Issue Year) - four digits; at least 2010 and at most 2020. return match year.parse::<usize>() { Ok(y) => y >= 2010 && y <= 2020, Err(_) => false, } } fn expiration_year_valid(year: &String) -> bool { //eyr (Expiration Year) - four digits; at least 2020 and at most 2030. return match year.parse::<usize>().map_err(InputError::Parse) { Ok(y) => y >= 2020 && y <= 2030, Err(_) => false, } } fn height_valid(height: &String) -> bool { //hgt (Height) - a number followed by either cm or in: //If cm, the number must be at least 150 and at most 193. //If in, the number must be at least 59 and at most 76. let height_parts = height.split_at(height.len() - 2); let h = match height_parts.0.parse::<usize>() { Ok(h) => h, Err(_) => return false, }; return match height_parts.1 { "cm" => h >= 150 && h <= 193, "in" => h >= 59 && h <= 76, _ => false, }; } fn hair_color_valid(hair_color: &String) -> bool { //hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. return match regex::Regex::new(r"^#[0-9a-f]{6}$") { Ok(r) => r.is_match(&hair_color), Err(_) => false, }; } fn eye_color_valid(eye_color: &String) -> bool { //ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. return vec!("amb", "blu", "brn", "gry", "grn", "hzl", "oth").iter() .any(|c| c == &eye_color); } fn passport_id_valid(passport_id: &String) -> bool { //pid (Passport ID) - a nine-digit number, including leading zeroes. return match regex::Regex::new(r"^[0-9]{9}$") { Ok(r) => r.is_match(&passport_id), Err(_) => false, }; } //cid (Country ID) - ignored, missing or not. } #[cfg(test)] mod tests { use super::InputError; use super::Passport; #[test] fn count_valid_passports_with_validation() -> Result<(), InputError> { let values = vec!( String::from("ecl:gry pid:860033327 eyr:2020 hcl:#fffffd"), String::from("byr:1937 iyr:2017 cid:147 hgt:183cm"), String::from(""), String::from("iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884"), String::from("hcl:#cfa07d byr:1929"), String::from(""), String::from("hcl:#ae17e1 iyr:2013"), String::from("eyr:2024"), String::from("ecl:brn pid:760753108 byr:1931"), String::from("hgt:179cm"), String::from(""), String::from("hcl:#cfa07d eyr:2025 pid:166559648"), String::from("iyr:2011 ecl:brn hgt:59in"), ); let mut passports: Vec<Passport> = Vec::new(); let mut key_value_row: String = String::from(""); for i in 0..values.len() { let line = &values[i]; if line == "" { passports.push(Passport::new(&key_value_row.trim())?); key_value_row = String::from(""); } else { key_value_row.push_str(" "); key_value_row.push_str(line); } } if key_value_row != "" { passports.push(Passport::new(&key_value_row.trim())?); } let actual = passports.iter().filter(|p| p.is_valid(false)).count(); assert_eq!(2, actual); return Ok(()); } #[test] fn count_invalid_passports_with_validators() -> Result<(), InputError> { let values = vec!( String::from("eyr:1972 cid:100"), String::from("hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926"), String::from(""), String::from("iyr:2019"), String::from("hcl:#602927 eyr:1967 hgt:170cm"), String::from("ecl:grn pid:012533040 byr:1946"), String::from(""), String::from("hcl:dab227 iyr:2012"), String::from("ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277"), String::from(""), String::from("hgt:59cm ecl:zzz"), String::from("eyr:2038 hcl:74454a iyr:2023"), String::from("pid:3556412378 byr:2007"), ); let mut passports: Vec<Passport> = Vec::new(); let mut key_value_row: String = String::from(""); for i in 0..values.len() { let line = &values[i]; if line == "" { passports.push(Passport::new(&key_value_row.trim())?); key_value_row = String::from(""); } else { key_value_row.push_str(" "); key_value_row.push_str(line); } } if key_value_row != "" { passports.push(Passport::new(&key_value_row.trim())?); } let actual = passports.iter().filter(|p| p.is_valid(true)).count(); assert_eq!(0, actual); return Ok(()); } #[test] fn count_valid_passports_with_validators() -> Result<(), InputError> { let values = vec!( String::from("pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980"), String::from("hcl:#623a2f"), String::from(""), String::from("eyr:2029 ecl:blu cid:129 byr:1989"), String::from("iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm"), String::from(""), String::from("hcl:#888785"), String::from("hgt:164cm byr:2001 iyr:2015 cid:88"), String::from("pid:545766238 ecl:hzl"), String::from("eyr:2022"), String::from(""), String::from("iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719"), ); let mut passports: Vec<Passport> = Vec::new(); let mut key_value_row: String = String::from(""); for i in 0..values.len() { let line = &values[i]; if line == "" { passports.push(Passport::new(&key_value_row.trim())?); key_value_row = String::from(""); } else { key_value_row.push_str(" "); key_value_row.push_str(line); } } if key_value_row != "" { passports.push(Passport::new(&key_value_row.trim())?); } let actual = passports.iter().filter(|p| p.is_valid(true)).count(); assert_eq!(4, actual); return Ok(()); } }
use crate::{ast::Position, parser::ParserSettings}; use sm_parser::Span; impl Default for ParserSettings { fn default() -> Self { Self { file: String::from("anonymous"), refine: true } } } impl ParserSettings { pub(crate) fn get_position(&self, s: Span) -> Position { Position { file: self.file.clone(), start: s.start_pos().line_col(), end: s.end_pos().line_col() } } }
use winapi::shared::minwindef::{HINSTANCE, HRSRC, HGLOBAL}; use winapi::um::winuser::{LoadImageW, LR_DEFAULTSIZE, LR_CREATEDIBSECTION}; use winapi::ctypes::c_void; use crate::win32::base_helper::{to_utf16, from_utf16}; use crate::NwgError; use super::{Icon, Bitmap, Cursor}; use std::{ptr, slice}; /// Raw resource type that can be stored into an embedded resource. #[derive(Copy, Clone, Debug)] pub enum RawResourceType { Cursor, Bitmap, Icon, Menu, Dialog, String, FontDir, Font, Accelerator, RawData, MessageTable, Version, DlgInclude, PlugPlay, Vxd, AnimatedCursor, AnimatedIcon, Html, Manifest, Other(&'static str) } /** Represents a raw handle to a embed resource. Manipulating raw resources is inherently unsafe. `RawResources` are loaded using `EmbedResource::raw` and `EmbedResource::raw_str` In order to access the raw resource data use `as_mut_ptr()` or `as_mut_slice()` and cast the pointer to your data type. */ pub struct RawResource { module: HINSTANCE, handle: HRSRC, data_handle: HGLOBAL, ty: RawResourceType, } impl RawResource { /// Returns the system handle for the resource pub fn handle(&self) -> HRSRC { self.handle } /// Returns the system handle for the resource data pub fn data_handle(&self) -> HGLOBAL { self.data_handle } /// Returns the resource type set during texture loading pub fn resource_type(&self) -> RawResourceType { self.ty } /// Returns the size in bytes of the resource pub fn len(&self) -> usize { use winapi::um::libloaderapi::SizeofResource; unsafe { SizeofResource(self.module, self.handle) as usize } } /// Return a const pointer to the resource. pub unsafe fn as_mut_ptr(&mut self) -> *mut c_void { self.lock() } /// Return the resource data as a byte slice. This is equivalent to using `slice::from_raw_parts_mut` pub unsafe fn as_mut_slice(&self) -> &mut [u8] { std::slice::from_raw_parts_mut(self.lock() as *mut u8, self.len()) } fn lock(&self) -> *mut c_void { use winapi::um::libloaderapi::LockResource; unsafe { LockResource(self.data_handle) } } } /** EmbedResource represent an embed resource file (".rc") inside on the executable module. By default (without any arguments), the embed resources wraps the executable. If the embed resources are in a dll, it's also possible to load them by setting the "module" parameter to the dll name. **Builder parameters:** * `module`: The name of the module that owns the embed resources. If `None`, use the executable name. ```rust use native_windows_gui as nwg; fn build_embed1() -> nwg::EmbedResource { nwg::EmbedResource::load(None).unwrap() } fn build_embed2() -> nwg::EmbedResource { nwg::EmbedResource::load(Some("external.dll")).unwrap() } ``` */ pub struct EmbedResource { pub hinst: HINSTANCE, } impl EmbedResource { /// Returns an embed resource that wraps the current executable. Shortcut for the builder API. pub fn load(name: Option<&str>) -> Result<EmbedResource, NwgError> { let mut embed = EmbedResource::default(); EmbedResource::builder() .module(name) .build(&mut embed)?; Ok(embed) } /// Creates a `EmbedResourceBuilder`. `EmbedResource::load` can also be used to skip the builder api pub fn builder() -> EmbedResourceBuilder { EmbedResourceBuilder { module: None } } /// Load a string the the RC file STRINGTABLE. Returns `None` if `id` does not map to a string. pub fn string(&self, id: u32) -> Option<String> { use winapi::um::libloaderapi::LoadStringW; unsafe { let mut str_ptr = ptr::null_mut(); let ccount = LoadStringW(self.hinst, id, (&mut str_ptr) as *mut *mut u16 as _, 0); match ccount { 0 => None, count => { let str_slice = slice::from_raw_parts(str_ptr, count as usize); Some(from_utf16(str_slice)) } } } } /// Load an icon from the rc file. Returns `None` if `id` does not map to a icon. /// For more feature, use the `Icon::builder` with the `embed` parameter. pub fn icon(&self, id: usize, size: Option<(u32, u32)>) -> Option<Icon> { use winapi::um::winuser::IMAGE_ICON; unsafe { let id_rc = id as _; let icon = match size { None => LoadImageW(self.hinst, id_rc, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE), Some((w, h)) => LoadImageW(self.hinst, id_rc, IMAGE_ICON, w as _, h as _, 0), }; if icon.is_null() { None } else { Some(Icon { handle: icon as _, owned: true } ) } } } /// Load an icon identified by a string in a resource file. Returns `None` if `id` does not map to a icon. pub fn icon_str(&self, id: &str, size: Option<(u32, u32)>) -> Option<Icon> { let name = to_utf16(id); self.icon(name.as_ptr() as usize, size) } /// Load a bitmap file from the rc file. Returns `None` if `id` does not map to a bitmap. pub fn bitmap(&self, id: usize, size: Option<(u32, u32)>) -> Option<Bitmap> { use winapi::um::winuser::IMAGE_BITMAP; unsafe { let id_rc = id as _; let bitmap = match size { None => LoadImageW(self.hinst, id_rc, IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE), Some((w, h)) => LoadImageW(self.hinst, id_rc, IMAGE_BITMAP, w as _, h as _, LR_CREATEDIBSECTION), }; if bitmap.is_null() { None } else { Some(Bitmap { handle: bitmap as _, owned: true } ) } } } /// Load a bitmap file from the rc file. Returns `None` if `id` does not map to a bitmap. pub fn bitmap_str(&self, id: &str, size: Option<(u32, u32)>) -> Option<Bitmap> { let name = to_utf16(id); self.bitmap(name.as_ptr() as usize, size) } #[cfg(feature="image-decoder")] /// Load an image from the embed files and returns a bitmap. An image is defined this way: `IMAGE_NAME IMAGE "../path/my_image.bmp"` /// This method can load any image type supported by the image decoder. pub fn image(&self, id: usize, size: Option<(u32, u32)>) -> Option<Bitmap> { use crate::win32::resources_helper as rh; match self.raw(id, RawResourceType::Other("Image")) { None => None, Some(raw) => { let src = unsafe { raw.as_mut_slice() }; let handle = unsafe { rh::build_image_decoder_from_memory(src, size) }; match handle { Ok(handle) => Some(Bitmap { handle, owned: true }), Err(e) => { println!("{:?}", e); None } } } } } #[cfg(feature="image-decoder")] /// Load a image using a string name. See `EmbedResource::image` pub fn image_str(&self, id: &str, size: Option<(u32, u32)>) -> Option<Bitmap> { let name = to_utf16(id); self.image(name.as_ptr() as usize, size) } /// Load a cursor file from the rc file. Returns `None` if `id` does not map to a cursor. pub fn cursor(&self, id: usize) -> Option<Cursor> { use winapi::um::winuser::IMAGE_CURSOR; unsafe { let id_rc = id as _; let cursor = LoadImageW(self.hinst, id_rc, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE); if cursor.is_null() { None } else { Some(Cursor { handle: cursor as _, owned: true } ) } } } /// Load a cursor file from the rc file. Returns `None` if `id` does not map to a cursor. pub fn cursor_str(&self, id: &str) -> Option<Cursor> { let name = to_utf16(id); self.cursor(name.as_ptr() as usize) } /// Return a wrapper over the data of an embed resource. Return `None` `id` does not map to a resource. pub fn raw(&self, id: usize, ty: RawResourceType) -> Option<RawResource> { use winapi::um::libloaderapi::{FindResourceW, LoadResource}; use RawResourceType::*; unsafe { let data_u16; let ty_value = match ty { Cursor => 1, Bitmap => 2, Icon => 3, Menu => 4, Dialog => 5, String => 6, FontDir => 7, Font => 8, Accelerator => 9, RawData => 10, MessageTable => 11, Version => 16, DlgInclude => 17, PlugPlay => 19, Vxd => 20, AnimatedCursor => 21, AnimatedIcon => 22, Html => 23, Manifest => 24, Other(value) => { data_u16 = Some(to_utf16(value)); data_u16.as_ref().map(|v| v.as_ptr() as usize).unwrap() } }; let handle = FindResourceW(self.hinst as _, id as _, ty_value as _); if handle.is_null() { return None; } let data_handle = LoadResource(self.hinst as _, handle); Some(RawResource { module: self.hinst, handle, data_handle, ty }) } } /// Return a wrapper over the data of an embed resource. Return `None` `id` does not map to a resource. pub fn raw_str(&self, id: &str, ty: RawResourceType) -> Option<RawResource> { let name = to_utf16(id); self.raw(name.as_ptr() as usize, ty) } } impl Default for EmbedResource { fn default() -> EmbedResource { EmbedResource { hinst: ptr::null_mut() } } } /** The EmbedResource builder. See `EmbedResource` docs. */ pub struct EmbedResourceBuilder { module: Option<String> } impl EmbedResourceBuilder { pub fn module(mut self, module: Option<&str>) -> EmbedResourceBuilder { self.module = module.map(|s| s.to_string()); self } pub fn build(self, out: &mut EmbedResource) -> Result<(), NwgError> { use winapi::um::libloaderapi::GetModuleHandleW; let hinst = match self.module.as_ref() { Some(name) => { let name = to_utf16(name); unsafe { GetModuleHandleW(name.as_ptr()) as HINSTANCE } }, None => unsafe { GetModuleHandleW(ptr::null_mut()) as HINSTANCE } }; if hinst.is_null() { let name = self.module.as_ref().map(|name| name as &str ).unwrap_or(""); return Err(NwgError::resource_create(format!("No module named \"{}\" in application", name))); } *out = EmbedResource { hinst }; Ok(()) } }
// Note: Rasa needs tensorflow_text use std::collections::HashMap; use std::convert::{Into, TryInto}; use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use crate::nlu::{compare_sets_and_train, try_open_file_and_check, write_contents}; use crate::nlu::{ EntityData, EntityDef, Nlu, NluManager, NluManagerStatic, NluResponse, NluResponseSlot, NluUtterance, }; use crate::vars::NLU_RASA_PATH; use anyhow::{anyhow, Result}; use async_trait::async_trait; use log::error; use maplit::hashmap; use reqwest::Client; use serde::{Deserialize, Serialize}; use serde_yaml::Value; use thiserror::Error; use unic_langid::{langid, LanguageIdentifier}; #[derive(Debug)] pub struct RasaNlu { client: Client, _process: Child, } impl RasaNlu { fn new(model_path: &Path) -> Result<Self> { let mod_path_str = model_path.to_str().ok_or_else(|| { anyhow!("Can't use provided path to rasa NLU data contains non-UTF8 characters") })?; let process_res = Command::new("rasa") .args(&["run", "--enable-api", "-m", mod_path_str]) .spawn(); let _process = process_res.map_err(|err| anyhow!("Rasa can't be executed: {:?}", err))?; let client = Client::new(); Ok(Self { client, _process }) } } #[derive(Deserialize, Debug)] struct RasaResponse { pub intent: RasaIntent, pub entities: Vec<RasaNluEntity>, // This one lacks the extractor field, but whe don't need it pub intent_ranking: Vec<RasaIntent>, } #[derive(Deserialize, Debug)] pub struct RasaIntent { pub name: String, pub confidence: f32, } #[async_trait(?Send)] impl Nlu for RasaNlu { async fn parse(&self, input: &str) -> Result<NluResponse> { let map = hashmap! {"text" => input}; let resp: RasaResponse = self .client .post("localhost:5005/model/parse") .json(&map) .send() .await? .json() .await?; Ok(resp.into()) } } #[derive(Serialize)] struct RasaTrainSet { #[serde(rename = "rasa_nlu_data")] data: RasaNluData, } #[derive(Serialize)] struct RasaNluData { common_examples: Vec<RasaNluCommmonExample>, regex_features: Vec<RasaNluRegexFeature>, lookup_tables: Vec<RasaNluLookupTable>, entity_synonyms: Vec<EntityData>, } #[derive(Serialize)] struct RasaNluCommmonExample { text: String, intent: String, entities: Vec<RasaNluEntity>, } #[derive(Serialize)] struct RasaNluRegexFeature { name: String, pattern: String, } #[derive(Serialize)] struct RasaNluLookupTable { //NYI } #[derive(Deserialize, Serialize, Debug)] struct RasaNluEntity { start: u32, end: u32, value: String, entity: String, } #[derive(Serialize)] struct RasaNluTrainConfig { language: String, pipeline: Vec<HashMap<String, Value>>, #[serde(skip_serializing_if = "Option::is_none")] data: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] policies: Option<Vec<HashMap<String, Value>>>, } #[derive(Serialize)] struct RasaNluPipelineElement { name: String, } #[derive(Debug)] pub struct RasaNluManager { intents: Vec<(String, Vec<NluUtterance>)>, synonyms: Vec<EntityData>, equivalences: HashMap<String, Vec<String>>, } impl RasaNluManager { fn make_pipeline() -> Vec<HashMap<String, Value>> { vec![ hashmap! {"name".to_owned() => "ConveRTTokenizer".into()}, hashmap! {"name".to_owned() => "ConveRTFeaturizer".into()}, hashmap! {"name".to_owned() => "RegexFeaturizer".into()}, hashmap! {"name".to_owned() => "LexicalSyntacticFeaturizer".into()}, hashmap! {"name".to_owned() => "CountVectorsFeaturizer".into()}, hashmap! {"name".to_owned() => "CountVectorsFeaturizer".into(), "analyzer".to_owned() => "char_wb".into(), "min_ngram".to_owned() => 1.into(), "max_ngram".to_owned() => 1.into()}, hashmap! {"name".to_owned() => "DIETClassifier".into(), "epochs".to_owned() => 100.into()}, hashmap! {"name".to_owned() => "EntitySynonymMapper".into()}, hashmap! {"name".to_owned() => "ResponseSelector".into(), "epochs".to_owned() => 100.into()}, ] } fn make_train_conf(lang: &LanguageIdentifier) -> Result<String> { let conf = RasaNluTrainConfig { language: lang.to_string(), pipeline: Self::make_pipeline(), data: None, policies: None, }; Ok(serde_yaml::to_string(&conf)?) } fn make_train_set_json(&self) -> Result<String> { let common_examples: Vec<RasaNluCommmonExample> = transform_intents(self.intents.clone()); let data = RasaNluData { common_examples, entity_synonyms: self.synonyms.clone(), regex_features: vec![], lookup_tables: vec![], }; let train_set = RasaTrainSet { data }; // Output JSON Ok(serde_json::to_string(&train_set)?) } } impl NluManager for RasaNluManager { type NluType = RasaNlu; fn ready_lang(&mut self, _lang: &LanguageIdentifier) -> Result<()> { // Nothing to be done right now Ok(()) } fn add_intent(&mut self, order_name: &str, phrases: Vec<NluUtterance>) { self.intents.push((order_name.to_string(), phrases)); } fn add_entity(&mut self, name: String, def: EntityDef) { self.equivalences .insert(name, def.data.iter().map(|d| d.value.clone()).collect()); self.synonyms.extend(def.data.into_iter()); } fn add_entity_value(&mut self, name: &str, value: String) -> Result<()> { // TODO: Finish this! std::unimplemented!(); } fn train( &self, train_set_path: &Path, engine_path: &Path, lang: &LanguageIdentifier, ) -> Result<RasaNlu> { let train_set = self.make_train_set_json()?; let train_conf = Self::make_train_conf(lang)?; let engine_path = Path::new(engine_path); let rasa_path = train_set_path .parent() .expect("Failed to get rasa's path from data's path"); if let Some(mut file) = try_open_file_and_check(&rasa_path.join("conf.yml"), &train_conf)? { write_contents(&mut file, &train_conf)?; }; // Make sure it's different, otherwise no need to train it compare_sets_and_train(train_set_path, &train_set, engine_path, || { std::process::Command::new("rasa") .args(&["train", "nlu"]) .spawn() .expect("Failed to execute rasa") .wait() .expect("rasa failed it's training, maybe some argument it's wrong?"); })?; RasaNlu::new(engine_path) } } fn transform_intents(org: Vec<(String, Vec<NluUtterance>)>) -> Vec<RasaNluCommmonExample> { let mut result: Vec<RasaNluCommmonExample> = Vec::with_capacity(org.len()); for (name, utts) in org.into_iter() { for utt in utts.into_iter() { let ex = match utt { NluUtterance::Direct(text) => RasaNluCommmonExample { text, intent: name.clone(), entities: vec![], }, NluUtterance::WithEntities { text, entities: conf_entities, } => { let mut entities = Vec::with_capacity(conf_entities.len()); for (name_ent, entity) in conf_entities.into_iter() { match text.find(&entity.example) { Some(start_usize) => match start_usize.try_into() { Ok(start) => { let res: Result<u32, _> = entity.example.len().try_into(); match res { Ok(len_u32) => { let end = start + len_u32; let en = RasaNluEntity { start, end, value: entity.example, entity: name_ent, }; entities.push(en); } Err(_) => { error!("The length of \"{}\" is far too big (more than a u32), this is not supported", entity.example); } } } Err(_) => { error!("The index at which the example \"{}\" starts is greater than a u32, and this is not supported today, report this.", entity.example); } }, None => { error!("Entity text \"{}\" doesn't have example \"{}\" as detailed in the YAML data, won't be taken into account", text, entity.example); } } } RasaNluCommmonExample { text, intent: name.clone(), entities, } } }; result.push(ex); } } result } impl NluManagerStatic for RasaNluManager { fn new() -> Self { Self { intents: vec![], synonyms: vec![], equivalences: HashMap::new(), } } fn list_compatible_langs() -> Vec<LanguageIdentifier> { vec![ langid!("de"), langid!("en"), langid!("es"), langid!("fr"), langid!("it"), langid!("nl"), langid!("pt"), langid!("zh"), ] } fn name() -> &'static str { "Rasa" } fn get_paths() -> (PathBuf, PathBuf) { let train_path = NLU_RASA_PATH .resolve() .join("models") .join("main_model.tar.gz"); let model_path = NLU_RASA_PATH.resolve().join("data"); (train_path, model_path) } } impl Into<NluResponse> for RasaResponse { fn into(self) -> NluResponse { NluResponse { name: Some(self.intent.name), confidence: self.intent.confidence, slots: self .entities .into_iter() .map(|e| NluResponseSlot { value: e.value, name: e.entity, }) .collect(), } } } #[derive(Error, Debug)] pub enum RasaError { #[error("Failed to write training configuration")] CantWriteConf(#[from] std::io::Error), }
use crate::grid::{Grid, Point}; use crate::reader::get_lines; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Lines}; use std::iter::FromIterator; use std::str::FromStr; fn parse_to_grid(input: Lines<BufReader<File>>) -> Grid { let mut grid = Grid::new(); for (y, line) in input.enumerate() { let line = line.unwrap(); //println!("{:?}", line.clone().trim().chars().collect::<Vec<char>>()); for (x, nr) in line .trim() .chars() .map(|s| u64::from_str(&*s.to_string()).unwrap()) .enumerate() { grid.add_to_grid(Point::new(x as isize, y as isize), nr); } } grid } pub fn part_1(filename: &str) -> usize { let input = get_lines(filename); let mut grid = parse_to_grid(input); let mut total = 0; for _ in 0..100 { let sparked = perform_round(&mut grid); total += sparked.len() } println!("found {} sparks", total); total } pub fn part_2(filename: &str) -> usize { let input = get_lines(filename); let mut grid = parse_to_grid(input); let mut index = 0; loop { let sparked = perform_round(&mut grid); index += 1; if sparked.len() == grid.get_map().keys().len() { break; } } println!("after {} iterations", index); index } fn perform_round(mut grid: &mut Grid) -> HashSet<Point> { // round starts with increment increment(&mut grid); let mut sparked: HashSet<Point> = HashSet::new(); loop { let new_sparks: HashSet<Point> = HashSet::from_iter( grid.get_map() .iter() .filter(|(_k, v)| v > &&(9 as u64)) .map(|(key, _value)| key) .filter(|point| !sparked.contains(*point)) .cloned() .collect::<Vec<Point>>(), ); if new_sparks.is_empty() { break; } // each loc can occur multiple times let incrementable_locs = new_sparks .iter() .map(|loc| grid.get_neighbours_diag(loc)) .flatten() .collect::<Vec<Point>>(); // increment perhaps even multiple times for loc in incrementable_locs { grid.increment_loc(&loc, 1); } sparked.extend(new_sparks); } // add current set to sparks for loc in &sparked { grid.update_loc(loc.clone(), 0); } sparked } fn increment(grid: &mut Grid) { let locs = grid.get_locations(); for loc in locs { grid.increment_loc(&loc, 1); } } #[cfg(test)] mod tests { use crate::day11::{part_1, part_2}; #[test] fn test_part1() { assert_eq!(1656, part_1("./resources/inputs/day11-example.txt")); assert_eq!(1741, part_1("./resources/inputs/day11-input.txt")); } #[test] fn test_part2() { assert_eq!(195, part_2("./resources/inputs/day11-example.txt")); assert_eq!(440, part_2("./resources/inputs/day11-input.txt")); } }
use std::io; use std::net::Shutdown; use std::pin::Pin; use std::task::{Context, Poll}; use crate::runtime::{AsyncRead, AsyncWrite, TcpStream}; use crate::url::Url; use self::Inner::*; pub struct MaybeTlsStream { inner: Inner, } enum Inner { NotTls(TcpStream), #[cfg(feature = "tls")] Tls(async_native_tls::TlsStream<TcpStream>), #[cfg(feature = "tls")] Upgrading, } impl MaybeTlsStream { pub async fn connect(url: &Url, default_port: u16) -> crate::Result<Self> { let conn = TcpStream::connect((url.host(), url.port(default_port))).await?; Ok(Self { inner: Inner::NotTls(conn), }) } #[allow(dead_code)] pub fn is_tls(&self) -> bool { match self.inner { Inner::NotTls(_) => false, #[cfg(feature = "tls")] Inner::Tls(_) => true, #[cfg(feature = "tls")] Inner::Upgrading => false, } } #[cfg(feature = "tls")] #[cfg_attr(docsrs, doc(cfg(feature = "tls")))] pub async fn upgrade( &mut self, url: &Url, connector: async_native_tls::TlsConnector, ) -> crate::Result<()> { let conn = match std::mem::replace(&mut self.inner, Upgrading) { NotTls(conn) => conn, Tls(_) => return Err(tls_err!("connection already upgraded").into()), Upgrading => return Err(tls_err!("connection already failed to upgrade").into()), }; self.inner = Tls(connector.connect(url.host(), conn).await?); Ok(()) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { match self.inner { NotTls(ref conn) => conn.shutdown(how), #[cfg(feature = "tls")] Tls(ref conn) => conn.get_ref().shutdown(how), #[cfg(feature = "tls")] // connection already closed Upgrading => Ok(()), } } } macro_rules! forward_pin ( ($self:ident.$method:ident($($arg:ident),*)) => ( match &mut $self.inner { NotTls(ref mut conn) => Pin::new(conn).$method($($arg),*), #[cfg(feature = "tls")] Tls(ref mut conn) => Pin::new(conn).$method($($arg),*), #[cfg(feature = "tls")] Upgrading => Err(io::Error::new(io::ErrorKind::Other, "connection broken; TLS upgrade failed")).into(), } ) ); impl AsyncRead for MaybeTlsStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { forward_pin!(self.poll_read(cx, buf)) } #[cfg(feature = "runtime-async-std")] fn poll_read_vectored( mut self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [std::io::IoSliceMut], ) -> Poll<io::Result<usize>> { forward_pin!(self.poll_read_vectored(cx, bufs)) } } impl AsyncWrite for MaybeTlsStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8], ) -> Poll<io::Result<usize>> { forward_pin!(self.poll_write(cx, buf)) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { forward_pin!(self.poll_flush(cx)) } #[cfg(feature = "runtime-async-std")] fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { forward_pin!(self.poll_close(cx)) } #[cfg(feature = "runtime-tokio")] fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { forward_pin!(self.poll_shutdown(cx)) } #[cfg(feature = "runtime-async-std")] fn poll_write_vectored( mut self: Pin<&mut Self>, cx: &mut Context, bufs: &[std::io::IoSlice], ) -> Poll<io::Result<usize>> { forward_pin!(self.poll_write_vectored(cx, bufs)) } }
use itertools::Itertools; use std::cmp; use std::fmt; use std::str; use thiserror::Error; use crate::domain::catalog::{ brands::Brand, categories::Category, rolling_stocks::RollingStock, scales::Scale, }; use super::rolling_stocks::Epoch; /// It represent a catalog item number. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct ItemNumber(String); impl ItemNumber { /// Creates a new ItemNumber from the string slice, it needs to panic when the /// provided string slice is empty. pub fn new(value: &str) -> Result<Self, &'static str> { if value.is_empty() { Err("Item number cannot blank") } else { Ok(ItemNumber(value.to_owned())) } } /// Returns the item number value, this cannot be blank. pub fn value(&self) -> &str { &self.0 } } impl fmt::Display for ItemNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } pub type Quarter = u8; pub type Year = i32; #[derive(Debug, PartialEq, Eq)] pub enum DeliveryDate { ByYear(Year), ByQuarter(Year, Quarter), } impl DeliveryDate { /// Creates a new delivery date without the quarter pub fn by_year(year: Year) -> Self { DeliveryDate::ByYear(year) } /// Creates a new delivery date with the quarter information pub fn by_quarter(year: Year, quarter: Quarter) -> Self { DeliveryDate::ByQuarter(year, quarter) } pub fn year(&self) -> Year { match self { DeliveryDate::ByQuarter(y, _) => *y, DeliveryDate::ByYear(y) => *y, } } pub fn quarter(&self) -> Option<Quarter> { match self { DeliveryDate::ByQuarter(_, q) => Some(*q), DeliveryDate::ByYear(_) => None, } } fn parse_year(s: &str) -> Result<Year, DeliveryDateParseError> { let year = s .parse::<Year>() .map_err(|_| DeliveryDateParseError::InvalidYearValue)?; if year < 1900 && year >= 2999 { return Err(DeliveryDateParseError::InvalidYearValue); } Ok(year) } fn parse_quarter(s: &str) -> Result<Quarter, DeliveryDateParseError> { if s.len() != 2 { return Err(DeliveryDateParseError::InvalidQuarterValue); } let quarter = s[1..] .parse::<Quarter>() .map_err(|_| DeliveryDateParseError::InvalidQuarterValue)?; if quarter < 1 && quarter >= 4 { return Err(DeliveryDateParseError::InvalidQuarterValue); } Ok(quarter) } } impl str::FromStr for DeliveryDate { type Err = DeliveryDateParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(DeliveryDateParseError::EmptyValue); } if s.contains("/") { let tokens: Vec<&str> = s.split_terminator("/").collect(); if tokens.len() != 2 { return Err(DeliveryDateParseError::InvalidByQuarterValue); } let year = DeliveryDate::parse_year(tokens[0])?; let quarter = DeliveryDate::parse_quarter(tokens[1])?; Ok(DeliveryDate::ByQuarter(year, quarter)) } else { let year = DeliveryDate::parse_year(s)?; Ok(DeliveryDate::ByYear(year)) } } } impl fmt::Display for DeliveryDate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DeliveryDate::ByQuarter(y, q) => write!(f, "{}/Q{}", y, q), DeliveryDate::ByYear(y) => write!(f, "{}", y), } } } #[derive(Debug, Error)] pub enum DeliveryDateParseError { #[error("Delivery date cannot be empty")] EmptyValue, #[error("Invalid delivery date by quarter")] InvalidByQuarterValue, #[error("Delivery date year component is not valid")] InvalidYearValue, #[error("Delivery date quarter component is not valid")] InvalidQuarterValue, } // The power methods for the model. #[derive(Debug, Copy, Clone, PartialEq)] pub enum PowerMethod { /// Direct current. DC, /// Alternating current (Maerklin). AC, } impl fmt::Display for PowerMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl str::FromStr for PowerMethod { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "DC" => Ok(PowerMethod::DC), "AC" => Ok(PowerMethod::AC), _ => Err("Invalid value for power methods [allowed: 'AC' or 'DC']"), } } } /// A catalog item, it can contain one or more rolling stock. /// /// A catalog item is identified by its catalog item number. #[derive(Debug)] pub struct CatalogItem { brand: Brand, item_number: ItemNumber, description: String, rolling_stocks: Vec<RollingStock>, category: Category, scale: Scale, power_method: PowerMethod, delivery_date: Option<DeliveryDate>, count: u8, } impl PartialEq for CatalogItem { fn eq(&self, other: &Self) -> bool { self.brand == other.brand && self.item_number == other.item_number } } impl cmp::Eq for CatalogItem {} impl cmp::Ord for CatalogItem { fn cmp(&self, other: &Self) -> cmp::Ordering { let cmp1 = self.brand().cmp(other.brand()); if cmp1 == cmp::Ordering::Equal { return self.item_number.cmp(&other.item_number); } cmp1 } } impl cmp::PartialOrd for CatalogItem { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl CatalogItem { pub fn new( brand: Brand, item_number: ItemNumber, description: String, rolling_stocks: Vec<RollingStock>, power_method: PowerMethod, scale: Scale, delivery_date: Option<DeliveryDate>, count: u8, ) -> Self { let category = Self::extract_category(&rolling_stocks); CatalogItem { brand, item_number, description, rolling_stocks, category, count, delivery_date, power_method, scale, } } /// Brand for this catalog item. pub fn brand(&self) -> &Brand { &self.brand } /// The item number as in the corresponding brand catalog. pub fn item_number(&self) -> &ItemNumber { &self.item_number } pub fn rolling_stocks(&self) -> &Vec<RollingStock> { &self.rolling_stocks } pub fn is_locomotive(&self) -> bool { self.category() == Category::Locomotives } pub fn category(&self) -> Category { self.category } pub fn count(&self) -> u8 { self.count } pub fn description(&self) -> &str { &self.description } pub fn scale(&self) -> &Scale { &self.scale } pub fn power_method(&self) -> PowerMethod { self.power_method } pub fn delivery_date(&self) -> &Option<DeliveryDate> { &self.delivery_date } fn extract_category(rolling_stocks: &Vec<RollingStock>) -> Category { let categories = rolling_stocks .iter() .map(|rs| rs.category()) .sorted() .dedup() .collect::<Vec<Category>>(); if categories.len() == 1 { return categories[0]; } Category::Trains } // fn extract_epoch(rolling_stocks: &Vec<RollingStock>) -> Option<&Epoch> { // let epochs = rolling_stocks // .iter() // .map(|rs| rs.epoch()) // .sorted() // .dedup() // .collect::<Vec<Epoch>>(); // if epochs.len() == 1 { // return epochs.get(0); // } // None // } } impl fmt::Display for CatalogItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{} {} ({})", self.brand, self.item_number, self.category.symbol(), ) } } #[cfg(test)] mod tests { use super::*; mod item_number_tests { use super::*; #[test] fn it_should_create_new_item_numbers() { let n = ItemNumber::new("123456"); assert_eq!(n.unwrap().value(), "123456"); } #[test] fn it_should_fail_to_convert_empty_string_slices_as_item_numbers() { let item_number = ItemNumber::new(""); assert!(item_number.is_err()); } } mod power_method_tests { use super::*; #[test] fn it_should_parse_string_as_power_methods() { let pm = "AC".parse::<PowerMethod>(); assert!(pm.is_ok()); assert_eq!("AC", pm.unwrap().to_string()); } } mod delivery_date_tests { use super::*; #[test] fn it_should_parse_string_as_delivery_dates() { let dd1 = "2020/Q1".parse::<DeliveryDate>(); let dd2 = "2020".parse::<DeliveryDate>(); assert!(dd1.is_ok()); let dd1_val = dd1.unwrap(); assert_eq!(2020, dd1_val.year()); assert_eq!(Some(1), dd1_val.quarter()); assert!(dd2.is_ok()); let dd2_val = dd2.unwrap(); assert_eq!(2020, dd2_val.year()); assert_eq!(None, dd2_val.quarter()); } #[test] fn it_should_produce_string_representations_from_delivery_dates() { let dd1 = "2020/Q1".parse::<DeliveryDate>().unwrap(); let dd2 = "2020".parse::<DeliveryDate>().unwrap(); assert_eq!("2020/Q1", dd1.to_string()); assert_eq!("2020", dd2.to_string()); } } mod catalog_item_tests { use crate::domain::catalog::{ categories::{FreightCarType, LocomotiveType, PassengerCarType}, railways::Railway, rolling_stocks::{ Control, DccInterface, LengthOverBuffer, ServiceLevel, }, }; use super::*; fn new_locomotive() -> RollingStock { RollingStock::new_locomotive( String::from("E.656"), String::from("E.656 210"), Some(String::from("1a serie")), Railway::new("FS"), Epoch::IV, LocomotiveType::ElectricLocomotive, Some(String::from("Milano Centrale")), Some(String::from("blu/grigio")), Some(LengthOverBuffer::new(210)), Some(Control::DccReady), Some(DccInterface::Nem652), ) } fn new_passenger_car() -> RollingStock { RollingStock::new_passenger_car( String::from("UIC-Z"), None, Railway::new("FS"), Epoch::IV, Some(PassengerCarType::OpenCoach), Some(ServiceLevel::FirstClass), None, Some(String::from("bandiera")), Some(LengthOverBuffer::new(303)), ) } fn new_freight_car() -> RollingStock { RollingStock::new_freight_car( String::from("Gbhs"), None, Railway::new("FS"), Epoch::V, Some(FreightCarType::SwingRoofWagon), None, Some(String::from("marrone")), Some(LengthOverBuffer::new(122)), ) } fn new_locomotive_catalog_item() -> CatalogItem { CatalogItem::new( Brand::new("ACME"), ItemNumber::new("123456").unwrap(), String::from("My first catalog item"), vec![new_locomotive()], PowerMethod::DC, Scale::from_name("H0").unwrap(), None, 1, ) } fn new_passenger_cars_catalog_item() -> CatalogItem { CatalogItem::new( Brand::new("Roco"), ItemNumber::new("654321").unwrap(), String::from("My first catalog item"), vec![new_passenger_car(), new_passenger_car()], PowerMethod::DC, Scale::from_name("H0").unwrap(), None, 2, ) } fn new_set_catalog_item() -> CatalogItem { CatalogItem::new( Brand::new("ACME"), ItemNumber::new("123456").unwrap(), String::from("My first catalog item"), vec![ new_passenger_car(), new_passenger_car(), new_freight_car(), ], PowerMethod::DC, Scale::from_name("H0").unwrap(), None, 2, ) } #[test] fn it_should_create_new_catalog_items() { let item = CatalogItem::new( Brand::new("ACME"), ItemNumber::new("123456").unwrap(), String::from("My first catalog item"), vec![new_locomotive()], PowerMethod::DC, Scale::from_name("H0").unwrap(), Some(DeliveryDate::by_year(2020)), 1, ); assert_eq!(&Brand::new("ACME"), item.brand()); assert_eq!(&ItemNumber::new("123456").unwrap(), item.item_number()); assert_eq!("My first catalog item", item.description()); assert_eq!(&vec![new_locomotive()], item.rolling_stocks()); assert_eq!(PowerMethod::DC, item.power_method()); assert_eq!(&Scale::from_name("H0").unwrap(), item.scale()); assert_eq!( &Some(DeliveryDate::by_year(2020)), item.delivery_date() ); assert_eq!(1, item.count()); } #[test] fn it_should_check_whether_catalog_item_is_a_locomotive() { let item = new_locomotive_catalog_item(); assert!(true, item.is_locomotive()); } #[test] fn it_should_extract_the_category_from_catalog_items() { let item1 = new_locomotive_catalog_item(); let item2 = new_passenger_cars_catalog_item(); assert_eq!(Category::Locomotives, item1.category()); assert_eq!(Category::PassengerCars, item2.category()); } #[test] fn it_should_produce_string_representations_from_catalog_items() { let item = new_locomotive_catalog_item(); assert_eq!("ACME 123456 (L)", item.to_string()); } #[test] fn it_should_check_whether_two_catalog_items_are_equal() { let item1 = new_locomotive_catalog_item(); let item2 = new_locomotive_catalog_item(); let item3 = new_passenger_cars_catalog_item(); assert!(item1 == item2); assert!(item1 != item3); } } }
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; pub struct Header { pub version: i32, pub vert_cache_size: i32, pub max_bones_per_strip: u16, pub max_bones_per_tri: u16, pub max_bones_per_vert: i32, pub checksum: i32, pub lods_count: i32, pub material_replacement_list_offset: i32, pub body_parts_count: i32, pub body_parts_offset: i32 } impl Header { pub fn read(read: &mut dyn Read) -> IOResult<Self> { let version = read.read_i32()?; let vert_cache_size = read.read_i32()?; let max_bones_per_strip = read.read_u16()?; let max_bones_per_tri = read.read_u16()?; let max_bones_per_vert = read.read_i32()?; let checksum = read.read_i32()?; let lods_count = read.read_i32()?; let material_replacement_list_offset = read.read_i32()?; let body_parts_count = read.read_i32()?; let body_parts_offset = read.read_i32()?; Ok(Self { version, vert_cache_size, max_bones_per_strip, max_bones_per_tri, max_bones_per_vert, checksum, lods_count, material_replacement_list_offset, body_parts_count, body_parts_offset }) } }
extern crate jlib; use jlib::api::subscription::data::SubscribeResponse; use jlib::api::subscription::api::on; use jlib::api::config::Config; // static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; static TEST_SERVER: &'static str = "ws://59.175.148.101:5020"; fn main() { let config = Config::new(TEST_SERVER, true); on(config, |x| { match x { Ok(response) => { let res: SubscribeResponse = response; println!("Response fee_base : {}", res.fee_base); }, Err(err) => { println!("error: {}", err); } } }); }
use std::mem; type BytePointer = *const u8; fn show_bytes(p: BytePointer, len: usize) { for i in 0..len { unsafe { print!(" {:02x}", *p.offset(i as isize)); } } println!(""); } fn show_i32(x: i32) { unsafe { show_bytes(mem::transmute::<&i32, BytePointer>(&x), std::mem::size_of_val(&x)); } } fn show_f32(x: f32) { unsafe { show_bytes(mem::transmute::<&f32, BytePointer>(&x), std::mem::size_of_val(&x)); } } fn show_pointer(x: BytePointer) { unsafe { show_bytes(mem::transmute::<&BytePointer, BytePointer>(&x), std::mem::size_of_val(&x)); } }
use math; // Return the first factor of n that is not 1 or n itself. // Return None if no such factor found (i.e. n is prime) pub fn factor(n: u64) -> Option<(u64, u64)> { for x in 2..math::sqrt_u64(n)+1 { if n % x == 0 { return Some((n / x, x)); } } None }
//! HTTP service implementations for `router`. pub mod write; use std::{str::Utf8Error, time::Instant}; use bytes::{Bytes, BytesMut}; use futures::StreamExt; use hashbrown::HashMap; use hyper::{header::CONTENT_ENCODING, Body, Method, Request, Response, StatusCode}; use iox_time::{SystemProvider, TimeProvider}; use metric::{DurationHistogram, U64Counter}; use mutable_batch::MutableBatch; use mutable_batch_lp::LinesConverter; use observability_deps::tracing::*; use thiserror::Error; use tokio::sync::{Semaphore, TryAcquireError}; use trace::ctx::SpanContext; use self::write::{ multi_tenant::MultiTenantExtractError, single_tenant::SingleTenantExtractError, WriteParams, WriteRequestUnifier, }; use crate::{ dml_handlers::{ client::RpcWriteClientError, DmlError, DmlHandler, PartitionError, RetentionError, RpcWriteError, SchemaError, }, namespace_resolver::NamespaceResolver, }; /// Errors returned by the `router` HTTP request handler. #[derive(Debug, Error)] pub enum Error { /// The requested path has no registered handler. #[error("not found")] NoHandler, /// A delete request was rejected (not supported). #[error("deletes are not supported")] DeletesUnsupported, /// An error parsing a single-tenant HTTP request. #[error(transparent)] SingleTenantError(#[from] SingleTenantExtractError), /// An error parsing a multi-tenant HTTP request. #[error(transparent)] MultiTenantError(#[from] MultiTenantExtractError), /// The request body content is not valid utf8. #[error("body content is not valid utf8: {0}")] NonUtf8Body(Utf8Error), /// The `Content-Encoding` header is invalid and cannot be read. #[error("invalid content-encoding header: {0}")] NonUtf8ContentHeader(hyper::header::ToStrError), /// The specified `Content-Encoding` is not acceptable. #[error("unacceptable content-encoding: {0}")] InvalidContentEncoding(String), /// The client disconnected. #[error("client disconnected")] ClientHangup(hyper::Error), /// The client sent a request body that exceeds the configured maximum. #[error("max request size ({0} bytes) exceeded")] RequestSizeExceeded(usize), /// Decoding a gzip-compressed stream of data failed. #[error("error decoding gzip stream: {0}")] InvalidGzip(std::io::Error), /// Failure to decode the provided line protocol. #[error("failed to parse line protocol: {0}")] ParseLineProtocol(mutable_batch_lp::Error), /// An error returned from the [`DmlHandler`]. #[error("dml handler error: {0}")] DmlHandler(#[from] DmlError), /// An error that occurs when attempting to map the user-provided namespace /// name into a [`NamespaceId`]. /// /// [`NamespaceId`]: data_types::NamespaceId #[error(transparent)] NamespaceResolver(#[from] crate::namespace_resolver::Error), /// The router is currently servicing the maximum permitted number of /// simultaneous requests. #[error("this service is overloaded, please try again later")] RequestLimit, /// The request has no authentication, but authorization is configured. #[error("authentication required")] Unauthenticated, /// The provided authorization is not sufficient to perform the request. #[error("access denied")] Forbidden, } impl Error { /// Convert the error into an appropriate [`StatusCode`] to be returned to /// the end user. pub fn as_status_code(&self) -> StatusCode { match self { Error::NoHandler => StatusCode::NOT_FOUND, Error::DeletesUnsupported => StatusCode::NOT_IMPLEMENTED, Error::ClientHangup(_) => StatusCode::BAD_REQUEST, Error::InvalidGzip(_) => StatusCode::BAD_REQUEST, Error::NonUtf8ContentHeader(_) => StatusCode::BAD_REQUEST, Error::NonUtf8Body(_) => StatusCode::BAD_REQUEST, Error::ParseLineProtocol(_) => StatusCode::BAD_REQUEST, Error::RequestSizeExceeded(_) => StatusCode::PAYLOAD_TOO_LARGE, Error::InvalidContentEncoding(_) => { // https://www.rfc-editor.org/rfc/rfc7231#section-6.5.13 StatusCode::UNSUPPORTED_MEDIA_TYPE } Error::DmlHandler(err) => StatusCode::from(err), // Error from the namespace resolver is 4xx if autocreation is disabled, 5xx otherwise Error::NamespaceResolver(crate::namespace_resolver::Error::Create( crate::namespace_resolver::ns_autocreation::NamespaceCreationError::Reject(_), )) => StatusCode::BAD_REQUEST, Error::NamespaceResolver(_) => StatusCode::INTERNAL_SERVER_ERROR, Error::RequestLimit => StatusCode::SERVICE_UNAVAILABLE, Error::Unauthenticated => StatusCode::UNAUTHORIZED, Error::Forbidden => StatusCode::FORBIDDEN, Error::SingleTenantError(e) => StatusCode::from(e), Error::MultiTenantError(e) => StatusCode::from(e), } } } impl From<&DmlError> for StatusCode { fn from(e: &DmlError) -> Self { match e { DmlError::NamespaceNotFound(_) => StatusCode::NOT_FOUND, DmlError::Schema(SchemaError::ServiceLimit(_)) => { // https://docs.influxdata.com/influxdb/cloud/account-management/limits/#api-error-responses StatusCode::BAD_REQUEST } DmlError::Schema(SchemaError::Conflict(_)) => StatusCode::BAD_REQUEST, DmlError::Schema(SchemaError::UnexpectedCatalogError(_)) => { StatusCode::INTERNAL_SERVER_ERROR } DmlError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, DmlError::Partition(PartitionError::BatchWrite(_)) => StatusCode::INTERNAL_SERVER_ERROR, DmlError::Partition(PartitionError::Partitioner(_)) => { StatusCode::INTERNAL_SERVER_ERROR } DmlError::Retention(RetentionError::OutsideRetention { .. }) => StatusCode::FORBIDDEN, DmlError::RpcWrite(RpcWriteError::Client(RpcWriteClientError::Upstream(_))) => { StatusCode::INTERNAL_SERVER_ERROR } DmlError::RpcWrite(RpcWriteError::Client( RpcWriteClientError::MisconfiguredMetadataKey(_), )) => StatusCode::INTERNAL_SERVER_ERROR, DmlError::RpcWrite(RpcWriteError::Client( RpcWriteClientError::MisconfiguredMetadataValue(_), )) => StatusCode::INTERNAL_SERVER_ERROR, DmlError::RpcWrite(RpcWriteError::Client( RpcWriteClientError::UpstreamNotConnected(_), )) => StatusCode::SERVICE_UNAVAILABLE, DmlError::RpcWrite(RpcWriteError::Timeout(_)) => StatusCode::GATEWAY_TIMEOUT, DmlError::RpcWrite( RpcWriteError::NoHealthyUpstreams | RpcWriteError::NotEnoughReplicas | RpcWriteError::PartialWrite { .. }, ) => StatusCode::SERVICE_UNAVAILABLE, } } } /// This type is responsible for servicing requests to the `router` HTTP /// endpoint. /// /// Requests to some paths may be handled externally by the caller - the IOx /// server runner framework takes care of implementing the heath endpoint, /// metrics, pprof, etc. #[derive(Debug)] pub struct HttpDelegate<D, N, T = SystemProvider> { max_request_bytes: usize, time_provider: T, namespace_resolver: N, dml_handler: D, write_request_mode_handler: Box<dyn WriteRequestUnifier>, // A request limiter to restrict the number of simultaneous requests this // router services. // // This allows the router to drop a portion of requests when experiencing an // unusual flood of requests (i.e. due to peer routers crashing and // depleting the available instances in the pool) in order to preserve // overall system availability, instead of OOMing or otherwise failing. request_sem: Semaphore, write_metric_lines: U64Counter, http_line_protocol_parse_duration: DurationHistogram, write_metric_fields: U64Counter, write_metric_tables: U64Counter, write_metric_body_size: U64Counter, request_limit_rejected: U64Counter, } impl<D, N> HttpDelegate<D, N, SystemProvider> { /// Initialise a new [`HttpDelegate`] passing valid requests to the /// specified `dml_handler`. /// /// HTTP request bodies are limited to `max_request_bytes` in size, /// returning an error if exceeded. pub fn new( max_request_bytes: usize, max_requests: usize, namespace_resolver: N, dml_handler: D, metrics: &metric::Registry, write_request_mode_handler: Box<dyn WriteRequestUnifier>, ) -> Self { let write_metric_lines = metrics .register_metric::<U64Counter>( "http_write_lines", "cumulative number of line protocol lines successfully routed", ) .recorder(&[]); let write_metric_fields = metrics .register_metric::<U64Counter>( "http_write_fields", "cumulative number of line protocol fields successfully routed", ) .recorder(&[]); let write_metric_tables = metrics .register_metric::<U64Counter>( "http_write_tables", "cumulative number of tables in each write request", ) .recorder(&[]); let write_metric_body_size = metrics .register_metric::<U64Counter>( "http_write_body_bytes", "cumulative byte size of successfully routed (decompressed) line protocol write requests", ) .recorder(&[]); let request_limit_rejected = metrics .register_metric::<U64Counter>( "http_request_limit_rejected", "number of HTTP requests rejected due to exceeding parallel request limit", ) .recorder(&[]); let http_line_protocol_parse_duration = metrics .register_metric::<DurationHistogram>( "http_line_protocol_parse_duration", "write latency of line protocol parsing", ) .recorder(&[]); Self { max_request_bytes, time_provider: SystemProvider::default(), namespace_resolver, write_request_mode_handler, dml_handler, request_sem: Semaphore::new(max_requests), write_metric_lines, http_line_protocol_parse_duration, write_metric_fields, write_metric_tables, write_metric_body_size, request_limit_rejected, } } } impl<D, N, T> HttpDelegate<D, N, T> where D: DmlHandler<WriteInput = HashMap<String, MutableBatch>, WriteOutput = ()>, N: NamespaceResolver, T: TimeProvider, { /// Routes `req` to the appropriate handler, if any, returning the handler /// response. pub async fn route(&self, req: Request<Body>) -> Result<Response<Body>, Error> { // Acquire and hold a permit for the duration of this request, or return // a 503 if the existing requests have already exhausted the allocation. // // By dropping requests at the routing stage, before the request buffer // is read/decompressed, this limit can efficiently shed load to avoid // unnecessary memory pressure (the resource this request limit usually // aims to protect.) let _permit = match self.request_sem.try_acquire() { Ok(p) => p, Err(TryAcquireError::NoPermits) => { error!("simultaneous request limit exceeded - dropping request"); self.request_limit_rejected.inc(1); return Err(Error::RequestLimit); } Err(e) => panic!("request limiter error: {e}"), }; // Route the request to a handler. match (req.method(), req.uri().path()) { (&Method::POST, "/write") => { let dml_info = self.write_request_mode_handler.parse_v1(&req).await?; self.write_handler(req, dml_info).await } (&Method::POST, "/api/v2/write") => { let dml_info = self.write_request_mode_handler.parse_v2(&req).await?; self.write_handler(req, dml_info).await } (&Method::POST, "/api/v2/delete") => return Err(Error::DeletesUnsupported), _ => return Err(Error::NoHandler), } .map(|_summary| { Response::builder() .status(StatusCode::NO_CONTENT) .body(Body::empty()) .unwrap() }) } async fn write_handler( &self, req: Request<Body>, write_info: WriteParams, ) -> Result<(), Error> { let span_ctx: Option<SpanContext> = req.extensions().get().cloned(); trace!( namespace=%write_info.namespace, "processing write request" ); // Read the HTTP body and convert it to a str. let body = self.read_body(req).await?; let body = std::str::from_utf8(&body).map_err(Error::NonUtf8Body)?; // The time, in nanoseconds since the epoch, to assign to any points that don't // contain a timestamp let default_time = self.time_provider.now().timestamp_nanos(); let start_instant = Instant::now(); let mut converter = LinesConverter::new(default_time); converter.set_timestamp_base(write_info.precision.timestamp_base()); let (batches, stats) = match converter.write_lp(body).and_then(|_| converter.finish()) { Ok(v) => v, Err(mutable_batch_lp::Error::EmptyPayload) => { debug!("nothing to write"); return Ok(()); } Err(e) => return Err(Error::ParseLineProtocol(e)), }; let num_tables = batches.len(); let duration = start_instant.elapsed(); self.http_line_protocol_parse_duration.record(duration); debug!( num_lines=stats.num_lines, num_fields=stats.num_fields, num_tables, precision=?write_info.precision, body_size=body.len(), namespace=%write_info.namespace, duration=?duration, "routing write", ); // Retrieve the namespace schema for this namespace. let namespace_schema = self .namespace_resolver .get_namespace_schema(&write_info.namespace) .await?; self.dml_handler .write(&write_info.namespace, namespace_schema, batches, span_ctx) .await .map_err(Into::into)?; self.write_metric_lines.inc(stats.num_lines as _); self.write_metric_fields.inc(stats.num_fields as _); self.write_metric_tables.inc(num_tables as _); self.write_metric_body_size.inc(body.len() as _); Ok(()) } /// Parse the request's body into raw bytes, applying the configured size /// limits and decoding any content encoding. async fn read_body(&self, req: hyper::Request<Body>) -> Result<Bytes, Error> { let encoding = req .headers() .get(&CONTENT_ENCODING) .map(|v| v.to_str().map_err(Error::NonUtf8ContentHeader)) .transpose()?; let ungzip = match encoding { None | Some("identity") => false, Some("gzip") => true, Some(v) => return Err(Error::InvalidContentEncoding(v.to_string())), }; let mut payload = req.into_body(); let mut body = BytesMut::new(); while let Some(chunk) = payload.next().await { let chunk = chunk.map_err(Error::ClientHangup)?; // limit max size of in-memory payload if (body.len() + chunk.len()) > self.max_request_bytes { return Err(Error::RequestSizeExceeded(self.max_request_bytes)); } body.extend_from_slice(&chunk); } let body = body.freeze(); // If the body is not compressed, return early. if !ungzip { return Ok(body); } // Unzip the gzip-encoded content use std::io::Read; let decoder = flate2::read::GzDecoder::new(&body[..]); // Read at most max_request_bytes bytes to prevent a decompression bomb // based DoS. // // In order to detect if the entire stream ahs been read, or truncated, // read an extra byte beyond the limit and check the resulting data // length - see the max_request_size_truncation test. let mut decoder = decoder.take(self.max_request_bytes as u64 + 1); let mut decoded_data = Vec::new(); decoder .read_to_end(&mut decoded_data) .map_err(Error::InvalidGzip)?; // If the length is max_size+1, the body is at least max_size+1 bytes in // length, and possibly longer, but truncated. if decoded_data.len() > self.max_request_bytes { return Err(Error::RequestSizeExceeded(self.max_request_bytes)); } Ok(decoded_data.into()) } } #[cfg(test)] mod tests { use std::{io::Write, iter, sync::Arc, time::Duration}; use assert_matches::assert_matches; use data_types::{ NamespaceId, NamespaceName, NamespaceNameError, OrgBucketMappingError, TableId, }; use flate2::{write::GzEncoder, Compression}; use hyper::header::HeaderValue; use metric::{Attributes, Metric}; use mutable_batch::column::ColumnData; use mutable_batch_lp::LineWriteError; use test_helpers::timeout::FutureTimeout; use tokio_stream::wrappers::ReceiverStream; use super::*; use crate::{ dml_handlers::{ mock::{MockDmlHandler, MockDmlHandlerCall}, CachedServiceProtectionLimit, }, namespace_resolver::{mock::MockNamespaceResolver, NamespaceCreationError}, server::http::write::{ mock::{MockUnifyingParseCall, MockWriteRequestUnifier}, multi_tenant::MultiTenantRequestUnifier, v1::V1WriteParseError, v2::V2WriteParseError, Precision, }, }; const MAX_BYTES: usize = 1024; const NAMESPACE_ID: NamespaceId = NamespaceId::new(42); static NAMESPACE_NAME: &str = "bananas_test"; fn assert_metric_hit(metrics: &metric::Registry, name: &'static str, value: Option<u64>) { let counter = metrics .get_instrument::<Metric<U64Counter>>(name) .expect("failed to read metric") .get_observer(&Attributes::from(&[])) .expect("failed to get observer") .fetch(); if let Some(want) = value { assert_eq!(want, counter, "metric does not have expected value"); } else { assert!(counter > 0, "metric {name} did not record any values"); } } //////////////////////////////////////////////////////////////////////////// // // The following tests assert "cloud2" or "multi-tenant" mode only, as this // is the default operating mode. // // Tests of the single-tenant behaviour differs from the established norms, // and can be found alongside the single-tenant implementation. // //////////////////////////////////////////////////////////////////////////// // Generate two HTTP handler tests - one for a plain request and one with a // gzip-encoded body (and appropriate header), asserting the handler return // value & write op. macro_rules! test_http_handler { ( $name:ident, uri = $uri:expr, // Request URI body = $body:expr, // Request body content dml_write_handler = $dml_write_handler:expr, // DML write handler response (if called) dml_delete_handler = $dml_delete_handler:expr, // DML delete handler response (if called) want_result = $want_result:pat, // Expected handler return value (as pattern) want_dml_calls = $($want_dml_calls:tt )+ // assert_matches slice pattern for expected DML calls ) => { // Generate the three test cases by feed the same inputs, but varying // the encoding. test_http_handler!( $name, encoding=plain, uri = $uri, body = $body, dml_write_handler = $dml_write_handler, dml_delete_handler = $dml_delete_handler, want_result = $want_result, want_dml_calls = $($want_dml_calls)+ ); test_http_handler!( $name, encoding=identity, uri = $uri, body = $body, dml_write_handler = $dml_write_handler, dml_delete_handler = $dml_delete_handler, want_result = $want_result, want_dml_calls = $($want_dml_calls)+ ); test_http_handler!( $name, encoding=gzip, uri = $uri, body = $body, dml_write_handler = $dml_write_handler, dml_delete_handler = $dml_delete_handler, want_result = $want_result, want_dml_calls = $($want_dml_calls)+ ); }; // Actual test body generator. ( $name:ident, encoding = $encoding:tt, uri = $uri:expr, body = $body:expr, dml_write_handler = $dml_write_handler:expr, dml_delete_handler = $dml_delete_handler:expr, want_result = $want_result:pat, want_dml_calls = $($want_dml_calls:tt )+ ) => { paste::paste! { #[tokio::test] async fn [<test_http_handler_ $name _ $encoding>]() { let body = $body; // Optionally generate a fragment of code to encode the body let body = test_http_handler!(encoding=$encoding, body); #[allow(unused_mut)] let mut request = Request::builder() .uri($uri) .method("POST") .body(Body::from(body)) .unwrap(); // Optionally modify request to account for the desired // encoding test_http_handler!(encoding_header=$encoding, request); let mock_namespace_resolver = MockNamespaceResolver::default() .with_mapping(NAMESPACE_NAME, NAMESPACE_ID); let dml_handler = Arc::new(MockDmlHandler::default() .with_write_return($dml_write_handler) ); let metrics = Arc::new(metric::Registry::default()); let delegate = HttpDelegate::new( MAX_BYTES, 100, mock_namespace_resolver, Arc::clone(&dml_handler), &metrics, Box::<crate::server::http::write::multi_tenant::MultiTenantRequestUnifier>::default(), ); let got = delegate.route(request).await; assert_matches!(got, $want_result); // All successful responses should have a NO_CONTENT code // and metrics should be recorded. if let Ok(v) = got { assert_eq!(v.status(), StatusCode::NO_CONTENT); if $uri.contains("/api/v2/write") { assert_metric_hit(&metrics, "http_write_lines", None); assert_metric_hit(&metrics, "http_write_fields", None); assert_metric_hit(&metrics, "http_write_tables", None); assert_metric_hit(&metrics, "http_write_body_bytes", Some($body.len() as _)); } else { assert_metric_hit(&metrics, "http_delete_body_bytes", Some($body.len() as _)); } } let calls = dml_handler.calls(); assert_matches!(calls.as_slice(), $($want_dml_calls)+); } } }; (encoding=plain, $body:ident) => { $body }; (encoding=identity, $body:ident) => { $body }; (encoding=gzip, $body:ident) => {{ // Apply gzip compression to the body let mut e = GzEncoder::new(Vec::new(), Compression::default()); e.write_all(&$body).unwrap(); e.finish().expect("failed to compress test body") }}; (encoding_header=plain, $request:ident) => {}; (encoding_header=identity, $request:ident) => {{ // Set the identity content encoding $request .headers_mut() .insert(CONTENT_ENCODING, HeaderValue::from_static("identity")); }}; (encoding_header=gzip, $request:ident) => {{ // Set the gzip content encoding $request .headers_mut() .insert(CONTENT_ENCODING, HeaderValue::from_static("gzip")); }}; } // Wrapper over test_http_handler specifically for write requests. macro_rules! test_write_handler { ( $name:ident, query_string = $query_string:expr, // Request URI query string body = $body:expr, // Request body content dml_handler = $dml_handler:expr, // DML write handler response (if called) want_result = $want_result:pat, want_dml_calls = $($want_dml_calls:tt )+ ) => { paste::paste! { test_http_handler!( [<write_ $name>], uri = format!("https://bananas.example/api/v2/write{}", $query_string), body = $body, dml_write_handler = $dml_handler, dml_delete_handler = [], want_result = $want_result, want_dml_calls = $($want_dml_calls)+ ); } }; } test_write_handler!( ok, query_string = "?org=bananas&bucket=test", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); } ); test_write_handler!( ok_precision_s, query_string = "?org=bananas&bucket=test&precision=s", body = "platanos,tag1=A,tag2=B val=42i 1647622847".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, namespace_schema, write_input, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); assert_eq!(namespace_schema.id, NAMESPACE_ID); let table = write_input.get("platanos").expect("table not found"); let ts = table.timestamp_summary().expect("no timestamp summary"); assert_eq!(Some(1647622847000000000), ts.stats.min); } ); test_write_handler!( ok_precision_ms, query_string = "?org=bananas&bucket=test&precision=ms", body = "platanos,tag1=A,tag2=B val=42i 1647622847000".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, namespace_schema, write_input, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); assert_eq!(namespace_schema.id, NAMESPACE_ID); let table = write_input.get("platanos").expect("table not found"); let ts = table.timestamp_summary().expect("no timestamp summary"); assert_eq!(Some(1647622847000000000), ts.stats.min); } ); test_write_handler!( ok_precision_us, query_string = "?org=bananas&bucket=test&precision=us", body = "platanos,tag1=A,tag2=B val=42i 1647622847000000".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, namespace_schema, write_input, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); assert_eq!(namespace_schema.id, NAMESPACE_ID); let table = write_input.get("platanos").expect("table not found"); let ts = table.timestamp_summary().expect("no timestamp summary"); assert_eq!(Some(1647622847000000000), ts.stats.min); } ); test_write_handler!( ok_precision_ns, query_string = "?org=bananas&bucket=test&precision=ns", body = "platanos,tag1=A,tag2=B val=42i 1647622847000000000".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, namespace_schema, write_input, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); assert_eq!(namespace_schema.id, NAMESPACE_ID); let table = write_input.get("platanos").expect("table not found"); let ts = table.timestamp_summary().expect("no timestamp summary"); assert_eq!(Some(1647622847000000000), ts.stats.min); } ); test_write_handler!( precision_overflow, // SECONDS, so multiplies the provided timestamp by 1,000,000,000 query_string = "?org=bananas&bucket=test&precision=s", body = "platanos,tag1=A,tag2=B val=42i 1647622847000000000".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::ParseLineProtocol(_)), want_dml_calls = [] ); test_write_handler!( no_query_params, query_string = "", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::MultiTenantError( MultiTenantExtractError::ParseV2Request(V2WriteParseError::NoQueryParams) )), want_dml_calls = [] // None ); test_write_handler!( no_org_bucket, query_string = "?", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::MultiTenantError( MultiTenantExtractError::InvalidOrgAndBucket( OrgBucketMappingError::NoOrgBucketSpecified ) )), want_dml_calls = [] // None ); test_write_handler!( empty_org_bucket, query_string = "?org=&bucket=", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::MultiTenantError( MultiTenantExtractError::InvalidOrgAndBucket( OrgBucketMappingError::NoOrgBucketSpecified ) )), want_dml_calls = [] // None ); test_write_handler!( invalid_org_bucket, query_string = format!("?org=test&bucket={}", "A".repeat(1000)), body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::MultiTenantError( MultiTenantExtractError::InvalidOrgAndBucket( OrgBucketMappingError::InvalidNamespaceName( NamespaceNameError::LengthConstraint { .. } ) ) )), want_dml_calls = [] // None ); test_write_handler!( invalid_line_protocol, query_string = "?org=bananas&bucket=test", body = "not line protocol".as_bytes(), dml_handler = [Ok(())], want_result = Err(Error::ParseLineProtocol(_)), want_dml_calls = [] // None ); test_write_handler!( non_utf8_body, query_string = "?org=bananas&bucket=test", body = vec![0xc3, 0x28], dml_handler = [Ok(())], want_result = Err(Error::NonUtf8Body(_)), want_dml_calls = [] // None ); test_write_handler!( max_request_size_truncation, query_string = "?org=bananas&bucket=test", body = { // Generate a LP string in the form of: // // bananas,A=AAAAAAAAAA(repeated)... B=42 // ^ // | // MAX_BYTES boundary // // So that reading MAX_BYTES number of bytes produces the string: // // bananas,A=AAAAAAAAAA(repeated)... // // Effectively trimming off the " B=42" suffix. let body = "bananas,A="; iter::once(body) .chain(iter::repeat("A").take(MAX_BYTES - body.len())) .chain(iter::once(" B=42\n")) .flat_map(|s| s.bytes()) .collect::<Vec<u8>>() }, dml_handler = [Ok(())], want_result = Err(Error::RequestSizeExceeded(_)), want_dml_calls = [] // None ); test_write_handler!( db_not_found, query_string = "?org=bananas&bucket=test", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Err(DmlError::NamespaceNotFound(NAMESPACE_NAME.to_string()))], want_result = Err(Error::DmlHandler(DmlError::NamespaceNotFound(_))), want_dml_calls = [MockDmlHandlerCall::Write { namespace, .. }] => { assert_eq!(namespace, NAMESPACE_NAME); } ); test_write_handler!( dml_handler_error, query_string = "?org=bananas&bucket=test", body = "platanos,tag1=A,tag2=B val=42i 123456".as_bytes(), dml_handler = [Err(DmlError::Internal("💣".into()))], want_result = Err(Error::DmlHandler(DmlError::Internal(_))), want_dml_calls = [MockDmlHandlerCall::Write { namespace, .. }] => { assert_eq!(namespace, NAMESPACE_NAME); } ); test_write_handler!( field_upsert_within_batch, query_string = "?org=bananas&bucket=test", body = "test field=1u 100\ntest field=2u 100".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [ MockDmlHandlerCall::Write { namespace, namespace_schema, write_input, .. } ] => { assert_eq!(namespace, NAMESPACE_NAME); assert_eq!(namespace_schema.id, NAMESPACE_ID); let table = write_input.get("test").expect("table not in write"); let col = table.column("field").expect("column missing"); assert_matches!(col.data(), ColumnData::U64(data, _) => { // Ensure both values are recorded, in the correct order. assert_eq!(data.as_slice(), [1, 2]); }); } ); test_write_handler!( column_named_time, query_string = "?org=bananas&bucket=test", body = "test field=1u,time=42u 100".as_bytes(), dml_handler = [], want_result = Err(_), want_dml_calls = [] ); test_http_handler!( not_found, uri = "https://bananas.example/wat", body = "".as_bytes(), dml_write_handler = [], dml_delete_handler = [], want_result = Err(Error::NoHandler), want_dml_calls = [] ); // https://github.com/influxdata/influxdb_iox/issues/4326 mod issue4326 { use super::*; test_write_handler!( duplicate_fields_same_value, query_string = "?org=bananas&bucket=test", body = "whydo InputPower=300i,InputPower=300i".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [MockDmlHandlerCall::Write { namespace, write_input, .. }] => { assert_eq!(namespace, NAMESPACE_NAME); let table = write_input.get("whydo").expect("table not in write"); let col = table.column("InputPower").expect("column missing"); assert_matches!(col.data(), ColumnData::I64(data, _) => { // Ensure the duplicate values are coalesced. assert_eq!(data.as_slice(), [300]); }); } ); test_write_handler!( duplicate_fields_different_value, query_string = "?org=bananas&bucket=test", body = "whydo InputPower=300i,InputPower=42i".as_bytes(), dml_handler = [Ok(())], want_result = Ok(_), want_dml_calls = [MockDmlHandlerCall::Write { namespace, write_input, .. }] => { assert_eq!(namespace, NAMESPACE_NAME); let table = write_input.get("whydo").expect("table not in write"); let col = table.column("InputPower").expect("column missing"); assert_matches!(col.data(), ColumnData::I64(data, _) => { // Last value wins assert_eq!(data.as_slice(), [42]); }); } ); test_write_handler!( duplicate_fields_different_type, query_string = "?org=bananas&bucket=test", body = "whydo InputPower=300i,InputPower=4.2".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::ConflictedFieldTypes { .. }, .. })), want_dml_calls = [] ); test_write_handler!( duplicate_tags_same_value, query_string = "?org=bananas&bucket=test", body = "whydo,InputPower=300i,InputPower=300i field=42i".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::DuplicateTag { .. }, .. })), want_dml_calls = [] ); test_write_handler!( duplicate_tags_different_value, query_string = "?org=bananas&bucket=test", body = "whydo,InputPower=300i,InputPower=42i field=42i".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::DuplicateTag { .. }, .. })), want_dml_calls = [] ); test_write_handler!( duplicate_tags_different_type, query_string = "?org=bananas&bucket=test", body = "whydo,InputPower=300i,InputPower=4.2 field=42i".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::DuplicateTag { .. }, .. })), want_dml_calls = [] ); test_write_handler!( duplicate_is_tag_and_field, query_string = "?org=bananas&bucket=test", body = "whydo,InputPower=300i InputPower=300i".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::MutableBatch { source: mutable_batch::writer::Error::TypeMismatch { .. } }, .. })), want_dml_calls = [] ); test_write_handler!( duplicate_is_tag_and_field_different_types, query_string = "?org=bananas&bucket=test", body = "whydo,InputPower=300i InputPower=30.0".as_bytes(), dml_handler = [], want_result = Err(Error::ParseLineProtocol(mutable_batch_lp::Error::Write { source: LineWriteError::MutableBatch { source: mutable_batch::writer::Error::TypeMismatch { .. } }, .. })), want_dml_calls = [] ); } #[derive(Debug, Error)] enum MockError { #[error("bad stuff")] Terrible, } // This test ensures the request limiter drops requests once the configured // number of simultaneous requests are being serviced. #[tokio::test] async fn test_request_limit_enforced() { let mock_namespace_resolver = MockNamespaceResolver::default().with_mapping("bananas", NamespaceId::new(42)); let dml_handler = Arc::new(MockDmlHandler::default()); let metrics = Arc::new(metric::Registry::default()); let delegate = Arc::new(HttpDelegate::new( MAX_BYTES, 1, mock_namespace_resolver, Arc::clone(&dml_handler), &metrics, Box::new( MockWriteRequestUnifier::default().with_ret(iter::repeat_with(|| { Ok(WriteParams { namespace: NamespaceName::new(NAMESPACE_NAME).unwrap(), precision: Precision::default(), }) })), ), )); // Use a channel to hold open the request. // // This causes the request handler to block reading the request body // until tx is dropped and the body stream ends, completing the body and // unblocking the request handler. let (body_1_tx, rx) = tokio::sync::mpsc::channel(1); let request_1 = Request::builder() .uri("https://bananas.example/api/v2/write?org=bananas&bucket=test") .method("POST") .body(Body::wrap_stream(ReceiverStream::new(rx))) .unwrap(); // Spawn the first request and push at least 2 body chunks through tx. // // Spawning and writing through tx will avoid any race between which // request handler task is scheduled first by ensuring this request is // being actively read from - the first send() could fill the channel // buffer of 1, and therefore successfully returning from the second // send() MUST indicate the stream is being read by the handler (and // therefore the task has spawned and the request is actively being // serviced). let req_1 = tokio::spawn({ let delegate = Arc::clone(&delegate); async move { delegate.route(request_1).await } }); body_1_tx .send(Ok("cpu ")) .await .expect("req1 closed channel"); body_1_tx .send(Ok("field=1i")) // Never hang if there is no handler reading this request .with_timeout_panic(Duration::from_secs(1)) .await .expect("req1 closed channel"); // // At this point we can be certain that request 1 is being actively // serviced, and the HTTP server is in a state that should cause the // immediate drop of any subsequent requests. // assert_metric_hit(&metrics, "http_request_limit_rejected", Some(0)); // Retain this tx handle for the second request and use it to prove the // request dropped before anything was read from the body - the request // should error _before_ anything is sent over tx, and subsequently // attempting to send something over tx after the error should fail with // a "channel closed" error. let (body_2_tx, rx) = tokio::sync::mpsc::channel::<Result<&'static str, MockError>>(1); let request_2 = Request::builder() .uri("https://bananas.example/api/v2/write?org=bananas&bucket=test") .method("POST") .body(Body::wrap_stream(ReceiverStream::new(rx))) .unwrap(); // Attempt to service request 2. // // This should immediately return without requiring any body chunks to // be sent through tx. let err = delegate .route(request_2) .with_timeout_panic(Duration::from_secs(1)) .await .expect_err("second request should be rejected"); assert_matches!(err, Error::RequestLimit); // Ensure the "rejected requests" metric was incremented assert_metric_hit(&metrics, "http_request_limit_rejected", Some(1)); // Prove the dropped request body is not being read: body_2_tx .send(Ok("wat")) .await .expect_err("channel should be closed"); // Cause the first request handler to bail, releasing request capacity // back to the router. body_1_tx .send(Err(MockError::Terrible)) .await .expect("req1 closed channel"); // Wait for the handler to return to avoid any races. let req_1 = req_1 .with_timeout_panic(Duration::from_secs(1)) .await .expect("request 1 handler should not panic") .expect_err("request should fail"); assert_matches!(req_1, Error::ClientHangup(_)); // And submit a third request that should be serviced now there's no // concurrent request being handled. let request_3 = Request::builder() .uri("https://bananas.example/api/v2/write?org=bananas&bucket=test") .method("POST") .body(Body::from("")) .unwrap(); delegate .route(request_3) .with_timeout_panic(Duration::from_secs(1)) .await .expect("empty write should succeed"); // And the request rejected metric must remain unchanged assert_metric_hit(&metrics, "http_request_limit_rejected", Some(1)); } /// Assert the router rejects writes to the V1 endpoint when in /// "multi-tenant" mode. #[tokio::test] async fn test_multi_tenant_denies_v1_writes() { let mock_namespace_resolver = MockNamespaceResolver::default().with_mapping(NAMESPACE_NAME, NamespaceId::new(42)); let dml_handler = Arc::new(MockDmlHandler::default().with_write_return([Ok(())])); let metrics = Arc::new(metric::Registry::default()); let delegate = HttpDelegate::new( MAX_BYTES, 1, mock_namespace_resolver, Arc::clone(&dml_handler), &metrics, Box::<MultiTenantRequestUnifier>::default(), ); let request = Request::builder() .uri("https://bananas.example/write") .method("POST") .body(Body::from("platanos,tag1=A,tag2=B val=42i 123456")) .unwrap(); let got = delegate.route(request).await; assert_matches!(got, Err(Error::NoHandler)); } /// Assert the router delegates request parsing to the /// [`WriteRequestUnifier`] implementation. /// /// By validating request parsing is delegated, behavioural tests for each /// implementation can be implemented directly against those implementations /// (instead of putting them all here). #[tokio::test] async fn test_delegate_to_write_request_unifier_ok() { let mock_namespace_resolver = MockNamespaceResolver::default().with_mapping(NAMESPACE_NAME, NamespaceId::new(42)); let request_unifier = Arc::new(MockWriteRequestUnifier::default().with_ret( iter::repeat_with(|| { Ok(WriteParams { namespace: NamespaceName::new(NAMESPACE_NAME).unwrap(), precision: Precision::default(), }) }), )); let dml_handler = Arc::new(MockDmlHandler::default().with_write_return([Ok(()), Ok(()), Ok(())])); let metrics = Arc::new(metric::Registry::default()); let delegate = HttpDelegate::new( MAX_BYTES, 1, mock_namespace_resolver, Arc::clone(&dml_handler), &metrics, Box::new(Arc::clone(&request_unifier)), ); // A route miss does not invoke the parser let request = Request::builder() .uri("https://bananas.example/wat") .method("POST") .body(Body::from("")) .unwrap(); let got = delegate.route(request).await; assert_matches!(got, Err(Error::NoHandler)); // V1 write parsing is delegated let request = Request::builder() .uri("https://bananas.example/write") .method("POST") .body(Body::from("platanos,tag1=A,tag2=B val=42i 123456")) .unwrap(); let got = delegate.route(request).await; assert_matches!(got, Ok(_)); // Only one call was received, and it should be v1. assert_matches!( request_unifier.calls().as_slice(), [MockUnifyingParseCall::V1] ); // V2 write parsing is delegated let request = Request::builder() .uri("https://bananas.example/api/v2/write") .method("POST") .body(Body::from("platanos,tag1=A,tag2=B val=42i 123456")) .unwrap(); let got = delegate.route(request).await; assert_matches!(got, Ok(_)); // Both call were received. assert_matches!( request_unifier.calls().as_slice(), [MockUnifyingParseCall::V1, MockUnifyingParseCall::V2] ); } // The display text of Error gets passed through `ioxd_router::IoxHttpErrorAdaptor` then // `ioxd_common::http::error::HttpApiError` as the JSON "message" value in error response // bodies. These are fixture tests to document error messages that users might see when // making requests to `/api/v2/write`. macro_rules! check_errors { ( $(( // This macro expects a list of tuples, each specifying: $variant:ident // - One of the error enum variants $(($data:expr))?, // - If needed, an expression to construct the variant's data $msg:expr $(,)? // - The string expected for `Display`ing this variant )),*, ) => { // Generate code that contains all possible error variants, to ensure a compiler error // if any errors are not explicitly covered in this test. #[test] fn all_error_variants_are_checked() { #[allow(dead_code)] fn all_documented(ensure_all_error_variants_are_checked: Error) { #[allow(unreachable_patterns)] match ensure_all_error_variants_are_checked { $(Error::$variant { .. } => {},)* // If this test doesn't compile because of a non-exhaustive pattern, // a variant needs to be added to the `check_errors!` call with the // expected `to_string()` text. } } } // A test that covers all errors given to this macro. #[tokio::test] async fn error_messages_match() { // Generate an assert for each error given to this macro. $( let e = Error::$variant $(($data))?; assert_eq!(e.to_string(), $msg); )* } #[test] fn print_out_error_text() { println!("{}", concat!($(stringify!($variant), "\t", $msg, "\n",)*),) } }; } check_errors! { ( NoHandler, "not found", ), ( DeletesUnsupported, "deletes are not supported", ), ( NonUtf8Body(std::str::from_utf8(&[0, 159]).unwrap_err()), "body content is not valid utf8: invalid utf-8 sequence of 1 bytes from index 1", ), ( NonUtf8ContentHeader({ hyper::header::HeaderValue::from_bytes(&[159]).unwrap().to_str().unwrap_err() }), "invalid content-encoding header: failed to convert header to a str", ), ( InvalidContentEncoding("[invalid content encoding value]".into()), "unacceptable content-encoding: [invalid content encoding value]", ), ( ClientHangup({ let url = "wrong://999.999.999.999:999999".parse().unwrap(); hyper::Client::new().get(url).await.unwrap_err() }), "client disconnected", ), ( RequestSizeExceeded(1337), "max request size (1337 bytes) exceeded", ), ( InvalidGzip(std::io::Error::new(std::io::ErrorKind::Other, "[io Error]")), "error decoding gzip stream: [io Error]", ), ( ParseLineProtocol(mutable_batch_lp::Error::LineProtocol { source: influxdb_line_protocol::Error::FieldSetMissing, line: 42, }), "failed to parse line protocol: \ error parsing line 42 (1-based): No fields were provided", ), ( ParseLineProtocol(mutable_batch_lp::Error::Write { source: mutable_batch_lp::LineWriteError::DuplicateTag { name: "host".into(), }, line: 42, }), "failed to parse line protocol: \ error writing line 42: \ the tag 'host' is specified more than once with conflicting values", ), ( ParseLineProtocol(mutable_batch_lp::Error::Write { source: mutable_batch_lp::LineWriteError::ConflictedFieldTypes { name: "bananas".into(), }, line: 42, }), "failed to parse line protocol: \ error writing line 42: \ the field 'bananas' is specified more than once with conflicting types", ), ( ParseLineProtocol(mutable_batch_lp::Error::EmptyPayload), "failed to parse line protocol: empty write payload", ), ( ParseLineProtocol(mutable_batch_lp::Error::TimestampOverflow), "failed to parse line protocol: timestamp overflows i64", ), ( DmlHandler(DmlError::NamespaceNotFound("[namespace name]".into())), "dml handler error: namespace [namespace name] does not exist", ), ( NamespaceResolver({ let e = iox_catalog::interface::Error::NameExists { name: "[name]".into() }; crate::namespace_resolver::Error::Lookup(e) }), "failed to resolve namespace ID: \ name [name] already exists", ), ( NamespaceResolver( crate::namespace_resolver::Error::Create(NamespaceCreationError::Reject("bananas".to_string())) ), "rejecting write due to non-existing namespace: bananas", ), ( RequestLimit, "this service is overloaded, please try again later", ), ( Unauthenticated, "authentication required", ), ( Forbidden, "access denied", ), ( DmlHandler(DmlError::Schema(SchemaError::ServiceLimit(Box::new(CachedServiceProtectionLimit::Column { table_name: "bananas".to_string(), existing_column_count: 42, merged_column_count: 4242, max_columns_per_table: 24, })))), "dml handler error: service limit reached: couldn't create columns in table `bananas`; table contains 42 \ existing columns, applying this write would result in 4242 columns, limit is 24", ), ( DmlHandler(DmlError::Schema(SchemaError::ServiceLimit(Box::new(CachedServiceProtectionLimit::Table { existing_table_count: 42, merged_table_count: 4242, table_count_limit: 24, })))), "dml handler error: service limit reached: couldn't create new table; namespace contains 42 existing \ tables, applying this write would result in 4242 tables, limit is 24", ), ( DmlHandler(DmlError::Schema(SchemaError::ServiceLimit(Box::new(iox_catalog::interface::Error::ColumnCreateLimitError { column_name: "bananas".to_string(), table_id: TableId::new(42), })))), "dml handler error: service limit reached: couldn't create column bananas in table 42; limit reached on \ namespace", ), ( DmlHandler(DmlError::Schema(SchemaError::ServiceLimit(Box::new(iox_catalog::interface::Error::TableCreateLimitError { table_name: "bananas".to_string(), namespace_id: NamespaceId::new(42), })))), "dml handler error: service limit reached: couldn't create table bananas; limit reached on namespace 42", ), // A single-tenant namespace parsing error ( SingleTenantError(SingleTenantExtractError::InvalidNamespace(NamespaceNameError::LengthConstraint{name: "bananas".to_string()})), "namespace name bananas length must be between 1 and 64 characters", ), // A single-tenant v1 parsing error ( SingleTenantError(SingleTenantExtractError::ParseV1Request(V1WriteParseError::NoQueryParams)), "no db destination provided", ), // A single-tenant v2 parsing error ( SingleTenantError(SingleTenantExtractError::ParseV2Request(V2WriteParseError::NoQueryParams)), "no org/bucket destination provided", ), // A multi-tenant namespace parsing error ( MultiTenantError(MultiTenantExtractError::InvalidOrgAndBucket(OrgBucketMappingError::InvalidNamespaceName(NamespaceNameError::LengthConstraint{name: "bananas".to_string()}))), "invalid namespace name: namespace name bananas length must be between 1 and 64 characters", ), ( MultiTenantError(MultiTenantExtractError::InvalidOrgAndBucket(OrgBucketMappingError::NoOrgBucketSpecified)), "missing org/bucket value", ), // There is no multi-tenant support for v1 parsing, so no errors! // A multi-tenant v2 parsing error ( MultiTenantError(MultiTenantExtractError::ParseV2Request(V2WriteParseError::NoQueryParams)), "no org/bucket destination provided", ), } }
use crate::error::Error; use crate::hex_utils; use crate::services::PaginationRequest; use crate::services::PaginationResponse; use crate::services::PaymentsFilter; use bdk::database::SyncTime; use bdk::BlockTime; use bitcoin::BlockHash; use entity::access_token; use entity::access_token::Entity as AccessToken; use entity::kv_store; use entity::kv_store::Entity as KVStore; use entity::macaroon; use entity::macaroon::Entity as Macaroon; use entity::node; use entity::node::Entity as Node; use entity::payment; use entity::payment::Entity as Payment; use entity::peer; use entity::peer::Entity as Peer; use entity::peer_address; use entity::peer_address::Entity as PeerAddress; use entity::sea_orm; use entity::sea_orm::ActiveValue; use entity::sea_orm::QueryOrder; use entity::seconds_since_epoch; use entity::user; use entity::user::Entity as User; use migration::Condition; use migration::Expr; use rand::thread_rng; use rand::RngCore; use sea_orm::entity::EntityTrait; use sea_orm::{prelude::*, DatabaseConnection}; use serde::Deserialize; use serde::Serialize; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub struct LastSync { pub height: u32, pub hash: BlockHash, pub timestamp: u64, } impl From<LastSync> for BlockTime { fn from(last_sync: LastSync) -> Self { Self { height: last_sync.height, timestamp: last_sync.timestamp, } } } impl From<LastSync> for SyncTime { fn from(last_sync: LastSync) -> Self { Self { block_time: last_sync.into(), } } } pub struct SenseiDatabase { connection: DatabaseConnection, runtime_handle: tokio::runtime::Handle, } impl SenseiDatabase { pub fn new(connection: DatabaseConnection, runtime_handle: tokio::runtime::Handle) -> Self { Self { connection, runtime_handle, } } pub fn get_connection(&self) -> &DatabaseConnection { &self.connection } pub fn get_handle(&self) -> tokio::runtime::Handle { self.runtime_handle.clone() } pub async fn mark_all_nodes_stopped(&self) -> Result<(), Error> { Ok(Node::update_many() .col_expr(node::Column::Status, Expr::value(0)) .exec(&self.connection) .await .map(|_| ())?) } pub async fn get_node_by_pubkey(&self, pubkey: &str) -> Result<Option<node::Model>, Error> { Ok(Node::find() .filter(node::Column::Id.eq(pubkey)) .one(&self.connection) .await?) } pub async fn get_node_by_username(&self, username: &str) -> Result<Option<node::Model>, Error> { Ok(Node::find() .filter(node::Column::Username.eq(username)) .one(&self.connection) .await?) } pub async fn get_node_by_connection_info( &self, listen_addr: &str, listen_port: i32, ) -> Result<Option<node::Model>, Error> { Ok(Node::find() .filter(node::Column::ListenAddr.eq(listen_addr)) .filter(node::Column::ListenPort.eq(listen_port)) .one(&self.connection) .await?) } pub async fn list_ports_in_use(&self) -> Result<Vec<u16>, Error> { Ok(Node::find() .all(&self.connection) .await? .into_iter() .map(|node| node.listen_port as u16) .collect()) } pub async fn list_nodes( &self, pagination: PaginationRequest, ) -> Result<(Vec<node::Model>, PaginationResponse), Error> { let query_string = pagination.query.unwrap_or_else(|| String::from("")); let page_size: usize = pagination.take.try_into().unwrap(); let page: usize = pagination.page.try_into().unwrap(); let node_pages = Node::find() .filter( Condition::any() .add(node::Column::Alias.contains(&query_string)) .add(node::Column::Id.contains(&query_string)) .add(node::Column::Username.contains(&query_string)), ) .order_by_desc(node::Column::UpdatedAt) .paginate(&self.connection, page_size); let nodes = node_pages.fetch_page(page).await?; let total = node_pages.num_items().await?; let has_more = ((page + 1) * page_size) < total; Ok(( nodes, PaginationResponse { has_more, total: total.try_into().unwrap(), }, )) } pub async fn create_user( &self, username: String, passphrase: String, ) -> Result<user::Model, Error> { let hashed_password = bcrypt::hash(passphrase, 10).unwrap(); let user = user::ActiveModel { username: ActiveValue::Set(username), hashed_password: ActiveValue::Set(hashed_password), ..Default::default() }; Ok(user.insert(&self.connection).await?) } pub async fn verify_user(&self, username: String, passphrase: String) -> Result<bool, Error> { match User::find() .filter(user::Column::Username.eq(username)) .one(&self.connection) .await? { Some(user) => Ok(bcrypt::verify(passphrase, &user.hashed_password).unwrap()), None => Ok(false), } } pub async fn get_root_access_token(&self) -> Result<Option<access_token::Model>, Error> { Ok(AccessToken::find() .filter(access_token::Column::Scope.eq(String::from("*"))) .one(&self.connection) .await?) } pub async fn get_access_token_by_token( &self, token: String, ) -> Result<Option<access_token::Model>, Error> { Ok(AccessToken::find() .filter(access_token::Column::Token.eq(token)) .one(&self.connection) .await?) } pub async fn create_root_access_token(&self) -> Result<access_token::Model, Error> { self.create_access_token("root".to_string(), "*".to_string(), 0, false) .await } pub async fn create_access_token( &self, name: String, scope: String, expires_at: i64, single_use: bool, ) -> Result<access_token::Model, Error> { let mut token_bytes: [u8; 32] = [0; 32]; thread_rng().fill_bytes(&mut token_bytes); let token = hex_utils::hex_str(&token_bytes); let access_token = access_token::ActiveModel { id: ActiveValue::Set(Uuid::new_v4().to_string()), created_at: ActiveValue::NotSet, updated_at: ActiveValue::NotSet, name: ActiveValue::Set(name), token: ActiveValue::Set(token), scope: ActiveValue::Set(scope), expires_at: ActiveValue::Set(expires_at), single_use: ActiveValue::Set(single_use), }; Ok(access_token.insert(&self.connection).await?) } pub async fn delete_access_token(&self, id: String) -> Result<(), Error> { let _res = AccessToken::delete_by_id(id).exec(&self.connection).await?; Ok(()) } pub async fn list_access_tokens( &self, pagination: PaginationRequest, ) -> Result<(Vec<access_token::Model>, PaginationResponse), Error> { let query_string = pagination.query.unwrap_or_else(|| String::from("")); let page_size: usize = pagination.take.try_into().unwrap(); let page: usize = pagination.page.try_into().unwrap(); let access_token_pages = AccessToken::find() .filter( Condition::any() .add(access_token::Column::Token.contains(&query_string)) .add(access_token::Column::Name.contains(&query_string)), ) .order_by_desc(access_token::Column::UpdatedAt) .paginate(&self.connection, page_size); let access_tokens = access_token_pages.fetch_page(page).await?; let total = access_token_pages.num_items().await?; let has_more = ((page + 1) * page_size) < total; Ok(( access_tokens, PaginationResponse { has_more, total: total.try_into().unwrap(), }, )) } pub fn find_payment_sync( &self, node_id: String, payment_hash: String, ) -> Result<Option<payment::Model>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.find_payment(node_id, payment_hash).await }) }) } pub fn insert_payment_sync( &self, payment: payment::ActiveModel, ) -> Result<payment::Model, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { Ok(payment.insert(&self.connection).await?) }) }) } pub fn update_payment_sync( &self, payment: payment::ActiveModel, ) -> Result<payment::Model, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { Ok(payment.update(&self.connection).await?) }) }) } pub async fn find_payment( &self, node_id: String, payment_hash: String, ) -> Result<Option<payment::Model>, Error> { Ok(Payment::find() .filter(entity::payment::Column::NodeId.eq(node_id)) .filter(entity::payment::Column::PaymentHash.eq(payment_hash)) .one(&self.connection) .await?) } pub async fn delete_payment(&self, node_id: String, payment_hash: String) -> Result<(), Error> { match self.find_payment(node_id, payment_hash).await? { Some(payment) => { let _deleted = payment.delete(&self.connection).await?; Ok(()) } None => Ok(()), } } pub async fn label_payment( &self, node_id: String, payment_hash: String, label: String, ) -> Result<(), Error> { match self.find_payment(node_id, payment_hash).await? { Some(payment) => { let mut payment: payment::ActiveModel = payment.into(); payment.label = ActiveValue::Set(Some(label)); payment.update(&self.connection).await?; Ok(()) } None => Ok(()), } } pub fn list_payments_sync( &self, node_id: String, pagination: PaginationRequest, filter: PaymentsFilter, ) -> Result<(Vec<payment::Model>, PaginationResponse), Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.list_payments(node_id, pagination, filter).await }) }) } pub async fn list_payments( &self, node_id: String, pagination: PaginationRequest, filter: PaymentsFilter, ) -> Result<(Vec<payment::Model>, PaginationResponse), Error> { let origin_filter = filter.origin.unwrap_or_else(|| String::from("")); let status_filter = filter.status.unwrap_or_else(|| String::from("")); let query_string = pagination.query.unwrap_or_else(|| String::from("")); let page_size: usize = pagination.take.try_into().unwrap(); let page: usize = pagination.page.try_into().unwrap(); let payment_pages = Payment::find() .filter(payment::Column::NodeId.eq(node_id)) .filter(payment::Column::Origin.contains(&origin_filter)) .filter(payment::Column::Status.contains(&status_filter)) .filter( Condition::any() .add(payment::Column::PaymentHash.contains(&query_string)) .add(payment::Column::Label.contains(&query_string)) .add(payment::Column::Invoice.contains(&query_string)), ) .order_by_desc(payment::Column::UpdatedAt) .paginate(&self.connection, page_size); let payments = payment_pages.fetch_page(page).await?; let total = payment_pages.num_items().await?; let has_more = ((page + 1) * page_size) < total; Ok(( payments, PaginationResponse { has_more, total: total.try_into().unwrap(), }, )) } pub async fn find_peer_address_by_id( &self, id: &str, ) -> Result<Option<peer_address::Model>, Error> { Ok(PeerAddress::find() .filter(entity::peer_address::Column::Id.eq(id)) .one(&self.connection) .await?) } pub async fn list_peer_addresses( &self, node_id: &str, pubkey: &str, ) -> Result<Vec<peer_address::Model>, Error> { Ok(PeerAddress::find() .filter(entity::peer_address::Column::NodeId.eq(node_id)) .filter(entity::peer_address::Column::Pubkey.eq(pubkey)) .order_by_desc(entity::peer_address::Column::LastConnectedAt) .all(&self.connection) .await?) } pub async fn delete_peer_address(&self, id: &str) -> Result<(), Error> { match self.find_peer_address_by_id(id).await? { Some(peer_address) => { let _deleted = peer_address.delete(&self.connection).await?; Ok(()) } None => Ok(()), } } pub async fn delete_peer(&self, node_id: &str, pubkey: &str) -> Result<(), Error> { match self.find_peer(node_id, pubkey).await? { Some(peer) => { let _deleted = peer.delete(&self.connection).await?; Ok(()) } None => Ok(()), } } pub async fn find_peer( &self, node_id: &str, pubkey: &str, ) -> Result<Option<peer::Model>, Error> { Ok(Peer::find() .filter(entity::peer::Column::NodeId.eq(node_id)) .filter(entity::peer::Column::Pubkey.eq(pubkey)) .one(&self.connection) .await?) } pub async fn label_peer( &self, node_id: &str, pubkey: &str, label: String, ) -> Result<(), Error> { match self.find_peer(node_id, pubkey).await? { Some(peer) => { let mut peer: peer::ActiveModel = peer.into(); peer.label = ActiveValue::Set(Some(label)); peer.update(&self.connection).await?; Ok(()) } None => Ok(()), } } pub fn find_peer_sync( &self, node_id: &str, pubkey: &str, ) -> Result<Option<peer::Model>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.find_peer(node_id, pubkey).await }) }) } pub async fn list_peers( &self, node_id: &str, pagination: PaginationRequest, ) -> Result<(Vec<peer::Model>, PaginationResponse), Error> { let query_string = pagination.query.unwrap_or_else(|| String::from("")); let page_size: usize = pagination.take.try_into().unwrap(); let page: usize = pagination.page.try_into().unwrap(); let peer_pages = Peer::find() .filter(peer::Column::NodeId.eq(node_id)) .filter( Condition::any() .add(peer::Column::Pubkey.contains(&query_string)) .add(peer::Column::Label.contains(&query_string)), ) .order_by_desc(peer::Column::CreatedAt) .paginate(&self.connection, page_size); let peers = peer_pages.fetch_page(page).await?; let total = peer_pages.num_items().await?; let has_more = ((page + 1) * page_size) < total; Ok(( peers, PaginationResponse { has_more, total: total.try_into().unwrap(), }, )) } pub async fn port_in_use(&self, listen_addr: &str, listen_port: i32) -> Result<bool, Error> { self.get_node_by_connection_info(listen_addr, listen_port) .await .map(|node| node.is_some()) } pub async fn get_value( &self, node_id: String, key: String, ) -> Result<Option<kv_store::Model>, Error> { Ok(KVStore::find() .filter(kv_store::Column::NodeId.eq(node_id)) .filter(kv_store::Column::K.eq(key)) .one(&self.connection) .await?) } pub fn get_value_sync( &self, node_id: String, key: String, ) -> Result<Option<kv_store::Model>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.get_value(node_id, key).await }) }) } pub async fn list_values( &self, node_id: String, key_prefix: String, ) -> Result<Vec<kv_store::Model>, Error> { Ok(KVStore::find() .filter(kv_store::Column::NodeId.eq(node_id)) .filter(kv_store::Column::K.starts_with(&key_prefix)) .all(&self.connection) .await?) } // TODO: do not select value column or update read monitors to not separate list keys and read monitor pub async fn list_keys(&self, node_id: String, key_prefix: &str) -> Result<Vec<String>, Error> { Ok(KVStore::find() .filter(kv_store::Column::NodeId.eq(node_id)) .filter(kv_store::Column::K.starts_with(key_prefix)) .all(&self.connection) .await? .iter() .map(|entity| entity.k.clone()) .collect()) } pub fn list_keys_sync(&self, node_id: String, key_prefix: &str) -> Result<Vec<String>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.list_keys(node_id, key_prefix).await }) }) } pub fn list_values_sync( &self, node_id: String, key_prefix: String, ) -> Result<Vec<kv_store::Model>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.list_values(node_id, key_prefix).await }) }) } pub async fn create_value( &self, node_id: String, key: String, value: Vec<u8>, ) -> Result<kv_store::Model, Error> { let entry = kv_store::ActiveModel { node_id: ActiveValue::Set(node_id), k: ActiveValue::Set(key), v: ActiveValue::Set(value), ..Default::default() } .insert(&self.connection) .await?; Ok(entry) } pub async fn set_value( &self, node_id: String, key: String, value: Vec<u8>, ) -> Result<kv_store::Model, Error> { let entry = match self.get_value(node_id.clone(), key.clone()).await? { Some(entry) => { let mut existing_entry: kv_store::ActiveModel = entry.into(); existing_entry.v = ActiveValue::Set(value); existing_entry.update(&self.connection) } None => kv_store::ActiveModel { node_id: ActiveValue::Set(node_id), k: ActiveValue::Set(key), v: ActiveValue::Set(value), ..Default::default() } .insert(&self.connection), } .await?; Ok(entry) } pub fn set_value_sync( &self, node_id: String, key: String, value: Vec<u8>, ) -> Result<kv_store::Model, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.set_value(node_id, key, value).await }) }) } pub async fn get_entropy(&self, node_id: String) -> Result<Option<Vec<u8>>, Error> { self.get_value(node_id, String::from("entropy")) .await .map(|model| model.map(|model| model.v)) } pub fn get_entropy_sync(&self, node_id: String) -> Result<Option<Vec<u8>>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.get_entropy(node_id).await }) }) } pub async fn set_entropy( &self, node_id: String, entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { self.set_value(node_id, String::from("entropy"), entropy) .await } pub fn set_entropy_sync( &self, node_id: String, entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.set_entropy(node_id, entropy).await }) }) } pub async fn create_entropy( &self, node_id: String, entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { self.create_value(node_id, String::from("entropy"), entropy) .await } pub fn get_entropy_active_model( &self, node_id: String, entropy: Vec<u8>, ) -> kv_store::ActiveModel { let now = seconds_since_epoch(); kv_store::ActiveModel { node_id: ActiveValue::Set(node_id), k: ActiveValue::Set(String::from("entropy")), v: ActiveValue::Set(entropy), created_at: ActiveValue::Set(now), updated_at: ActiveValue::Set(now), ..Default::default() } } pub async fn get_cross_node_entropy(&self, node_id: String) -> Result<Option<Vec<u8>>, Error> { self.get_value(node_id, String::from("cross_node_entropy")) .await .map(|model| model.map(|model| model.v)) } pub fn get_cross_node_entropy_sync(&self, node_id: String) -> Result<Option<Vec<u8>>, Error> { tokio::task::block_in_place(move || { self.runtime_handle .block_on(async move { self.get_cross_node_entropy(node_id).await }) }) } pub async fn set_cross_node_entropy( &self, node_id: String, cross_node_entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { self.set_value( node_id, String::from("cross_node_entropy"), cross_node_entropy, ) .await } pub fn set_cross_node_entropy_sync( &self, node_id: String, cross_node_entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { tokio::task::block_in_place(move || { self.runtime_handle.block_on(async move { self.set_cross_node_entropy(node_id, cross_node_entropy) .await }) }) } pub async fn create_cross_node_entropy( &self, node_id: String, cross_node_entropy: Vec<u8>, ) -> Result<kv_store::Model, Error> { self.create_value( node_id, String::from("cross_node_entropy"), cross_node_entropy, ) .await } pub fn get_cross_node_entropy_active_model( &self, node_id: String, cross_node_entropy: Vec<u8>, ) -> kv_store::ActiveModel { let now = seconds_since_epoch(); kv_store::ActiveModel { node_id: ActiveValue::Set(node_id), k: ActiveValue::Set(String::from("cross_node_entropy")), v: ActiveValue::Set(cross_node_entropy), created_at: ActiveValue::Set(now), updated_at: ActiveValue::Set(now), ..Default::default() } } pub async fn insert_kv_store( &self, entity: kv_store::ActiveModel, ) -> Result<kv_store::Model, Error> { Ok(entity.insert(&self.connection).await?) } // Note: today we assume there's only ever one macaroon for a user // once there's some `bakery` functionality exposed we need to define // which macaroon we return when a user unlocks their node pub async fn get_macaroon(&self, node_id: &str) -> Result<Option<macaroon::Model>, Error> { Ok(Macaroon::find() .filter(macaroon::Column::NodeId.eq(node_id)) .one(&self.connection) .await?) } pub async fn find_macaroon_by_id( &self, macaroon_id: String, ) -> Result<Option<macaroon::Model>, Error> { Ok(Macaroon::find_by_id(macaroon_id) .one(&self.connection) .await?) } pub async fn create_macaroon( &self, node_id: String, id: String, encrypted_macaroon: Vec<u8>, ) -> Result<macaroon::Model, Error> { let macaroon = macaroon::ActiveModel { node_id: ActiveValue::Set(node_id), id: ActiveValue::Set(id), encrypted_macaroon: ActiveValue::Set(encrypted_macaroon), ..Default::default() }; Ok(macaroon.insert(&self.connection).await?) } pub async fn create_or_update_last_onchain_wallet_sync( &self, node_id: String, hash: BlockHash, height: u32, timestamp: u64, ) -> Result<LastSync, Error> { match self .get_value(node_id.clone(), String::from("last_onchain_wallet_sync")) .await? { Some(entry) => { let last_sync: LastSync = serde_json::from_slice(&entry.v).unwrap(); Ok(last_sync) } None => { let last_sync = LastSync { hash, height, timestamp, }; let serialized_last_sync = serde_json::to_vec(&last_sync).unwrap(); self.set_value( node_id, String::from("last_onchain_wallet_sync"), serialized_last_sync, ) .await?; Ok(last_sync) } } } }
use rand::Rng; use std::{thread, time}; use test_deps::deps; static mut COUNTER_SERIAL: usize = 0; #[deps(SERIAL_000)] #[test] fn serial_000() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(0, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } #[deps(SERIAL_001: SERIAL_000)] #[test] fn serial_001() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(1, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } #[deps(SERIAL_002: SERIAL_001)] #[test] fn serial_002() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(2, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } #[deps(SERIAL_003: SERIAL_002)] #[test] fn serial_003() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(3, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } #[deps(SERIAL_004: SERIAL_003)] #[test] fn serial_004() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(4, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } #[deps(SERIAL_005: SERIAL_004)] #[test] fn serial_005() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert_eq!(5, COUNTER_SERIAL); COUNTER_SERIAL = COUNTER_SERIAL + 1; } } static mut LEAF_FORK: [bool; 6] = [false; 6]; #[deps(FORK_000)] #[test] fn fork_000() { thread::sleep(time::Duration::from_secs_f64(0.5)); unsafe { for l in &LEAF_FORK[1..] { assert!(!l); } LEAF_FORK[0] = true; } } #[deps(FORK_001: FORK_000)] #[test] fn fork_001() { unsafe { assert!(LEAF_FORK[0]); LEAF_FORK[1] = true; } } #[deps(FORK_002: FORK_000)] #[test] fn fork_002() { unsafe { assert!(LEAF_FORK[0]); LEAF_FORK[2] = true; } } #[deps(FORK_003: FORK_000)] #[test] fn fork_003() { unsafe { assert!(LEAF_FORK[0]); LEAF_FORK[3] = true; } } #[deps(FORK_004: FORK_000)] #[test] fn fork_004() { unsafe { assert!(LEAF_FORK[0]); LEAF_FORK[4] = true; } } #[deps(FORK_005: FORK_000)] #[test] fn fork_005() { unsafe { assert!(LEAF_FORK[0]); LEAF_FORK[5] = true; } } static mut LEAF_MERGE: [bool; 6] = [false; 6]; #[deps(MERGE_000: MERGE_001 MERGE_002 MERGE_003 MERGE_004 MERGE_005)] #[test] fn merge_000() { unsafe { for l in &LEAF_MERGE[1..] { assert!(l); } LEAF_MERGE[0] = true; } } #[deps(MERGE_001)] #[test] fn merge_001() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert!(!LEAF_MERGE[0]); LEAF_MERGE[1] = true; } } #[deps(MERGE_002)] #[test] fn merge_002() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert!(!LEAF_MERGE[0]); LEAF_MERGE[2] = true; } } #[deps(MERGE_003)] #[test] fn merge_003() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert!(!LEAF_MERGE[0]); LEAF_MERGE[3] = true; } } #[deps(MERGE_004)] #[test] fn merge_004() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert!(!LEAF_MERGE[0]); LEAF_MERGE[4] = true; } } #[deps(MERGE_005)] #[test] fn merge_005() { thread::sleep(time::Duration::from_secs_f64(0.100000 * rand::thread_rng().gen::<f64>())); unsafe { assert!(!LEAF_MERGE[0]); LEAF_MERGE[5] = true; } } static mut N: [usize; 10] = [0; 10]; #[deps(NN_000: NN_016 NN_017 NN_018 NN_019 NN_020)] #[test] fn neural_network_000() { let mut input = 0; let pos = 4 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(625, input); } #[deps(NN_001)] #[test] fn neural_network_001() { thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[..5] { assert_eq!(0, *n); } N[5 + 0] = 1; } } #[deps(NN_002)] #[test] fn neural_network_002() { thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[..5] { assert_eq!(0, *n); } N[5 + 1] = 1; } } #[deps(NN_003)] #[test] fn neural_network_003() { thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[..5] { assert_eq!(0, *n); } N[5 + 2] = 1; } } #[deps(NN_004)] #[test] fn neural_network_004() { thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[..5] { assert_eq!(0, *n); } N[5 + 3] = 1; } } #[deps(NN_005)] #[test] fn neural_network_005() { thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[..5] { assert_eq!(0, *n); } N[5 + 4] = 1; } } #[deps(NN_006: NN_001 NN_002 NN_003 NN_004 NN_005)] #[test] fn neural_network_006() { let mut input = 0; let pos = 1 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(5, input); unsafe { N[(pos ^ 1) * 5 + 0] = 5; } } #[deps(NN_007: NN_001 NN_002 NN_003 NN_004 NN_005)] #[test] fn neural_network_007() { let mut input = 0; let pos = 1 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(5, input); unsafe { N[(pos ^ 1) * 5 + 1] = 5; } } #[deps(NN_008: NN_001 NN_002 NN_003 NN_004 NN_005)] #[test] fn neural_network_008() { let mut input = 0; let pos = 1 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(5, input); unsafe { N[(pos ^ 1) * 5 + 2] = 5; } } #[deps(NN_009: NN_001 NN_002 NN_003 NN_004 NN_005)] #[test] fn neural_network_009() { let mut input = 0; let pos = 1 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(5, input); unsafe { N[(pos ^ 1) * 5 + 3] = 5; } } #[deps(NN_010: NN_001 NN_002 NN_003 NN_004 NN_005)] #[test] fn neural_network_010() { let mut input = 0; let pos = 1 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(5, input); unsafe { N[(pos ^ 1) * 5 + 4] = 5; } } #[deps(NN_011: NN_006 NN_007 NN_008 NN_009 NN_010)] #[test] fn neural_network_011() { let mut input = 0; let pos = 2 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(25, input); unsafe { N[(pos ^ 1) * 5 + 0] = 25; } } #[deps(NN_012: NN_006 NN_007 NN_008 NN_009 NN_010)] #[test] fn neural_network_012() { let mut input = 0; let pos = 2 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(25, input); unsafe { N[(pos ^ 1) * 5 + 1] = 25; } } #[deps(NN_013: NN_006 NN_007 NN_008 NN_009 NN_010)] #[test] fn neural_network_013() { let mut input = 0; let pos = 2 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(25, input); unsafe { N[(pos ^ 1) * 5 + 2] = 25; } } #[deps(NN_014: NN_006 NN_007 NN_008 NN_009 NN_010)] #[test] fn neural_network_014() { let mut input = 0; let pos = 2 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(25, input); unsafe { N[(pos ^ 1) * 5 + 3] = 25; } } #[deps(NN_015: NN_006 NN_007 NN_008 NN_009 NN_010)] #[test] fn neural_network_015() { let mut input = 0; let pos = 2 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(25, input); unsafe { N[(pos ^ 1) * 5 + 4] = 25; } } #[deps(NN_016: NN_011 NN_012 NN_013 NN_014 NN_015)] #[test] fn neural_network_016() { let mut input = 0; let pos = 3 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(125, input); unsafe { N[(pos ^ 1) * 5 + 0] = 125; } } #[deps(NN_017: NN_011 NN_012 NN_013 NN_014 NN_015)] #[test] fn neural_network_017() { let mut input = 0; let pos = 3 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(125, input); unsafe { N[(pos ^ 1) * 5 + 1] = 125; } } #[deps(NN_018: NN_011 NN_012 NN_013 NN_014 NN_015)] #[test] fn neural_network_018() { let mut input = 0; let pos = 3 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(125, input); unsafe { N[(pos ^ 1) * 5 + 2] = 125; } } #[deps(NN_019: NN_011 NN_012 NN_013 NN_014 NN_015)] #[test] fn neural_network_019() { let mut input = 0; let pos = 3 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(125, input); unsafe { N[(pos ^ 1) * 5 + 3] = 125; } } #[deps(NN_020: NN_011 NN_012 NN_013 NN_014 NN_015)] #[test] fn neural_network_020() { let mut input = 0; let pos = 3 % 2; thread::sleep(time::Duration::from_secs_f64(0.025000 * rand::thread_rng().gen::<f64>())); unsafe { for n in &N[(pos * 5)..((pos + 1) * 5)] { input = input + n; } } assert_eq!(125, input); unsafe { N[(pos ^ 1) * 5 + 4] = 125; } }
extern crate reqwest; extern crate scraper; use scraper::{Html, Selector}; use std::env; #[derive(Debug)] struct CrateListing { name: String, desc: String, date: String, url: String, } fn get_search_term() -> String { let cli_args: Vec<String> = env::args().collect(); let search_term: &str = &cli_args[1]; String::from(search_term) } fn main () -> Result<(), reqwest::Error> { // retrieves the CLI search term let search_term = get_search_term(); // defines the default search address let mut site_url = String::from("https://docs.rs/releases/search?query="); // pushes the search term into the url site_url.push_str(&search_term); let mut res = get_request(&site_url).unwrap(); let text_body = res.text().unwrap(); let fragment = Html::parse_document(&text_body); let crate_names = Selector::parse(".name").unwrap(); let crate_dates = Selector::parse(".date").unwrap(); // dont ask why but .descriptions fucks the entire thing up. need to use wacky class name from below let crate_descriptions = Selector::parse(".pure-u-sm-14-24").unwrap(); let mut crate_vector: Vec<CrateListing> = Vec::new(); // iterate over every crate name for crates in fragment.select(&crate_names){ // gets the crate name string let crate_name = crates.text().collect::<Vec<_>>(); //println!("crate_names length = {:#?}", crate_name.len()); // gets rid of all the crap let crate_name = crate_name[0].replace(&['(', ')', ',', '\"', ';', ':', '\'', ' ', '\n'][..], ""); // instantiates the crate struct let crate_listing = CrateListing { name: String::from(crate_name), desc: String::from(""), date: String::from(""), url: String::from("") }; // pushes the struct onto the vector crate_vector.push(crate_listing); } let mut i = 0; for crates in fragment.select(&crate_dates){ let crate_date = crates.text().collect::<Vec<_>>(); let crate_date = crate_date[0].replace(&['(', ')', ',', '\"', ';', ':', '\'', ' ', '\n'][..], ""); crate_vector[i].date = crate_date; i += 1; } let mut i = 0; for crates in fragment.select(&crate_descriptions){ // gets the crate name string let crate_description = crates.text().collect::<Vec<_>>(); let crate_description = crate_description[0].replace(&['(', ')', ',', '\"', ';', ':', '\'', '\n'][..], ""); crate_vector[i].desc = String::from(crate_description.trim()); i += 1; } crate_vector.iter().for_each(|it|{ println!("{} | {} | {}\n", it.name, it.desc, it.date); }); Ok(()) } fn get_request(url: &str) -> Result<reqwest::Response, reqwest::Error>{ let res = reqwest::get(url).unwrap(); assert!(res.status().is_success()); Ok(res) }
use core::borrow::BorrowMut; use embedded_graphics::{ draw_target::DrawTarget, mono_font::{MonoFont, MonoTextStyle, MonoTextStyleBuilder}, pixelcolor::{PixelColor, Rgb888}, prelude::{Dimensions, Point, Size}, primitives::Rectangle, text::renderer::{CharacterStyle, TextRenderer}, Drawable, }; use embedded_gui::{ geometry::{measurement::MeasureSpec, MeasuredSize, Position}, input::event::{Key, Modifier, ToStr}, prelude::WidgetData, state::selection::Selected, widgets::{ text_box::{TextBox, TextBoxFields, TextBoxProperties}, utils::WidgetDataHolder, }, WidgetRenderer, }; use embedded_text::{ style::{HeightMode, TextBoxStyleBuilder, VerticalOverdraw}, TextBox as EgTextBox, }; pub use embedded_text::alignment::{HorizontalAlignment, VerticalAlignment}; use heapless::String; use object_chain::ChainElement; use crate::{widgets::text_box::plugin::Cursor, EgCanvas, ToPoint, ToRectangle}; mod plugin; pub struct TextBoxStyle<T> where T: TextRenderer + CharacterStyle<Color = <T as TextRenderer>::Color>, { renderer: T, // Temporarily removed as alignments and editor together are a bit buggy horizontal: HorizontalAlignment, vertical: VerticalAlignment, cursor: Cursor, cursor_color: Option<<T as TextRenderer>::Color>, } impl<C, T> TextBoxStyle<T> where C: PixelColor, T: TextRenderer<Color = C> + CharacterStyle<Color = C>, { /// Customize the text color pub fn text_color(&mut self, text_color: C) { self.renderer.set_text_color(Some(text_color)); if self.cursor_color.is_none() { self.cursor_color(text_color); } } /// Customize the cursor color pub fn cursor_color(&mut self, color: <T as TextRenderer>::Color) { self.cursor_color = Some(color); } } impl<'a, C> TextBoxStyle<MonoTextStyle<'a, C>> where C: PixelColor, { pub fn get_text_color(&self) -> Option<C> { self.renderer.text_color } /// Customize the font pub fn font<'a2>(self, font: &'a2 MonoFont<'a2>) -> TextBoxStyle<MonoTextStyle<'a2, C>> { TextBoxStyle { renderer: MonoTextStyleBuilder::from(&self.renderer) .font(font) .build(), horizontal: self.horizontal, vertical: self.vertical, cursor: Cursor::default(), cursor_color: None, } } } impl<F, C> TextBoxProperties for TextBoxStyle<F> where F: TextRenderer<Color = C> + CharacterStyle<Color = C>, C: PixelColor + From<Rgb888>, { fn measure_text(&self, text: &str, spec: MeasureSpec) -> MeasuredSize { let max_width = spec.width.largest().unwrap_or(u32::MAX); let max_height = spec.height.largest().unwrap_or(u32::MAX); let bounding_box = EgTextBox::with_textbox_style( text, Rectangle::new(Point::zero(), Size::new(max_width, max_height)), self.renderer.clone(), TextBoxStyleBuilder::new() .height_mode(HeightMode::Exact(VerticalOverdraw::Hidden)) .leading_spaces(true) .trailing_spaces(true) .build(), ) .bounding_box(); MeasuredSize { width: bounding_box.size.width, height: bounding_box.size.height, } } fn handle_keypress<const N: usize>( &mut self, key: Key, modifier: Modifier, text: &mut String<N>, ) -> bool { match key { Key::ArrowUp => self.cursor.cursor_up(), Key::ArrowDown => self.cursor.cursor_down(), Key::ArrowLeft => self.cursor.cursor_left(), Key::ArrowRight => self.cursor.cursor_right(), Key::Del => self.cursor.delete_after(text), Key::Backspace => self.cursor.delete_before(text), _ => { if let Some(str) = (key, modifier).to_str() { self.cursor.insert(text, str); } else { return false; } } } true } fn handle_cursor_down(&mut self, coordinates: Position) { self.cursor.move_cursor_to(coordinates.to_point()) } } pub trait TextBoxStyling<B, D, T, const N: usize>: Sized where B: BorrowMut<String<N>>, D: WidgetData, T: TextRenderer + CharacterStyle<Color = <T as TextRenderer>::Color>, { type Color; fn text_color(mut self, color: Self::Color) -> Self { self.set_text_color(color); self } fn set_text_color(&mut self, color: Self::Color); fn text_renderer<T2>(self, renderer: T2) -> TextBox<B, TextBoxStyle<T2>, D, N> where T2: TextRenderer + CharacterStyle<Color = <T2 as TextRenderer>::Color>, <T2 as TextRenderer>::Color: From<Rgb888>; fn style<P>(self, props: P) -> TextBox<B, P, D, N> where P: TextBoxProperties; fn horizontal_alignment(self, alignment: HorizontalAlignment) -> Self; fn vertical_alignment(self, alignment: VerticalAlignment) -> Self; fn cursor_color(self, color: Self::Color) -> Self; } impl<'a, B, C, D, T, const N: usize> TextBoxStyling<B, D, T, N> for TextBox<B, TextBoxStyle<T>, D, N> where B: BorrowMut<String<N>>, D: WidgetData, C: PixelColor + From<Rgb888>, T: CharacterStyle<Color = C>, T: TextRenderer<Color = C>, { type Color = C; fn set_text_color(&mut self, color: Self::Color) { self.fields.label_properties.text_color(color); } fn text_renderer<T2>(self, renderer: T2) -> TextBox<B, TextBoxStyle<T2>, D, N> where T2: TextRenderer + CharacterStyle<Color = <T2 as TextRenderer>::Color>, <T2 as TextRenderer>::Color: From<Rgb888>, { let horizontal = self.fields.label_properties.horizontal; let vertical = self.fields.label_properties.vertical; let cursor = self.fields.label_properties.cursor.clone(); self.style(TextBoxStyle { renderer, horizontal, vertical, cursor, cursor_color: None, // TODO: convert }) } fn style<P>(self, props: P) -> TextBox<B, P, D, N> where P: TextBoxProperties, { TextBox { fields: TextBoxFields { state: self.fields.state, parent_index: self.fields.parent_index, text: self.fields.text, bounds: self.fields.bounds, label_properties: props, on_text_changed: self.fields.on_text_changed, on_parent_state_changed: |_, _| (), }, data_holder: WidgetDataHolder::new(self.data_holder.data), } } fn horizontal_alignment(self, alignment: HorizontalAlignment) -> Self { let renderer = self.fields.label_properties.renderer.clone(); let horizontal = alignment; let vertical = self.fields.label_properties.vertical; let cursor = self.fields.label_properties.cursor.clone(); let cursor_color = self.fields.label_properties.cursor_color; self.style(TextBoxStyle { renderer, horizontal, vertical, cursor, cursor_color, }) } fn vertical_alignment(self, alignment: VerticalAlignment) -> Self { let renderer = self.fields.label_properties.renderer.clone(); let horizontal = self.fields.label_properties.horizontal; let vertical = alignment; let cursor = self.fields.label_properties.cursor.clone(); let cursor_color = self.fields.label_properties.cursor_color; self.style(TextBoxStyle { renderer, horizontal, vertical, cursor, cursor_color, }) } fn cursor_color(self, color: C) -> Self { let renderer = self.fields.label_properties.renderer.clone(); let horizontal = self.fields.label_properties.horizontal; let vertical = self.fields.label_properties.vertical; let cursor = self.fields.label_properties.cursor.clone(); let cursor_color = Some(color); self.style(TextBoxStyle { renderer, horizontal, vertical, cursor, cursor_color, }) } } /// Font settings specific to `MonoFont`'s renderer. pub trait MonoFontTextBoxStyling<B, C, D, const N: usize>: Sized where B: BorrowMut<String<N>>, D: WidgetData, C: PixelColor, { fn font<'a>( self, font: &'a MonoFont<'a>, ) -> TextBox<B, TextBoxStyle<MonoTextStyle<'a, C>>, D, N>; } impl<'a, B, C, D, const N: usize> MonoFontTextBoxStyling<B, C, D, N> for TextBox<B, TextBoxStyle<MonoTextStyle<'a, C>>, D, N> where B: BorrowMut<String<N>>, D: WidgetData, C: PixelColor + From<Rgb888>, { fn font<'a2>( self, font: &'a2 MonoFont<'a2>, ) -> TextBox<B, TextBoxStyle<MonoTextStyle<'a2, C>>, D, N> { let renderer = MonoTextStyleBuilder::from(&self.fields.label_properties.renderer) .font(font) .build(); let horizontal = self.fields.label_properties.horizontal; let vertical = self.fields.label_properties.vertical; let cursor = self.fields.label_properties.cursor.clone(); let cursor_color = self.fields.label_properties.cursor_color; self.style(TextBoxStyle { renderer, horizontal, vertical, cursor, cursor_color, }) } } impl<B, F, C, DT, D, const N: usize> WidgetRenderer<EgCanvas<DT>> for TextBox<B, TextBoxStyle<F>, D, N> where B: BorrowMut<String<N>>, F: TextRenderer<Color = C> + CharacterStyle<Color = C>, C: PixelColor + From<Rgb888>, DT: DrawTarget<Color = C>, D: WidgetData, { fn draw(&mut self, canvas: &mut EgCanvas<DT>) -> Result<(), DT::Error> { let cursor_color = self.fields.label_properties.cursor_color; let textbox = EgTextBox::with_textbox_style( self.fields.text.borrow(), self.fields.bounds.to_rectangle(), self.fields.label_properties.renderer.clone(), TextBoxStyleBuilder::new() .height_mode(HeightMode::Exact(VerticalOverdraw::Hidden)) .leading_spaces(true) .trailing_spaces(true) .alignment(self.fields.label_properties.horizontal) .vertical_alignment(self.fields.label_properties.vertical) .build(), ); if self.fields.state.has_state(Selected) && cursor_color.is_some() { let textbox = textbox.add_plugin( self.fields .label_properties .cursor .plugin(cursor_color.unwrap()), ); let result = textbox.draw(&mut canvas.target).map(|_| ()); let plugins = textbox.take_plugins(); let (plugin, _plugins) = plugins.pop(); self.fields.label_properties.cursor = plugin.get_cursor(); result } else { textbox.draw(&mut canvas.target).map(|_| ()) } } } macro_rules! textbox_for_charset { ($charset:ident, $font:ident) => { pub mod $charset { use core::borrow::BorrowMut; use embedded_graphics::{ mono_font::{$charset, MonoTextStyle}, pixelcolor::PixelColor, }; use embedded_gui::{ data::WidgetData, geometry::BoundingBox, state::WidgetState, widgets::{ text_box::{TextBox, TextBoxFields}, utils::WidgetDataHolder, }, }; use embedded_text::alignment::{HorizontalAlignment, VerticalAlignment}; use heapless::String; use crate::{ themes::Theme, widgets::text_box::{plugin::Cursor, TextBoxStyle}, }; pub trait TextBoxConstructor<'a, B, C, D, const N: usize> where B: BorrowMut<String<N>>, D: WidgetData, C: PixelColor, { fn new(text: B) -> TextBox<B, TextBoxStyle<MonoTextStyle<'a, C>>, D, N>; } impl<'a, B, C, const N: usize> TextBoxConstructor<'a, B, C, (), N> for TextBox<B, TextBoxStyle<MonoTextStyle<'a, C>>, (), N> where C: PixelColor + Theme, B: BorrowMut<heapless::String<N>>, { fn new(text: B) -> Self { TextBox { fields: TextBoxFields { state: WidgetState::default(), parent_index: 0, text, label_properties: TextBoxStyle { renderer: MonoTextStyle::new( &$charset::$font, <C as Theme>::TEXT_COLOR, ), horizontal: HorizontalAlignment::Left, vertical: VerticalAlignment::Top, cursor: Cursor::default(), cursor_color: Some(<C as Theme>::TEXT_COLOR), }, bounds: BoundingBox::default(), on_text_changed: |_, _| (), on_parent_state_changed: |_, _| (), }, data_holder: WidgetDataHolder::default(), } } } } }; ($charset:ident) => { textbox_for_charset!($charset, FONT_6X10); }; } textbox_for_charset!(ascii); textbox_for_charset!(iso_8859_1); textbox_for_charset!(iso_8859_10); textbox_for_charset!(iso_8859_13); textbox_for_charset!(iso_8859_14); textbox_for_charset!(iso_8859_15); textbox_for_charset!(iso_8859_16); textbox_for_charset!(iso_8859_2); textbox_for_charset!(iso_8859_3); textbox_for_charset!(iso_8859_4); textbox_for_charset!(iso_8859_5); textbox_for_charset!(iso_8859_7); textbox_for_charset!(iso_8859_9); textbox_for_charset!(jis_x0201, FONT_6X13);
#[doc = "Reader of register FRCR"] pub type R = crate::R<u32, super::FRCR>; #[doc = "Writer for register FRCR"] pub type W = crate::W<u32, super::FRCR>; #[doc = "Register FRCR `reset()`'s with value 0x07"] impl crate::ResetValue for super::FRCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x07 } } #[doc = "Reader of field `FRL`"] pub type FRL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FRL`"] pub struct FRL_W<'a> { w: &'a mut W, } impl<'a> FRL_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 } } #[doc = "Reader of field `FSALL`"] pub type FSALL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `FSALL`"] pub struct FSALL_W<'a> { w: &'a mut W, } impl<'a> FSALL_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 & !(0x7f << 8)) | (((value as u32) & 0x7f) << 8); self.w } } #[doc = "Reader of field `FSDEF`"] pub type FSDEF_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FSDEF`"] pub struct FSDEF_W<'a> { w: &'a mut W, } impl<'a> FSDEF_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FSPOL_A { #[doc = "0: FS is active low (falling edge)"] FALLINGEDGE = 0, #[doc = "1: FS is active high (rising edge)"] RISINGEDGE = 1, } impl From<FSPOL_A> for bool { #[inline(always)] fn from(variant: FSPOL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FSPOL`"] pub type FSPOL_R = crate::R<bool, FSPOL_A>; impl FSPOL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FSPOL_A { match self.bits { false => FSPOL_A::FALLINGEDGE, true => FSPOL_A::RISINGEDGE, } } #[doc = "Checks if the value of the field is `FALLINGEDGE`"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { *self == FSPOL_A::FALLINGEDGE } #[doc = "Checks if the value of the field is `RISINGEDGE`"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { *self == FSPOL_A::RISINGEDGE } } #[doc = "Write proxy for field `FSPOL`"] pub struct FSPOL_W<'a> { w: &'a mut W, } impl<'a> FSPOL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FSPOL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "FS is active low (falling edge)"] #[inline(always)] pub fn falling_edge(self) -> &'a mut W { self.variant(FSPOL_A::FALLINGEDGE) } #[doc = "FS is active high (rising edge)"] #[inline(always)] pub fn rising_edge(self) -> &'a mut W { self.variant(FSPOL_A::RISINGEDGE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FSOFF_A { #[doc = "0: FS is asserted on the first bit of the slot 0"] ONFIRST = 0, #[doc = "1: FS is asserted one bit before the first bit of the slot 0"] BEFOREFIRST = 1, } impl From<FSOFF_A> for bool { #[inline(always)] fn from(variant: FSOFF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `FSOFF`"] pub type FSOFF_R = crate::R<bool, FSOFF_A>; impl FSOFF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FSOFF_A { match self.bits { false => FSOFF_A::ONFIRST, true => FSOFF_A::BEFOREFIRST, } } #[doc = "Checks if the value of the field is `ONFIRST`"] #[inline(always)] pub fn is_on_first(&self) -> bool { *self == FSOFF_A::ONFIRST } #[doc = "Checks if the value of the field is `BEFOREFIRST`"] #[inline(always)] pub fn is_before_first(&self) -> bool { *self == FSOFF_A::BEFOREFIRST } } #[doc = "Write proxy for field `FSOFF`"] pub struct FSOFF_W<'a> { w: &'a mut W, } impl<'a> FSOFF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FSOFF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "FS is asserted on the first bit of the slot 0"] #[inline(always)] pub fn on_first(self) -> &'a mut W { self.variant(FSOFF_A::ONFIRST) } #[doc = "FS is asserted one bit before the first bit of the slot 0"] #[inline(always)] pub fn before_first(self) -> &'a mut W { self.variant(FSOFF_A::BEFOREFIRST) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } impl R { #[doc = "Bits 0:7 - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block will behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC97 or SPDIF audio block configuration."] #[inline(always)] pub fn frl(&self) -> FRL_R { FRL_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:14 - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] pub fn fsall(&self) -> FSALL_R { FSALL_R::new(((self.bits >> 8) & 0x7f) as u8) } #[doc = "Bit 16 - Frame synchronization definition. This bit is set and cleared by software. When the bit is set, the number of slots defined in the SAI_xSLOTR register has to be even. It means that half of this number of slots will be dedicated to the left channel and the other slots for the right channel (e.g: this bit has to be set for I2S or MSB/LSB-justified protocols...). This bit is meaningless and is not used in AC97 or SPDIF audio block configuration. It must be configured when the audio block is disabled."] #[inline(always)] pub fn fsdef(&self) -> FSDEF_R { FSDEF_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fspol(&self) -> FSPOL_R { FSPOL_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fsoff(&self) -> FSOFF_R { FSOFF_R::new(((self.bits >> 18) & 0x01) != 0) } } impl W { #[doc = "Bits 0:7 - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block will behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC97 or SPDIF audio block configuration."] #[inline(always)] pub fn frl(&mut self) -> FRL_W { FRL_W { w: self } } #[doc = "Bits 8:14 - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] pub fn fsall(&mut self) -> FSALL_W { FSALL_W { w: self } } #[doc = "Bit 16 - Frame synchronization definition. This bit is set and cleared by software. When the bit is set, the number of slots defined in the SAI_xSLOTR register has to be even. It means that half of this number of slots will be dedicated to the left channel and the other slots for the right channel (e.g: this bit has to be set for I2S or MSB/LSB-justified protocols...). This bit is meaningless and is not used in AC97 or SPDIF audio block configuration. It must be configured when the audio block is disabled."] #[inline(always)] pub fn fsdef(&mut self) -> FSDEF_W { FSDEF_W { w: self } } #[doc = "Bit 17 - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fspol(&mut self) -> FSPOL_W { FSPOL_W { w: self } } #[doc = "Bit 18 - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fsoff(&mut self) -> FSOFF_W { FSOFF_W { w: self } } }
// TODO: remove this and windows-sys rather than generated bindings fn main() -> std::io::Result<()> { let tokens = macros::generate! { Windows::Foundation::{IReference, IStringable, PropertyValue}, Windows::Win32::Foundation::{CloseHandle, GetLastError, E_NOINTERFACE, CLASS_E_CLASSNOTAVAILABLE, E_OUTOFMEMORY, S_OK, CO_E_NOTINITIALIZED}, Windows::Win32::System::Com::{CoCreateGuid, CoTaskMemAlloc, CoTaskMemFree, IAgileObject, GetErrorInfo, IErrorInfo, SetErrorInfo}, Windows::Win32::System::Diagnostics::Debug::FormatMessageW, Windows::Win32::System::LibraryLoader::{FreeLibrary, GetProcAddress, LoadLibraryA}, Windows::Win32::System::Memory::{GetProcessHeap, HeapAlloc, HeapFree}, Windows::Win32::System::Threading::{CreateEventA, SetEvent, WaitForSingleObject}, Windows::Win32::System::WinRT::{ ILanguageExceptionErrorInfo2, IRestrictedErrorInfo, IWeakReference, IWeakReferenceSource, }, }; let mut path: std::path::PathBuf = reader::workspace_dir().into(); path.push("src/core/bindings.rs"); std::fs::write(&path, tokens)?; let mut cmd = ::std::process::Command::new("rustfmt"); cmd.arg(&path); cmd.output()?; Ok(()) }
#[cfg(test)] mod tests { #[test] fn work() { let _x = 5; let (_x, _y, _z) = (1, 2, 3); } }
pub mod qdnslookup; pub use self::qdnslookup::QDnsTextRecord; pub mod qnetworkinterface; pub use self::qnetworkinterface::QNetworkAddressEntry; pub mod qnetworkcookie; pub use self::qnetworkcookie::QNetworkCookie; pub mod qnetworkproxy; pub use self::qnetworkproxy::QNetworkProxy; pub mod qsslcipher; pub use self::qsslcipher::QSslCipher; pub mod qsslconfiguration; pub use self::qsslconfiguration::QSslConfiguration; pub mod qsslsocket; pub use self::qsslsocket::QSslSocket; pub mod qnetworkcookiejar; pub use self::qnetworkcookiejar::QNetworkCookieJar; pub mod qabstractnetworkcache; pub use self::qabstractnetworkcache::QNetworkCacheMetaData; pub use self::qdnslookup::QDnsDomainNameRecord; pub mod qnetworkrequest; pub use self::qnetworkrequest::QNetworkRequest; pub mod qsslcertificateextension; pub use self::qsslcertificateextension::QSslCertificateExtension; pub mod qsslerror; pub use self::qsslerror::QSslError; pub mod qnetworkdiskcache; pub use self::qnetworkdiskcache::QNetworkDiskCache; pub use self::qdnslookup::QDnsHostAddressRecord; pub mod qsslkey; pub use self::qsslkey::QSslKey; pub use self::qnetworkproxy::QNetworkProxyFactory; pub mod qudpsocket; pub use self::qudpsocket::QUdpSocket; pub mod qhostaddress; pub use self::qhostaddress::QHostAddress; pub mod qnetworksession; pub use self::qnetworksession::QNetworkSession; pub mod qnetworkconfigmanager; pub use self::qnetworkconfigmanager::QNetworkConfigurationManager; pub mod qtcpsocket; pub use self::qtcpsocket::QTcpSocket; pub mod qtcpserver; pub use self::qtcpserver::QTcpServer; pub use self::qdnslookup::QDnsMailExchangeRecord; pub mod qsslcertificate; pub use self::qsslcertificate::QSslCertificate; pub mod qsslpresharedkeyauthenticator; pub use self::qsslpresharedkeyauthenticator::QSslPreSharedKeyAuthenticator; pub mod qnetworkreply; pub use self::qnetworkreply::QNetworkReply; pub use self::qnetworkinterface::QNetworkInterface; pub mod qhttpmultipart; pub use self::qhttpmultipart::QHttpMultiPart; pub use self::qnetworkproxy::QNetworkProxyQuery; pub use self::qhostaddress::QIPv6Address; pub mod qlocalserver; pub use self::qlocalserver::QLocalServer; pub mod qnetworkconfiguration; pub use self::qnetworkconfiguration::QNetworkConfiguration; pub mod qsslellipticcurve; pub use self::qsslellipticcurve::QSslEllipticCurve; pub mod qauthenticator; pub use self::qauthenticator::QAuthenticator; pub use self::qabstractnetworkcache::QAbstractNetworkCache; pub mod qlocalsocket; pub use self::qlocalsocket::QLocalSocket; pub mod qhostinfo; pub use self::qhostinfo::QHostInfo; pub use self::qdnslookup::QDnsServiceRecord; pub use self::qhttpmultipart::QHttpPart; pub mod qabstractsocket; pub use self::qabstractsocket::QAbstractSocket; pub use self::qdnslookup::QDnsLookup; pub mod qnetworkaccessmanager; pub use self::qnetworkaccessmanager::QNetworkAccessManager;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CheckGamingPrivilegeSilently<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(privilegeid: u32, scope: Param1, policy: Param2) -> ::windows::core::Result<super::Foundation::BOOL> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CheckGamingPrivilegeSilently(privilegeid: u32, scope: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, policy: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, hasprivilege: *mut super::Foundation::BOOL) -> ::windows::core::HRESULT; } let mut result__: <super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); CheckGamingPrivilegeSilently(::core::mem::transmute(privilegeid), scope.into_param().abi(), policy.into_param().abi(), &mut result__).from_abi::<super::Foundation::BOOL>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn CheckGamingPrivilegeSilentlyForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, privilegeid: u32, scope: Param2, policy: Param3) -> ::windows::core::Result<super::Foundation::BOOL> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CheckGamingPrivilegeSilentlyForUser(user: ::windows::core::RawPtr, privilegeid: u32, scope: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, policy: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, hasprivilege: *mut super::Foundation::BOOL) -> ::windows::core::HRESULT; } let mut result__: <super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); CheckGamingPrivilegeSilentlyForUser(user.into_param().abi(), ::core::mem::transmute(privilegeid), scope.into_param().abi(), policy.into_param().abi(), &mut result__).from_abi::<super::Foundation::BOOL>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn CheckGamingPrivilegeWithUI<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(privilegeid: u32, scope: Param1, policy: Param2, friendlymessage: Param3, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CheckGamingPrivilegeWithUI(privilegeid: u32, scope: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, policy: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, friendlymessage: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } CheckGamingPrivilegeWithUI(::core::mem::transmute(privilegeid), scope.into_param().abi(), policy.into_param().abi(), friendlymessage.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn CheckGamingPrivilegeWithUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( user: Param0, privilegeid: u32, scope: Param2, policy: Param3, friendlymessage: Param4, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CheckGamingPrivilegeWithUIForUser(user: ::windows::core::RawPtr, privilegeid: u32, scope: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, policy: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, friendlymessage: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } CheckGamingPrivilegeWithUIForUser(user.into_param().abi(), ::core::mem::transmute(privilegeid), scope.into_param().abi(), policy.into_param().abi(), friendlymessage.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GAMESTATS_OPEN_RESULT(pub i32); pub const GAMESTATS_OPEN_CREATED: GAMESTATS_OPEN_RESULT = GAMESTATS_OPEN_RESULT(0i32); pub const GAMESTATS_OPEN_OPENED: GAMESTATS_OPEN_RESULT = GAMESTATS_OPEN_RESULT(1i32); impl ::core::convert::From<i32> for GAMESTATS_OPEN_RESULT { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GAMESTATS_OPEN_RESULT { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GAMESTATS_OPEN_TYPE(pub i32); pub const GAMESTATS_OPEN_OPENORCREATE: GAMESTATS_OPEN_TYPE = GAMESTATS_OPEN_TYPE(0i32); pub const GAMESTATS_OPEN_OPENONLY: GAMESTATS_OPEN_TYPE = GAMESTATS_OPEN_TYPE(1i32); impl ::core::convert::From<i32> for GAMESTATS_OPEN_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GAMESTATS_OPEN_TYPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GAME_INSTALL_SCOPE(pub i32); pub const GIS_NOT_INSTALLED: GAME_INSTALL_SCOPE = GAME_INSTALL_SCOPE(1i32); pub const GIS_CURRENT_USER: GAME_INSTALL_SCOPE = GAME_INSTALL_SCOPE(2i32); pub const GIS_ALL_USERS: GAME_INSTALL_SCOPE = GAME_INSTALL_SCOPE(3i32); impl ::core::convert::From<i32> for GAME_INSTALL_SCOPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GAME_INSTALL_SCOPE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GAMING_DEVICE_DEVICE_ID(pub i32); pub const GAMING_DEVICE_DEVICE_ID_NONE: GAMING_DEVICE_DEVICE_ID = GAMING_DEVICE_DEVICE_ID(0i32); pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE: GAMING_DEVICE_DEVICE_ID = GAMING_DEVICE_DEVICE_ID(1988865574i32); pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_S: GAMING_DEVICE_DEVICE_ID = GAMING_DEVICE_DEVICE_ID(712204761i32); pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_X: GAMING_DEVICE_DEVICE_ID = GAMING_DEVICE_DEVICE_ID(1523980231i32); pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_X_DEVKIT: GAMING_DEVICE_DEVICE_ID = GAMING_DEVICE_DEVICE_ID(284675555i32); impl ::core::convert::From<i32> for GAMING_DEVICE_DEVICE_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GAMING_DEVICE_DEVICE_ID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct GAMING_DEVICE_MODEL_INFORMATION { pub vendorId: GAMING_DEVICE_VENDOR_ID, pub deviceId: GAMING_DEVICE_DEVICE_ID, } impl GAMING_DEVICE_MODEL_INFORMATION {} impl ::core::default::Default for GAMING_DEVICE_MODEL_INFORMATION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for GAMING_DEVICE_MODEL_INFORMATION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("GAMING_DEVICE_MODEL_INFORMATION").field("vendorId", &self.vendorId).field("deviceId", &self.deviceId).finish() } } impl ::core::cmp::PartialEq for GAMING_DEVICE_MODEL_INFORMATION { fn eq(&self, other: &Self) -> bool { self.vendorId == other.vendorId && self.deviceId == other.deviceId } } impl ::core::cmp::Eq for GAMING_DEVICE_MODEL_INFORMATION {} unsafe impl ::windows::core::Abi for GAMING_DEVICE_MODEL_INFORMATION { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GAMING_DEVICE_VENDOR_ID(pub i32); pub const GAMING_DEVICE_VENDOR_ID_NONE: GAMING_DEVICE_VENDOR_ID = GAMING_DEVICE_VENDOR_ID(0i32); pub const GAMING_DEVICE_VENDOR_ID_MICROSOFT: GAMING_DEVICE_VENDOR_ID = GAMING_DEVICE_VENDOR_ID(-1024700366i32); impl ::core::convert::From<i32> for GAMING_DEVICE_VENDOR_ID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GAMING_DEVICE_VENDOR_ID { type Abi = Self; } pub const GameExplorer: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a5ea990_3034_4d6f_9128_01f3c61022bc); pub const GameStatistics: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdbc85a2c_c0dc_4961_b6e2_d28b62c11ad4); pub type GameUICompletionRoutine = unsafe extern "system" fn(returncode: ::windows::core::HRESULT, context: *const ::core::ffi::c_void); #[inline] pub unsafe fn GetExpandedResourceExclusiveCpuCount() -> ::windows::core::Result<u32> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetExpandedResourceExclusiveCpuCount(exclusivecpucount: *mut u32) -> ::windows::core::HRESULT; } let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); GetExpandedResourceExclusiveCpuCount(&mut result__).from_abi::<u32>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn GetGamingDeviceModelInformation() -> ::windows::core::Result<GAMING_DEVICE_MODEL_INFORMATION> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn GetGamingDeviceModelInformation(information: *mut GAMING_DEVICE_MODEL_INFORMATION) -> ::windows::core::HRESULT; } let mut result__: <GAMING_DEVICE_MODEL_INFORMATION as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); GetGamingDeviceModelInformation(&mut result__).from_abi::<GAMING_DEVICE_MODEL_INFORMATION>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn HasExpandedResources() -> ::windows::core::Result<super::Foundation::BOOL> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn HasExpandedResources(hasexpandedresources: *mut super::Foundation::BOOL) -> ::windows::core::HRESULT; } let mut result__: <super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); HasExpandedResources(&mut result__).from_abi::<super::Foundation::BOOL>(result__) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IGameExplorer(pub ::windows::core::IUnknown); impl IGameExplorer { #[cfg(feature = "Win32_Foundation")] pub unsafe fn AddGame<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::Foundation::BSTR>>(&self, bstrgdfbinarypath: Param0, bstrgameinstalldirectory: Param1, installscope: GAME_INSTALL_SCOPE, pguidinstanceid: *mut ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), bstrgdfbinarypath.into_param().abi(), bstrgameinstalldirectory.into_param().abi(), ::core::mem::transmute(installscope), ::core::mem::transmute(pguidinstanceid)).ok() } pub unsafe fn RemoveGame<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, guidinstanceid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), guidinstanceid.into_param().abi()).ok() } pub unsafe fn UpdateGame<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, guidinstanceid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), guidinstanceid.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn VerifyAccess<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::BSTR>>(&self, bstrgdfbinarypath: Param0) -> ::windows::core::Result<super::Foundation::BOOL> { let mut result__: <super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), bstrgdfbinarypath.into_param().abi(), &mut result__).from_abi::<super::Foundation::BOOL>(result__) } } unsafe impl ::windows::core::Interface for IGameExplorer { type Vtable = IGameExplorer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7b2fb72_d728_49b3_a5f2_18ebf5f1349e); } impl ::core::convert::From<IGameExplorer> for ::windows::core::IUnknown { fn from(value: IGameExplorer) -> Self { value.0 } } impl ::core::convert::From<&IGameExplorer> for ::windows::core::IUnknown { fn from(value: &IGameExplorer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGameExplorer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGameExplorer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IGameExplorer_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrgdfbinarypath: ::core::mem::ManuallyDrop<super::Foundation::BSTR>, bstrgameinstalldirectory: ::core::mem::ManuallyDrop<super::Foundation::BSTR>, installscope: GAME_INSTALL_SCOPE, pguidinstanceid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, guidinstanceid: ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, guidinstanceid: ::windows::core::GUID) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrgdfbinarypath: ::core::mem::ManuallyDrop<super::Foundation::BSTR>, pfhasaccess: *mut super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IGameExplorer2(pub ::windows::core::IUnknown); impl IGameExplorer2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn InstallGame<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, binarygdfpath: Param0, installdirectory: Param1, installscope: GAME_INSTALL_SCOPE) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), binarygdfpath.into_param().abi(), installdirectory.into_param().abi(), ::core::mem::transmute(installscope)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn UninstallGame<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, binarygdfpath: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), binarygdfpath.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CheckAccess<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, binarygdfpath: Param0) -> ::windows::core::Result<super::Foundation::BOOL> { let mut result__: <super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), binarygdfpath.into_param().abi(), &mut result__).from_abi::<super::Foundation::BOOL>(result__) } } unsafe impl ::windows::core::Interface for IGameExplorer2 { type Vtable = IGameExplorer2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x86874aa7_a1ed_450d_a7eb_b89e20b2fff3); } impl ::core::convert::From<IGameExplorer2> for ::windows::core::IUnknown { fn from(value: IGameExplorer2) -> Self { value.0 } } impl ::core::convert::From<&IGameExplorer2> for ::windows::core::IUnknown { fn from(value: &IGameExplorer2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGameExplorer2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGameExplorer2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IGameExplorer2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, binarygdfpath: super::Foundation::PWSTR, installdirectory: super::Foundation::PWSTR, installscope: GAME_INSTALL_SCOPE) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, binarygdfpath: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, binarygdfpath: super::Foundation::PWSTR, phasaccess: *mut super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IGameStatistics(pub ::windows::core::IUnknown); impl IGameStatistics { pub unsafe fn GetMaxCategoryLength(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetMaxNameLength(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetMaxValueLength(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetMaxCategories(&self) -> ::windows::core::Result<u16> { let mut result__: <u16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u16>(result__) } pub unsafe fn GetMaxStatsPerCategory(&self) -> ::windows::core::Result<u16> { let mut result__: <u16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u16>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetCategoryTitle<'a, Param1: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, categoryindex: u16, title: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(categoryindex), title.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetCategoryTitle(&self, categoryindex: u16) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(categoryindex), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetStatistic(&self, categoryindex: u16, statindex: u16, pname: *mut super::Foundation::PWSTR, pvalue: *mut super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(categoryindex), ::core::mem::transmute(statindex), ::core::mem::transmute(pname), ::core::mem::transmute(pvalue)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetStatistic<'a, Param2: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, categoryindex: u16, statindex: u16, name: Param2, value: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(categoryindex), ::core::mem::transmute(statindex), name.into_param().abi(), value.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Save<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::BOOL>>(&self, trackchanges: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), trackchanges.into_param().abi()).ok() } pub unsafe fn SetLastPlayedCategory(&self, categoryindex: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(categoryindex)).ok() } pub unsafe fn GetLastPlayedCategory(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for IGameStatistics { type Vtable = IGameStatistics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3887c9ca_04a0_42ae_bc4c_5fa6c7721145); } impl ::core::convert::From<IGameStatistics> for ::windows::core::IUnknown { fn from(value: IGameStatistics) -> Self { value.0 } } impl ::core::convert::From<&IGameStatistics> for ::windows::core::IUnknown { fn from(value: &IGameStatistics) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGameStatistics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGameStatistics { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IGameStatistics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cch: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cch: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cch: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pmax: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pmax: *mut u16) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, categoryindex: u16, title: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, categoryindex: u16, ptitle: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, categoryindex: u16, statindex: u16, pname: *mut super::Foundation::PWSTR, pvalue: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, categoryindex: u16, statindex: u16, name: super::Foundation::PWSTR, value: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, trackchanges: super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, categoryindex: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcategoryindex: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IGameStatisticsMgr(pub ::windows::core::IUnknown); impl IGameStatisticsMgr { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetGameStatistics<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, gdfbinarypath: Param0, opentype: GAMESTATS_OPEN_TYPE, popenresult: *mut GAMESTATS_OPEN_RESULT, ppistats: *mut ::core::option::Option<IGameStatistics>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), gdfbinarypath.into_param().abi(), ::core::mem::transmute(opentype), ::core::mem::transmute(popenresult), ::core::mem::transmute(ppistats)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn RemoveGameStatistics<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, gdfbinarypath: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), gdfbinarypath.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IGameStatisticsMgr { type Vtable = IGameStatisticsMgr_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaff3ea11_e70e_407d_95dd_35e612c41ce2); } impl ::core::convert::From<IGameStatisticsMgr> for ::windows::core::IUnknown { fn from(value: IGameStatisticsMgr) -> Self { value.0 } } impl ::core::convert::From<&IGameStatisticsMgr> for ::windows::core::IUnknown { fn from(value: &IGameStatisticsMgr) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IGameStatisticsMgr { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IGameStatisticsMgr { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IGameStatisticsMgr_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, gdfbinarypath: super::Foundation::PWSTR, opentype: GAMESTATS_OPEN_TYPE, popenresult: *mut GAMESTATS_OPEN_RESULT, ppistats: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, gdfbinarypath: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IXblIdpAuthManager(pub ::windows::core::IUnknown); impl IXblIdpAuthManager { #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetGamerAccount<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, msaaccountid: Param0, xuid: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), msaaccountid.into_param().abi(), xuid.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetGamerAccount(&self, msaaccountid: *mut super::Foundation::PWSTR, xuid: *mut super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(msaaccountid), ::core::mem::transmute(xuid)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetAppViewInitialized<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>>(&self, appsid: Param0, msaaccountid: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), appsid.into_param().abi(), msaaccountid.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetEnvironment(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetSandbox(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetTokenAndSignatureWithTokenResult< 'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param4: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param5: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param6: ::windows::core::IntoParam<'a, super::Foundation::PWSTR>, Param9: ::windows::core::IntoParam<'a, super::Foundation::BOOL>, >( &self, msaaccountid: Param0, appsid: Param1, msatarget: Param2, msapolicy: Param3, httpmethod: Param4, uri: Param5, headers: Param6, body: *const u8, bodysize: u32, forcerefresh: Param9, ) -> ::windows::core::Result<IXblIdpAuthTokenResult> { let mut result__: <IXblIdpAuthTokenResult as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)( ::core::mem::transmute_copy(self), msaaccountid.into_param().abi(), appsid.into_param().abi(), msatarget.into_param().abi(), msapolicy.into_param().abi(), httpmethod.into_param().abi(), uri.into_param().abi(), headers.into_param().abi(), ::core::mem::transmute(body), ::core::mem::transmute(bodysize), forcerefresh.into_param().abi(), &mut result__, ) .from_abi::<IXblIdpAuthTokenResult>(result__) } } unsafe impl ::windows::core::Interface for IXblIdpAuthManager { type Vtable = IXblIdpAuthManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xeb5ddb08_8bbf_449b_ac21_b02ddeb3b136); } impl ::core::convert::From<IXblIdpAuthManager> for ::windows::core::IUnknown { fn from(value: IXblIdpAuthManager) -> Self { value.0 } } impl ::core::convert::From<&IXblIdpAuthManager> for ::windows::core::IUnknown { fn from(value: &IXblIdpAuthManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IXblIdpAuthManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IXblIdpAuthManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IXblIdpAuthManager_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msaaccountid: super::Foundation::PWSTR, xuid: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msaaccountid: *mut super::Foundation::PWSTR, xuid: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, appsid: super::Foundation::PWSTR, msaaccountid: super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, environment: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sandbox: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msaaccountid: super::Foundation::PWSTR, appsid: super::Foundation::PWSTR, msatarget: super::Foundation::PWSTR, msapolicy: super::Foundation::PWSTR, httpmethod: super::Foundation::PWSTR, uri: super::Foundation::PWSTR, headers: super::Foundation::PWSTR, body: *const u8, bodysize: u32, forcerefresh: super::Foundation::BOOL, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IXblIdpAuthTokenResult(pub ::windows::core::IUnknown); impl IXblIdpAuthTokenResult { pub unsafe fn GetStatus(&self) -> ::windows::core::Result<XBL_IDP_AUTH_TOKEN_STATUS> { let mut result__: <XBL_IDP_AUTH_TOKEN_STATUS as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<XBL_IDP_AUTH_TOKEN_STATUS>(result__) } pub unsafe fn GetErrorCode(&self) -> ::windows::core::Result<::windows::core::HRESULT> { let mut result__: <::windows::core::HRESULT as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::HRESULT>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetToken(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetSignature(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetSandbox(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetEnvironment(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMsaAccountId(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetXuid(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetGamertag(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetAgeGroup(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetPrivileges(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMsaTarget(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMsaPolicy(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMsaAppId(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRedirect(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMessage(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetHelpId(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetEnforcementBans(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetRestrictions(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetTitleRestrictions(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } } unsafe impl ::windows::core::Interface for IXblIdpAuthTokenResult { type Vtable = IXblIdpAuthTokenResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x46ce0225_f267_4d68_b299_b2762552dec1); } impl ::core::convert::From<IXblIdpAuthTokenResult> for ::windows::core::IUnknown { fn from(value: IXblIdpAuthTokenResult) -> Self { value.0 } } impl ::core::convert::From<&IXblIdpAuthTokenResult> for ::windows::core::IUnknown { fn from(value: &IXblIdpAuthTokenResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IXblIdpAuthTokenResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IXblIdpAuthTokenResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IXblIdpAuthTokenResult_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: *mut XBL_IDP_AUTH_TOKEN_STATUS) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, errorcode: *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, signature: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sandbox: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, environment: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msaaccountid: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xuid: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, gamertag: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, agegroup: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, privileges: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msatarget: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msapolicy: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, msaappid: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, redirect: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, message: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, helpid: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, enforcementbans: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, restrictions: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, titlerestrictions: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IXblIdpAuthTokenResult2(pub ::windows::core::IUnknown); impl IXblIdpAuthTokenResult2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetModernGamertag(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetModernGamertagSuffix(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetUniqueModernGamertag(&self) -> ::windows::core::Result<super::Foundation::PWSTR> { let mut result__: <super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::Foundation::PWSTR>(result__) } } unsafe impl ::windows::core::Interface for IXblIdpAuthTokenResult2 { type Vtable = IXblIdpAuthTokenResult2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75d760b0_60b9_412d_994f_26b2cd5f7812); } impl ::core::convert::From<IXblIdpAuthTokenResult2> for ::windows::core::IUnknown { fn from(value: IXblIdpAuthTokenResult2) -> Self { value.0 } } impl ::core::convert::From<&IXblIdpAuthTokenResult2> for ::windows::core::IUnknown { fn from(value: &IXblIdpAuthTokenResult2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IXblIdpAuthTokenResult2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IXblIdpAuthTokenResult2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IXblIdpAuthTokenResult2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct KnownGamingPrivileges(pub i32); pub const XPRIVILEGE_BROADCAST: KnownGamingPrivileges = KnownGamingPrivileges(190i32); pub const XPRIVILEGE_VIEW_FRIENDS_LIST: KnownGamingPrivileges = KnownGamingPrivileges(197i32); pub const XPRIVILEGE_GAME_DVR: KnownGamingPrivileges = KnownGamingPrivileges(198i32); pub const XPRIVILEGE_SHARE_KINECT_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(199i32); pub const XPRIVILEGE_MULTIPLAYER_PARTIES: KnownGamingPrivileges = KnownGamingPrivileges(203i32); pub const XPRIVILEGE_COMMUNICATION_VOICE_INGAME: KnownGamingPrivileges = KnownGamingPrivileges(205i32); pub const XPRIVILEGE_COMMUNICATION_VOICE_SKYPE: KnownGamingPrivileges = KnownGamingPrivileges(206i32); pub const XPRIVILEGE_CLOUD_GAMING_MANAGE_SESSION: KnownGamingPrivileges = KnownGamingPrivileges(207i32); pub const XPRIVILEGE_CLOUD_GAMING_JOIN_SESSION: KnownGamingPrivileges = KnownGamingPrivileges(208i32); pub const XPRIVILEGE_CLOUD_SAVED_GAMES: KnownGamingPrivileges = KnownGamingPrivileges(209i32); pub const XPRIVILEGE_SHARE_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(211i32); pub const XPRIVILEGE_PREMIUM_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(214i32); pub const XPRIVILEGE_SUBSCRIPTION_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(219i32); pub const XPRIVILEGE_SOCIAL_NETWORK_SHARING: KnownGamingPrivileges = KnownGamingPrivileges(220i32); pub const XPRIVILEGE_PREMIUM_VIDEO: KnownGamingPrivileges = KnownGamingPrivileges(224i32); pub const XPRIVILEGE_VIDEO_COMMUNICATIONS: KnownGamingPrivileges = KnownGamingPrivileges(235i32); pub const XPRIVILEGE_PURCHASE_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(245i32); pub const XPRIVILEGE_USER_CREATED_CONTENT: KnownGamingPrivileges = KnownGamingPrivileges(247i32); pub const XPRIVILEGE_PROFILE_VIEWING: KnownGamingPrivileges = KnownGamingPrivileges(249i32); pub const XPRIVILEGE_COMMUNICATIONS: KnownGamingPrivileges = KnownGamingPrivileges(252i32); pub const XPRIVILEGE_MULTIPLAYER_SESSIONS: KnownGamingPrivileges = KnownGamingPrivileges(254i32); pub const XPRIVILEGE_ADD_FRIEND: KnownGamingPrivileges = KnownGamingPrivileges(255i32); impl ::core::convert::From<i32> for KnownGamingPrivileges { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for KnownGamingPrivileges { type Abi = Self; } pub type PlayerPickerUICompletionRoutine = unsafe extern "system" fn(returncode: ::windows::core::HRESULT, context: *const ::core::ffi::c_void, selectedxuids: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, selectedxuidscount: usize); #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ProcessPendingGameUI<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::BOOL>>(waitforcompletion: Param0) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ProcessPendingGameUI(waitforcompletion: super::Foundation::BOOL) -> ::windows::core::HRESULT; } ProcessPendingGameUI(waitforcompletion.into_param().abi()).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ReleaseExclusiveCpuSets() -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ReleaseExclusiveCpuSets() -> ::windows::core::HRESULT; } ReleaseExclusiveCpuSets().ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowChangeFriendRelationshipUI<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(targetuserxuid: Param0, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowChangeFriendRelationshipUI(targetuserxuid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowChangeFriendRelationshipUI(targetuserxuid.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowChangeFriendRelationshipUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, targetuserxuid: Param1, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowChangeFriendRelationshipUIForUser(user: ::windows::core::RawPtr, targetuserxuid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowChangeFriendRelationshipUIForUser(user.into_param().abi(), targetuserxuid.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowCustomizeUserProfileUI(completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowCustomizeUserProfileUI(completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowCustomizeUserProfileUI(::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowCustomizeUserProfileUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(user: Param0, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowCustomizeUserProfileUIForUser(user: ::windows::core::RawPtr, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowCustomizeUserProfileUIForUser(user.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowFindFriendsUI(completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowFindFriendsUI(completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowFindFriendsUI(::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowFindFriendsUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(user: Param0, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowFindFriendsUIForUser(user: ::windows::core::RawPtr, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowFindFriendsUIForUser(user.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInfoUI(titleid: u32, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInfoUI(titleid: u32, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowGameInfoUI(::core::mem::transmute(titleid), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInfoUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(user: Param0, titleid: u32, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInfoUIForUser(user: ::windows::core::RawPtr, titleid: u32, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowGameInfoUIForUser(user.into_param().abi(), ::core::mem::transmute(titleid), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInviteUI<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( serviceconfigurationid: Param0, sessiontemplatename: Param1, sessionid: Param2, invitationdisplaytext: Param3, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInviteUI(serviceconfigurationid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessiontemplatename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, invitationdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowGameInviteUI(serviceconfigurationid.into_param().abi(), sessiontemplatename.into_param().abi(), sessionid.into_param().abi(), invitationdisplaytext.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInviteUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( user: Param0, serviceconfigurationid: Param1, sessiontemplatename: Param2, sessionid: Param3, invitationdisplaytext: Param4, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInviteUIForUser(user: ::windows::core::RawPtr, serviceconfigurationid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessiontemplatename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, invitationdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowGameInviteUIForUser(user.into_param().abi(), serviceconfigurationid.into_param().abi(), sessiontemplatename.into_param().abi(), sessionid.into_param().abi(), invitationdisplaytext.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInviteUIWithContext<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( serviceconfigurationid: Param0, sessiontemplatename: Param1, sessionid: Param2, invitationdisplaytext: Param3, customactivationcontext: Param4, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInviteUIWithContext( serviceconfigurationid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessiontemplatename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, invitationdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, customactivationcontext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void, ) -> ::windows::core::HRESULT; } ShowGameInviteUIWithContext(serviceconfigurationid.into_param().abi(), sessiontemplatename.into_param().abi(), sessionid.into_param().abi(), invitationdisplaytext.into_param().abi(), customactivationcontext.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowGameInviteUIWithContextForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param5: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( user: Param0, serviceconfigurationid: Param1, sessiontemplatename: Param2, sessionid: Param3, invitationdisplaytext: Param4, customactivationcontext: Param5, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowGameInviteUIWithContextForUser( user: ::windows::core::RawPtr, serviceconfigurationid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessiontemplatename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, sessionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, invitationdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, customactivationcontext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void, ) -> ::windows::core::HRESULT; } ShowGameInviteUIWithContextForUser(user.into_param().abi(), serviceconfigurationid.into_param().abi(), sessiontemplatename.into_param().abi(), sessionid.into_param().abi(), invitationdisplaytext.into_param().abi(), customactivationcontext.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowPlayerPickerUI<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(promptdisplaytext: Param0, xuids: *const ::windows::core::HSTRING, xuidscount: usize, preselectedxuids: *const ::windows::core::HSTRING, preselectedxuidscount: usize, minselectioncount: usize, maxselectioncount: usize, completionroutine: ::core::option::Option<PlayerPickerUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowPlayerPickerUI(promptdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, xuids: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, xuidscount: usize, preselectedxuids: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, preselectedxuidscount: usize, minselectioncount: usize, maxselectioncount: usize, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowPlayerPickerUI( promptdisplaytext.into_param().abi(), ::core::mem::transmute(xuids), ::core::mem::transmute(xuidscount), ::core::mem::transmute(preselectedxuids), ::core::mem::transmute(preselectedxuidscount), ::core::mem::transmute(minselectioncount), ::core::mem::transmute(maxselectioncount), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context), ) .ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowPlayerPickerUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( user: Param0, promptdisplaytext: Param1, xuids: *const ::windows::core::HSTRING, xuidscount: usize, preselectedxuids: *const ::windows::core::HSTRING, preselectedxuidscount: usize, minselectioncount: usize, maxselectioncount: usize, completionroutine: ::core::option::Option<PlayerPickerUICompletionRoutine>, context: *const ::core::ffi::c_void, ) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowPlayerPickerUIForUser(user: ::windows::core::RawPtr, promptdisplaytext: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, xuids: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, xuidscount: usize, preselectedxuids: *const ::core::mem::ManuallyDrop<::windows::core::HSTRING>, preselectedxuidscount: usize, minselectioncount: usize, maxselectioncount: usize, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowPlayerPickerUIForUser( user.into_param().abi(), promptdisplaytext.into_param().abi(), ::core::mem::transmute(xuids), ::core::mem::transmute(xuidscount), ::core::mem::transmute(preselectedxuids), ::core::mem::transmute(preselectedxuidscount), ::core::mem::transmute(minselectioncount), ::core::mem::transmute(maxselectioncount), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context), ) .ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowProfileCardUI<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(targetuserxuid: Param0, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowProfileCardUI(targetuserxuid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowProfileCardUI(targetuserxuid.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowProfileCardUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(user: Param0, targetuserxuid: Param1, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowProfileCardUIForUser(user: ::windows::core::RawPtr, targetuserxuid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowProfileCardUIForUser(user.into_param().abi(), targetuserxuid.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowTitleAchievementsUI(titleid: u32, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowTitleAchievementsUI(titleid: u32, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowTitleAchievementsUI(::core::mem::transmute(titleid), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowTitleAchievementsUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(user: Param0, titleid: u32, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowTitleAchievementsUIForUser(user: ::windows::core::RawPtr, titleid: u32, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowTitleAchievementsUIForUser(user.into_param().abi(), ::core::mem::transmute(titleid), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowUserSettingsUI(completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowUserSettingsUI(completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowUserSettingsUI(::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ShowUserSettingsUIForUser<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(user: Param0, completionroutine: ::core::option::Option<GameUICompletionRoutine>, context: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ShowUserSettingsUIForUser(user: ::windows::core::RawPtr, completionroutine: ::windows::core::RawPtr, context: *const ::core::ffi::c_void) -> ::windows::core::HRESULT; } ShowUserSettingsUIForUser(user.into_param().abi(), ::core::mem::transmute(completionroutine), ::core::mem::transmute(context)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn TryCancelPendingGameUI() -> super::Foundation::BOOL { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn TryCancelPendingGameUI() -> super::Foundation::BOOL; } ::core::mem::transmute(TryCancelPendingGameUI()) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XBL_IDP_AUTH_TOKEN_STATUS(pub i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_SUCCESS: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(0i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_OFFLINE_SUCCESS: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(1i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_NO_ACCOUNT_SET: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(2i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_LOAD_MSA_ACCOUNT_FAILED: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(3i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_XBOX_VETO: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(4i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_MSA_INTERRUPT: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(5i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_OFFLINE_NO_CONSENT: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(6i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_VIEW_NOT_SET: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(7i32); pub const XBL_IDP_AUTH_TOKEN_STATUS_UNKNOWN: XBL_IDP_AUTH_TOKEN_STATUS = XBL_IDP_AUTH_TOKEN_STATUS(-1i32); impl ::core::convert::From<i32> for XBL_IDP_AUTH_TOKEN_STATUS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XBL_IDP_AUTH_TOKEN_STATUS { type Abi = Self; } pub const XblIdpAuthManager: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xce23534b_56d8_4978_86a2_7ee570640468); pub const XblIdpAuthTokenResult: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f493441_744a_410c_ae2b_9a22f7c7731f);
use std::{ path::{Path, PathBuf}, process::Command, str, }; pub fn clone_repo<P: AsRef<Path>>(url: &str, path: P) { let path = path.as_ref(); println!("git cloning path {}", path.display()); let status = Command::new("git") .arg("clone") .arg(url) .arg(&path) .status() .expect("Failed to get status"); println!("Exit status {}", status); }
/* * Author: Dave Eddy <dave@daveeddy.com> * Date: February 15, 2022 * License: MIT */ //! Subcommands for `vsv`. pub mod enable_disable; pub mod external; pub mod status;
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { s: Chars, k: usize, } let mut candidate = vec![String::from("~"); k]; let n = s.len(); 'outer: for i in 0..n { 'inner: for j in i + 1..=n { let t = s[i..j].iter().collect::<String>(); if t > candidate[k - 1] { continue 'outer; } // eprintln!("{}", t); for k in 0..k { if candidate[k] == t { continue 'inner; } } for a in 0..k { if t < candidate[a] { for b in (a + 1..k).rev() { candidate.swap(b - 1, b); } candidate[a] = t; break; } } } } // eprintln!("{:?}", candidate); println!("{}", candidate[k - 1]); }
#![feature(exclusive_range_pattern)] #[macro_use] extern crate lazy_static; extern crate boardgameai_rs; extern crate rand; use boardgameai_rs::*; use boardgameai_rs::state::State; use boardgameai_rs::action::Action; // use std::collections::{HashMap, HashSet}; use std::fmt::Display; // use std::rand::{Rng, thread_rng}; pub mod player; pub mod playermat; pub mod farmtile; pub mod fieldtile; pub mod pasture; pub mod agricolaaction; pub mod agricolastate; pub mod board; pub mod misc; pub mod majorimprovement; pub use player::*; pub use playermat::*; pub use farmtile::*; pub use fieldtile::*; pub use pasture::*; pub use agricolaaction::*; pub use agricolastate::*; pub use board::*; pub use misc::*; pub use pasture::*; pub use majorimprovement::*;
use super::BOOL; use std::{ ffi::CStr, fmt, os::raw::{c_char, c_void}, ptr::NonNull, }; #[macro_use] mod macros; /// A method selector. /// /// Selectors can be safely created using the /// [`selector!`](../macro.selector.html) macro. /// /// See [documentation](https://developer.apple.com/documentation/objectivec/sel). #[repr(transparent)] #[derive(Copy, Clone)] pub struct SEL(NonNull<c_void>); unsafe impl Send for SEL {} unsafe impl Sync for SEL {} impl PartialEq for SEL { #[inline] fn eq(&self, other: &Self) -> bool { extern "C" { fn sel_isEqual(lhs: SEL, rhs: SEL) -> BOOL; } unsafe { sel_isEqual(*self, *other) != 0 } } } impl Eq for SEL {} impl fmt::Debug for SEL { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.name().fmt(f) } } impl SEL { /// Registers a method name with the Objective-C runtime and returns the /// selector. /// /// # Safety /// /// The name must be a non-null UTF-8 C string. #[inline] pub unsafe fn register(name: *const c_char) -> Self { sel_registerName(name) } /// Returns the name of the method this selector refers to. #[inline] pub fn name(self) -> &'static CStr { unsafe { CStr::from_ptr(sel_getName(self)) } } } extern "C" { fn sel_registerName(name: *const c_char) -> SEL; fn sel_getName(sel: SEL) -> *const c_char; }
use super::vertex::Vertex; // print',\n'.join(["[Vertex(%d - 1), Vertex(%d + 1), Vertex(%d - 21), Vertex(%d + 21)]" % (i, i, i, i) for i in range(21 * 21)]) pub static NEIGHBOURS: [[Vertex; 4]; 21 * 21] = [ [Vertex(0 - 1), Vertex(0 + 1), Vertex(0 - 21), Vertex(0 + 21)], [Vertex(1 - 1), Vertex(1 + 1), Vertex(1 - 21), Vertex(1 + 21)], [Vertex(2 - 1), Vertex(2 + 1), Vertex(2 - 21), Vertex(2 + 21)], [Vertex(3 - 1), Vertex(3 + 1), Vertex(3 - 21), Vertex(3 + 21)], [Vertex(4 - 1), Vertex(4 + 1), Vertex(4 - 21), Vertex(4 + 21)], [Vertex(5 - 1), Vertex(5 + 1), Vertex(5 - 21), Vertex(5 + 21)], [Vertex(6 - 1), Vertex(6 + 1), Vertex(6 - 21), Vertex(6 + 21)], [Vertex(7 - 1), Vertex(7 + 1), Vertex(7 - 21), Vertex(7 + 21)], [Vertex(8 - 1), Vertex(8 + 1), Vertex(8 - 21), Vertex(8 + 21)], [Vertex(9 - 1), Vertex(9 + 1), Vertex(9 - 21), Vertex(9 + 21)], [Vertex(10 - 1), Vertex(10 + 1), Vertex(10 - 21), Vertex(10 + 21)], [Vertex(11 - 1), Vertex(11 + 1), Vertex(11 - 21), Vertex(11 + 21)], [Vertex(12 - 1), Vertex(12 + 1), Vertex(12 - 21), Vertex(12 + 21)], [Vertex(13 - 1), Vertex(13 + 1), Vertex(13 - 21), Vertex(13 + 21)], [Vertex(14 - 1), Vertex(14 + 1), Vertex(14 - 21), Vertex(14 + 21)], [Vertex(15 - 1), Vertex(15 + 1), Vertex(15 - 21), Vertex(15 + 21)], [Vertex(16 - 1), Vertex(16 + 1), Vertex(16 - 21), Vertex(16 + 21)], [Vertex(17 - 1), Vertex(17 + 1), Vertex(17 - 21), Vertex(17 + 21)], [Vertex(18 - 1), Vertex(18 + 1), Vertex(18 - 21), Vertex(18 + 21)], [Vertex(19 - 1), Vertex(19 + 1), Vertex(19 - 21), Vertex(19 + 21)], [Vertex(20 - 1), Vertex(20 + 1), Vertex(20 - 21), Vertex(20 + 21)], [Vertex(21 - 1), Vertex(21 + 1), Vertex(21 - 21), Vertex(21 + 21)], [Vertex(22 - 1), Vertex(22 + 1), Vertex(22 - 21), Vertex(22 + 21)], [Vertex(23 - 1), Vertex(23 + 1), Vertex(23 - 21), Vertex(23 + 21)], [Vertex(24 - 1), Vertex(24 + 1), Vertex(24 - 21), Vertex(24 + 21)], [Vertex(25 - 1), Vertex(25 + 1), Vertex(25 - 21), Vertex(25 + 21)], [Vertex(26 - 1), Vertex(26 + 1), Vertex(26 - 21), Vertex(26 + 21)], [Vertex(27 - 1), Vertex(27 + 1), Vertex(27 - 21), Vertex(27 + 21)], [Vertex(28 - 1), Vertex(28 + 1), Vertex(28 - 21), Vertex(28 + 21)], [Vertex(29 - 1), Vertex(29 + 1), Vertex(29 - 21), Vertex(29 + 21)], [Vertex(30 - 1), Vertex(30 + 1), Vertex(30 - 21), Vertex(30 + 21)], [Vertex(31 - 1), Vertex(31 + 1), Vertex(31 - 21), Vertex(31 + 21)], [Vertex(32 - 1), Vertex(32 + 1), Vertex(32 - 21), Vertex(32 + 21)], [Vertex(33 - 1), Vertex(33 + 1), Vertex(33 - 21), Vertex(33 + 21)], [Vertex(34 - 1), Vertex(34 + 1), Vertex(34 - 21), Vertex(34 + 21)], [Vertex(35 - 1), Vertex(35 + 1), Vertex(35 - 21), Vertex(35 + 21)], [Vertex(36 - 1), Vertex(36 + 1), Vertex(36 - 21), Vertex(36 + 21)], [Vertex(37 - 1), Vertex(37 + 1), Vertex(37 - 21), Vertex(37 + 21)], [Vertex(38 - 1), Vertex(38 + 1), Vertex(38 - 21), Vertex(38 + 21)], [Vertex(39 - 1), Vertex(39 + 1), Vertex(39 - 21), Vertex(39 + 21)], [Vertex(40 - 1), Vertex(40 + 1), Vertex(40 - 21), Vertex(40 + 21)], [Vertex(41 - 1), Vertex(41 + 1), Vertex(41 - 21), Vertex(41 + 21)], [Vertex(42 - 1), Vertex(42 + 1), Vertex(42 - 21), Vertex(42 + 21)], [Vertex(43 - 1), Vertex(43 + 1), Vertex(43 - 21), Vertex(43 + 21)], [Vertex(44 - 1), Vertex(44 + 1), Vertex(44 - 21), Vertex(44 + 21)], [Vertex(45 - 1), Vertex(45 + 1), Vertex(45 - 21), Vertex(45 + 21)], [Vertex(46 - 1), Vertex(46 + 1), Vertex(46 - 21), Vertex(46 + 21)], [Vertex(47 - 1), Vertex(47 + 1), Vertex(47 - 21), Vertex(47 + 21)], [Vertex(48 - 1), Vertex(48 + 1), Vertex(48 - 21), Vertex(48 + 21)], [Vertex(49 - 1), Vertex(49 + 1), Vertex(49 - 21), Vertex(49 + 21)], [Vertex(50 - 1), Vertex(50 + 1), Vertex(50 - 21), Vertex(50 + 21)], [Vertex(51 - 1), Vertex(51 + 1), Vertex(51 - 21), Vertex(51 + 21)], [Vertex(52 - 1), Vertex(52 + 1), Vertex(52 - 21), Vertex(52 + 21)], [Vertex(53 - 1), Vertex(53 + 1), Vertex(53 - 21), Vertex(53 + 21)], [Vertex(54 - 1), Vertex(54 + 1), Vertex(54 - 21), Vertex(54 + 21)], [Vertex(55 - 1), Vertex(55 + 1), Vertex(55 - 21), Vertex(55 + 21)], [Vertex(56 - 1), Vertex(56 + 1), Vertex(56 - 21), Vertex(56 + 21)], [Vertex(57 - 1), Vertex(57 + 1), Vertex(57 - 21), Vertex(57 + 21)], [Vertex(58 - 1), Vertex(58 + 1), Vertex(58 - 21), Vertex(58 + 21)], [Vertex(59 - 1), Vertex(59 + 1), Vertex(59 - 21), Vertex(59 + 21)], [Vertex(60 - 1), Vertex(60 + 1), Vertex(60 - 21), Vertex(60 + 21)], [Vertex(61 - 1), Vertex(61 + 1), Vertex(61 - 21), Vertex(61 + 21)], [Vertex(62 - 1), Vertex(62 + 1), Vertex(62 - 21), Vertex(62 + 21)], [Vertex(63 - 1), Vertex(63 + 1), Vertex(63 - 21), Vertex(63 + 21)], [Vertex(64 - 1), Vertex(64 + 1), Vertex(64 - 21), Vertex(64 + 21)], [Vertex(65 - 1), Vertex(65 + 1), Vertex(65 - 21), Vertex(65 + 21)], [Vertex(66 - 1), Vertex(66 + 1), Vertex(66 - 21), Vertex(66 + 21)], [Vertex(67 - 1), Vertex(67 + 1), Vertex(67 - 21), Vertex(67 + 21)], [Vertex(68 - 1), Vertex(68 + 1), Vertex(68 - 21), Vertex(68 + 21)], [Vertex(69 - 1), Vertex(69 + 1), Vertex(69 - 21), Vertex(69 + 21)], [Vertex(70 - 1), Vertex(70 + 1), Vertex(70 - 21), Vertex(70 + 21)], [Vertex(71 - 1), Vertex(71 + 1), Vertex(71 - 21), Vertex(71 + 21)], [Vertex(72 - 1), Vertex(72 + 1), Vertex(72 - 21), Vertex(72 + 21)], [Vertex(73 - 1), Vertex(73 + 1), Vertex(73 - 21), Vertex(73 + 21)], [Vertex(74 - 1), Vertex(74 + 1), Vertex(74 - 21), Vertex(74 + 21)], [Vertex(75 - 1), Vertex(75 + 1), Vertex(75 - 21), Vertex(75 + 21)], [Vertex(76 - 1), Vertex(76 + 1), Vertex(76 - 21), Vertex(76 + 21)], [Vertex(77 - 1), Vertex(77 + 1), Vertex(77 - 21), Vertex(77 + 21)], [Vertex(78 - 1), Vertex(78 + 1), Vertex(78 - 21), Vertex(78 + 21)], [Vertex(79 - 1), Vertex(79 + 1), Vertex(79 - 21), Vertex(79 + 21)], [Vertex(80 - 1), Vertex(80 + 1), Vertex(80 - 21), Vertex(80 + 21)], [Vertex(81 - 1), Vertex(81 + 1), Vertex(81 - 21), Vertex(81 + 21)], [Vertex(82 - 1), Vertex(82 + 1), Vertex(82 - 21), Vertex(82 + 21)], [Vertex(83 - 1), Vertex(83 + 1), Vertex(83 - 21), Vertex(83 + 21)], [Vertex(84 - 1), Vertex(84 + 1), Vertex(84 - 21), Vertex(84 + 21)], [Vertex(85 - 1), Vertex(85 + 1), Vertex(85 - 21), Vertex(85 + 21)], [Vertex(86 - 1), Vertex(86 + 1), Vertex(86 - 21), Vertex(86 + 21)], [Vertex(87 - 1), Vertex(87 + 1), Vertex(87 - 21), Vertex(87 + 21)], [Vertex(88 - 1), Vertex(88 + 1), Vertex(88 - 21), Vertex(88 + 21)], [Vertex(89 - 1), Vertex(89 + 1), Vertex(89 - 21), Vertex(89 + 21)], [Vertex(90 - 1), Vertex(90 + 1), Vertex(90 - 21), Vertex(90 + 21)], [Vertex(91 - 1), Vertex(91 + 1), Vertex(91 - 21), Vertex(91 + 21)], [Vertex(92 - 1), Vertex(92 + 1), Vertex(92 - 21), Vertex(92 + 21)], [Vertex(93 - 1), Vertex(93 + 1), Vertex(93 - 21), Vertex(93 + 21)], [Vertex(94 - 1), Vertex(94 + 1), Vertex(94 - 21), Vertex(94 + 21)], [Vertex(95 - 1), Vertex(95 + 1), Vertex(95 - 21), Vertex(95 + 21)], [Vertex(96 - 1), Vertex(96 + 1), Vertex(96 - 21), Vertex(96 + 21)], [Vertex(97 - 1), Vertex(97 + 1), Vertex(97 - 21), Vertex(97 + 21)], [Vertex(98 - 1), Vertex(98 + 1), Vertex(98 - 21), Vertex(98 + 21)], [Vertex(99 - 1), Vertex(99 + 1), Vertex(99 - 21), Vertex(99 + 21)], [Vertex(100 - 1), Vertex(100 + 1), Vertex(100 - 21), Vertex(100 + 21)], [Vertex(101 - 1), Vertex(101 + 1), Vertex(101 - 21), Vertex(101 + 21)], [Vertex(102 - 1), Vertex(102 + 1), Vertex(102 - 21), Vertex(102 + 21)], [Vertex(103 - 1), Vertex(103 + 1), Vertex(103 - 21), Vertex(103 + 21)], [Vertex(104 - 1), Vertex(104 + 1), Vertex(104 - 21), Vertex(104 + 21)], [Vertex(105 - 1), Vertex(105 + 1), Vertex(105 - 21), Vertex(105 + 21)], [Vertex(106 - 1), Vertex(106 + 1), Vertex(106 - 21), Vertex(106 + 21)], [Vertex(107 - 1), Vertex(107 + 1), Vertex(107 - 21), Vertex(107 + 21)], [Vertex(108 - 1), Vertex(108 + 1), Vertex(108 - 21), Vertex(108 + 21)], [Vertex(109 - 1), Vertex(109 + 1), Vertex(109 - 21), Vertex(109 + 21)], [Vertex(110 - 1), Vertex(110 + 1), Vertex(110 - 21), Vertex(110 + 21)], [Vertex(111 - 1), Vertex(111 + 1), Vertex(111 - 21), Vertex(111 + 21)], [Vertex(112 - 1), Vertex(112 + 1), Vertex(112 - 21), Vertex(112 + 21)], [Vertex(113 - 1), Vertex(113 + 1), Vertex(113 - 21), Vertex(113 + 21)], [Vertex(114 - 1), Vertex(114 + 1), Vertex(114 - 21), Vertex(114 + 21)], [Vertex(115 - 1), Vertex(115 + 1), Vertex(115 - 21), Vertex(115 + 21)], [Vertex(116 - 1), Vertex(116 + 1), Vertex(116 - 21), Vertex(116 + 21)], [Vertex(117 - 1), Vertex(117 + 1), Vertex(117 - 21), Vertex(117 + 21)], [Vertex(118 - 1), Vertex(118 + 1), Vertex(118 - 21), Vertex(118 + 21)], [Vertex(119 - 1), Vertex(119 + 1), Vertex(119 - 21), Vertex(119 + 21)], [Vertex(120 - 1), Vertex(120 + 1), Vertex(120 - 21), Vertex(120 + 21)], [Vertex(121 - 1), Vertex(121 + 1), Vertex(121 - 21), Vertex(121 + 21)], [Vertex(122 - 1), Vertex(122 + 1), Vertex(122 - 21), Vertex(122 + 21)], [Vertex(123 - 1), Vertex(123 + 1), Vertex(123 - 21), Vertex(123 + 21)], [Vertex(124 - 1), Vertex(124 + 1), Vertex(124 - 21), Vertex(124 + 21)], [Vertex(125 - 1), Vertex(125 + 1), Vertex(125 - 21), Vertex(125 + 21)], [Vertex(126 - 1), Vertex(126 + 1), Vertex(126 - 21), Vertex(126 + 21)], [Vertex(127 - 1), Vertex(127 + 1), Vertex(127 - 21), Vertex(127 + 21)], [Vertex(128 - 1), Vertex(128 + 1), Vertex(128 - 21), Vertex(128 + 21)], [Vertex(129 - 1), Vertex(129 + 1), Vertex(129 - 21), Vertex(129 + 21)], [Vertex(130 - 1), Vertex(130 + 1), Vertex(130 - 21), Vertex(130 + 21)], [Vertex(131 - 1), Vertex(131 + 1), Vertex(131 - 21), Vertex(131 + 21)], [Vertex(132 - 1), Vertex(132 + 1), Vertex(132 - 21), Vertex(132 + 21)], [Vertex(133 - 1), Vertex(133 + 1), Vertex(133 - 21), Vertex(133 + 21)], [Vertex(134 - 1), Vertex(134 + 1), Vertex(134 - 21), Vertex(134 + 21)], [Vertex(135 - 1), Vertex(135 + 1), Vertex(135 - 21), Vertex(135 + 21)], [Vertex(136 - 1), Vertex(136 + 1), Vertex(136 - 21), Vertex(136 + 21)], [Vertex(137 - 1), Vertex(137 + 1), Vertex(137 - 21), Vertex(137 + 21)], [Vertex(138 - 1), Vertex(138 + 1), Vertex(138 - 21), Vertex(138 + 21)], [Vertex(139 - 1), Vertex(139 + 1), Vertex(139 - 21), Vertex(139 + 21)], [Vertex(140 - 1), Vertex(140 + 1), Vertex(140 - 21), Vertex(140 + 21)], [Vertex(141 - 1), Vertex(141 + 1), Vertex(141 - 21), Vertex(141 + 21)], [Vertex(142 - 1), Vertex(142 + 1), Vertex(142 - 21), Vertex(142 + 21)], [Vertex(143 - 1), Vertex(143 + 1), Vertex(143 - 21), Vertex(143 + 21)], [Vertex(144 - 1), Vertex(144 + 1), Vertex(144 - 21), Vertex(144 + 21)], [Vertex(145 - 1), Vertex(145 + 1), Vertex(145 - 21), Vertex(145 + 21)], [Vertex(146 - 1), Vertex(146 + 1), Vertex(146 - 21), Vertex(146 + 21)], [Vertex(147 - 1), Vertex(147 + 1), Vertex(147 - 21), Vertex(147 + 21)], [Vertex(148 - 1), Vertex(148 + 1), Vertex(148 - 21), Vertex(148 + 21)], [Vertex(149 - 1), Vertex(149 + 1), Vertex(149 - 21), Vertex(149 + 21)], [Vertex(150 - 1), Vertex(150 + 1), Vertex(150 - 21), Vertex(150 + 21)], [Vertex(151 - 1), Vertex(151 + 1), Vertex(151 - 21), Vertex(151 + 21)], [Vertex(152 - 1), Vertex(152 + 1), Vertex(152 - 21), Vertex(152 + 21)], [Vertex(153 - 1), Vertex(153 + 1), Vertex(153 - 21), Vertex(153 + 21)], [Vertex(154 - 1), Vertex(154 + 1), Vertex(154 - 21), Vertex(154 + 21)], [Vertex(155 - 1), Vertex(155 + 1), Vertex(155 - 21), Vertex(155 + 21)], [Vertex(156 - 1), Vertex(156 + 1), Vertex(156 - 21), Vertex(156 + 21)], [Vertex(157 - 1), Vertex(157 + 1), Vertex(157 - 21), Vertex(157 + 21)], [Vertex(158 - 1), Vertex(158 + 1), Vertex(158 - 21), Vertex(158 + 21)], [Vertex(159 - 1), Vertex(159 + 1), Vertex(159 - 21), Vertex(159 + 21)], [Vertex(160 - 1), Vertex(160 + 1), Vertex(160 - 21), Vertex(160 + 21)], [Vertex(161 - 1), Vertex(161 + 1), Vertex(161 - 21), Vertex(161 + 21)], [Vertex(162 - 1), Vertex(162 + 1), Vertex(162 - 21), Vertex(162 + 21)], [Vertex(163 - 1), Vertex(163 + 1), Vertex(163 - 21), Vertex(163 + 21)], [Vertex(164 - 1), Vertex(164 + 1), Vertex(164 - 21), Vertex(164 + 21)], [Vertex(165 - 1), Vertex(165 + 1), Vertex(165 - 21), Vertex(165 + 21)], [Vertex(166 - 1), Vertex(166 + 1), Vertex(166 - 21), Vertex(166 + 21)], [Vertex(167 - 1), Vertex(167 + 1), Vertex(167 - 21), Vertex(167 + 21)], [Vertex(168 - 1), Vertex(168 + 1), Vertex(168 - 21), Vertex(168 + 21)], [Vertex(169 - 1), Vertex(169 + 1), Vertex(169 - 21), Vertex(169 + 21)], [Vertex(170 - 1), Vertex(170 + 1), Vertex(170 - 21), Vertex(170 + 21)], [Vertex(171 - 1), Vertex(171 + 1), Vertex(171 - 21), Vertex(171 + 21)], [Vertex(172 - 1), Vertex(172 + 1), Vertex(172 - 21), Vertex(172 + 21)], [Vertex(173 - 1), Vertex(173 + 1), Vertex(173 - 21), Vertex(173 + 21)], [Vertex(174 - 1), Vertex(174 + 1), Vertex(174 - 21), Vertex(174 + 21)], [Vertex(175 - 1), Vertex(175 + 1), Vertex(175 - 21), Vertex(175 + 21)], [Vertex(176 - 1), Vertex(176 + 1), Vertex(176 - 21), Vertex(176 + 21)], [Vertex(177 - 1), Vertex(177 + 1), Vertex(177 - 21), Vertex(177 + 21)], [Vertex(178 - 1), Vertex(178 + 1), Vertex(178 - 21), Vertex(178 + 21)], [Vertex(179 - 1), Vertex(179 + 1), Vertex(179 - 21), Vertex(179 + 21)], [Vertex(180 - 1), Vertex(180 + 1), Vertex(180 - 21), Vertex(180 + 21)], [Vertex(181 - 1), Vertex(181 + 1), Vertex(181 - 21), Vertex(181 + 21)], [Vertex(182 - 1), Vertex(182 + 1), Vertex(182 - 21), Vertex(182 + 21)], [Vertex(183 - 1), Vertex(183 + 1), Vertex(183 - 21), Vertex(183 + 21)], [Vertex(184 - 1), Vertex(184 + 1), Vertex(184 - 21), Vertex(184 + 21)], [Vertex(185 - 1), Vertex(185 + 1), Vertex(185 - 21), Vertex(185 + 21)], [Vertex(186 - 1), Vertex(186 + 1), Vertex(186 - 21), Vertex(186 + 21)], [Vertex(187 - 1), Vertex(187 + 1), Vertex(187 - 21), Vertex(187 + 21)], [Vertex(188 - 1), Vertex(188 + 1), Vertex(188 - 21), Vertex(188 + 21)], [Vertex(189 - 1), Vertex(189 + 1), Vertex(189 - 21), Vertex(189 + 21)], [Vertex(190 - 1), Vertex(190 + 1), Vertex(190 - 21), Vertex(190 + 21)], [Vertex(191 - 1), Vertex(191 + 1), Vertex(191 - 21), Vertex(191 + 21)], [Vertex(192 - 1), Vertex(192 + 1), Vertex(192 - 21), Vertex(192 + 21)], [Vertex(193 - 1), Vertex(193 + 1), Vertex(193 - 21), Vertex(193 + 21)], [Vertex(194 - 1), Vertex(194 + 1), Vertex(194 - 21), Vertex(194 + 21)], [Vertex(195 - 1), Vertex(195 + 1), Vertex(195 - 21), Vertex(195 + 21)], [Vertex(196 - 1), Vertex(196 + 1), Vertex(196 - 21), Vertex(196 + 21)], [Vertex(197 - 1), Vertex(197 + 1), Vertex(197 - 21), Vertex(197 + 21)], [Vertex(198 - 1), Vertex(198 + 1), Vertex(198 - 21), Vertex(198 + 21)], [Vertex(199 - 1), Vertex(199 + 1), Vertex(199 - 21), Vertex(199 + 21)], [Vertex(200 - 1), Vertex(200 + 1), Vertex(200 - 21), Vertex(200 + 21)], [Vertex(201 - 1), Vertex(201 + 1), Vertex(201 - 21), Vertex(201 + 21)], [Vertex(202 - 1), Vertex(202 + 1), Vertex(202 - 21), Vertex(202 + 21)], [Vertex(203 - 1), Vertex(203 + 1), Vertex(203 - 21), Vertex(203 + 21)], [Vertex(204 - 1), Vertex(204 + 1), Vertex(204 - 21), Vertex(204 + 21)], [Vertex(205 - 1), Vertex(205 + 1), Vertex(205 - 21), Vertex(205 + 21)], [Vertex(206 - 1), Vertex(206 + 1), Vertex(206 - 21), Vertex(206 + 21)], [Vertex(207 - 1), Vertex(207 + 1), Vertex(207 - 21), Vertex(207 + 21)], [Vertex(208 - 1), Vertex(208 + 1), Vertex(208 - 21), Vertex(208 + 21)], [Vertex(209 - 1), Vertex(209 + 1), Vertex(209 - 21), Vertex(209 + 21)], [Vertex(210 - 1), Vertex(210 + 1), Vertex(210 - 21), Vertex(210 + 21)], [Vertex(211 - 1), Vertex(211 + 1), Vertex(211 - 21), Vertex(211 + 21)], [Vertex(212 - 1), Vertex(212 + 1), Vertex(212 - 21), Vertex(212 + 21)], [Vertex(213 - 1), Vertex(213 + 1), Vertex(213 - 21), Vertex(213 + 21)], [Vertex(214 - 1), Vertex(214 + 1), Vertex(214 - 21), Vertex(214 + 21)], [Vertex(215 - 1), Vertex(215 + 1), Vertex(215 - 21), Vertex(215 + 21)], [Vertex(216 - 1), Vertex(216 + 1), Vertex(216 - 21), Vertex(216 + 21)], [Vertex(217 - 1), Vertex(217 + 1), Vertex(217 - 21), Vertex(217 + 21)], [Vertex(218 - 1), Vertex(218 + 1), Vertex(218 - 21), Vertex(218 + 21)], [Vertex(219 - 1), Vertex(219 + 1), Vertex(219 - 21), Vertex(219 + 21)], [Vertex(220 - 1), Vertex(220 + 1), Vertex(220 - 21), Vertex(220 + 21)], [Vertex(221 - 1), Vertex(221 + 1), Vertex(221 - 21), Vertex(221 + 21)], [Vertex(222 - 1), Vertex(222 + 1), Vertex(222 - 21), Vertex(222 + 21)], [Vertex(223 - 1), Vertex(223 + 1), Vertex(223 - 21), Vertex(223 + 21)], [Vertex(224 - 1), Vertex(224 + 1), Vertex(224 - 21), Vertex(224 + 21)], [Vertex(225 - 1), Vertex(225 + 1), Vertex(225 - 21), Vertex(225 + 21)], [Vertex(226 - 1), Vertex(226 + 1), Vertex(226 - 21), Vertex(226 + 21)], [Vertex(227 - 1), Vertex(227 + 1), Vertex(227 - 21), Vertex(227 + 21)], [Vertex(228 - 1), Vertex(228 + 1), Vertex(228 - 21), Vertex(228 + 21)], [Vertex(229 - 1), Vertex(229 + 1), Vertex(229 - 21), Vertex(229 + 21)], [Vertex(230 - 1), Vertex(230 + 1), Vertex(230 - 21), Vertex(230 + 21)], [Vertex(231 - 1), Vertex(231 + 1), Vertex(231 - 21), Vertex(231 + 21)], [Vertex(232 - 1), Vertex(232 + 1), Vertex(232 - 21), Vertex(232 + 21)], [Vertex(233 - 1), Vertex(233 + 1), Vertex(233 - 21), Vertex(233 + 21)], [Vertex(234 - 1), Vertex(234 + 1), Vertex(234 - 21), Vertex(234 + 21)], [Vertex(235 - 1), Vertex(235 + 1), Vertex(235 - 21), Vertex(235 + 21)], [Vertex(236 - 1), Vertex(236 + 1), Vertex(236 - 21), Vertex(236 + 21)], [Vertex(237 - 1), Vertex(237 + 1), Vertex(237 - 21), Vertex(237 + 21)], [Vertex(238 - 1), Vertex(238 + 1), Vertex(238 - 21), Vertex(238 + 21)], [Vertex(239 - 1), Vertex(239 + 1), Vertex(239 - 21), Vertex(239 + 21)], [Vertex(240 - 1), Vertex(240 + 1), Vertex(240 - 21), Vertex(240 + 21)], [Vertex(241 - 1), Vertex(241 + 1), Vertex(241 - 21), Vertex(241 + 21)], [Vertex(242 - 1), Vertex(242 + 1), Vertex(242 - 21), Vertex(242 + 21)], [Vertex(243 - 1), Vertex(243 + 1), Vertex(243 - 21), Vertex(243 + 21)], [Vertex(244 - 1), Vertex(244 + 1), Vertex(244 - 21), Vertex(244 + 21)], [Vertex(245 - 1), Vertex(245 + 1), Vertex(245 - 21), Vertex(245 + 21)], [Vertex(246 - 1), Vertex(246 + 1), Vertex(246 - 21), Vertex(246 + 21)], [Vertex(247 - 1), Vertex(247 + 1), Vertex(247 - 21), Vertex(247 + 21)], [Vertex(248 - 1), Vertex(248 + 1), Vertex(248 - 21), Vertex(248 + 21)], [Vertex(249 - 1), Vertex(249 + 1), Vertex(249 - 21), Vertex(249 + 21)], [Vertex(250 - 1), Vertex(250 + 1), Vertex(250 - 21), Vertex(250 + 21)], [Vertex(251 - 1), Vertex(251 + 1), Vertex(251 - 21), Vertex(251 + 21)], [Vertex(252 - 1), Vertex(252 + 1), Vertex(252 - 21), Vertex(252 + 21)], [Vertex(253 - 1), Vertex(253 + 1), Vertex(253 - 21), Vertex(253 + 21)], [Vertex(254 - 1), Vertex(254 + 1), Vertex(254 - 21), Vertex(254 + 21)], [Vertex(255 - 1), Vertex(255 + 1), Vertex(255 - 21), Vertex(255 + 21)], [Vertex(256 - 1), Vertex(256 + 1), Vertex(256 - 21), Vertex(256 + 21)], [Vertex(257 - 1), Vertex(257 + 1), Vertex(257 - 21), Vertex(257 + 21)], [Vertex(258 - 1), Vertex(258 + 1), Vertex(258 - 21), Vertex(258 + 21)], [Vertex(259 - 1), Vertex(259 + 1), Vertex(259 - 21), Vertex(259 + 21)], [Vertex(260 - 1), Vertex(260 + 1), Vertex(260 - 21), Vertex(260 + 21)], [Vertex(261 - 1), Vertex(261 + 1), Vertex(261 - 21), Vertex(261 + 21)], [Vertex(262 - 1), Vertex(262 + 1), Vertex(262 - 21), Vertex(262 + 21)], [Vertex(263 - 1), Vertex(263 + 1), Vertex(263 - 21), Vertex(263 + 21)], [Vertex(264 - 1), Vertex(264 + 1), Vertex(264 - 21), Vertex(264 + 21)], [Vertex(265 - 1), Vertex(265 + 1), Vertex(265 - 21), Vertex(265 + 21)], [Vertex(266 - 1), Vertex(266 + 1), Vertex(266 - 21), Vertex(266 + 21)], [Vertex(267 - 1), Vertex(267 + 1), Vertex(267 - 21), Vertex(267 + 21)], [Vertex(268 - 1), Vertex(268 + 1), Vertex(268 - 21), Vertex(268 + 21)], [Vertex(269 - 1), Vertex(269 + 1), Vertex(269 - 21), Vertex(269 + 21)], [Vertex(270 - 1), Vertex(270 + 1), Vertex(270 - 21), Vertex(270 + 21)], [Vertex(271 - 1), Vertex(271 + 1), Vertex(271 - 21), Vertex(271 + 21)], [Vertex(272 - 1), Vertex(272 + 1), Vertex(272 - 21), Vertex(272 + 21)], [Vertex(273 - 1), Vertex(273 + 1), Vertex(273 - 21), Vertex(273 + 21)], [Vertex(274 - 1), Vertex(274 + 1), Vertex(274 - 21), Vertex(274 + 21)], [Vertex(275 - 1), Vertex(275 + 1), Vertex(275 - 21), Vertex(275 + 21)], [Vertex(276 - 1), Vertex(276 + 1), Vertex(276 - 21), Vertex(276 + 21)], [Vertex(277 - 1), Vertex(277 + 1), Vertex(277 - 21), Vertex(277 + 21)], [Vertex(278 - 1), Vertex(278 + 1), Vertex(278 - 21), Vertex(278 + 21)], [Vertex(279 - 1), Vertex(279 + 1), Vertex(279 - 21), Vertex(279 + 21)], [Vertex(280 - 1), Vertex(280 + 1), Vertex(280 - 21), Vertex(280 + 21)], [Vertex(281 - 1), Vertex(281 + 1), Vertex(281 - 21), Vertex(281 + 21)], [Vertex(282 - 1), Vertex(282 + 1), Vertex(282 - 21), Vertex(282 + 21)], [Vertex(283 - 1), Vertex(283 + 1), Vertex(283 - 21), Vertex(283 + 21)], [Vertex(284 - 1), Vertex(284 + 1), Vertex(284 - 21), Vertex(284 + 21)], [Vertex(285 - 1), Vertex(285 + 1), Vertex(285 - 21), Vertex(285 + 21)], [Vertex(286 - 1), Vertex(286 + 1), Vertex(286 - 21), Vertex(286 + 21)], [Vertex(287 - 1), Vertex(287 + 1), Vertex(287 - 21), Vertex(287 + 21)], [Vertex(288 - 1), Vertex(288 + 1), Vertex(288 - 21), Vertex(288 + 21)], [Vertex(289 - 1), Vertex(289 + 1), Vertex(289 - 21), Vertex(289 + 21)], [Vertex(290 - 1), Vertex(290 + 1), Vertex(290 - 21), Vertex(290 + 21)], [Vertex(291 - 1), Vertex(291 + 1), Vertex(291 - 21), Vertex(291 + 21)], [Vertex(292 - 1), Vertex(292 + 1), Vertex(292 - 21), Vertex(292 + 21)], [Vertex(293 - 1), Vertex(293 + 1), Vertex(293 - 21), Vertex(293 + 21)], [Vertex(294 - 1), Vertex(294 + 1), Vertex(294 - 21), Vertex(294 + 21)], [Vertex(295 - 1), Vertex(295 + 1), Vertex(295 - 21), Vertex(295 + 21)], [Vertex(296 - 1), Vertex(296 + 1), Vertex(296 - 21), Vertex(296 + 21)], [Vertex(297 - 1), Vertex(297 + 1), Vertex(297 - 21), Vertex(297 + 21)], [Vertex(298 - 1), Vertex(298 + 1), Vertex(298 - 21), Vertex(298 + 21)], [Vertex(299 - 1), Vertex(299 + 1), Vertex(299 - 21), Vertex(299 + 21)], [Vertex(300 - 1), Vertex(300 + 1), Vertex(300 - 21), Vertex(300 + 21)], [Vertex(301 - 1), Vertex(301 + 1), Vertex(301 - 21), Vertex(301 + 21)], [Vertex(302 - 1), Vertex(302 + 1), Vertex(302 - 21), Vertex(302 + 21)], [Vertex(303 - 1), Vertex(303 + 1), Vertex(303 - 21), Vertex(303 + 21)], [Vertex(304 - 1), Vertex(304 + 1), Vertex(304 - 21), Vertex(304 + 21)], [Vertex(305 - 1), Vertex(305 + 1), Vertex(305 - 21), Vertex(305 + 21)], [Vertex(306 - 1), Vertex(306 + 1), Vertex(306 - 21), Vertex(306 + 21)], [Vertex(307 - 1), Vertex(307 + 1), Vertex(307 - 21), Vertex(307 + 21)], [Vertex(308 - 1), Vertex(308 + 1), Vertex(308 - 21), Vertex(308 + 21)], [Vertex(309 - 1), Vertex(309 + 1), Vertex(309 - 21), Vertex(309 + 21)], [Vertex(310 - 1), Vertex(310 + 1), Vertex(310 - 21), Vertex(310 + 21)], [Vertex(311 - 1), Vertex(311 + 1), Vertex(311 - 21), Vertex(311 + 21)], [Vertex(312 - 1), Vertex(312 + 1), Vertex(312 - 21), Vertex(312 + 21)], [Vertex(313 - 1), Vertex(313 + 1), Vertex(313 - 21), Vertex(313 + 21)], [Vertex(314 - 1), Vertex(314 + 1), Vertex(314 - 21), Vertex(314 + 21)], [Vertex(315 - 1), Vertex(315 + 1), Vertex(315 - 21), Vertex(315 + 21)], [Vertex(316 - 1), Vertex(316 + 1), Vertex(316 - 21), Vertex(316 + 21)], [Vertex(317 - 1), Vertex(317 + 1), Vertex(317 - 21), Vertex(317 + 21)], [Vertex(318 - 1), Vertex(318 + 1), Vertex(318 - 21), Vertex(318 + 21)], [Vertex(319 - 1), Vertex(319 + 1), Vertex(319 - 21), Vertex(319 + 21)], [Vertex(320 - 1), Vertex(320 + 1), Vertex(320 - 21), Vertex(320 + 21)], [Vertex(321 - 1), Vertex(321 + 1), Vertex(321 - 21), Vertex(321 + 21)], [Vertex(322 - 1), Vertex(322 + 1), Vertex(322 - 21), Vertex(322 + 21)], [Vertex(323 - 1), Vertex(323 + 1), Vertex(323 - 21), Vertex(323 + 21)], [Vertex(324 - 1), Vertex(324 + 1), Vertex(324 - 21), Vertex(324 + 21)], [Vertex(325 - 1), Vertex(325 + 1), Vertex(325 - 21), Vertex(325 + 21)], [Vertex(326 - 1), Vertex(326 + 1), Vertex(326 - 21), Vertex(326 + 21)], [Vertex(327 - 1), Vertex(327 + 1), Vertex(327 - 21), Vertex(327 + 21)], [Vertex(328 - 1), Vertex(328 + 1), Vertex(328 - 21), Vertex(328 + 21)], [Vertex(329 - 1), Vertex(329 + 1), Vertex(329 - 21), Vertex(329 + 21)], [Vertex(330 - 1), Vertex(330 + 1), Vertex(330 - 21), Vertex(330 + 21)], [Vertex(331 - 1), Vertex(331 + 1), Vertex(331 - 21), Vertex(331 + 21)], [Vertex(332 - 1), Vertex(332 + 1), Vertex(332 - 21), Vertex(332 + 21)], [Vertex(333 - 1), Vertex(333 + 1), Vertex(333 - 21), Vertex(333 + 21)], [Vertex(334 - 1), Vertex(334 + 1), Vertex(334 - 21), Vertex(334 + 21)], [Vertex(335 - 1), Vertex(335 + 1), Vertex(335 - 21), Vertex(335 + 21)], [Vertex(336 - 1), Vertex(336 + 1), Vertex(336 - 21), Vertex(336 + 21)], [Vertex(337 - 1), Vertex(337 + 1), Vertex(337 - 21), Vertex(337 + 21)], [Vertex(338 - 1), Vertex(338 + 1), Vertex(338 - 21), Vertex(338 + 21)], [Vertex(339 - 1), Vertex(339 + 1), Vertex(339 - 21), Vertex(339 + 21)], [Vertex(340 - 1), Vertex(340 + 1), Vertex(340 - 21), Vertex(340 + 21)], [Vertex(341 - 1), Vertex(341 + 1), Vertex(341 - 21), Vertex(341 + 21)], [Vertex(342 - 1), Vertex(342 + 1), Vertex(342 - 21), Vertex(342 + 21)], [Vertex(343 - 1), Vertex(343 + 1), Vertex(343 - 21), Vertex(343 + 21)], [Vertex(344 - 1), Vertex(344 + 1), Vertex(344 - 21), Vertex(344 + 21)], [Vertex(345 - 1), Vertex(345 + 1), Vertex(345 - 21), Vertex(345 + 21)], [Vertex(346 - 1), Vertex(346 + 1), Vertex(346 - 21), Vertex(346 + 21)], [Vertex(347 - 1), Vertex(347 + 1), Vertex(347 - 21), Vertex(347 + 21)], [Vertex(348 - 1), Vertex(348 + 1), Vertex(348 - 21), Vertex(348 + 21)], [Vertex(349 - 1), Vertex(349 + 1), Vertex(349 - 21), Vertex(349 + 21)], [Vertex(350 - 1), Vertex(350 + 1), Vertex(350 - 21), Vertex(350 + 21)], [Vertex(351 - 1), Vertex(351 + 1), Vertex(351 - 21), Vertex(351 + 21)], [Vertex(352 - 1), Vertex(352 + 1), Vertex(352 - 21), Vertex(352 + 21)], [Vertex(353 - 1), Vertex(353 + 1), Vertex(353 - 21), Vertex(353 + 21)], [Vertex(354 - 1), Vertex(354 + 1), Vertex(354 - 21), Vertex(354 + 21)], [Vertex(355 - 1), Vertex(355 + 1), Vertex(355 - 21), Vertex(355 + 21)], [Vertex(356 - 1), Vertex(356 + 1), Vertex(356 - 21), Vertex(356 + 21)], [Vertex(357 - 1), Vertex(357 + 1), Vertex(357 - 21), Vertex(357 + 21)], [Vertex(358 - 1), Vertex(358 + 1), Vertex(358 - 21), Vertex(358 + 21)], [Vertex(359 - 1), Vertex(359 + 1), Vertex(359 - 21), Vertex(359 + 21)], [Vertex(360 - 1), Vertex(360 + 1), Vertex(360 - 21), Vertex(360 + 21)], [Vertex(361 - 1), Vertex(361 + 1), Vertex(361 - 21), Vertex(361 + 21)], [Vertex(362 - 1), Vertex(362 + 1), Vertex(362 - 21), Vertex(362 + 21)], [Vertex(363 - 1), Vertex(363 + 1), Vertex(363 - 21), Vertex(363 + 21)], [Vertex(364 - 1), Vertex(364 + 1), Vertex(364 - 21), Vertex(364 + 21)], [Vertex(365 - 1), Vertex(365 + 1), Vertex(365 - 21), Vertex(365 + 21)], [Vertex(366 - 1), Vertex(366 + 1), Vertex(366 - 21), Vertex(366 + 21)], [Vertex(367 - 1), Vertex(367 + 1), Vertex(367 - 21), Vertex(367 + 21)], [Vertex(368 - 1), Vertex(368 + 1), Vertex(368 - 21), Vertex(368 + 21)], [Vertex(369 - 1), Vertex(369 + 1), Vertex(369 - 21), Vertex(369 + 21)], [Vertex(370 - 1), Vertex(370 + 1), Vertex(370 - 21), Vertex(370 + 21)], [Vertex(371 - 1), Vertex(371 + 1), Vertex(371 - 21), Vertex(371 + 21)], [Vertex(372 - 1), Vertex(372 + 1), Vertex(372 - 21), Vertex(372 + 21)], [Vertex(373 - 1), Vertex(373 + 1), Vertex(373 - 21), Vertex(373 + 21)], [Vertex(374 - 1), Vertex(374 + 1), Vertex(374 - 21), Vertex(374 + 21)], [Vertex(375 - 1), Vertex(375 + 1), Vertex(375 - 21), Vertex(375 + 21)], [Vertex(376 - 1), Vertex(376 + 1), Vertex(376 - 21), Vertex(376 + 21)], [Vertex(377 - 1), Vertex(377 + 1), Vertex(377 - 21), Vertex(377 + 21)], [Vertex(378 - 1), Vertex(378 + 1), Vertex(378 - 21), Vertex(378 + 21)], [Vertex(379 - 1), Vertex(379 + 1), Vertex(379 - 21), Vertex(379 + 21)], [Vertex(380 - 1), Vertex(380 + 1), Vertex(380 - 21), Vertex(380 + 21)], [Vertex(381 - 1), Vertex(381 + 1), Vertex(381 - 21), Vertex(381 + 21)], [Vertex(382 - 1), Vertex(382 + 1), Vertex(382 - 21), Vertex(382 + 21)], [Vertex(383 - 1), Vertex(383 + 1), Vertex(383 - 21), Vertex(383 + 21)], [Vertex(384 - 1), Vertex(384 + 1), Vertex(384 - 21), Vertex(384 + 21)], [Vertex(385 - 1), Vertex(385 + 1), Vertex(385 - 21), Vertex(385 + 21)], [Vertex(386 - 1), Vertex(386 + 1), Vertex(386 - 21), Vertex(386 + 21)], [Vertex(387 - 1), Vertex(387 + 1), Vertex(387 - 21), Vertex(387 + 21)], [Vertex(388 - 1), Vertex(388 + 1), Vertex(388 - 21), Vertex(388 + 21)], [Vertex(389 - 1), Vertex(389 + 1), Vertex(389 - 21), Vertex(389 + 21)], [Vertex(390 - 1), Vertex(390 + 1), Vertex(390 - 21), Vertex(390 + 21)], [Vertex(391 - 1), Vertex(391 + 1), Vertex(391 - 21), Vertex(391 + 21)], [Vertex(392 - 1), Vertex(392 + 1), Vertex(392 - 21), Vertex(392 + 21)], [Vertex(393 - 1), Vertex(393 + 1), Vertex(393 - 21), Vertex(393 + 21)], [Vertex(394 - 1), Vertex(394 + 1), Vertex(394 - 21), Vertex(394 + 21)], [Vertex(395 - 1), Vertex(395 + 1), Vertex(395 - 21), Vertex(395 + 21)], [Vertex(396 - 1), Vertex(396 + 1), Vertex(396 - 21), Vertex(396 + 21)], [Vertex(397 - 1), Vertex(397 + 1), Vertex(397 - 21), Vertex(397 + 21)], [Vertex(398 - 1), Vertex(398 + 1), Vertex(398 - 21), Vertex(398 + 21)], [Vertex(399 - 1), Vertex(399 + 1), Vertex(399 - 21), Vertex(399 + 21)], [Vertex(400 - 1), Vertex(400 + 1), Vertex(400 - 21), Vertex(400 + 21)], [Vertex(401 - 1), Vertex(401 + 1), Vertex(401 - 21), Vertex(401 + 21)], [Vertex(402 - 1), Vertex(402 + 1), Vertex(402 - 21), Vertex(402 + 21)], [Vertex(403 - 1), Vertex(403 + 1), Vertex(403 - 21), Vertex(403 + 21)], [Vertex(404 - 1), Vertex(404 + 1), Vertex(404 - 21), Vertex(404 + 21)], [Vertex(405 - 1), Vertex(405 + 1), Vertex(405 - 21), Vertex(405 + 21)], [Vertex(406 - 1), Vertex(406 + 1), Vertex(406 - 21), Vertex(406 + 21)], [Vertex(407 - 1), Vertex(407 + 1), Vertex(407 - 21), Vertex(407 + 21)], [Vertex(408 - 1), Vertex(408 + 1), Vertex(408 - 21), Vertex(408 + 21)], [Vertex(409 - 1), Vertex(409 + 1), Vertex(409 - 21), Vertex(409 + 21)], [Vertex(410 - 1), Vertex(410 + 1), Vertex(410 - 21), Vertex(410 + 21)], [Vertex(411 - 1), Vertex(411 + 1), Vertex(411 - 21), Vertex(411 + 21)], [Vertex(412 - 1), Vertex(412 + 1), Vertex(412 - 21), Vertex(412 + 21)], [Vertex(413 - 1), Vertex(413 + 1), Vertex(413 - 21), Vertex(413 + 21)], [Vertex(414 - 1), Vertex(414 + 1), Vertex(414 - 21), Vertex(414 + 21)], [Vertex(415 - 1), Vertex(415 + 1), Vertex(415 - 21), Vertex(415 + 21)], [Vertex(416 - 1), Vertex(416 + 1), Vertex(416 - 21), Vertex(416 + 21)], [Vertex(417 - 1), Vertex(417 + 1), Vertex(417 - 21), Vertex(417 + 21)], [Vertex(418 - 1), Vertex(418 + 1), Vertex(418 - 21), Vertex(418 + 21)], [Vertex(419 - 1), Vertex(419 + 1), Vertex(419 - 21), Vertex(419 + 21)], [Vertex(420 - 1), Vertex(420 + 1), Vertex(420 - 21), Vertex(420 + 21)], [Vertex(421 - 1), Vertex(421 + 1), Vertex(421 - 21), Vertex(421 + 21)], [Vertex(422 - 1), Vertex(422 + 1), Vertex(422 - 21), Vertex(422 + 21)], [Vertex(423 - 1), Vertex(423 + 1), Vertex(423 - 21), Vertex(423 + 21)], [Vertex(424 - 1), Vertex(424 + 1), Vertex(424 - 21), Vertex(424 + 21)], [Vertex(425 - 1), Vertex(425 + 1), Vertex(425 - 21), Vertex(425 + 21)], [Vertex(426 - 1), Vertex(426 + 1), Vertex(426 - 21), Vertex(426 + 21)], [Vertex(427 - 1), Vertex(427 + 1), Vertex(427 - 21), Vertex(427 + 21)], [Vertex(428 - 1), Vertex(428 + 1), Vertex(428 - 21), Vertex(428 + 21)], [Vertex(429 - 1), Vertex(429 + 1), Vertex(429 - 21), Vertex(429 + 21)], [Vertex(430 - 1), Vertex(430 + 1), Vertex(430 - 21), Vertex(430 + 21)], [Vertex(431 - 1), Vertex(431 + 1), Vertex(431 - 21), Vertex(431 + 21)], [Vertex(432 - 1), Vertex(432 + 1), Vertex(432 - 21), Vertex(432 + 21)], [Vertex(433 - 1), Vertex(433 + 1), Vertex(433 - 21), Vertex(433 + 21)], [Vertex(434 - 1), Vertex(434 + 1), Vertex(434 - 21), Vertex(434 + 21)], [Vertex(435 - 1), Vertex(435 + 1), Vertex(435 - 21), Vertex(435 + 21)], [Vertex(436 - 1), Vertex(436 + 1), Vertex(436 - 21), Vertex(436 + 21)], [Vertex(437 - 1), Vertex(437 + 1), Vertex(437 - 21), Vertex(437 + 21)], [Vertex(438 - 1), Vertex(438 + 1), Vertex(438 - 21), Vertex(438 + 21)], [Vertex(439 - 1), Vertex(439 + 1), Vertex(439 - 21), Vertex(439 + 21)], [Vertex(440 - 1), Vertex(440 + 1), Vertex(440 - 21), Vertex(440 + 21)] ]; // print',\n'.join(["[Vertex(%d - 22), Vertex(%d - 20), Vertex(%d + 20), Vertex(%d + 22)]" % (i, i, i, i) for i in range(21 * 21)]) pub static DIAG_NEIGHBOURS: [[Vertex; 4]; 21 * 21] = [ [Vertex(0 - 22), Vertex(0 - 20), Vertex(0 + 20), Vertex(0 + 22)], [Vertex(1 - 22), Vertex(1 - 20), Vertex(1 + 20), Vertex(1 + 22)], [Vertex(2 - 22), Vertex(2 - 20), Vertex(2 + 20), Vertex(2 + 22)], [Vertex(3 - 22), Vertex(3 - 20), Vertex(3 + 20), Vertex(3 + 22)], [Vertex(4 - 22), Vertex(4 - 20), Vertex(4 + 20), Vertex(4 + 22)], [Vertex(5 - 22), Vertex(5 - 20), Vertex(5 + 20), Vertex(5 + 22)], [Vertex(6 - 22), Vertex(6 - 20), Vertex(6 + 20), Vertex(6 + 22)], [Vertex(7 - 22), Vertex(7 - 20), Vertex(7 + 20), Vertex(7 + 22)], [Vertex(8 - 22), Vertex(8 - 20), Vertex(8 + 20), Vertex(8 + 22)], [Vertex(9 - 22), Vertex(9 - 20), Vertex(9 + 20), Vertex(9 + 22)], [Vertex(10 - 22), Vertex(10 - 20), Vertex(10 + 20), Vertex(10 + 22)], [Vertex(11 - 22), Vertex(11 - 20), Vertex(11 + 20), Vertex(11 + 22)], [Vertex(12 - 22), Vertex(12 - 20), Vertex(12 + 20), Vertex(12 + 22)], [Vertex(13 - 22), Vertex(13 - 20), Vertex(13 + 20), Vertex(13 + 22)], [Vertex(14 - 22), Vertex(14 - 20), Vertex(14 + 20), Vertex(14 + 22)], [Vertex(15 - 22), Vertex(15 - 20), Vertex(15 + 20), Vertex(15 + 22)], [Vertex(16 - 22), Vertex(16 - 20), Vertex(16 + 20), Vertex(16 + 22)], [Vertex(17 - 22), Vertex(17 - 20), Vertex(17 + 20), Vertex(17 + 22)], [Vertex(18 - 22), Vertex(18 - 20), Vertex(18 + 20), Vertex(18 + 22)], [Vertex(19 - 22), Vertex(19 - 20), Vertex(19 + 20), Vertex(19 + 22)], [Vertex(20 - 22), Vertex(20 - 20), Vertex(20 + 20), Vertex(20 + 22)], [Vertex(21 - 22), Vertex(21 - 20), Vertex(21 + 20), Vertex(21 + 22)], [Vertex(22 - 22), Vertex(22 - 20), Vertex(22 + 20), Vertex(22 + 22)], [Vertex(23 - 22), Vertex(23 - 20), Vertex(23 + 20), Vertex(23 + 22)], [Vertex(24 - 22), Vertex(24 - 20), Vertex(24 + 20), Vertex(24 + 22)], [Vertex(25 - 22), Vertex(25 - 20), Vertex(25 + 20), Vertex(25 + 22)], [Vertex(26 - 22), Vertex(26 - 20), Vertex(26 + 20), Vertex(26 + 22)], [Vertex(27 - 22), Vertex(27 - 20), Vertex(27 + 20), Vertex(27 + 22)], [Vertex(28 - 22), Vertex(28 - 20), Vertex(28 + 20), Vertex(28 + 22)], [Vertex(29 - 22), Vertex(29 - 20), Vertex(29 + 20), Vertex(29 + 22)], [Vertex(30 - 22), Vertex(30 - 20), Vertex(30 + 20), Vertex(30 + 22)], [Vertex(31 - 22), Vertex(31 - 20), Vertex(31 + 20), Vertex(31 + 22)], [Vertex(32 - 22), Vertex(32 - 20), Vertex(32 + 20), Vertex(32 + 22)], [Vertex(33 - 22), Vertex(33 - 20), Vertex(33 + 20), Vertex(33 + 22)], [Vertex(34 - 22), Vertex(34 - 20), Vertex(34 + 20), Vertex(34 + 22)], [Vertex(35 - 22), Vertex(35 - 20), Vertex(35 + 20), Vertex(35 + 22)], [Vertex(36 - 22), Vertex(36 - 20), Vertex(36 + 20), Vertex(36 + 22)], [Vertex(37 - 22), Vertex(37 - 20), Vertex(37 + 20), Vertex(37 + 22)], [Vertex(38 - 22), Vertex(38 - 20), Vertex(38 + 20), Vertex(38 + 22)], [Vertex(39 - 22), Vertex(39 - 20), Vertex(39 + 20), Vertex(39 + 22)], [Vertex(40 - 22), Vertex(40 - 20), Vertex(40 + 20), Vertex(40 + 22)], [Vertex(41 - 22), Vertex(41 - 20), Vertex(41 + 20), Vertex(41 + 22)], [Vertex(42 - 22), Vertex(42 - 20), Vertex(42 + 20), Vertex(42 + 22)], [Vertex(43 - 22), Vertex(43 - 20), Vertex(43 + 20), Vertex(43 + 22)], [Vertex(44 - 22), Vertex(44 - 20), Vertex(44 + 20), Vertex(44 + 22)], [Vertex(45 - 22), Vertex(45 - 20), Vertex(45 + 20), Vertex(45 + 22)], [Vertex(46 - 22), Vertex(46 - 20), Vertex(46 + 20), Vertex(46 + 22)], [Vertex(47 - 22), Vertex(47 - 20), Vertex(47 + 20), Vertex(47 + 22)], [Vertex(48 - 22), Vertex(48 - 20), Vertex(48 + 20), Vertex(48 + 22)], [Vertex(49 - 22), Vertex(49 - 20), Vertex(49 + 20), Vertex(49 + 22)], [Vertex(50 - 22), Vertex(50 - 20), Vertex(50 + 20), Vertex(50 + 22)], [Vertex(51 - 22), Vertex(51 - 20), Vertex(51 + 20), Vertex(51 + 22)], [Vertex(52 - 22), Vertex(52 - 20), Vertex(52 + 20), Vertex(52 + 22)], [Vertex(53 - 22), Vertex(53 - 20), Vertex(53 + 20), Vertex(53 + 22)], [Vertex(54 - 22), Vertex(54 - 20), Vertex(54 + 20), Vertex(54 + 22)], [Vertex(55 - 22), Vertex(55 - 20), Vertex(55 + 20), Vertex(55 + 22)], [Vertex(56 - 22), Vertex(56 - 20), Vertex(56 + 20), Vertex(56 + 22)], [Vertex(57 - 22), Vertex(57 - 20), Vertex(57 + 20), Vertex(57 + 22)], [Vertex(58 - 22), Vertex(58 - 20), Vertex(58 + 20), Vertex(58 + 22)], [Vertex(59 - 22), Vertex(59 - 20), Vertex(59 + 20), Vertex(59 + 22)], [Vertex(60 - 22), Vertex(60 - 20), Vertex(60 + 20), Vertex(60 + 22)], [Vertex(61 - 22), Vertex(61 - 20), Vertex(61 + 20), Vertex(61 + 22)], [Vertex(62 - 22), Vertex(62 - 20), Vertex(62 + 20), Vertex(62 + 22)], [Vertex(63 - 22), Vertex(63 - 20), Vertex(63 + 20), Vertex(63 + 22)], [Vertex(64 - 22), Vertex(64 - 20), Vertex(64 + 20), Vertex(64 + 22)], [Vertex(65 - 22), Vertex(65 - 20), Vertex(65 + 20), Vertex(65 + 22)], [Vertex(66 - 22), Vertex(66 - 20), Vertex(66 + 20), Vertex(66 + 22)], [Vertex(67 - 22), Vertex(67 - 20), Vertex(67 + 20), Vertex(67 + 22)], [Vertex(68 - 22), Vertex(68 - 20), Vertex(68 + 20), Vertex(68 + 22)], [Vertex(69 - 22), Vertex(69 - 20), Vertex(69 + 20), Vertex(69 + 22)], [Vertex(70 - 22), Vertex(70 - 20), Vertex(70 + 20), Vertex(70 + 22)], [Vertex(71 - 22), Vertex(71 - 20), Vertex(71 + 20), Vertex(71 + 22)], [Vertex(72 - 22), Vertex(72 - 20), Vertex(72 + 20), Vertex(72 + 22)], [Vertex(73 - 22), Vertex(73 - 20), Vertex(73 + 20), Vertex(73 + 22)], [Vertex(74 - 22), Vertex(74 - 20), Vertex(74 + 20), Vertex(74 + 22)], [Vertex(75 - 22), Vertex(75 - 20), Vertex(75 + 20), Vertex(75 + 22)], [Vertex(76 - 22), Vertex(76 - 20), Vertex(76 + 20), Vertex(76 + 22)], [Vertex(77 - 22), Vertex(77 - 20), Vertex(77 + 20), Vertex(77 + 22)], [Vertex(78 - 22), Vertex(78 - 20), Vertex(78 + 20), Vertex(78 + 22)], [Vertex(79 - 22), Vertex(79 - 20), Vertex(79 + 20), Vertex(79 + 22)], [Vertex(80 - 22), Vertex(80 - 20), Vertex(80 + 20), Vertex(80 + 22)], [Vertex(81 - 22), Vertex(81 - 20), Vertex(81 + 20), Vertex(81 + 22)], [Vertex(82 - 22), Vertex(82 - 20), Vertex(82 + 20), Vertex(82 + 22)], [Vertex(83 - 22), Vertex(83 - 20), Vertex(83 + 20), Vertex(83 + 22)], [Vertex(84 - 22), Vertex(84 - 20), Vertex(84 + 20), Vertex(84 + 22)], [Vertex(85 - 22), Vertex(85 - 20), Vertex(85 + 20), Vertex(85 + 22)], [Vertex(86 - 22), Vertex(86 - 20), Vertex(86 + 20), Vertex(86 + 22)], [Vertex(87 - 22), Vertex(87 - 20), Vertex(87 + 20), Vertex(87 + 22)], [Vertex(88 - 22), Vertex(88 - 20), Vertex(88 + 20), Vertex(88 + 22)], [Vertex(89 - 22), Vertex(89 - 20), Vertex(89 + 20), Vertex(89 + 22)], [Vertex(90 - 22), Vertex(90 - 20), Vertex(90 + 20), Vertex(90 + 22)], [Vertex(91 - 22), Vertex(91 - 20), Vertex(91 + 20), Vertex(91 + 22)], [Vertex(92 - 22), Vertex(92 - 20), Vertex(92 + 20), Vertex(92 + 22)], [Vertex(93 - 22), Vertex(93 - 20), Vertex(93 + 20), Vertex(93 + 22)], [Vertex(94 - 22), Vertex(94 - 20), Vertex(94 + 20), Vertex(94 + 22)], [Vertex(95 - 22), Vertex(95 - 20), Vertex(95 + 20), Vertex(95 + 22)], [Vertex(96 - 22), Vertex(96 - 20), Vertex(96 + 20), Vertex(96 + 22)], [Vertex(97 - 22), Vertex(97 - 20), Vertex(97 + 20), Vertex(97 + 22)], [Vertex(98 - 22), Vertex(98 - 20), Vertex(98 + 20), Vertex(98 + 22)], [Vertex(99 - 22), Vertex(99 - 20), Vertex(99 + 20), Vertex(99 + 22)], [Vertex(100 - 22), Vertex(100 - 20), Vertex(100 + 20), Vertex(100 + 22)], [Vertex(101 - 22), Vertex(101 - 20), Vertex(101 + 20), Vertex(101 + 22)], [Vertex(102 - 22), Vertex(102 - 20), Vertex(102 + 20), Vertex(102 + 22)], [Vertex(103 - 22), Vertex(103 - 20), Vertex(103 + 20), Vertex(103 + 22)], [Vertex(104 - 22), Vertex(104 - 20), Vertex(104 + 20), Vertex(104 + 22)], [Vertex(105 - 22), Vertex(105 - 20), Vertex(105 + 20), Vertex(105 + 22)], [Vertex(106 - 22), Vertex(106 - 20), Vertex(106 + 20), Vertex(106 + 22)], [Vertex(107 - 22), Vertex(107 - 20), Vertex(107 + 20), Vertex(107 + 22)], [Vertex(108 - 22), Vertex(108 - 20), Vertex(108 + 20), Vertex(108 + 22)], [Vertex(109 - 22), Vertex(109 - 20), Vertex(109 + 20), Vertex(109 + 22)], [Vertex(110 - 22), Vertex(110 - 20), Vertex(110 + 20), Vertex(110 + 22)], [Vertex(111 - 22), Vertex(111 - 20), Vertex(111 + 20), Vertex(111 + 22)], [Vertex(112 - 22), Vertex(112 - 20), Vertex(112 + 20), Vertex(112 + 22)], [Vertex(113 - 22), Vertex(113 - 20), Vertex(113 + 20), Vertex(113 + 22)], [Vertex(114 - 22), Vertex(114 - 20), Vertex(114 + 20), Vertex(114 + 22)], [Vertex(115 - 22), Vertex(115 - 20), Vertex(115 + 20), Vertex(115 + 22)], [Vertex(116 - 22), Vertex(116 - 20), Vertex(116 + 20), Vertex(116 + 22)], [Vertex(117 - 22), Vertex(117 - 20), Vertex(117 + 20), Vertex(117 + 22)], [Vertex(118 - 22), Vertex(118 - 20), Vertex(118 + 20), Vertex(118 + 22)], [Vertex(119 - 22), Vertex(119 - 20), Vertex(119 + 20), Vertex(119 + 22)], [Vertex(120 - 22), Vertex(120 - 20), Vertex(120 + 20), Vertex(120 + 22)], [Vertex(121 - 22), Vertex(121 - 20), Vertex(121 + 20), Vertex(121 + 22)], [Vertex(122 - 22), Vertex(122 - 20), Vertex(122 + 20), Vertex(122 + 22)], [Vertex(123 - 22), Vertex(123 - 20), Vertex(123 + 20), Vertex(123 + 22)], [Vertex(124 - 22), Vertex(124 - 20), Vertex(124 + 20), Vertex(124 + 22)], [Vertex(125 - 22), Vertex(125 - 20), Vertex(125 + 20), Vertex(125 + 22)], [Vertex(126 - 22), Vertex(126 - 20), Vertex(126 + 20), Vertex(126 + 22)], [Vertex(127 - 22), Vertex(127 - 20), Vertex(127 + 20), Vertex(127 + 22)], [Vertex(128 - 22), Vertex(128 - 20), Vertex(128 + 20), Vertex(128 + 22)], [Vertex(129 - 22), Vertex(129 - 20), Vertex(129 + 20), Vertex(129 + 22)], [Vertex(130 - 22), Vertex(130 - 20), Vertex(130 + 20), Vertex(130 + 22)], [Vertex(131 - 22), Vertex(131 - 20), Vertex(131 + 20), Vertex(131 + 22)], [Vertex(132 - 22), Vertex(132 - 20), Vertex(132 + 20), Vertex(132 + 22)], [Vertex(133 - 22), Vertex(133 - 20), Vertex(133 + 20), Vertex(133 + 22)], [Vertex(134 - 22), Vertex(134 - 20), Vertex(134 + 20), Vertex(134 + 22)], [Vertex(135 - 22), Vertex(135 - 20), Vertex(135 + 20), Vertex(135 + 22)], [Vertex(136 - 22), Vertex(136 - 20), Vertex(136 + 20), Vertex(136 + 22)], [Vertex(137 - 22), Vertex(137 - 20), Vertex(137 + 20), Vertex(137 + 22)], [Vertex(138 - 22), Vertex(138 - 20), Vertex(138 + 20), Vertex(138 + 22)], [Vertex(139 - 22), Vertex(139 - 20), Vertex(139 + 20), Vertex(139 + 22)], [Vertex(140 - 22), Vertex(140 - 20), Vertex(140 + 20), Vertex(140 + 22)], [Vertex(141 - 22), Vertex(141 - 20), Vertex(141 + 20), Vertex(141 + 22)], [Vertex(142 - 22), Vertex(142 - 20), Vertex(142 + 20), Vertex(142 + 22)], [Vertex(143 - 22), Vertex(143 - 20), Vertex(143 + 20), Vertex(143 + 22)], [Vertex(144 - 22), Vertex(144 - 20), Vertex(144 + 20), Vertex(144 + 22)], [Vertex(145 - 22), Vertex(145 - 20), Vertex(145 + 20), Vertex(145 + 22)], [Vertex(146 - 22), Vertex(146 - 20), Vertex(146 + 20), Vertex(146 + 22)], [Vertex(147 - 22), Vertex(147 - 20), Vertex(147 + 20), Vertex(147 + 22)], [Vertex(148 - 22), Vertex(148 - 20), Vertex(148 + 20), Vertex(148 + 22)], [Vertex(149 - 22), Vertex(149 - 20), Vertex(149 + 20), Vertex(149 + 22)], [Vertex(150 - 22), Vertex(150 - 20), Vertex(150 + 20), Vertex(150 + 22)], [Vertex(151 - 22), Vertex(151 - 20), Vertex(151 + 20), Vertex(151 + 22)], [Vertex(152 - 22), Vertex(152 - 20), Vertex(152 + 20), Vertex(152 + 22)], [Vertex(153 - 22), Vertex(153 - 20), Vertex(153 + 20), Vertex(153 + 22)], [Vertex(154 - 22), Vertex(154 - 20), Vertex(154 + 20), Vertex(154 + 22)], [Vertex(155 - 22), Vertex(155 - 20), Vertex(155 + 20), Vertex(155 + 22)], [Vertex(156 - 22), Vertex(156 - 20), Vertex(156 + 20), Vertex(156 + 22)], [Vertex(157 - 22), Vertex(157 - 20), Vertex(157 + 20), Vertex(157 + 22)], [Vertex(158 - 22), Vertex(158 - 20), Vertex(158 + 20), Vertex(158 + 22)], [Vertex(159 - 22), Vertex(159 - 20), Vertex(159 + 20), Vertex(159 + 22)], [Vertex(160 - 22), Vertex(160 - 20), Vertex(160 + 20), Vertex(160 + 22)], [Vertex(161 - 22), Vertex(161 - 20), Vertex(161 + 20), Vertex(161 + 22)], [Vertex(162 - 22), Vertex(162 - 20), Vertex(162 + 20), Vertex(162 + 22)], [Vertex(163 - 22), Vertex(163 - 20), Vertex(163 + 20), Vertex(163 + 22)], [Vertex(164 - 22), Vertex(164 - 20), Vertex(164 + 20), Vertex(164 + 22)], [Vertex(165 - 22), Vertex(165 - 20), Vertex(165 + 20), Vertex(165 + 22)], [Vertex(166 - 22), Vertex(166 - 20), Vertex(166 + 20), Vertex(166 + 22)], [Vertex(167 - 22), Vertex(167 - 20), Vertex(167 + 20), Vertex(167 + 22)], [Vertex(168 - 22), Vertex(168 - 20), Vertex(168 + 20), Vertex(168 + 22)], [Vertex(169 - 22), Vertex(169 - 20), Vertex(169 + 20), Vertex(169 + 22)], [Vertex(170 - 22), Vertex(170 - 20), Vertex(170 + 20), Vertex(170 + 22)], [Vertex(171 - 22), Vertex(171 - 20), Vertex(171 + 20), Vertex(171 + 22)], [Vertex(172 - 22), Vertex(172 - 20), Vertex(172 + 20), Vertex(172 + 22)], [Vertex(173 - 22), Vertex(173 - 20), Vertex(173 + 20), Vertex(173 + 22)], [Vertex(174 - 22), Vertex(174 - 20), Vertex(174 + 20), Vertex(174 + 22)], [Vertex(175 - 22), Vertex(175 - 20), Vertex(175 + 20), Vertex(175 + 22)], [Vertex(176 - 22), Vertex(176 - 20), Vertex(176 + 20), Vertex(176 + 22)], [Vertex(177 - 22), Vertex(177 - 20), Vertex(177 + 20), Vertex(177 + 22)], [Vertex(178 - 22), Vertex(178 - 20), Vertex(178 + 20), Vertex(178 + 22)], [Vertex(179 - 22), Vertex(179 - 20), Vertex(179 + 20), Vertex(179 + 22)], [Vertex(180 - 22), Vertex(180 - 20), Vertex(180 + 20), Vertex(180 + 22)], [Vertex(181 - 22), Vertex(181 - 20), Vertex(181 + 20), Vertex(181 + 22)], [Vertex(182 - 22), Vertex(182 - 20), Vertex(182 + 20), Vertex(182 + 22)], [Vertex(183 - 22), Vertex(183 - 20), Vertex(183 + 20), Vertex(183 + 22)], [Vertex(184 - 22), Vertex(184 - 20), Vertex(184 + 20), Vertex(184 + 22)], [Vertex(185 - 22), Vertex(185 - 20), Vertex(185 + 20), Vertex(185 + 22)], [Vertex(186 - 22), Vertex(186 - 20), Vertex(186 + 20), Vertex(186 + 22)], [Vertex(187 - 22), Vertex(187 - 20), Vertex(187 + 20), Vertex(187 + 22)], [Vertex(188 - 22), Vertex(188 - 20), Vertex(188 + 20), Vertex(188 + 22)], [Vertex(189 - 22), Vertex(189 - 20), Vertex(189 + 20), Vertex(189 + 22)], [Vertex(190 - 22), Vertex(190 - 20), Vertex(190 + 20), Vertex(190 + 22)], [Vertex(191 - 22), Vertex(191 - 20), Vertex(191 + 20), Vertex(191 + 22)], [Vertex(192 - 22), Vertex(192 - 20), Vertex(192 + 20), Vertex(192 + 22)], [Vertex(193 - 22), Vertex(193 - 20), Vertex(193 + 20), Vertex(193 + 22)], [Vertex(194 - 22), Vertex(194 - 20), Vertex(194 + 20), Vertex(194 + 22)], [Vertex(195 - 22), Vertex(195 - 20), Vertex(195 + 20), Vertex(195 + 22)], [Vertex(196 - 22), Vertex(196 - 20), Vertex(196 + 20), Vertex(196 + 22)], [Vertex(197 - 22), Vertex(197 - 20), Vertex(197 + 20), Vertex(197 + 22)], [Vertex(198 - 22), Vertex(198 - 20), Vertex(198 + 20), Vertex(198 + 22)], [Vertex(199 - 22), Vertex(199 - 20), Vertex(199 + 20), Vertex(199 + 22)], [Vertex(200 - 22), Vertex(200 - 20), Vertex(200 + 20), Vertex(200 + 22)], [Vertex(201 - 22), Vertex(201 - 20), Vertex(201 + 20), Vertex(201 + 22)], [Vertex(202 - 22), Vertex(202 - 20), Vertex(202 + 20), Vertex(202 + 22)], [Vertex(203 - 22), Vertex(203 - 20), Vertex(203 + 20), Vertex(203 + 22)], [Vertex(204 - 22), Vertex(204 - 20), Vertex(204 + 20), Vertex(204 + 22)], [Vertex(205 - 22), Vertex(205 - 20), Vertex(205 + 20), Vertex(205 + 22)], [Vertex(206 - 22), Vertex(206 - 20), Vertex(206 + 20), Vertex(206 + 22)], [Vertex(207 - 22), Vertex(207 - 20), Vertex(207 + 20), Vertex(207 + 22)], [Vertex(208 - 22), Vertex(208 - 20), Vertex(208 + 20), Vertex(208 + 22)], [Vertex(209 - 22), Vertex(209 - 20), Vertex(209 + 20), Vertex(209 + 22)], [Vertex(210 - 22), Vertex(210 - 20), Vertex(210 + 20), Vertex(210 + 22)], [Vertex(211 - 22), Vertex(211 - 20), Vertex(211 + 20), Vertex(211 + 22)], [Vertex(212 - 22), Vertex(212 - 20), Vertex(212 + 20), Vertex(212 + 22)], [Vertex(213 - 22), Vertex(213 - 20), Vertex(213 + 20), Vertex(213 + 22)], [Vertex(214 - 22), Vertex(214 - 20), Vertex(214 + 20), Vertex(214 + 22)], [Vertex(215 - 22), Vertex(215 - 20), Vertex(215 + 20), Vertex(215 + 22)], [Vertex(216 - 22), Vertex(216 - 20), Vertex(216 + 20), Vertex(216 + 22)], [Vertex(217 - 22), Vertex(217 - 20), Vertex(217 + 20), Vertex(217 + 22)], [Vertex(218 - 22), Vertex(218 - 20), Vertex(218 + 20), Vertex(218 + 22)], [Vertex(219 - 22), Vertex(219 - 20), Vertex(219 + 20), Vertex(219 + 22)], [Vertex(220 - 22), Vertex(220 - 20), Vertex(220 + 20), Vertex(220 + 22)], [Vertex(221 - 22), Vertex(221 - 20), Vertex(221 + 20), Vertex(221 + 22)], [Vertex(222 - 22), Vertex(222 - 20), Vertex(222 + 20), Vertex(222 + 22)], [Vertex(223 - 22), Vertex(223 - 20), Vertex(223 + 20), Vertex(223 + 22)], [Vertex(224 - 22), Vertex(224 - 20), Vertex(224 + 20), Vertex(224 + 22)], [Vertex(225 - 22), Vertex(225 - 20), Vertex(225 + 20), Vertex(225 + 22)], [Vertex(226 - 22), Vertex(226 - 20), Vertex(226 + 20), Vertex(226 + 22)], [Vertex(227 - 22), Vertex(227 - 20), Vertex(227 + 20), Vertex(227 + 22)], [Vertex(228 - 22), Vertex(228 - 20), Vertex(228 + 20), Vertex(228 + 22)], [Vertex(229 - 22), Vertex(229 - 20), Vertex(229 + 20), Vertex(229 + 22)], [Vertex(230 - 22), Vertex(230 - 20), Vertex(230 + 20), Vertex(230 + 22)], [Vertex(231 - 22), Vertex(231 - 20), Vertex(231 + 20), Vertex(231 + 22)], [Vertex(232 - 22), Vertex(232 - 20), Vertex(232 + 20), Vertex(232 + 22)], [Vertex(233 - 22), Vertex(233 - 20), Vertex(233 + 20), Vertex(233 + 22)], [Vertex(234 - 22), Vertex(234 - 20), Vertex(234 + 20), Vertex(234 + 22)], [Vertex(235 - 22), Vertex(235 - 20), Vertex(235 + 20), Vertex(235 + 22)], [Vertex(236 - 22), Vertex(236 - 20), Vertex(236 + 20), Vertex(236 + 22)], [Vertex(237 - 22), Vertex(237 - 20), Vertex(237 + 20), Vertex(237 + 22)], [Vertex(238 - 22), Vertex(238 - 20), Vertex(238 + 20), Vertex(238 + 22)], [Vertex(239 - 22), Vertex(239 - 20), Vertex(239 + 20), Vertex(239 + 22)], [Vertex(240 - 22), Vertex(240 - 20), Vertex(240 + 20), Vertex(240 + 22)], [Vertex(241 - 22), Vertex(241 - 20), Vertex(241 + 20), Vertex(241 + 22)], [Vertex(242 - 22), Vertex(242 - 20), Vertex(242 + 20), Vertex(242 + 22)], [Vertex(243 - 22), Vertex(243 - 20), Vertex(243 + 20), Vertex(243 + 22)], [Vertex(244 - 22), Vertex(244 - 20), Vertex(244 + 20), Vertex(244 + 22)], [Vertex(245 - 22), Vertex(245 - 20), Vertex(245 + 20), Vertex(245 + 22)], [Vertex(246 - 22), Vertex(246 - 20), Vertex(246 + 20), Vertex(246 + 22)], [Vertex(247 - 22), Vertex(247 - 20), Vertex(247 + 20), Vertex(247 + 22)], [Vertex(248 - 22), Vertex(248 - 20), Vertex(248 + 20), Vertex(248 + 22)], [Vertex(249 - 22), Vertex(249 - 20), Vertex(249 + 20), Vertex(249 + 22)], [Vertex(250 - 22), Vertex(250 - 20), Vertex(250 + 20), Vertex(250 + 22)], [Vertex(251 - 22), Vertex(251 - 20), Vertex(251 + 20), Vertex(251 + 22)], [Vertex(252 - 22), Vertex(252 - 20), Vertex(252 + 20), Vertex(252 + 22)], [Vertex(253 - 22), Vertex(253 - 20), Vertex(253 + 20), Vertex(253 + 22)], [Vertex(254 - 22), Vertex(254 - 20), Vertex(254 + 20), Vertex(254 + 22)], [Vertex(255 - 22), Vertex(255 - 20), Vertex(255 + 20), Vertex(255 + 22)], [Vertex(256 - 22), Vertex(256 - 20), Vertex(256 + 20), Vertex(256 + 22)], [Vertex(257 - 22), Vertex(257 - 20), Vertex(257 + 20), Vertex(257 + 22)], [Vertex(258 - 22), Vertex(258 - 20), Vertex(258 + 20), Vertex(258 + 22)], [Vertex(259 - 22), Vertex(259 - 20), Vertex(259 + 20), Vertex(259 + 22)], [Vertex(260 - 22), Vertex(260 - 20), Vertex(260 + 20), Vertex(260 + 22)], [Vertex(261 - 22), Vertex(261 - 20), Vertex(261 + 20), Vertex(261 + 22)], [Vertex(262 - 22), Vertex(262 - 20), Vertex(262 + 20), Vertex(262 + 22)], [Vertex(263 - 22), Vertex(263 - 20), Vertex(263 + 20), Vertex(263 + 22)], [Vertex(264 - 22), Vertex(264 - 20), Vertex(264 + 20), Vertex(264 + 22)], [Vertex(265 - 22), Vertex(265 - 20), Vertex(265 + 20), Vertex(265 + 22)], [Vertex(266 - 22), Vertex(266 - 20), Vertex(266 + 20), Vertex(266 + 22)], [Vertex(267 - 22), Vertex(267 - 20), Vertex(267 + 20), Vertex(267 + 22)], [Vertex(268 - 22), Vertex(268 - 20), Vertex(268 + 20), Vertex(268 + 22)], [Vertex(269 - 22), Vertex(269 - 20), Vertex(269 + 20), Vertex(269 + 22)], [Vertex(270 - 22), Vertex(270 - 20), Vertex(270 + 20), Vertex(270 + 22)], [Vertex(271 - 22), Vertex(271 - 20), Vertex(271 + 20), Vertex(271 + 22)], [Vertex(272 - 22), Vertex(272 - 20), Vertex(272 + 20), Vertex(272 + 22)], [Vertex(273 - 22), Vertex(273 - 20), Vertex(273 + 20), Vertex(273 + 22)], [Vertex(274 - 22), Vertex(274 - 20), Vertex(274 + 20), Vertex(274 + 22)], [Vertex(275 - 22), Vertex(275 - 20), Vertex(275 + 20), Vertex(275 + 22)], [Vertex(276 - 22), Vertex(276 - 20), Vertex(276 + 20), Vertex(276 + 22)], [Vertex(277 - 22), Vertex(277 - 20), Vertex(277 + 20), Vertex(277 + 22)], [Vertex(278 - 22), Vertex(278 - 20), Vertex(278 + 20), Vertex(278 + 22)], [Vertex(279 - 22), Vertex(279 - 20), Vertex(279 + 20), Vertex(279 + 22)], [Vertex(280 - 22), Vertex(280 - 20), Vertex(280 + 20), Vertex(280 + 22)], [Vertex(281 - 22), Vertex(281 - 20), Vertex(281 + 20), Vertex(281 + 22)], [Vertex(282 - 22), Vertex(282 - 20), Vertex(282 + 20), Vertex(282 + 22)], [Vertex(283 - 22), Vertex(283 - 20), Vertex(283 + 20), Vertex(283 + 22)], [Vertex(284 - 22), Vertex(284 - 20), Vertex(284 + 20), Vertex(284 + 22)], [Vertex(285 - 22), Vertex(285 - 20), Vertex(285 + 20), Vertex(285 + 22)], [Vertex(286 - 22), Vertex(286 - 20), Vertex(286 + 20), Vertex(286 + 22)], [Vertex(287 - 22), Vertex(287 - 20), Vertex(287 + 20), Vertex(287 + 22)], [Vertex(288 - 22), Vertex(288 - 20), Vertex(288 + 20), Vertex(288 + 22)], [Vertex(289 - 22), Vertex(289 - 20), Vertex(289 + 20), Vertex(289 + 22)], [Vertex(290 - 22), Vertex(290 - 20), Vertex(290 + 20), Vertex(290 + 22)], [Vertex(291 - 22), Vertex(291 - 20), Vertex(291 + 20), Vertex(291 + 22)], [Vertex(292 - 22), Vertex(292 - 20), Vertex(292 + 20), Vertex(292 + 22)], [Vertex(293 - 22), Vertex(293 - 20), Vertex(293 + 20), Vertex(293 + 22)], [Vertex(294 - 22), Vertex(294 - 20), Vertex(294 + 20), Vertex(294 + 22)], [Vertex(295 - 22), Vertex(295 - 20), Vertex(295 + 20), Vertex(295 + 22)], [Vertex(296 - 22), Vertex(296 - 20), Vertex(296 + 20), Vertex(296 + 22)], [Vertex(297 - 22), Vertex(297 - 20), Vertex(297 + 20), Vertex(297 + 22)], [Vertex(298 - 22), Vertex(298 - 20), Vertex(298 + 20), Vertex(298 + 22)], [Vertex(299 - 22), Vertex(299 - 20), Vertex(299 + 20), Vertex(299 + 22)], [Vertex(300 - 22), Vertex(300 - 20), Vertex(300 + 20), Vertex(300 + 22)], [Vertex(301 - 22), Vertex(301 - 20), Vertex(301 + 20), Vertex(301 + 22)], [Vertex(302 - 22), Vertex(302 - 20), Vertex(302 + 20), Vertex(302 + 22)], [Vertex(303 - 22), Vertex(303 - 20), Vertex(303 + 20), Vertex(303 + 22)], [Vertex(304 - 22), Vertex(304 - 20), Vertex(304 + 20), Vertex(304 + 22)], [Vertex(305 - 22), Vertex(305 - 20), Vertex(305 + 20), Vertex(305 + 22)], [Vertex(306 - 22), Vertex(306 - 20), Vertex(306 + 20), Vertex(306 + 22)], [Vertex(307 - 22), Vertex(307 - 20), Vertex(307 + 20), Vertex(307 + 22)], [Vertex(308 - 22), Vertex(308 - 20), Vertex(308 + 20), Vertex(308 + 22)], [Vertex(309 - 22), Vertex(309 - 20), Vertex(309 + 20), Vertex(309 + 22)], [Vertex(310 - 22), Vertex(310 - 20), Vertex(310 + 20), Vertex(310 + 22)], [Vertex(311 - 22), Vertex(311 - 20), Vertex(311 + 20), Vertex(311 + 22)], [Vertex(312 - 22), Vertex(312 - 20), Vertex(312 + 20), Vertex(312 + 22)], [Vertex(313 - 22), Vertex(313 - 20), Vertex(313 + 20), Vertex(313 + 22)], [Vertex(314 - 22), Vertex(314 - 20), Vertex(314 + 20), Vertex(314 + 22)], [Vertex(315 - 22), Vertex(315 - 20), Vertex(315 + 20), Vertex(315 + 22)], [Vertex(316 - 22), Vertex(316 - 20), Vertex(316 + 20), Vertex(316 + 22)], [Vertex(317 - 22), Vertex(317 - 20), Vertex(317 + 20), Vertex(317 + 22)], [Vertex(318 - 22), Vertex(318 - 20), Vertex(318 + 20), Vertex(318 + 22)], [Vertex(319 - 22), Vertex(319 - 20), Vertex(319 + 20), Vertex(319 + 22)], [Vertex(320 - 22), Vertex(320 - 20), Vertex(320 + 20), Vertex(320 + 22)], [Vertex(321 - 22), Vertex(321 - 20), Vertex(321 + 20), Vertex(321 + 22)], [Vertex(322 - 22), Vertex(322 - 20), Vertex(322 + 20), Vertex(322 + 22)], [Vertex(323 - 22), Vertex(323 - 20), Vertex(323 + 20), Vertex(323 + 22)], [Vertex(324 - 22), Vertex(324 - 20), Vertex(324 + 20), Vertex(324 + 22)], [Vertex(325 - 22), Vertex(325 - 20), Vertex(325 + 20), Vertex(325 + 22)], [Vertex(326 - 22), Vertex(326 - 20), Vertex(326 + 20), Vertex(326 + 22)], [Vertex(327 - 22), Vertex(327 - 20), Vertex(327 + 20), Vertex(327 + 22)], [Vertex(328 - 22), Vertex(328 - 20), Vertex(328 + 20), Vertex(328 + 22)], [Vertex(329 - 22), Vertex(329 - 20), Vertex(329 + 20), Vertex(329 + 22)], [Vertex(330 - 22), Vertex(330 - 20), Vertex(330 + 20), Vertex(330 + 22)], [Vertex(331 - 22), Vertex(331 - 20), Vertex(331 + 20), Vertex(331 + 22)], [Vertex(332 - 22), Vertex(332 - 20), Vertex(332 + 20), Vertex(332 + 22)], [Vertex(333 - 22), Vertex(333 - 20), Vertex(333 + 20), Vertex(333 + 22)], [Vertex(334 - 22), Vertex(334 - 20), Vertex(334 + 20), Vertex(334 + 22)], [Vertex(335 - 22), Vertex(335 - 20), Vertex(335 + 20), Vertex(335 + 22)], [Vertex(336 - 22), Vertex(336 - 20), Vertex(336 + 20), Vertex(336 + 22)], [Vertex(337 - 22), Vertex(337 - 20), Vertex(337 + 20), Vertex(337 + 22)], [Vertex(338 - 22), Vertex(338 - 20), Vertex(338 + 20), Vertex(338 + 22)], [Vertex(339 - 22), Vertex(339 - 20), Vertex(339 + 20), Vertex(339 + 22)], [Vertex(340 - 22), Vertex(340 - 20), Vertex(340 + 20), Vertex(340 + 22)], [Vertex(341 - 22), Vertex(341 - 20), Vertex(341 + 20), Vertex(341 + 22)], [Vertex(342 - 22), Vertex(342 - 20), Vertex(342 + 20), Vertex(342 + 22)], [Vertex(343 - 22), Vertex(343 - 20), Vertex(343 + 20), Vertex(343 + 22)], [Vertex(344 - 22), Vertex(344 - 20), Vertex(344 + 20), Vertex(344 + 22)], [Vertex(345 - 22), Vertex(345 - 20), Vertex(345 + 20), Vertex(345 + 22)], [Vertex(346 - 22), Vertex(346 - 20), Vertex(346 + 20), Vertex(346 + 22)], [Vertex(347 - 22), Vertex(347 - 20), Vertex(347 + 20), Vertex(347 + 22)], [Vertex(348 - 22), Vertex(348 - 20), Vertex(348 + 20), Vertex(348 + 22)], [Vertex(349 - 22), Vertex(349 - 20), Vertex(349 + 20), Vertex(349 + 22)], [Vertex(350 - 22), Vertex(350 - 20), Vertex(350 + 20), Vertex(350 + 22)], [Vertex(351 - 22), Vertex(351 - 20), Vertex(351 + 20), Vertex(351 + 22)], [Vertex(352 - 22), Vertex(352 - 20), Vertex(352 + 20), Vertex(352 + 22)], [Vertex(353 - 22), Vertex(353 - 20), Vertex(353 + 20), Vertex(353 + 22)], [Vertex(354 - 22), Vertex(354 - 20), Vertex(354 + 20), Vertex(354 + 22)], [Vertex(355 - 22), Vertex(355 - 20), Vertex(355 + 20), Vertex(355 + 22)], [Vertex(356 - 22), Vertex(356 - 20), Vertex(356 + 20), Vertex(356 + 22)], [Vertex(357 - 22), Vertex(357 - 20), Vertex(357 + 20), Vertex(357 + 22)], [Vertex(358 - 22), Vertex(358 - 20), Vertex(358 + 20), Vertex(358 + 22)], [Vertex(359 - 22), Vertex(359 - 20), Vertex(359 + 20), Vertex(359 + 22)], [Vertex(360 - 22), Vertex(360 - 20), Vertex(360 + 20), Vertex(360 + 22)], [Vertex(361 - 22), Vertex(361 - 20), Vertex(361 + 20), Vertex(361 + 22)], [Vertex(362 - 22), Vertex(362 - 20), Vertex(362 + 20), Vertex(362 + 22)], [Vertex(363 - 22), Vertex(363 - 20), Vertex(363 + 20), Vertex(363 + 22)], [Vertex(364 - 22), Vertex(364 - 20), Vertex(364 + 20), Vertex(364 + 22)], [Vertex(365 - 22), Vertex(365 - 20), Vertex(365 + 20), Vertex(365 + 22)], [Vertex(366 - 22), Vertex(366 - 20), Vertex(366 + 20), Vertex(366 + 22)], [Vertex(367 - 22), Vertex(367 - 20), Vertex(367 + 20), Vertex(367 + 22)], [Vertex(368 - 22), Vertex(368 - 20), Vertex(368 + 20), Vertex(368 + 22)], [Vertex(369 - 22), Vertex(369 - 20), Vertex(369 + 20), Vertex(369 + 22)], [Vertex(370 - 22), Vertex(370 - 20), Vertex(370 + 20), Vertex(370 + 22)], [Vertex(371 - 22), Vertex(371 - 20), Vertex(371 + 20), Vertex(371 + 22)], [Vertex(372 - 22), Vertex(372 - 20), Vertex(372 + 20), Vertex(372 + 22)], [Vertex(373 - 22), Vertex(373 - 20), Vertex(373 + 20), Vertex(373 + 22)], [Vertex(374 - 22), Vertex(374 - 20), Vertex(374 + 20), Vertex(374 + 22)], [Vertex(375 - 22), Vertex(375 - 20), Vertex(375 + 20), Vertex(375 + 22)], [Vertex(376 - 22), Vertex(376 - 20), Vertex(376 + 20), Vertex(376 + 22)], [Vertex(377 - 22), Vertex(377 - 20), Vertex(377 + 20), Vertex(377 + 22)], [Vertex(378 - 22), Vertex(378 - 20), Vertex(378 + 20), Vertex(378 + 22)], [Vertex(379 - 22), Vertex(379 - 20), Vertex(379 + 20), Vertex(379 + 22)], [Vertex(380 - 22), Vertex(380 - 20), Vertex(380 + 20), Vertex(380 + 22)], [Vertex(381 - 22), Vertex(381 - 20), Vertex(381 + 20), Vertex(381 + 22)], [Vertex(382 - 22), Vertex(382 - 20), Vertex(382 + 20), Vertex(382 + 22)], [Vertex(383 - 22), Vertex(383 - 20), Vertex(383 + 20), Vertex(383 + 22)], [Vertex(384 - 22), Vertex(384 - 20), Vertex(384 + 20), Vertex(384 + 22)], [Vertex(385 - 22), Vertex(385 - 20), Vertex(385 + 20), Vertex(385 + 22)], [Vertex(386 - 22), Vertex(386 - 20), Vertex(386 + 20), Vertex(386 + 22)], [Vertex(387 - 22), Vertex(387 - 20), Vertex(387 + 20), Vertex(387 + 22)], [Vertex(388 - 22), Vertex(388 - 20), Vertex(388 + 20), Vertex(388 + 22)], [Vertex(389 - 22), Vertex(389 - 20), Vertex(389 + 20), Vertex(389 + 22)], [Vertex(390 - 22), Vertex(390 - 20), Vertex(390 + 20), Vertex(390 + 22)], [Vertex(391 - 22), Vertex(391 - 20), Vertex(391 + 20), Vertex(391 + 22)], [Vertex(392 - 22), Vertex(392 - 20), Vertex(392 + 20), Vertex(392 + 22)], [Vertex(393 - 22), Vertex(393 - 20), Vertex(393 + 20), Vertex(393 + 22)], [Vertex(394 - 22), Vertex(394 - 20), Vertex(394 + 20), Vertex(394 + 22)], [Vertex(395 - 22), Vertex(395 - 20), Vertex(395 + 20), Vertex(395 + 22)], [Vertex(396 - 22), Vertex(396 - 20), Vertex(396 + 20), Vertex(396 + 22)], [Vertex(397 - 22), Vertex(397 - 20), Vertex(397 + 20), Vertex(397 + 22)], [Vertex(398 - 22), Vertex(398 - 20), Vertex(398 + 20), Vertex(398 + 22)], [Vertex(399 - 22), Vertex(399 - 20), Vertex(399 + 20), Vertex(399 + 22)], [Vertex(400 - 22), Vertex(400 - 20), Vertex(400 + 20), Vertex(400 + 22)], [Vertex(401 - 22), Vertex(401 - 20), Vertex(401 + 20), Vertex(401 + 22)], [Vertex(402 - 22), Vertex(402 - 20), Vertex(402 + 20), Vertex(402 + 22)], [Vertex(403 - 22), Vertex(403 - 20), Vertex(403 + 20), Vertex(403 + 22)], [Vertex(404 - 22), Vertex(404 - 20), Vertex(404 + 20), Vertex(404 + 22)], [Vertex(405 - 22), Vertex(405 - 20), Vertex(405 + 20), Vertex(405 + 22)], [Vertex(406 - 22), Vertex(406 - 20), Vertex(406 + 20), Vertex(406 + 22)], [Vertex(407 - 22), Vertex(407 - 20), Vertex(407 + 20), Vertex(407 + 22)], [Vertex(408 - 22), Vertex(408 - 20), Vertex(408 + 20), Vertex(408 + 22)], [Vertex(409 - 22), Vertex(409 - 20), Vertex(409 + 20), Vertex(409 + 22)], [Vertex(410 - 22), Vertex(410 - 20), Vertex(410 + 20), Vertex(410 + 22)], [Vertex(411 - 22), Vertex(411 - 20), Vertex(411 + 20), Vertex(411 + 22)], [Vertex(412 - 22), Vertex(412 - 20), Vertex(412 + 20), Vertex(412 + 22)], [Vertex(413 - 22), Vertex(413 - 20), Vertex(413 + 20), Vertex(413 + 22)], [Vertex(414 - 22), Vertex(414 - 20), Vertex(414 + 20), Vertex(414 + 22)], [Vertex(415 - 22), Vertex(415 - 20), Vertex(415 + 20), Vertex(415 + 22)], [Vertex(416 - 22), Vertex(416 - 20), Vertex(416 + 20), Vertex(416 + 22)], [Vertex(417 - 22), Vertex(417 - 20), Vertex(417 + 20), Vertex(417 + 22)], [Vertex(418 - 22), Vertex(418 - 20), Vertex(418 + 20), Vertex(418 + 22)], [Vertex(419 - 22), Vertex(419 - 20), Vertex(419 + 20), Vertex(419 + 22)], [Vertex(420 - 22), Vertex(420 - 20), Vertex(420 + 20), Vertex(420 + 22)], [Vertex(421 - 22), Vertex(421 - 20), Vertex(421 + 20), Vertex(421 + 22)], [Vertex(422 - 22), Vertex(422 - 20), Vertex(422 + 20), Vertex(422 + 22)], [Vertex(423 - 22), Vertex(423 - 20), Vertex(423 + 20), Vertex(423 + 22)], [Vertex(424 - 22), Vertex(424 - 20), Vertex(424 + 20), Vertex(424 + 22)], [Vertex(425 - 22), Vertex(425 - 20), Vertex(425 + 20), Vertex(425 + 22)], [Vertex(426 - 22), Vertex(426 - 20), Vertex(426 + 20), Vertex(426 + 22)], [Vertex(427 - 22), Vertex(427 - 20), Vertex(427 + 20), Vertex(427 + 22)], [Vertex(428 - 22), Vertex(428 - 20), Vertex(428 + 20), Vertex(428 + 22)], [Vertex(429 - 22), Vertex(429 - 20), Vertex(429 + 20), Vertex(429 + 22)], [Vertex(430 - 22), Vertex(430 - 20), Vertex(430 + 20), Vertex(430 + 22)], [Vertex(431 - 22), Vertex(431 - 20), Vertex(431 + 20), Vertex(431 + 22)], [Vertex(432 - 22), Vertex(432 - 20), Vertex(432 + 20), Vertex(432 + 22)], [Vertex(433 - 22), Vertex(433 - 20), Vertex(433 + 20), Vertex(433 + 22)], [Vertex(434 - 22), Vertex(434 - 20), Vertex(434 + 20), Vertex(434 + 22)], [Vertex(435 - 22), Vertex(435 - 20), Vertex(435 + 20), Vertex(435 + 22)], [Vertex(436 - 22), Vertex(436 - 20), Vertex(436 + 20), Vertex(436 + 22)], [Vertex(437 - 22), Vertex(437 - 20), Vertex(437 + 20), Vertex(437 + 22)], [Vertex(438 - 22), Vertex(438 - 20), Vertex(438 + 20), Vertex(438 + 22)], [Vertex(439 - 22), Vertex(439 - 20), Vertex(439 + 20), Vertex(439 + 22)], [Vertex(440 - 22), Vertex(440 - 20), Vertex(440 + 20), Vertex(440 + 22)] ];
use proc_macro2::TokenTree; use std::env; use std::ffi::OsStr; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use syn::{ visit::{self, Visit}, Macro, }; use walkdir::WalkDir; fn main() { // Parse all .rs files to collect everything which implements Command. // This code won't work properly with lib.rs or mod.rs. let mut data = Data::new(); for entry in WalkDir::new("src").into_iter() .filter_map(|e| e.ok()) .filter(|e| !e.file_type().is_dir()) .filter(|e| e.path().extension() == Some(OsStr::new("rs"))) { let mut path = String::new(); for name in entry.path().with_extension("").iter().skip(1) { path.push_str(&format!("::{}", name.to_str().unwrap())); } let entry_data = get_data(entry.path()); data.commands.extend(entry_data.commands .into_iter() .map(|c| format!("crate{}::{}", &path, c))); data.cvars.extend(entry_data.cvars .into_iter() .map(|c| format!("crate{}::{}", &path, c))); } let command_array = make_command_array(data.commands); let cvar_array = make_cvar_array(data.cvars); let out_dir = env::var("OUT_DIR").unwrap(); let dest_path = Path::new(&out_dir).join("command_array.rs"); let mut f = File::create(&dest_path).unwrap(); write!(f, "{}", command_array).unwrap(); let dest_path = Path::new(&out_dir).join("cvar_array.rs"); let mut f = File::create(&dest_path).unwrap(); write!(f, "{}", cvar_array).unwrap(); } struct Data { commands: Vec<String>, cvars: Vec<String>, } impl Data { fn new() -> Self { Self { commands: Vec::new(), cvars: Vec::new() } } } fn get_data(path: &Path) -> Data { let mut source = String::new(); File::open(path).unwrap() .read_to_string(&mut source) .unwrap(); if let Ok(file) = syn::parse_file(&source) { let mut visitor = MyVisitor::new(); visitor.visit_file(&file); Data { commands: visitor.commands, cvars: visitor.cvars } } else { Data::new() } } fn make_command_array(commands: Vec<String>) -> String { let mut buf = format!("pub const COMMANDS: [&Command; {}] = [", commands.len()); let mut iter = commands.into_iter(); if let Some(first) = iter.next() { buf.push_str(&format!("&{}", first)); } for command in iter { buf.push_str(&format!(", &{}", command)); } buf.push_str("];"); buf } fn make_cvar_array(cvars: Vec<String>) -> String { let mut buf = format!("pub static CVARS: [&crate::cvar::CVar; {}] = [", cvars.len()); let mut iter = cvars.into_iter(); if let Some(first) = iter.next() { buf.push_str(&format!("&{}", first)); } for cvar in iter { buf.push_str(&format!(", &{}", cvar)); } buf.push_str("];"); buf } struct MyVisitor { commands: Vec<String>, cvars: Vec<String>, } impl MyVisitor { fn new() -> Self { Self { commands: Vec::new(), cvars: Vec::new() } } } impl<'ast> Visit<'ast> for MyVisitor { fn visit_macro(&mut self, mac: &'ast Macro) { if mac.path .segments .first() .map(|x| x.value().ident == "command") .unwrap_or(false) { if let Some(TokenTree::Ident(ident)) = mac.tts.clone().into_iter().next() { self.commands.push(format!("{}", ident)); } } if mac.path .segments .first() .map(|x| x.value().ident == "cvar") .unwrap_or(false) { if let Some(TokenTree::Ident(ident)) = mac.tts.clone().into_iter().next() { self.cvars.push(format!("{}", ident)); } } visit::visit_macro(self, mac); } }
use std::ops::Range; fn main() { let input = include_str!("./input.txt").lines().next().unwrap(); //let input = include_str!("./input_test.txt").lines().next().unwrap(); let mut phase: Vec<isize> = input.chars().map(|c| c.to_digit(10).unwrap() as isize).collect(); let pattern: Vec<isize> = vec![0,1,0,-1]; let offset = input[0..7].parse::<usize>().unwrap(); for _ in 1..10_000 { for i in 0..input.len() { phase.push(phase[i]); } } //println!("{:?}", phase); println!("{:?}", offset); let mut phase2 = &mut phase[offset..]; for _ in 0..100 { for i in (0..phase2.len()).rev() { let prev = if (i+1) == phase2.len() { 0 } else { phase2[i + 1] }; phase2[i] = (prev + phase2[i]).abs() % 10; } } for i in 0..8 { println!("{}", phase2[i]); } } fn fft(input: &Vec<isize>, base_pattern: &Vec<isize>) -> Vec<isize> { let mut output = vec![0; input.len()]; let mut lines: Vec<String> = Vec::new(); for idx in 0..input.len() { let mut s: Vec<String> = Vec::new(); let base = idx + 1; let mut prev_base = 0; let mut ranges: Vec<Range<usize>> = Vec::new(); for i in 0..(input.len() / base) { let start = prev_base + i*base; let end = (i*base) + prev_base; prev_base = end; ranges.push(Range { start, end }); } let r = input.iter().enumerate().fold(0, |acc, (i, &item)| { let p = (i+1) / (idx + 1); let modifier = base_pattern[p % base_pattern.len()]; s.push(format!("{}*{}", item, modifier)); acc + (item * modifier) }).abs() % 10; output[idx] = r; } output }
#[doc = "Reader of register CPT2CR"] pub type R = crate::R<u32, super::CPT2CR>; #[doc = "Reader of field `CPT2x`"] pub type CPT2X_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Timerx Capture 2 value"] #[inline(always)] pub fn cpt2x(&self) -> CPT2X_R { CPT2X_R::new((self.bits & 0xffff) as u16) } }
use crate::token::*; use std::fmt; #[derive(Debug, Eq, Hash, PartialEq, Clone)] pub enum Statement { Let { token: Token, identifier: Token, value: Expression, }, Return { token: Token, return_value: Expression, }, Expression { token: Token, expression: Expression, }, Block { token: Token, // Token::LBracket { statements: Vec<Statement>, }, } impl fmt::Display for Statement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Statement::Expression { token: _, expression, } => write!(f, "{}", expression), Statement::Let { token, identifier, value, } => write!(f, "{} {} = {};", token, identifier, value), Statement::Return { token, return_value, } => write!(f, "{} {};", token, return_value), Statement::Block { token: _, statements, } => { let s = statements .iter() .fold(String::new(), |acc, x| acc + format!("{}", x).as_str()); write!(f, "{}", s) } } } } #[derive(Debug, Eq, Hash, PartialEq, Clone)] pub enum Expression { Identifier(Token), IntegerLiteral { token: Token, value: i64, }, Prefix { operator: Token, right: Box<Expression>, }, Infix { operator: Token, left: Box<Expression>, right: Box<Expression>, }, Boolean { token: Token, value: bool, }, If { token: Token, // Token::If condition: Box<Expression>, consequence: Box<Statement>, // Statement::Block alternative: Option<Box<Statement>>, // Statement::Block }, FunctionLiteral { token: Token, // Token::FUNCTION parameters: Vec<Expression>, // Vec<Expression::Identifier> body: Box<Statement>, // Statement::Block }, Call { token: Token, // Token::LPAREN ( function: Box<Expression>, // Expression::Identifier | Expression::FunctionLiteral arguments: Vec<Expression>, }, StringLiteral { token: Token, }, } impl fmt::Display for Expression { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Expression::Identifier(token) => write!(f, "{}", token), Expression::IntegerLiteral { token: _, value } => write!(f, "{}", value), Expression::Prefix { operator, right } => write!(f, "({}{})", operator, right), Expression::Infix { operator, left, right, } => write!(f, "({} {} {})", left, operator, right), Expression::Boolean { token: _, value } => write!(f, "{}", value), Expression::If { token, condition, consequence, alternative, } => { let alt_txt = match alternative { Some(b) => format!("{}", **b), _ => String::new(), }; write!(f, "{}{} {}else {}", token, condition, consequence, alt_txt) } Expression::FunctionLiteral { token, parameters, body, } => { let mut parameter_list = String::new(); for (i, e) in parameters.iter().enumerate() { match i == 0 { true => parameter_list.push_str(&format!("{}", e)), _ => parameter_list.push_str(&format!(", {}", e)), }; } write!(f, "{}({}){}", token, parameter_list, *body) } Expression::Call { token: _, function, arguments, } => { let mut argument_list = String::new(); for (i, e) in arguments.iter().enumerate() { match i == 0 { true => argument_list.push_str(&format!("{}", e)), _ => argument_list.push_str(&format!(", {}", e)), }; } write!(f, "{}({})", function, argument_list) } Expression::StringLiteral { token } => write!(f, "{}", token.to_string()), } } } pub struct Program { pub statements: Vec<Statement>, pub errors: Vec<String>, } impl fmt::Display for Program { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = self .statements .iter() .fold(String::new(), |acc, x| acc + format!("{}", x).as_str()); write!(f, "{}", s) } }
use std::convert::TryInto; use solana_program::program_error::ProgramError; use crate::error::EscrowError::InvalidInstruction; pub enum EscrowInstruction { /// create and populate escrow account & transfer ownership of temp token to program derived address /// 5 accounts in total as params /// /// [signer] - acct of person init escrow /// [writable] - temp token acct, owned by initializer (should already exist) /// [] - initializer's token acct for the token they will receive /// [writable] for escrow account /// [] - rent sysvar /// [] - token program /// /// [] is read-only /// [writable] changes data field /// api endpoint to start escrow InitEscrow { //amount A expects amount: u64 }, Exchange { /// the amount the taker expects to be paid in the other token, as a u64 because that's the max possible supply of a token amount: u64, } } impl EscrowInstruction { ///unpack looks at first byte to determine how to decode pub fn unpack(input :&[u8]) -> Result<Self, ProgramError> { //splitting instruction, else throw invalid let (tag, rest) = input.split_first().ok_or(InvalidInstruction)?; //match tag input to instruction, either 0 or _ Ok(match tag { 0 => Self::InitEscrow { amount: Self::unpack_amount(rest)?, }, 1 => Self::Exchange { amount: Self::unpack_amount(rest)? }, _ => return Err(InvalidInstruction.into()), }) } /// decodes 'rest' to get a u64 representing the amount /// choose which instruction to build, then builds and returns that instruction pub fn unpack_amount(input: &[u8]) -> Result<u64, ProgramError> { let amount = input .get(..8) .and_then(|slice| slice.try_into().ok()) .map(u64::from_le_bytes) .ok_or(InvalidInstruction)?; Ok(amount) } }
//! //! The Semaphone CI pipeline demo binary. //! #[derive(Debug)] pub enum Error {} /// /// The main function gets the HTTP port from the command line arguments /// and starts the Hyper HTTP server. /// fn main() -> Result<(), Error> { let args = clap::App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg( clap::Arg::with_name("port") .help("The HTTP server port") .short("p") .long("port") .value_name("NUMBER") .takes_value(true) .required(true), ) .get_matches(); let port = args.value_of("port").expect("Unreachable"); let port: u16 = port.parse().expect("Unreachable"); semaphore_rust_hyper::run(port); Ok(()) }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib_sys; use libc; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLCanvasElement(Object<webkit2_webextension_sys::WebKitDOMHTMLCanvasElement, webkit2_webextension_sys::WebKitDOMHTMLCanvasElementClass, DOMHTMLCanvasElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_canvas_element_get_type(), } } pub const NONE_DOMHTML_CANVAS_ELEMENT: Option<&DOMHTMLCanvasElement> = None; pub trait DOMHTMLCanvasElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_height(&self) -> libc::c_long; #[cfg_attr(feature = "v2_22", deprecated)] fn get_width(&self) -> libc::c_long; #[cfg_attr(feature = "v2_22", deprecated)] fn set_height(&self, value: libc::c_long); #[cfg_attr(feature = "v2_22", deprecated)] fn set_width(&self, value: libc::c_long); fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLCanvasElement>> DOMHTMLCanvasElementExt for O { fn get_height(&self) -> libc::c_long { unsafe { webkit2_webextension_sys::webkit_dom_html_canvas_element_get_height( self.as_ref().to_glib_none().0, ) } } fn get_width(&self) -> libc::c_long { unsafe { webkit2_webextension_sys::webkit_dom_html_canvas_element_get_width( self.as_ref().to_glib_none().0, ) } } fn set_height(&self, value: libc::c_long) { unsafe { webkit2_webextension_sys::webkit_dom_html_canvas_element_set_height( self.as_ref().to_glib_none().0, value, ); } } fn set_width(&self, value: libc::c_long) { unsafe { webkit2_webextension_sys::webkit_dom_html_canvas_element_set_width( self.as_ref().to_glib_none().0, value, ); } } fn connect_property_height_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_height_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLCanvasElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLCanvasElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLCanvasElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::height\0".as_ptr() as *const _, Some(transmute(notify_height_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_width_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_width_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLCanvasElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLCanvasElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLCanvasElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::width\0".as_ptr() as *const _, Some(transmute(notify_width_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMHTMLCanvasElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLCanvasElement") } }
mod config; mod db; mod graphql; mod handlers; mod models; use crate::graphql::{create_schema, Schema}; use crate::models::Data; use actix_cors::Cors; use actix_web::*; use dotenv::dotenv; // use std::sync::Mutex; use tokio_postgres::NoTls; #[actix_rt::main] async fn main() -> std::io::Result<()> { dotenv().ok(); let config = crate::config::Config::from_env().unwrap(); let pool = config.pg.create_pool(NoTls).unwrap(); // let pool2 = pool.into_inner(); let client = pool.get().await.unwrap(); let schema = std::sync::Arc::new(create_schema()); let allowed_url = String::from(config.server.allowed_url); HttpServer::new(move || { let cors = Cors::default() .allowed_origin(&allowed_url) .allowed_origin_fn(|origin, _req_head| origin.as_bytes().ends_with(b".rust-lang.org")) .allowed_methods(vec!["GET", "POST"]) .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT]) .allowed_header(http::header::CONTENT_TYPE) .max_age(3600); // let data = web::Data::new(Mutex::new(Data { // pool: pool.clone(), // schema: schema.clone(), // })); let data = Data { pool: std::sync::Arc::new(pool.clone()), schema: schema.clone(), }; App::new() .wrap(cors) .data(data) .route("/graphql", web::post().to(handlers::graphql)) // .route("/graphiql", web::post().to(graphiql)) }) .bind(format!("{}:{}", config.server.host, config.server.port))? .run() .await }
use super::ip_rules::do_bash_cmd; use crate::config::{IPSET_NETHASH_TABLE, IPSET_TABLE, IPSET_TABLE6}; pub fn set_ipset() { // sudo ipset -N LPROXY iphash let arg = format!( "ipset -N {} iphash;ipset -N {} iphash family inet6;ipset -N {} nethash;\ ipset -F {};ipset -F {};ipset -F {}", IPSET_TABLE, IPSET_TABLE6, IPSET_NETHASH_TABLE, IPSET_TABLE, IPSET_TABLE6, IPSET_NETHASH_TABLE ); match do_bash_cmd(&arg) { Ok(_) => {} Err(_) => {} } } pub fn unset_ipset() { // sudo ipset -X LPROXY let arg = format!( "ipset -X {};ipset -X {};ipset -X {}", IPSET_TABLE, IPSET_TABLE6, IPSET_NETHASH_TABLE ); match do_bash_cmd(&arg) { Ok(_) => {} Err(_) => {} } }
#[allow(unused_imports)] use stringify::Stringify; #[allow(unused_imports)] use std::ffi::{CStr, CString}; #[allow(unused_imports)] use std::borrow::Cow; #[test] fn convert_to_cow_str_test() { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); let cow_str = Cow::Borrowed(libc_char.convert_to_str()); assert_eq!(libc_char.convert_to_cow_str(), cow_str); } #[test] fn convert_to_cstr_test() { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); let cstr = unsafe { CStr::from_ptr(CString::new(libc_char.convert_to_str()).unwrap().as_ptr()) }; assert_eq!(libc_char.convert_to_cstr(), cstr); } #[test] fn convert_to_str_test() { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); assert_eq!(libc_char.convert_to_str(), "something"); } #[test] fn convert_to_string_test() { let libc_char = CString::new("something".to_string()).unwrap().as_ptr(); assert_eq!(libc_char.convert_to_string(), "something".to_string()); } #[test] fn convert_to_libc_char_test() { let libc_char1 = CString::new("something".to_string()).unwrap().as_ptr(); let libc_char2 = CString::new("something".to_string()).unwrap().as_ptr(); assert_eq!(libc_char1.convert_to_libc_char(), libc_char2); }
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #[allow(dead_code)] mod helpers; use futures::StreamExt; use helpers::{ block_builders::{ append_block, chain_block, chain_block_with_coinbase, create_coinbase, create_genesis_block, find_header_with_achieved_difficulty, }, chain_metadata::{random_peer_metadata, MockChainMetadata}, nodes::{ create_network_with_2_base_nodes_with_config, create_network_with_3_base_nodes_with_config, random_node_identity, BaseNodeBuilder, }, }; use rand::{rngs::OsRng, RngCore}; use std::{thread, time::Duration}; use tari_core::{ base_node::{ chain_metadata_service::PeerChainMetadata, service::BaseNodeServiceConfig, states::{ BestChainMetadataBlockSyncInfo, BlockSyncConfig, ListeningInfo, StateEvent, SyncStatus, SyncStatus::Lagging, }, BaseNodeStateMachine, BaseNodeStateMachineConfig, }, consensus::{ConsensusConstantsBuilder, ConsensusManagerBuilder, Network}, helpers::create_mem_db, mempool::MempoolServiceConfig, transactions::types::CryptoFactories, validation::{ accum_difficulty_validators::MockAccumDifficultyValidator, block_validators::StatelessBlockValidator, mocks::MockValidator, }, }; use tari_mmr::MmrCacheConfig; use tari_p2p::services::liveness::LivenessConfig; use tari_shutdown::Shutdown; use tari_test_utils::{async_assert_eventually, random::string}; use tempdir::TempDir; use tokio::{runtime::Runtime, time}; #[test] fn test_listening_lagging() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let network = Network::LocalNet; let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let (alice_node, bob_node, consensus_manager) = create_network_with_2_base_nodes_with_config( &mut runtime, BaseNodeServiceConfig::default(), MmrCacheConfig::default(), MempoolServiceConfig::default(), LivenessConfig { enable_auto_join: false, auto_ping_interval: Some(Duration::from_millis(100)), ..Default::default() }, consensus_manager, temp_dir.path().to_str().unwrap(), ); let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), BaseNodeStateMachineConfig::default(), shutdown.to_signal(), ); let await_event_task = runtime.spawn(async move { ListeningInfo.next_event(&mut alice_state_machine).await }); runtime.block_on(async move { let bob_db = bob_node.blockchain_db; let mut bob_local_nci = bob_node.local_nci; // Bob Block 1 - no block event let prev_block = append_block( &bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 3.into(), ) .unwrap(); // Bob Block 2 - with block event and liveness service metadata update let prev_block = bob_db .calculate_mmr_roots(chain_block( &prev_block, vec![], &consensus_manager.consensus_constants(), )) .unwrap(); bob_local_nci.submit_block(prev_block).await.unwrap(); assert_eq!(bob_db.get_height(), Ok(Some(2))); let next_event = time::timeout(Duration::from_secs(10), await_event_task) .await .expect("Alice did not emit `StateEvent::FallenBehind` within 10 seconds") .unwrap(); match next_event { StateEvent::FallenBehind(Lagging(_, _)) => assert!(true), _ => assert!(false), } alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; }); } #[test] fn test_event_channel() { let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let mut runtime = Runtime::new().unwrap(); let (node, consensus_manager) = BaseNodeBuilder::new(Network::Rincewind).start(&mut runtime, temp_dir.path().to_str().unwrap()); // let shutdown = Shutdown::new(); let db = create_mem_db(&consensus_manager); let mut shutdown = Shutdown::new(); let mut mock = MockChainMetadata::new(); let state_machine = BaseNodeStateMachine::new( &db, &node.outbound_nci, node.comms.peer_manager(), node.comms.connection_manager(), mock.subscriber(), BaseNodeStateMachineConfig::default(), shutdown.to_signal(), ); let rx = state_machine.get_state_change_event_stream(); runtime.spawn(state_machine.run()); let PeerChainMetadata { node_id, chain_metadata, } = random_peer_metadata(10, 5_000.into()); runtime .block_on(mock.publish_chain_metadata(&node_id, &chain_metadata)) .expect("Could not publish metadata"); thread::sleep(Duration::from_millis(50)); runtime.block_on(async { let mut fused = rx.fuse(); let event = fused.next().await; assert_eq!(*event.unwrap(), StateEvent::Initialized); let event = fused.next().await; match *event.unwrap() { StateEvent::FallenBehind(SyncStatus::Lagging(ref data, ref id)) => { assert_eq!(data.height_of_longest_chain, Some(10)); assert_eq!(data.accumulated_difficulty, Some(5_000.into())); assert_eq!(id[0], node_id); }, _ => assert!(false), } node.comms.shutdown().await; }); let _ = shutdown.trigger(); } #[test] fn test_block_sync() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let network = Network::LocalNet; let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (mut prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let (alice_node, bob_node, consensus_manager) = create_network_with_2_base_nodes_with_config( &mut runtime, BaseNodeServiceConfig::default(), MmrCacheConfig::default(), MempoolServiceConfig::default(), LivenessConfig::default(), consensus_manager, temp_dir.path().to_str().unwrap(), ); let state_machine_config = BaseNodeStateMachineConfig { block_sync_config: BlockSyncConfig { random_sync_peer_with_chain: true, max_metadata_request_retry_attempts: 3, max_header_request_retry_attempts: 20, max_block_request_retry_attempts: 20, max_add_block_retry_attempts: 3, header_request_size: 5, block_request_size: 1, ..Default::default() }, }; let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), state_machine_config, shutdown.to_signal(), ); runtime.block_on(async { let alice_db = &alice_node.blockchain_db; let bob_db = &bob_node.blockchain_db; for _ in 1..6 { prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); } // Sync Blocks from genesis block to tip let network_tip = bob_db.get_metadata().unwrap(); let mut sync_peers = vec![bob_node.node_identity.node_id().clone()]; let state_event = BestChainMetadataBlockSyncInfo {} .next_event(&mut alice_state_machine, &network_tip, &mut sync_peers) .await; assert_eq!(state_event, StateEvent::BlocksSynchronized); assert_eq!(alice_db.get_height(), bob_db.get_height()); for height in 1..=network_tip.height_of_longest_chain.unwrap() { assert_eq!(alice_db.fetch_block(height), bob_db.fetch_block(height)); } alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; }); } #[test] fn test_lagging_block_sync() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let network = Network::LocalNet; let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (mut prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let (alice_node, bob_node, consensus_manager) = create_network_with_2_base_nodes_with_config( &mut runtime, BaseNodeServiceConfig::default(), MmrCacheConfig::default(), MempoolServiceConfig::default(), LivenessConfig::default(), consensus_manager, temp_dir.path().to_str().unwrap(), ); let state_machine_config = BaseNodeStateMachineConfig { block_sync_config: BlockSyncConfig { random_sync_peer_with_chain: true, max_metadata_request_retry_attempts: 3, max_header_request_retry_attempts: 20, max_block_request_retry_attempts: 20, max_add_block_retry_attempts: 3, header_request_size: 5, block_request_size: 1, ..Default::default() }, }; let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), state_machine_config, shutdown.to_signal(), ); runtime.block_on(async { let alice_db = &alice_node.blockchain_db; let bob_db = &bob_node.blockchain_db; for _ in 0..4 { prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); alice_db.add_block(prev_block.clone()).unwrap(); } for _ in 0..4 { prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); } assert_eq!(alice_db.get_height(), Ok(Some(4))); assert_eq!(bob_db.get_height(), Ok(Some(8))); // Lagging state beyond horizon, sync remaining Blocks to tip let network_tip = bob_db.get_metadata().unwrap(); let mut sync_peers = vec![bob_node.node_identity.node_id().clone()]; let state_event = BestChainMetadataBlockSyncInfo {} .next_event(&mut alice_state_machine, &network_tip, &mut sync_peers) .await; assert_eq!(state_event, StateEvent::BlocksSynchronized); assert_eq!(alice_db.get_height(), bob_db.get_height()); for height in 0..=network_tip.height_of_longest_chain.unwrap() { assert_eq!( alice_node.blockchain_db.fetch_block(height), bob_node.blockchain_db.fetch_block(height) ); } alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; }); } #[test] fn test_block_sync_recovery() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let network = Network::LocalNet; let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (mut prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let (alice_node, bob_node, carol_node, _) = create_network_with_3_base_nodes_with_config( &mut runtime, BaseNodeServiceConfig::default(), MmrCacheConfig::default(), MempoolServiceConfig::default(), LivenessConfig::default(), consensus_manager.clone(), temp_dir.path().to_str().unwrap(), ); let state_machine_config = BaseNodeStateMachineConfig { block_sync_config: BlockSyncConfig { random_sync_peer_with_chain: true, max_metadata_request_retry_attempts: 3, max_header_request_retry_attempts: 20, max_block_request_retry_attempts: 20, max_add_block_retry_attempts: 3, header_request_size: 5, block_request_size: 1, ..Default::default() }, }; let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), state_machine_config, shutdown.to_signal(), ); runtime.block_on(async { let alice_db = &alice_node.blockchain_db; let bob_db = &bob_node.blockchain_db; let carol_db = &carol_node.blockchain_db; // Bob and Carol is ahead of Alice and Bob is ahead of Carol prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); carol_db.add_block(prev_block.clone()).unwrap(); for _ in 0..2 { prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); } // Sync Blocks from genesis block to tip. Alice will notice that the chain tip is equivalent to Bobs tip and // start to request blocks from her random peers. When Alice requests these blocks from Carol, Carol // won't always have these blocks and Alice will have to request these blocks again until her maximum attempts // have been reached. let network_tip = bob_db.get_metadata().unwrap(); let mut sync_peers = vec![bob_node.node_identity.node_id().clone()]; let state_event = BestChainMetadataBlockSyncInfo .next_event(&mut alice_state_machine, &network_tip, &mut sync_peers) .await; assert_eq!(state_event, StateEvent::BlocksSynchronized); for height in 1..=network_tip.height_of_longest_chain.unwrap() { assert_eq!( alice_db.fetch_block(height).unwrap().block(), bob_db.fetch_block(height).unwrap().block() ); } alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; carol_node.comms.shutdown().await; }); } #[test] fn test_forked_block_sync() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let network = Network::LocalNet; let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (mut prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let (alice_node, bob_node, consensus_manager) = create_network_with_2_base_nodes_with_config( &mut runtime, BaseNodeServiceConfig::default(), MmrCacheConfig::default(), MempoolServiceConfig::default(), LivenessConfig::default(), consensus_manager, temp_dir.path().to_str().unwrap(), ); let state_machine_config = BaseNodeStateMachineConfig { block_sync_config: BlockSyncConfig { random_sync_peer_with_chain: true, max_metadata_request_retry_attempts: 3, max_header_request_retry_attempts: 20, max_block_request_retry_attempts: 20, max_add_block_retry_attempts: 3, header_request_size: 5, block_request_size: 1, ..Default::default() }, }; let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), state_machine_config, shutdown.to_signal(), ); runtime.block_on(async { // Shared chain let alice_db = &alice_node.blockchain_db; let bob_db = &bob_node.blockchain_db; for _ in 0..2 { prev_block = append_block( bob_db, &prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); alice_db.add_block(prev_block.clone()).unwrap(); } assert_eq!(alice_db.get_height(), Ok(Some(2))); assert_eq!(bob_db.get_height(), Ok(Some(2))); let mut alice_prev_block = prev_block.clone(); let mut bob_prev_block = prev_block; // Alice fork for _ in 0..2 { alice_prev_block = append_block( alice_db, &alice_prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); } // Bob fork for _ in 0..7 { bob_prev_block = append_block( bob_db, &bob_prev_block, vec![], &consensus_manager.consensus_constants(), 1.into(), ) .unwrap(); } assert_eq!(alice_db.get_height(), Ok(Some(4))); assert_eq!(bob_db.get_height(), Ok(Some(9))); let network_tip = bob_db.get_metadata().unwrap(); let mut sync_peers = vec![bob_node.node_identity.node_id().clone()]; let state_event = BestChainMetadataBlockSyncInfo {} .next_event(&mut alice_state_machine, &network_tip, &mut sync_peers) .await; assert_eq!(state_event, StateEvent::BlocksSynchronized); assert_eq!(alice_db.get_height(), bob_db.get_height()); for height in 0..=network_tip.height_of_longest_chain.unwrap() { assert_eq!(alice_db.fetch_block(height), bob_db.fetch_block(height)); } alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; }); } #[test] fn test_sync_peer_banning() { let mut runtime = Runtime::new().unwrap(); let factories = CryptoFactories::default(); let temp_dir = TempDir::new(string(8).as_str()).unwrap(); let network = Network::LocalNet; let consensus_constants = ConsensusConstantsBuilder::new(network) .with_emission_amounts(100_000_000.into(), 0.999, 100.into()) .build(); let (mut prev_block, _) = create_genesis_block(&factories, &consensus_constants); let consensus_manager = ConsensusManagerBuilder::new(network) .with_consensus_constants(consensus_constants) .with_block(prev_block.clone()) .build(); let stateless_block_validator = StatelessBlockValidator::new(consensus_manager.consensus_constants()); let mock_validator = MockValidator::new(true); // Create base nodes let alice_node_identity = random_node_identity(); let bob_node_identity = random_node_identity(); let base_node_service_config = BaseNodeServiceConfig::default(); let mmr_cache_config = MmrCacheConfig::default(); let mempool_service_config = MempoolServiceConfig::default(); let liveness_service_config = LivenessConfig::default(); let data_path = temp_dir.path().to_str().unwrap(); let network = Network::LocalNet; let (alice_node, consensus_manager) = BaseNodeBuilder::new(network) .with_node_identity(alice_node_identity.clone()) .with_peers(vec![bob_node_identity.clone()]) .with_base_node_service_config(base_node_service_config) .with_mmr_cache_config(mmr_cache_config) .with_mempool_service_config(mempool_service_config) .with_liveness_service_config(liveness_service_config) .with_consensus_manager(consensus_manager) .with_validators( mock_validator, stateless_block_validator, MockAccumDifficultyValidator {}, ) .start(&mut runtime, data_path); let (bob_node, consensus_manager) = BaseNodeBuilder::new(network) .with_node_identity(bob_node_identity) .with_base_node_service_config(base_node_service_config) .with_mmr_cache_config(mmr_cache_config) .with_mempool_service_config(mempool_service_config) .with_liveness_service_config(liveness_service_config) .with_consensus_manager(consensus_manager) .start(&mut runtime, data_path); // Wait for peers to connect runtime.block_on(async { let _ = alice_node .comms .connection_manager() .dial_peer(bob_node.node_identity.node_id().clone()) .await; async_assert_eventually!( bob_node .comms .peer_manager() .exists(alice_node.node_identity.public_key()) .await, expect = true, max_attempts = 20, interval = Duration::from_millis(1000) ); }); let state_machine_config = BaseNodeStateMachineConfig { block_sync_config: BlockSyncConfig { random_sync_peer_with_chain: true, max_metadata_request_retry_attempts: 3, max_header_request_retry_attempts: 20, max_block_request_retry_attempts: 20, max_add_block_retry_attempts: 3, header_request_size: 5, block_request_size: 1, ..Default::default() }, }; let shutdown = Shutdown::new(); let mut alice_state_machine = BaseNodeStateMachine::new( &alice_node.blockchain_db, &alice_node.outbound_nci, alice_node.comms.peer_manager(), alice_node.comms.connection_manager(), alice_node.chain_metadata_handle.get_event_stream(), state_machine_config, shutdown.to_signal(), ); runtime.block_on(async { // Shared chain let alice_db = &alice_node.blockchain_db; let alice_peer_manager = &alice_node.comms.peer_manager(); let bob_db = &bob_node.blockchain_db; let bob_public_key = &bob_node.node_identity.public_key(); for height in 1..=2 { let coinbase_value = consensus_manager.emission_schedule().block_reward(height); let (coinbase_utxo, coinbase_kernel, _) = create_coinbase( &factories, coinbase_value, height + consensus_manager.consensus_constants().coinbase_lock_height(), ); let template = chain_block_with_coinbase( &prev_block, vec![], coinbase_utxo, coinbase_kernel, &consensus_manager.consensus_constants(), ); prev_block = bob_db.calculate_mmr_roots(template).unwrap(); prev_block.header.nonce = OsRng.next_u64(); find_header_with_achieved_difficulty(&mut prev_block.header, 1.into()); alice_db.add_block(prev_block.clone()).unwrap(); bob_db.add_block(prev_block.clone()).unwrap(); } assert_eq!(alice_db.get_height(), Ok(Some(2))); assert_eq!(bob_db.get_height(), Ok(Some(2))); let peer = alice_peer_manager.find_by_public_key(bob_public_key).await.unwrap(); assert_eq!(peer.is_banned(), false); // Alice fork let mut alice_prev_block = prev_block.clone(); for height in 3..=4 { let coinbase_value = consensus_manager.emission_schedule().block_reward(height); let (coinbase_utxo, coinbase_kernel, _) = create_coinbase( &factories, coinbase_value, height + consensus_manager.consensus_constants().coinbase_lock_height(), ); let template = chain_block_with_coinbase( &alice_prev_block, vec![], coinbase_utxo, coinbase_kernel, &consensus_manager.consensus_constants(), ); alice_prev_block = alice_db.calculate_mmr_roots(template).unwrap(); alice_prev_block.header.nonce = OsRng.next_u64(); find_header_with_achieved_difficulty(&mut alice_prev_block.header, 1.into()); alice_db.add_block(alice_prev_block.clone()).unwrap(); } // Bob fork with invalid coinbases let mut bob_prev_block = prev_block; for _ in 3..=6 { bob_prev_block = append_block( bob_db, &bob_prev_block, vec![], &consensus_manager.consensus_constants(), 3.into(), ) .unwrap(); } assert_eq!(alice_db.get_height(), Ok(Some(4))); assert_eq!(bob_db.get_height(), Ok(Some(6))); let network_tip = bob_db.get_metadata().unwrap(); let mut sync_peers = vec![bob_node.node_identity.node_id().clone()]; let state_event = BestChainMetadataBlockSyncInfo {} .next_event(&mut alice_state_machine, &network_tip, &mut sync_peers) .await; assert_eq!(state_event, StateEvent::BlockSyncFailure); assert_eq!(alice_db.get_height(), Ok(Some(4))); let peer = alice_peer_manager.find_by_public_key(bob_public_key).await.unwrap(); assert_eq!(peer.is_banned(), true); alice_node.comms.shutdown().await; bob_node.comms.shutdown().await; }); }
pub mod chain; pub mod channels; pub mod config; pub mod database; pub mod disk; pub mod error; pub mod event_handler; pub mod events; pub mod hex_utils; pub mod node; pub mod p2p; pub mod persist; pub mod services; pub mod utils; pub mod version;
use std::fmt::Debug; use std::io; use std::str::FromStr; struct Edge<'a> { node: Option<&Node>, next: Option<&Edge<'a>>, } struct Node { value: i64, edges: Option<&Edge>, } fn read_and_divide_line<T>() -> Vec<T> where T: FromStr, <T as FromStr>::Err: Debug, { let mut target_line = String::new(); io::stdin().read_line(&mut target_line).unwrap(); target_line .trim() .split_whitespace() .map(|c| T::from_str(c).unwrap()) .collect() } fn main() { let tree_vertex_num: i64 = read_and_divide_line()[0]; let first_line_nodes = read_and_divide_line(); let root = Node { value: first_line_nodes[0], edges: None, }; let next_node = Node { value: first_line_nodes[1], } for _ in 1..tree_vertex_num {} }
use std::time::Duration; use criterion::{ criterion_group, criterion_main, Bencher, Benchmark, Criterion, Throughput, }; const CORPUS_HTML: &'static [u8] = include_bytes!("../../data/html"); const CORPUS_URLS_10K: &'static [u8] = include_bytes!("../../data/urls.10K"); const CORPUS_FIREWORKS: &'static [u8] = include_bytes!("../../data/fireworks.jpeg"); const CORPUS_PAPER_100K: &'static [u8] = include_bytes!("../../data/paper-100k.pdf"); const CORPUS_HTML_X_4: &'static [u8] = include_bytes!("../../data/html_x_4"); const CORPUS_ALICE29: &'static [u8] = include_bytes!("../../data/alice29.txt"); const CORPUS_ASYOULIK: &'static [u8] = include_bytes!("../../data/asyoulik.txt"); const CORPUS_LCET10: &'static [u8] = include_bytes!("../../data/lcet10.txt"); const CORPUS_PLRABN12: &'static [u8] = include_bytes!("../../data/plrabn12.txt"); const CORPUS_GEOPROTO: &'static [u8] = include_bytes!("../../data/geo.protodata"); const CORPUS_KPPKN: &'static [u8] = include_bytes!("../../data/kppkn.gtb"); macro_rules! compress { ($c:expr, $comp:expr, $group:expr, $name:expr, $corpus:expr) => { compress!($c, $comp, $group, $name, $corpus, 0); }; ($c:expr, $comp:expr, $group:expr, $name:expr, $corpus:expr, $size:expr) => { let mut corpus = $corpus; if $size > 0 { corpus = &corpus[..$size]; } let mut dst = vec![0; snap::raw::max_compress_len(corpus.len())]; define($c, $group, &format!("compress/{}", $name), corpus, move |b| { b.iter(|| { $comp(corpus, &mut dst).unwrap(); }); }); }; } macro_rules! decompress { ($c:expr, $decomp:expr, $group:expr, $name:expr, $corpus:expr) => { decompress!($c, $decomp, $group, $name, $corpus, 0); }; ($c:expr, $decomp:expr, $group:expr, $name:expr, $corpus:expr, $size:expr) => { let mut corpus = $corpus; if $size > 0 { corpus = &corpus[..$size]; } let compressed = snap::raw::Encoder::new().compress_vec(corpus).unwrap(); let mut dst = vec![0; corpus.len()]; define( $c, $group, &format!("decompress/{}", $name), corpus, move |b| { b.iter(|| { $decomp(&compressed, &mut dst).unwrap(); }); }, ); }; } fn all(c: &mut Criterion) { rust(c); #[cfg(feature = "cpp")] cpp(c); } fn rust(c: &mut Criterion) { fn compress(input: &[u8], output: &mut [u8]) -> snap::Result<usize> { snap::raw::Encoder::new().compress(input, output) } fn decompress(input: &[u8], output: &mut [u8]) -> snap::Result<usize> { snap::raw::Decoder::new().decompress(input, output) } compress!(c, compress, "snap", "zflat00_html", CORPUS_HTML); compress!(c, compress, "snap", "zflat01_urls", CORPUS_URLS_10K); compress!(c, compress, "snap", "zflat02_jpg", CORPUS_FIREWORKS); compress!(c, compress, "snap", "zflat03_jpg_200", CORPUS_FIREWORKS, 200); compress!(c, compress, "snap", "zflat04_pdf", CORPUS_PAPER_100K); compress!(c, compress, "snap", "zflat05_html4", CORPUS_HTML_X_4); compress!(c, compress, "snap", "zflat06_txt1", CORPUS_ALICE29); compress!(c, compress, "snap", "zflat07_txt2", CORPUS_ASYOULIK); compress!(c, compress, "snap", "zflat08_txt3", CORPUS_LCET10); compress!(c, compress, "snap", "zflat09_txt4", CORPUS_PLRABN12); compress!(c, compress, "snap", "zflat10_pb", CORPUS_GEOPROTO); compress!(c, compress, "snap", "zflat11_gaviota", CORPUS_KPPKN); decompress!(c, decompress, "snap", "uflat00_html", CORPUS_HTML); decompress!(c, decompress, "snap", "uflat01_urls", CORPUS_URLS_10K); decompress!(c, decompress, "snap", "uflat02_jpg", CORPUS_FIREWORKS); decompress!( c, decompress, "snap", "uflat03_jpg_200", CORPUS_FIREWORKS, 200 ); decompress!(c, decompress, "snap", "uflat04_pdf", CORPUS_PAPER_100K); decompress!(c, decompress, "snap", "uflat05_html4", CORPUS_HTML_X_4); decompress!(c, decompress, "snap", "uflat06_txt1", CORPUS_ALICE29); decompress!(c, decompress, "snap", "uflat07_txt2", CORPUS_ASYOULIK); decompress!(c, decompress, "snap", "uflat08_txt3", CORPUS_LCET10); decompress!(c, decompress, "snap", "uflat09_txt4", CORPUS_PLRABN12); decompress!(c, decompress, "snap", "uflat10_pb", CORPUS_GEOPROTO); decompress!(c, decompress, "snap", "uflat11_gaviota", CORPUS_KPPKN); } #[cfg(feature = "cpp")] fn cpp(c: &mut Criterion) { use snappy_cpp::{compress, decompress}; compress!(c, compress, "cpp", "zflat00_html", CORPUS_HTML); compress!(c, compress, "cpp", "zflat01_urls", CORPUS_URLS_10K); compress!(c, compress, "cpp", "zflat02_jpg", CORPUS_FIREWORKS); compress!(c, compress, "cpp", "zflat03_jpg_200", CORPUS_FIREWORKS, 200); compress!(c, compress, "cpp", "zflat04_pdf", CORPUS_PAPER_100K); compress!(c, compress, "cpp", "zflat05_html4", CORPUS_HTML_X_4); compress!(c, compress, "cpp", "zflat06_txt1", CORPUS_ALICE29); compress!(c, compress, "cpp", "zflat07_txt2", CORPUS_ASYOULIK); compress!(c, compress, "cpp", "zflat08_txt3", CORPUS_LCET10); compress!(c, compress, "cpp", "zflat09_txt4", CORPUS_PLRABN12); compress!(c, compress, "cpp", "zflat10_pb", CORPUS_GEOPROTO); compress!(c, compress, "cpp", "zflat11_gaviota", CORPUS_KPPKN); decompress!(c, decompress, "cpp", "uflat00_html", CORPUS_HTML); decompress!(c, decompress, "cpp", "uflat01_urls", CORPUS_URLS_10K); decompress!(c, decompress, "cpp", "uflat02_jpg", CORPUS_FIREWORKS); decompress!( c, decompress, "cpp", "uflat03_jpg_200", CORPUS_FIREWORKS, 200 ); decompress!(c, decompress, "cpp", "uflat04_pdf", CORPUS_PAPER_100K); decompress!(c, decompress, "cpp", "uflat05_html4", CORPUS_HTML_X_4); decompress!(c, decompress, "cpp", "uflat06_txt1", CORPUS_ALICE29); decompress!(c, decompress, "cpp", "uflat07_txt2", CORPUS_ASYOULIK); decompress!(c, decompress, "cpp", "uflat08_txt3", CORPUS_LCET10); decompress!(c, decompress, "cpp", "uflat09_txt4", CORPUS_PLRABN12); decompress!(c, decompress, "cpp", "uflat10_pb", CORPUS_GEOPROTO); decompress!(c, decompress, "cpp", "uflat11_gaviota", CORPUS_KPPKN); } fn define( c: &mut Criterion, group_name: &str, bench_name: &str, corpus: &[u8], bench: impl FnMut(&mut Bencher) + 'static, ) { let tput = Throughput::Bytes(corpus.len() as u64); let benchmark = Benchmark::new(bench_name, bench) .throughput(tput) .sample_size(50) .warm_up_time(Duration::from_millis(500)) .measurement_time(Duration::from_secs(3)); c.bench(group_name, benchmark); } criterion_group!(g, all); criterion_main!(g);
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(optin_builtin_traits)] use std::marker::Send; pub struct WaitToken; impl !Send for WaitToken {} pub struct Test<T>(T); unsafe impl<T: 'static> Send for Test<T> {} pub fn spawn<F>(_: F) -> () where F: FnOnce(), F: Send + 'static {} fn main() { let wt = Test(WaitToken); spawn(move || { let x = wt; println!("Hello, World!"); }); }
use core::marker::PhantomData; use poll::Poll; use Async; use stream::Stream; /// A stream combinator to change the error type of a stream. /// /// This is created by the `Stream::from_err` method. #[derive(Debug)] #[must_use = "futures do nothing unless polled"] pub struct FromErr<S, E> { stream: S, f: PhantomData<E> } pub fn new<S, E>(stream: S) -> FromErr<S, E> where S: Stream { FromErr { stream: stream, f: PhantomData } } impl<S, E> FromErr<S, E> { /// Acquires a reference to the underlying stream that this combinator is /// pulling from. pub fn get_ref(&self) -> &S { &self.stream } /// Acquires a mutable reference to the underlying stream that this /// combinator is pulling from. /// /// Note that care must be taken to avoid tampering with the state of the /// stream which may otherwise confuse this combinator. pub fn get_mut(&mut self) -> &mut S { &mut self.stream } /// Consumes this combinator, returning the underlying stream. /// /// Note that this may discard intermediate state of this combinator, so /// care should be taken to avoid losing resources when this is called. pub fn into_inner(self) -> S { self.stream } } impl<S: Stream, E: From<S::Error>> Stream for FromErr<S, E> { type Item = S::Item; type Error = E; fn poll(&mut self) -> Poll<Option<S::Item>, E> { let e = match self.stream.poll() { Ok(Async::NotReady) => return Ok(Async::NotReady), other => other, }; e.map_err(From::from) } } // Forwarding impl of Sink from the underlying stream impl<S: Stream + ::sink::Sink, E> ::sink::Sink for FromErr<S, E> { type SinkItem = S::SinkItem; type SinkError = S::SinkError; fn start_send(&mut self, item: Self::SinkItem) -> ::StartSend<Self::SinkItem, Self::SinkError> { self.stream.start_send(item) } fn poll_complete(&mut self) -> Poll<(), Self::SinkError> { self.stream.poll_complete() } fn close(&mut self) -> Poll<(), Self::SinkError> { self.stream.close() } }
//! The Rust core prelude. #[macro_use] pub mod macros; #[cfg(target_arch = "x86_64")] pub mod x86_64; pub mod rand; pub mod prelude { pub use core::slice::{SliceExt, from_raw_parts}; pub use core::iter::{Iterator, IteratorExt, Zip, range, count, DoubleEndedIterator}; pub use core::option::Option::{self, Some, None}; pub use core::raw::{Repr}; pub use core::intrinsics::{offset, uninit, copy_nonoverlapping_memory}; pub use core::ops::*; pub use core::ptr::{PtrExt}; pub use core::clone::{Clone}; pub use core::num::{Int, Float}; pub use core::mem::transmute; pub use super::rand::{Rand, os_rand}; #[inline(always)] pub unsafe fn offset_mut<T>(dst: *mut T, n: isize) -> *mut T { offset(dst as *const T, n) as *mut T } pub unsafe fn transmute_copy<T,U>(p: &T) -> U { let p = p as *const T as *const U; let mut u = uninit(); copy_nonoverlapping_memory(&mut u, p, 1); u } } use core; #[lang = "stack_exhausted"] unsafe fn stack_exhausted() { ::syscalls::sys_exit(1); } #[lang = "eh_personality"] unsafe fn eh_personality() { ::syscalls::sys_exit(1); } #[lang = "panic_fmt"] unsafe fn panic_fmt(_args: &core::fmt::Arguments, _file: &str, _line: u32) -> ! { ::syscalls::sys_exit(1); loop { }; }
use crate::constants::APOD_URL; use crate::services::database::apod::DBApod; use serde::{Deserialize, Serialize}; use std::error::Error; use std::fmt; #[derive(Serialize, Deserialize, Debug)] pub struct Apod { pub copyright: Option<String>, pub date: String, pub explanation: String, pub hdurl: String, pub title: String, } impl Apod { pub async fn fetch(key: &String) -> Result<Self, ApodError> { let res = match reqwest::get(format!("{}{}", APOD_URL, key)).await { Ok(res) => res, Err(e) => return Err(ApodError::new(format!("Reqwest error {}", e).as_str())), }; if !res.status().is_success() { return Err(ApodError::new( format!("Status code incorrect: {}", res.status().as_u16()).as_str(), )); } return match res.json::<Apod>().await { Ok(apod) => Ok(apod), Err(e) => Err(ApodError::new( format!("Reqwest json error: {}", e).as_str(), )), }; } } impl From<DBApod> for Apod { fn from(a: DBApod) -> Self { Apod { copyright: a.copyright, date: a.publish_date.to_string(), explanation: a.explanation, hdurl: a.hdurl, title: a.title, } } } #[derive(Debug)] pub struct ApodError { details: String, } impl ApodError { fn new(msg: &str) -> ApodError { ApodError { details: msg.to_string(), } } } impl fmt::Display for ApodError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.details) } } impl Error for ApodError { fn description(&self) -> &str { &self.details } }
use std::cell::RefCell; use std::fmt; use std::rc::Rc; use apu::ApuReg; use cpu_instr::{Cycles, Instr, Mode, Op}; use ppu::PpuReg; use rom::Rom; pub struct Cpu { reg: Reg, ram: [u8; 0x800], ppu_reg: Rc<RefCell<PpuReg>>, apu_reg: Rc<RefCell<ApuReg>>, sram: [u8; 0x2000], prg_rom: [u8; 0x8000], } impl Cpu { pub fn new(ppu_reg: Rc<RefCell<PpuReg>>, apu_reg: Rc<RefCell<ApuReg>>, rom: Rom) -> Cpu { let mut prg_rom = [0u8; 0x8000]; for (i, b) in rom.prg_rom .iter() .cycle() .take(0x8000) .enumerate() { prg_rom[i] = *b; } Cpu { reg: Reg::default(), ram: [0; 0x800], ppu_reg: ppu_reg, apu_reg: apu_reg, sram: [0; 0x2000], prg_rom: prg_rom, } } fn read_u8(&self, addr: u16) -> u8 { match addr { 0x0000...0x07ff => self.ram[addr as usize], 0x0800...0x1fff => self.ram[(addr % 0x800) as usize], 0x2000...0x2007 => self.ppu_reg.borrow().read(addr - 0x2000), 0x2008...0x3fff => self.ppu_reg.borrow().read((addr - 0x2008) % 8), 0x4000...0x401f => self.apu_reg.borrow().read(addr - 0x4000), 0x4020...0x5fff => panic!("expansion rom"), 0x6000...0x7fff => self.sram[(addr - 0x6000) as usize], 0x8000...0xffff => self.prg_rom[(addr - 0x8000) as usize], _ => unreachable!(), } } fn read_i8(&self, addr: u16) -> i8 { self.read_u8(addr) as i8 } fn read_u16(&self, addr: u16) -> u16 { self.read_u8(addr) as u16 | (self.read_u8(addr + 1) as u16) << 8 } fn read_bytes(&self, addr: u16, len: u16) -> Vec<u8> { let mut bytes = Vec::with_capacity(len as usize); for i in addr..addr + len { bytes.push(self.read_u8(i)); } bytes } fn write_u8(&mut self, addr: u16, value: u8) { match addr { 0x0000...0x07ff => self.ram[addr as usize] = value, 0x0800...0x1fff => self.ram[(addr % 0x800) as usize] = value, 0x2000...0x2007 => self.ppu_reg.borrow_mut().write(addr - 0x2000, value), 0x2008...0x3fff => self.ppu_reg.borrow_mut().write((addr - 0x2008) % 8, value), 0x4000...0x401f => self.apu_reg.borrow_mut().write(addr - 0x4000, value), 0x4020...0x5fff => panic!("expansion rom"), 0x6000...0x7fff => self.sram[(addr - 0x6000) as usize] = value, 0x8000...0xffff => self.prg_rom[(addr - 0x8000) as usize] = value, _ => unreachable!(), } } fn pop_u8(&mut self) -> u8 { let addr = self.reg.sp.wrapping_add(1); self.reg.sp = addr; self.read_u8(0x100 | addr as u16) } fn pop_u16(&mut self) -> u16 { let lo = self.pop_u8(); let hi = self.pop_u8(); lo as u16 | (hi as u16) << 8 } fn push_u8(&mut self, value: u8) { let addr = 0x100 | self.reg.sp as u16; self.write_u8(addr, value); self.reg.sp = self.reg.sp.wrapping_sub(1); } pub fn exec(&mut self) -> u8 { let addr = self.reg.pc; let bytes = self.read_bytes(addr, 3); let instr = Instr::from(&bytes); println!("{:#06x} {:?}", addr, instr); self.reg.pc = self.reg.pc.wrapping_add(1 + instr.1.payload_len()); match instr { Instr(Op::And, m, _) => { let mem = self.payload_u8(m); let val = self.reg.acc & mem; self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.reg.acc = val; } Instr(Op::Asl, m, _) => { let addr = self.payload_u16(m); let old_val = self.read_u8(addr); let new_val = old_val << 1; self.reg.status.carry = old_val & 0b1000_0000 != 0; self.reg.status.neg = new_val & 0b1000_0000 != 0; self.reg.status.zero = new_val == 0; self.write_u8(addr, new_val); } Instr(Op::Bcs, m, _) => { let addr = self.payload_u16(m); if self.reg.status.carry { self.reg.pc = addr; } } Instr(Op::Beq, m, _) => { let addr = self.payload_u16(m); if self.reg.status.zero { self.reg.pc = addr; } } Instr(Op::Bit, m, _) => { let val = self.payload_u8(m); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.overflow = val & 0b0100_0000 != 0; self.reg.status.zero = val & self.reg.acc == 0; } Instr(Op::Bmi, m, _) => { let addr = self.payload_u16(m); if self.reg.status.neg { self.reg.pc = addr; } } Instr(Op::Bne, m, _) => { let addr = self.payload_u16(m); if !self.reg.status.zero { self.reg.pc = addr; } } Instr(Op::Bpl, m, _) => { let addr = self.payload_addr(m); if !self.reg.status.neg { self.reg.pc = addr; } } Instr(Op::Brk, _, _) => self.interrupt(Interrupt::Brk), Instr(Op::Cld, _, _) => self.reg.status.decimal_mode = false, Instr(Op::Cmp, m, _) => { let mem = self.payload_u8(m); let val = self.reg.acc - mem; self.reg.status.carry = self.reg.acc >= mem; self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; } Instr(Op::Dec, m, _) => { let addr = self.payload_u16(m); let val = self.read_u8(addr).wrapping_sub(1); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.write_u8(addr, val); } Instr(Op::Dex, _, _) => { self.reg.x = self.reg.x.wrapping_sub(1); self.reg.status.neg = self.reg.x & 0b1000_0000 != 0; self.reg.status.zero = self.reg.x == 0; } Instr(Op::Dey, _, _) => { self.reg.y = self.reg.y.wrapping_sub(1); self.reg.status.neg = self.reg.y & 0b1000_0000 != 0; self.reg.status.zero = self.reg.y == 0; } Instr(Op::Inc, m, _) => { let addr = self.payload_u16(m); let val = self.read_u8(addr).wrapping_add(1); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.write_u8(addr, val); } Instr(Op::Inx, _, _) => { self.reg.x = self.reg.x.wrapping_add(1); self.reg.status.neg = self.reg.x & 0b1000_0000 != 0; self.reg.status.zero = self.reg.x == 0; } Instr(Op::Iny, _, _) => { self.reg.y = self.reg.y.wrapping_add(1); self.reg.status.neg = self.reg.y & 0b1000_0000 != 0; self.reg.status.zero = self.reg.y == 0; } Instr(Op::Lda, m, _) => { let val = self.payload_u8(m); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.reg.acc = val; } Instr(Op::Ldx, m, _) => { let val = self.payload_u8(m); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.reg.x = val; } Instr(Op::Ldy, m, _) => { let val = self.payload_u8(m); self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; self.reg.y = val; } Instr(Op::Ora, m, _) => { let mem = self.payload_u8(m); let val = self.reg.acc | mem; self.reg.status.neg = val & 0b1000_0000 != 0; self.reg.status.zero = val == 0; } Instr(Op::Rts, _, _) => self.reg.pc = self.pop_u16().wrapping_add(1), Instr(Op::Sei, _, _) => self.reg.status.irq_disabled = true, Instr(Op::Sta, m, _) => { let addr = self.payload_addr(m); let val = self.reg.acc; self.write_u8(addr, val); } Instr(Op::Stx, m, _) => { let addr = self.payload_addr(m); let val = self.reg.x; self.write_u8(addr, val); } Instr(Op::Sty, m, _) => { let addr = self.payload_addr(m); let val = self.reg.y; self.write_u8(addr, val); } Instr(Op::Txa, _, _) => { self.reg.status.neg = self.reg.x & 0b1000_0000 != 0; self.reg.status.zero = self.reg.x == 0; self.reg.acc = self.reg.x; } Instr(Op::Txs, _, _) => { self.reg.status.neg = self.reg.x & 0b1000_0000 != 0; self.reg.status.zero = self.reg.x == 0; self.reg.sp = self.reg.x; } Instr(Op::Tya, _, _) => { self.reg.status.neg = self.reg.y & 0b1000_0000 != 0; self.reg.status.zero = self.reg.y == 0; self.reg.acc = self.reg.y; } _ => { panic!("Unknown instruction {:?} from opcode {:#x} at {:#x}", instr, bytes[0], addr) } } match instr.2 { Cycles::A(c) | Cycles::B(c) | Cycles::C(c) => c, } } fn payload_addr(&mut self, mode: Mode) -> u16 { match mode { Mode::Abs(addr) => addr, Mode::AbsX(offset) => (self.reg.x as u16).wrapping_add(offset), Mode::AbsY(offset) => (self.reg.y as u16).wrapping_add(offset), Mode::Imm(_) => unreachable!(), Mode::Ind(addr_addr) => self.read_u16(addr_addr), Mode::IndX(offset) => { let zero_addr = self.reg.x as u16 + offset as u16; self.read_u16(zero_addr) } Mode::IndY(offset) => { let zero_addr = self.read_u16(offset as u16); zero_addr + self.reg.y as u16 } Mode::Rel(offset) => { if offset < 0 { self.reg .pc .wrapping_sub(offset.wrapping_neg() as u16) } else { self.reg .pc .wrapping_add(offset as u16) } } Mode::Zero(addr) => addr as u16, Mode::ZeroX(offset) => self.reg.x.wrapping_add(offset) as u16, Mode::ZeroY(offset) => self.reg.y.wrapping_add(offset) as u16, _ => panic!("Unsupported address mode: {:?}", mode), } } fn payload_u8(&mut self, mode: Mode) -> u8 { match mode { Mode::Imm(p) => p, _ => { let addr = self.payload_addr(mode); self.read_u8(addr) } } } fn payload_u16(&mut self, mode: Mode) -> u16 { let addr = self.payload_addr(mode); self.read_u16(addr) } pub fn interrupt(&mut self, int: Interrupt) { if self.reg.status.irq_disabled && int == Interrupt::Irq { return; } let vec_addr = int.addr(); let addr = self.read_u16(vec_addr); println!("Interrupt vector for {:?} is {:#06x} at {:#06x}", int, addr, vec_addr); self.reg.pc = addr; } } impl fmt::Debug for Cpu { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.reg) } } struct Reg { pc: u16, sp: u8, status: StatusReg, acc: u8, x: u8, y: u8, } impl fmt::Debug for Reg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "pc={:#x} sp={:#x} acc={:#x} x={:#x} y={:#x} status={:#?}", self.pc, self.sp, self.acc, self.x, self.y, self.status) } } impl Default for Reg { fn default() -> Reg { Reg { pc: 0, sp: 0xfd, status: StatusReg::default(), acc: 0, x: 0, y: 0, } } } #[derive(Debug)] struct StatusReg { neg: bool, overflow: bool, is_brk: bool, decimal_mode: bool, irq_disabled: bool, zero: bool, carry: bool, } impl Default for StatusReg { fn default() -> StatusReg { StatusReg { neg: false, overflow: false, is_brk: false, decimal_mode: false, irq_disabled: true, zero: false, carry: false, } } } #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum Interrupt { Brk, Irq, Nmi, Reset, } impl Interrupt { fn addr(&self) -> u16 { match *self { Interrupt::Brk | Interrupt::Irq => 0xfffe, Interrupt::Nmi => 0xfffa, Interrupt::Reset => 0xfffc, } } }
/// A state identifier especially tailored for lazy DFAs. /// /// A lazy state ID logically represents a pointer to a DFA state. In practice, /// by limiting the number of DFA states it can address, it reserves some /// bits of its representation to encode some additional information. That /// additional information is called a "tag." That tag is used to record /// whether the state it points to is an unknown, dead, quit, start or match /// state. /// /// When implementing a low level search routine with a lazy DFA, it is /// necessary to query the type of the current state to know what to do: /// /// * **Unknown** - The state has not yet been computed. The /// parameters used to get this state ID must be re-passed to /// [`DFA::next_state`](crate::hybrid::dfa::DFA), which will never return an /// unknown state ID. /// * **Dead** - A dead state only has transitions to itself. It indicates that /// the search cannot do anything else and should stop with whatever result it /// has. /// * **Quit** - A quit state indicates that the automaton could not answer /// whether a match exists or not. Correct search implementations must return a /// [`MatchError::Quit`](crate::MatchError::Quit). /// * **Start** - A start state indicates that the automaton will begin /// searching at a starting state. Branching on this isn't required for /// correctness, but a common optimization is to use this to more quickly look /// for a prefix. /// * **Match** - A match state indicates that a match has been found. /// Depending on the semantics of your search implementation, it may either /// continue until the end of the haystack or a dead state, or it might quit /// and return the match immediately. /// /// As an optimization, the [`is_tagged`](LazyStateID::is_tagged) predicate /// can be used to determine if a tag exists at all. This is useful to avoid /// branching on all of the above types for every byte searched. /// /// # Example /// /// This example shows how `LazyStateID` can be used to implement a correct /// search routine with minimal branching. In particular, this search routine /// implements "leftmost" matching, which means that it doesn't immediately /// stop once a match is found. Instead, it continues until it reaches a dead /// state. /// /// Notice also how a correct search implementation deals with /// [`CacheError`](crate::hybrid::CacheError)s returned by some of /// the lazy DFA routines. When a `CacheError` occurs, it returns /// [`MatchError::GaveUp`](crate::MatchError::GaveUp). /// /// ``` /// use regex_automata::{ /// hybrid::dfa::{Cache, DFA}, /// HalfMatch, MatchError, PatternID, /// }; /// /// fn find_leftmost_first( /// dfa: &DFA, /// cache: &mut Cache, /// haystack: &[u8], /// ) -> Result<Option<HalfMatch>, MatchError> { /// // The start state is determined by inspecting the position and the /// // initial bytes of the haystack. Note that start states can never /// // be match states (since DFAs in this crate delay matches by 1 /// // byte), so we don't need to check if the start state is a match. /// let mut sid = dfa.start_state_forward( /// cache, None, haystack, 0, haystack.len(), /// ).map_err(|_| MatchError::GaveUp { offset: 0 })?; /// let mut last_match = None; /// // Walk all the bytes in the haystack. We can quit early if we see /// // a dead or a quit state. The former means the automaton will /// // never transition to any other state. The latter means that the /// // automaton entered a condition in which its search failed. /// for (i, &b) in haystack.iter().enumerate() { /// sid = dfa /// .next_state(cache, sid, b) /// .map_err(|_| MatchError::GaveUp { offset: i })?; /// if sid.is_tagged() { /// if sid.is_match() { /// last_match = Some(HalfMatch::new( /// dfa.match_pattern(cache, sid, 0), /// i, /// )); /// } else if sid.is_dead() { /// return Ok(last_match); /// } else if sid.is_quit() { /// // It is possible to enter into a quit state after /// // observing a match has occurred. In that case, we /// // should return the match instead of an error. /// if last_match.is_some() { /// return Ok(last_match); /// } /// return Err(MatchError::Quit { byte: b, offset: i }); /// } /// // Implementors may also want to check for start states and /// // handle them differently for performance reasons. But it is /// // not necessary for correctness. /// } /// } /// // Matches are always delayed by 1 byte, so we must explicitly walk /// // the special "EOI" transition at the end of the search. /// sid = dfa /// .next_eoi_state(cache, sid) /// .map_err(|_| MatchError::GaveUp { offset: haystack.len() })?; /// if sid.is_match() { /// last_match = Some(HalfMatch::new( /// dfa.match_pattern(cache, sid, 0), /// haystack.len(), /// )); /// } /// Ok(last_match) /// } /// /// // We use a greedy '+' operator to show how the search doesn't just stop /// // once a match is detected. It continues extending the match. Using /// // '[a-z]+?' would also work as expected and stop the search early. /// // Greediness is built into the automaton. /// let dfa = DFA::new(r"[a-z]+")?; /// let mut cache = dfa.create_cache(); /// let haystack = "123 foobar 4567".as_bytes(); /// let mat = find_leftmost_first(&dfa, &mut cache, haystack)?.unwrap(); /// assert_eq!(mat.pattern().as_usize(), 0); /// assert_eq!(mat.offset(), 10); /// /// // Here's another example that tests our handling of the special /// // EOI transition. This will fail to find a match if we don't call /// // 'next_eoi_state' at the end of the search since the match isn't found /// // until the final byte in the haystack. /// let dfa = DFA::new(r"[0-9]{4}")?; /// let mut cache = dfa.create_cache(); /// let haystack = "123 foobar 4567".as_bytes(); /// let mat = find_leftmost_first(&dfa, &mut cache, haystack)?.unwrap(); /// assert_eq!(mat.pattern().as_usize(), 0); /// assert_eq!(mat.offset(), 15); /// /// // And note that our search implementation above automatically works /// // with multi-DFAs. Namely, `dfa.match_pattern(match_state, 0)` selects /// // the appropriate pattern ID for us. /// let dfa = DFA::new_many(&[r"[a-z]+", r"[0-9]+"])?; /// let mut cache = dfa.create_cache(); /// let haystack = "123 foobar 4567".as_bytes(); /// let mat = find_leftmost_first(&dfa, &mut cache, haystack)?.unwrap(); /// assert_eq!(mat.pattern().as_usize(), 1); /// assert_eq!(mat.offset(), 3); /// let mat = find_leftmost_first(&dfa, &mut cache, &haystack[3..])?.unwrap(); /// assert_eq!(mat.pattern().as_usize(), 0); /// assert_eq!(mat.offset(), 7); /// let mat = find_leftmost_first(&dfa, &mut cache, &haystack[10..])?.unwrap(); /// assert_eq!(mat.pattern().as_usize(), 1); /// assert_eq!(mat.offset(), 5); /// /// # Ok::<(), Box<dyn std::error::Error>>(()) /// ``` #[derive( Clone, Copy, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord, )] pub struct LazyStateID(u32); impl LazyStateID { #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] const MAX_BIT: usize = 31; #[cfg(target_pointer_width = "16")] const MAX_BIT: usize = 15; const MASK_UNKNOWN: usize = 1 << (LazyStateID::MAX_BIT); const MASK_DEAD: usize = 1 << (LazyStateID::MAX_BIT - 1); const MASK_QUIT: usize = 1 << (LazyStateID::MAX_BIT - 2); const MASK_START: usize = 1 << (LazyStateID::MAX_BIT - 3); const MASK_MATCH: usize = 1 << (LazyStateID::MAX_BIT - 4); const MAX: usize = LazyStateID::MASK_MATCH - 1; /// Create a new lazy state ID. /// /// If the given identifier exceeds [`LazyStateID::MAX`], then this returns /// an error. #[inline] pub(crate) fn new(id: usize) -> Result<LazyStateID, LazyStateIDError> { if id > LazyStateID::MAX { return Err(LazyStateIDError { attempted: id as u64 }); } Ok(LazyStateID::new_unchecked(id)) } /// Create a new lazy state ID without checking whether the given value /// exceeds [`LazyStateID::MAX`]. /// /// While this is unchecked, providing an incorrect value must never /// sacrifice memory safety. #[inline] const fn new_unchecked(id: usize) -> LazyStateID { LazyStateID(id as u32) } /// Return this lazy state ID as its raw value if and only if it is not /// tagged (and thus not an unknown, dead, quit, start or match state ID). #[inline] pub(crate) fn as_usize(&self) -> Option<usize> { if self.is_tagged() { None } else { Some(self.as_usize_unchecked()) } } /// Return this lazy state ID as an untagged `usize`. /// /// If this lazy state ID is tagged, then the usize returned is the state /// ID without the tag. If the ID was not tagged, then the usize returned /// is equivalent to the state ID. #[inline] pub(crate) fn as_usize_untagged(&self) -> usize { self.as_usize_unchecked() & LazyStateID::MAX } /// Return this lazy state ID as its raw internal `usize` value, which may /// be tagged (and thus greater than LazyStateID::MAX). #[inline] pub(crate) const fn as_usize_unchecked(&self) -> usize { self.0 as usize } #[inline] pub(crate) const fn to_unknown(&self) -> LazyStateID { LazyStateID::new_unchecked( self.as_usize_unchecked() | LazyStateID::MASK_UNKNOWN, ) } #[inline] pub(crate) const fn to_dead(&self) -> LazyStateID { LazyStateID::new_unchecked( self.as_usize_unchecked() | LazyStateID::MASK_DEAD, ) } #[inline] pub(crate) const fn to_quit(&self) -> LazyStateID { LazyStateID::new_unchecked( self.as_usize_unchecked() | LazyStateID::MASK_QUIT, ) } /// Return this lazy state ID as a state ID that is tagged as a start /// state. #[inline] pub(crate) const fn to_start(&self) -> LazyStateID { LazyStateID::new_unchecked( self.as_usize_unchecked() | LazyStateID::MASK_START, ) } /// Return this lazy state ID as a lazy state ID that is tagged as a match /// state. #[inline] pub(crate) const fn to_match(&self) -> LazyStateID { LazyStateID::new_unchecked( self.as_usize_unchecked() | LazyStateID::MASK_MATCH, ) } /// Return true if and only if this lazy state ID is tagged. /// /// When a lazy state ID is tagged, then one can conclude that it is one /// of a match, start, dead, quit or unknown state. #[inline] pub const fn is_tagged(&self) -> bool { self.as_usize_unchecked() > LazyStateID::MAX } /// Return true if and only if this represents a lazy state ID that is /// "unknown." That is, the state has not yet been created. When a caller /// sees this state ID, it generally means that a state has to be computed /// in order to proceed. #[inline] pub const fn is_unknown(&self) -> bool { self.as_usize_unchecked() & LazyStateID::MASK_UNKNOWN > 0 } /// Return true if and only if this represents a dead state. A dead state /// is a state that can never transition to any other state except the /// dead state. When a dead state is seen, it generally indicates that a /// search should stop. #[inline] pub const fn is_dead(&self) -> bool { self.as_usize_unchecked() & LazyStateID::MASK_DEAD > 0 } /// Return true if and only if this represents a quit state. A quit state /// is a state that is representationally equivalent to a dead state, /// except it indicates the automaton has reached a point at which it can /// no longer determine whether a match exists or not. In general, this /// indicates an error during search and the caller must either pass this /// error up or use a different search technique. #[inline] pub const fn is_quit(&self) -> bool { self.as_usize_unchecked() & LazyStateID::MASK_QUIT > 0 } /// Return true if and only if this lazy state ID has been tagged as a /// start state. #[inline] pub const fn is_start(&self) -> bool { self.as_usize_unchecked() & LazyStateID::MASK_START > 0 } /// Return true if and only if this lazy state ID has been tagged as a /// match state. #[inline] pub const fn is_match(&self) -> bool { self.as_usize_unchecked() & LazyStateID::MASK_MATCH > 0 } } /// This error occurs when a lazy state ID could not be constructed. /// /// This occurs when given an integer exceeding the maximum lazy state ID /// value. /// /// When the `std` feature is enabled, this implements the `Error` trait. #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) struct LazyStateIDError { attempted: u64, } impl LazyStateIDError { /// Returns the value that failed to constructed a lazy state ID. pub(crate) fn attempted(&self) -> u64 { self.attempted } } #[cfg(feature = "std")] impl std::error::Error for LazyStateIDError {} impl core::fmt::Display for LazyStateIDError { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!( f, "failed to create LazyStateID from {:?}, which exceeds {:?}", self.attempted(), LazyStateID::MAX, ) } } /// Represents the current state of an overlapping search. /// /// This is used for overlapping searches since they need to know something /// about the previous search. For example, when multiple patterns match at the /// same position, this state tracks the last reported pattern so that the next /// search knows whether to report another matching pattern or continue with /// the search at the next position. Additionally, it also tracks which state /// the last search call terminated in. /// /// This type provides no introspection capabilities. The only thing a caller /// can do is construct it and pass it around to permit search routines to use /// it to track state. /// /// Callers should always provide a fresh state constructed via /// [`OverlappingState::start`] when starting a new search. Reusing state from /// a previous search may result in incorrect results. #[derive(Clone, Debug, Eq, PartialEq)] pub struct OverlappingState { /// The state ID of the state at which the search was in when the call /// terminated. When this is a match state, `last_match` must be set to a /// non-None value. /// /// A `None` value indicates the start state of the corresponding /// automaton. We cannot use the actual ID, since any one automaton may /// have many start states, and which one is in use depends on several /// search-time factors. id: Option<LazyStateID>, /// Information associated with a match when `id` corresponds to a match /// state. last_match: Option<StateMatch>, } /// Internal state about the last match that occurred. This records both the /// offset of the match and the match index. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) struct StateMatch { /// The index into the matching patterns for the current match state. pub(crate) match_index: usize, /// The offset in the haystack at which the match occurred. This is used /// when reporting multiple matches at the same offset. That is, when /// an overlapping search runs, the first thing it checks is whether it's /// already in a match state, and if so, whether there are more patterns /// to report as matches in that state. If so, it increments `match_index` /// and returns the pattern and this offset. Once `match_index` exceeds the /// number of matching patterns in the current state, the search continues. pub(crate) offset: usize, } impl OverlappingState { /// Create a new overlapping state that begins at the start state of any /// automaton. pub fn start() -> OverlappingState { OverlappingState { id: None, last_match: None } } pub(crate) fn id(&self) -> Option<LazyStateID> { self.id } pub(crate) fn set_id(&mut self, id: LazyStateID) { self.id = Some(id); } pub(crate) fn last_match(&mut self) -> Option<&mut StateMatch> { self.last_match.as_mut() } pub(crate) fn set_last_match(&mut self, last_match: StateMatch) { self.last_match = Some(last_match); } }
use std::fs::File; use std::io::Read; use std::str::FromStr; use computer::IntCodeComputer; fn main() { let mut in_dat_fh = File::open("./data/input_02.txt").unwrap(); let mut in_dat = String::new(); in_dat_fh.read_to_string(&mut in_dat).unwrap(); let mut icc = IntCodeComputer::from_str(&in_dat).unwrap(); // The instructions indicate to make these replacments before running icc.store(1, 12).unwrap(); icc.store(2, 2).unwrap(); if let Err(err) = icc.run() { println!("Program crashed with error: {:?}", err); }; println!("Answer to step 1 is: {}", icc.mem_read(0).unwrap()); println!("Brute force searching the answer to step 2..."); // Alright so there are two possibilities for how I could go about finding the answer to step // 2. The simple and straight forward is brute forcing the two values. They're both between // 0-99 which means there is only 10k possibilities and Rust is very fast here. A more "fun" // way to solve this would be to attempt to reverse the execution of the computer. This is // still possible because there are no jumps only linear advancement, the only failure // possibility here is if one of the opcodes got overwritten by the program... which is // possible... Nah I'm just going to bruteforce it. for noun in 0..100 { for verb in 0..100 { icc.reset(); icc.store(1, noun).unwrap(); icc.store(2, verb).unwrap(); icc.run().unwrap(); if icc.mem_read(0).unwrap() == 19_690_720 { println!("Found a valid answer: {:0>2}{:0>2}", noun, verb); } } } }
use std::os::raw::{c_int, c_void}; #[cfg(feature = "libsodium")] use std::{ffi::CStr, os::raw::c_char}; extern "C" { fn zmq_version(major: *mut i32, minor: *mut i32, patch: *mut i32) -> c_void; #[cfg(feature = "libsodium")] fn sodium_version_string() -> *const c_char; } pub fn version() -> (i32, i32, i32) { let mut major = 0; let mut minor = 0; let mut patch = 0; unsafe { zmq_version( &mut major as *mut c_int, &mut minor as *mut c_int, &mut patch as *mut c_int, ); } (major, minor, patch) } #[cfg(feature = "libsodium")] pub fn sodium_version() -> &'static CStr { unsafe { CStr::from_ptr(sodium_version_string()) } }
use super::*; #[derive(Debug)] pub enum Screen { GameWorld, Console, Inventory, Character, } #[derive(Debug)] pub enum Action { Nothing, Exit, OpenInventory, OpenCharacterScreen, ListObjects, GameAction(game::Action), } impl State for Screen { type World = Game; type Action = Action; fn render(&self, con: &mut Offscreen, game: &Self::World) { use Screen::*; match self { GameWorld => { game.render_game_world(con); game.render_messages(con); } Inventory => println!("Show inventory"), Character => println!("Show character"), Console => println!("Show console"), }; } fn interpret(&self, event: &Event) -> Self::Action { use Action::*; use Event::*; use KeyCode::{Char, Escape}; use Screen::*; match self { GameWorld => match event { KeyEvent(Key { code: Escape, .. }) => Exit, KeyEvent(Key { code: Char, printable: 'i', .. }) => OpenInventory, KeyEvent(Key { code: Char, printable: 'c', .. }) => OpenCharacterScreen, KeyEvent(Key { code: Char, printable: c, .. }) => game_action(c), KeyEvent(_) | Event::Nothing => Action::Nothing, Command(c) => execute(c), }, Inventory => Exit, Character => Exit, Console => Exit, } } fn update(&mut self, action: Self::Action, game: &mut Self::World) -> Transition<Self> { use Action::*; use Screen::*; match self { GameWorld => match action { Exit => Transition::Exit, Nothing => Transition::Continue, OpenInventory => Transition::Next(Inventory), OpenCharacterScreen => Transition::Next(Character), GameAction(action) => { game.update(action); Transition::Continue }, ListObjects => { for (i, o) in game.objects.iter().enumerate() { println!("{}: {:?}", i, o); } Transition::Continue } }, Inventory => Transition::Exit, Character => Transition::Exit, Console => Transition::Exit, } } } fn game_action(c: &char) -> Action { use game::Action::*; let a = match c { 'k' => Move(PLAYER, Direction(0, -1)), 'j' => Move(PLAYER, Direction(0, 1)), 'h' => Move(PLAYER, Direction(-1, 0)), 'l' => Move(PLAYER, Direction(1, 0)), 'y' => Move(PLAYER, Direction(-1, -1)), 'u' => Move(PLAYER, Direction(1, -1)), 'b' => Move(PLAYER, Direction(-1, 1)), 'n' => Move(PLAYER, Direction(1, 1)), _ => game::Action::Nothing, }; Action::GameAction(a) } fn execute(command: &str) -> Action { match command { "ls" => { println!("List objects"); Action::ListObjects } _ => { println!("Unknown command: {:?}", command); Action::Nothing } } }
use std::collections::HashMap; use std::fmt; use std::rc::Rc; use self::MalType::*; use super::env::Env; pub type MalHashContainer = HashMap<String, MalValue>; /// The different types a MAL value can take. #[allow(non_camel_case_types)] pub enum MalType { Nil, True, False, Integer(i32), Str(String), Symbol(String), List(Vec<MalValue>), Vector(Vec<MalValue>), Hash(MalHashContainer), /// A native function, implemented in the host language (i.e. in Rust). Function(FunctionData<'static>), /// A lambda function, defined in Make A Lisp. MalFunction(MalFunctionData), } impl MalType { /// If the type defines a function, apply it to the given arguments. pub fn apply(&self, args: Vec<MalValue>) -> MalResult { match *self { Function(ref data) => { if data.arity.is_some() && args.len() != data.arity.unwrap() { err_string(format!("wrong arity ({}) for {:?}", args.len(), data)) } else { (data.function)(args) } } MalFunction(ref data) => { let exprs = new_list(args); match super::env::bind(&data.env, data.args.clone(), exprs) { Ok(eval_env) => (data.eval)(data.exp.clone(), eval_env), Err(why) => err_string(why), } } _ => err_str("cannot call a non-function"), } } } impl PartialEq for MalType { fn eq(&self, other: &MalType) -> bool { match (self, other) { (&Nil, &Nil) => true, (&True, &True) => true, (&False, &False) => true, (&Integer(a), &Integer(b)) => a == b, (&Str(ref a), &Str(ref b)) => a == b, (&Symbol(ref a), &Symbol(ref b)) => a == b, (&List(ref a), &List(ref b)) => a == b, (&Vector(ref a), &Vector(ref b)) => a == b, (&Hash(ref a), &Hash(ref b)) => a == b, (&Function(_), &Function(_)) => { warn!("cannot compare two functions"); false } (&MalFunction(_), &MalFunction(_)) => { // data.eval could be ignored // but data.env would have to be compared : // equality doesn't really make sense warn!("cannot compare two functions"); false } _ => false, } } } /// Metadata for a native Rust function operating on MAL values. pub struct FunctionData<'a> { /// The Rust evaluating function. function: fn(Vec<MalValue>) -> MalResult, /// Its arity (the number of MAL values it takes as parameters). /// If none, can accept any number of parameters. /// Should be at least a minimum bound in the number of parameters, /// and optionally can be stricly respected if 'MalType::apply' only /// accept an equal number of parameters. arity: Option<usize>, /// The name of the function (only a hint used for printing). name: &'a str, } impl<'a> fmt::Debug for FunctionData<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Rust function \"{}\" ({} parameter(s))", self.name, match self.arity { Some(n) => n.to_string(), None => "?".to_string(), } ) } } /// Metadata for a function defined in MAL (a lambda). pub struct MalFunctionData { /// The Rust function used to evaluate the function body. eval: fn(MalValue, Env) -> MalResult, /// The function outer environment. env: Env, /// The function parameters (list of symbols). args: MalValue, /// The function body. exp: MalValue, } impl fmt::Debug for MalFunctionData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(fn* {:?} {:?})", self.args, self.exp) } } /// A reference-counted MAL value. pub type MalValue = Rc<MalType>; #[derive(Debug)] pub enum MalError { ErrString(String), ErrEmptyLine, } /// Frequently used return type for functions dealing with MAL values. pub type MalResult = Result<MalValue, MalError>; pub fn err_str(error: &str) -> MalResult { Err(MalError::ErrString(error.into())) } pub fn err_string(error: String) -> MalResult { Err(MalError::ErrString(error)) } pub fn new_nil() -> MalValue { Rc::new(Nil) } pub fn new_true() -> MalValue { Rc::new(True) } pub fn new_false() -> MalValue { Rc::new(False) } pub fn new_integer(integer: i32) -> MalValue { Rc::new(Integer(integer)) } pub fn new_str(string: String) -> MalValue { Rc::new(Str(string)) } pub fn new_str_from_slice(slice: &str) -> MalValue { Rc::new(Str(slice.into())) } pub fn new_symbol(symbol: String) -> MalValue { Rc::new(Symbol(symbol)) } pub fn new_list(seq: Vec<MalValue>) -> MalValue { Rc::new(List(seq)) } pub fn new_vector(seq: Vec<MalValue>) -> MalValue { Rc::new(Vector(seq)) } pub fn new_hash(map: MalHashContainer) -> MalValue { Rc::new(Hash(map)) } pub fn new_function( function: fn(Vec<MalValue>) -> MalResult, arity: Option<usize>, name: &'static str, ) -> MalValue { Rc::new(Function(FunctionData { function, arity, name, })) } pub fn new_mal_function( eval: fn(MalValue, Env) -> MalResult, env: Env, args: MalValue, exp: MalValue, ) -> MalValue { Rc::new(MalFunction(MalFunctionData { eval, env, args, exp, })) }
use std::vec::IntoIter; use {Error, Result}; const TOPIC_PATH_DELIMITER: char = '/'; use self::Topic::{ Normal, System, Blank, SingleWildcard, MultiWildcard }; /// FIXME: replace String with &str #[derive(Debug, Clone, PartialEq)] pub enum Topic { Normal(String), System(String), // $SYS = Topic::System("$SYS") Blank, SingleWildcard, // + MultiWildcard, // # } impl Into<String> for Topic { fn into(self) -> String { match self { Normal(s) | System(s) => s, Blank => "".to_string(), SingleWildcard => "+".to_string(), MultiWildcard => "#".to_string() } } } impl Topic { pub fn validate(topic: &str) -> bool { match topic { "+" | "#" => true, _ => !(topic.contains("+") || topic.contains("#")) } } pub fn fit(&self, other: &Topic) -> bool { match *self { Normal(ref str) => { match *other { Normal(ref s) => str == s, SingleWildcard | MultiWildcard => true, _ => false } }, System(ref str) => { match *other { System(ref s) => str == s, _ => false } }, Blank => { match *other { Blank | SingleWildcard | MultiWildcard => true, _ => false } }, SingleWildcard => { match *other { System(_) => false, _ => true } }, MultiWildcard => { match *other { System(_) => false, _ => true } } } } } #[derive(Debug, Clone)] pub struct TopicPath { pub path: String, // Should be false for Topic Name pub wildcards: bool, topics: Vec<Topic> } impl TopicPath { pub fn path(&self) -> String { self.path.clone() } pub fn get(&self, index: usize) -> Option<&Topic> { self.topics.get(index) } pub fn get_mut(&mut self, index: usize) -> Option<&mut Topic> { self.topics.get_mut(index) } pub fn len(&self) -> usize { self.topics.len() } pub fn is_final(&self, index: usize) -> bool { let len = self.topics.len(); len == 0 || len-1 == index } pub fn is_multi(&self, index: usize) -> bool { match self.topics.get(index) { Some(topic) => *topic == Topic::MultiWildcard, None => false } } pub fn from_str<T: AsRef<str>>(path: T) -> Result<TopicPath> { let mut valid = true; let topics: Vec<Topic> = path.as_ref().split(TOPIC_PATH_DELIMITER).map( |topic| { match topic { "+" => Topic::SingleWildcard, "#" => Topic::MultiWildcard, "" => Topic::Blank, _ => { if !Topic::validate(topic) { valid = false; } if topic.chars().nth(0) == Some('$') { Topic::System(String::from(topic)) } else { Topic::Normal(String::from(topic)) } } } }).collect(); if !valid { return Err(Error::InvalidTopicPath); } // check for wildcards let wildcards = topics.iter().any(|topic| { match *topic { Topic::SingleWildcard | Topic::MultiWildcard => true, _ => false } }); Ok(TopicPath { path: String::from(path.as_ref()), topics: topics, wildcards: wildcards }) } } impl IntoIterator for TopicPath { type Item = Topic; type IntoIter = IntoIter<Topic>; fn into_iter(self) -> Self::IntoIter { self.topics.into_iter() } } impl<'a> From<&'a str> for TopicPath { fn from(str: &'a str) -> TopicPath { Self::from_str(str).unwrap() } } impl From<String> for TopicPath { fn from(path: String) -> TopicPath { Self::from_str(path).unwrap() } } impl Into<String> for TopicPath { fn into(self) -> String { self.path } } pub trait ToTopicPath { fn to_topic_path(&self) -> Result<TopicPath>; fn to_topic_name(&self) -> Result<TopicPath> { let topic_name = try!(self.to_topic_path()); match topic_name.wildcards { false => Ok(topic_name), true => Err(Error::TopicNameMustNotContainWildcard) } } } impl ToTopicPath for TopicPath { fn to_topic_path(&self) -> Result<TopicPath> { Ok(self.clone()) } } impl ToTopicPath for String { fn to_topic_path(&self) -> Result<TopicPath> { TopicPath::from_str(self.clone()) } } impl<'a> ToTopicPath for &'a str { fn to_topic_path(&self) -> Result<TopicPath> { TopicPath::from_str(*self) } } #[cfg(test)] mod test { use super::{TopicPath, Topic}; #[test] fn topic_path_test() { let path = "/$SYS/test/+/#"; let topic = TopicPath::from(path); let mut iter = topic.into_iter(); assert_eq!(iter.next().unwrap(), Topic::Blank); assert_eq!(iter.next().unwrap(), Topic::System("$SYS".to_string())); assert_eq!(iter.next().unwrap(), Topic::Normal("test".to_string())); assert_eq!(iter.next().unwrap(), Topic::SingleWildcard); assert_eq!(iter.next().unwrap(), Topic::MultiWildcard); } #[test] fn wildcards_test() { let topic = TopicPath::from("/a/b/c"); assert!(!topic.wildcards); let topic = TopicPath::from("/a/+/c"); assert!(topic.wildcards); let topic = TopicPath::from("/a/b/#"); assert!(topic.wildcards); } #[test] fn topic_is_not_valid_test() { assert!(TopicPath::from_str("+wrong").is_err()); assert!(TopicPath::from_str("wro#ng").is_err()); assert!(TopicPath::from_str("w/r/o/n/g+").is_err()); } }
// Copyright (c) 2020 ESRLabs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use derive_new::new; use npk::manifest::{Manifest, Version}; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, path::PathBuf}; use crate::runtime::{ExitStatus as ExitStatusRuntime, Notification as NotificationRuntime}; pub type Name = String; pub type RepositoryId = String; pub type MessageId = String; // UUID pub type Container = crate::runtime::Container; const VERSION: &str = "0.0.2"; pub fn version() -> Version { Version::parse(VERSION).unwrap() } pub type ExitCode = i32; pub type Signal = u32; #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum ExitStatus { /// Process exited with exit code Exit(ExitCode), /// Process was terminated by a signal Signaled(Signal), } impl From<ExitStatusRuntime> for ExitStatus { fn from(e: ExitStatusRuntime) -> Self { match e { ExitStatusRuntime::Exit(e) => ExitStatus::Exit(e), ExitStatusRuntime::Signaled(s) => ExitStatus::Signaled(s as u32), } } } #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct Message { pub id: MessageId, // used to match response with a request pub payload: Payload, } impl Message { pub fn new(payload: Payload) -> Message { Message { id: uuid::Uuid::new_v4().to_string(), payload, } } pub fn new_request(request: Request) -> Message { Message::new(Payload::Request(request)) } pub fn new_response(respone: Response) -> Message { Message::new(Payload::Response(respone)) } pub fn new_notification(notification: Notification) -> Message { Message::new(Payload::Notification(notification)) } } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum Payload { Request(Request), Response(Response), Notification(Notification), } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum Notification { OutOfMemory(Container), Exit { container: Container, status: ExitStatus, }, Install(Name, Version), Uninstalled(Name, Version), Started(Container), Stopped(Container), Shutdown, } impl From<NotificationRuntime> for Notification { fn from(n: NotificationRuntime) -> Self { match n { NotificationRuntime::OutOfMemory(container) => Notification::OutOfMemory(container), NotificationRuntime::Exit { container, status } => Notification::Exit { container, status: status.into(), }, NotificationRuntime::Started(container) => Notification::Started(container), NotificationRuntime::Stopped(container) => Notification::Stopped(container), } } } #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum Request { Containers, Install(RepositoryId, u64), Mount(Vec<Container>), Repositories, Shutdown, Start(Container), /// Stop the given container. If the process does not exit within /// the timeout in seconds it is SIGKILLED Stop(Container, u64), Umount(Container), Uninstall(Container), } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct ContainerData { pub container: Container, pub repository: RepositoryId, pub manifest: Manifest, pub process: Option<Process>, pub mounted: bool, } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct Repository { pub dir: PathBuf, } #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct Process { /// Process id pub pid: u32, /// Process uptime in nanoseconds pub uptime: u64, /// Resources used and allocated by this process pub resources: Resources, } #[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct Resources { /// Memory resources used by process pub memory: Option<Memory>, } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub struct Memory { pub size: u64, pub resident: u64, pub shared: u64, pub text: u64, pub data: u64, } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum MountResult { Ok, Err(Error), } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum Response { Ok(()), Containers(Vec<ContainerData>), Repositories(HashMap<RepositoryId, Repository>), Mount(Vec<(Container, MountResult)>), Err(Error), } #[derive(new, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum Error { InvalidContainer(Container), UmountBusy(Container), StartContainerStarted(Container), StartContainerResource(Container), StartContainerMissingResource(Container, Container), StopContainerNotStarted(Container), InvalidRepository(RepositoryId), InstallDuplicate(Container), Npk(String), NpkArchive(String), Process(String), Console(String), Cgroups(String), Mount(String), Key(String), Io(String), Os(String), }
use shrev::{EventChannel, ReaderId}; use specs::prelude::{Read, Resources, System, Write}; use crate::event; use crate::input::InputHandler; use wasm_bindgen::prelude::*; use wasm_bindgen::*; use web_sys::*; use web_sys::WebGl2RenderingContext as GL; pub struct InputSystem { reader: Option<ReaderId<event::InputEvent>>, } impl InputSystem { pub fn new() -> Self { InputSystem { reader: None, } } fn process_event( event: &event::InputEvent, handler: &mut InputHandler, ) { match event { event::InputEvent::KeyPressed(key) => { if !handler.is_pressed(key) { info!("Key press: {}", key); } handler.press(key); }, event::InputEvent::KeyReleased(key) => { handler.release(key); info!("Key release: {}", key); }, } } } impl<'a> System<'a> for InputSystem { type SystemData = ( Read<'a, EventChannel<event::InputEvent>>, Write<'a, InputHandler>, ); fn run(&mut self, (input, mut handler): Self::SystemData) { for event in input.read(&mut self.reader.as_mut().unwrap()) { Self::process_event(event, &mut *handler); } } fn setup(&mut self, res: &mut Resources) { use specs::prelude::SystemData; Self::SystemData::setup(res); self.reader = Some(res.fetch_mut::<EventChannel<event::InputEvent>>().register_reader()); info!("Setting up InputSystem"); } }
#[doc = "Reader of register CIER"] pub type R = crate::R<u32, super::CIER>; #[doc = "Writer for register CIER"] pub type W = crate::W<u32, super::CIER>; #[doc = "Register CIER `reset()`'s with value 0"] impl crate::ResetValue for super::CIER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "LSI ready Interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LSIRDYIE_A { #[doc = "0: Interrupt disabled"] DISABLED = 0, #[doc = "1: Interrupt enabled"] ENABLED = 1, } impl From<LSIRDYIE_A> for bool { #[inline(always)] fn from(variant: LSIRDYIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LSIRDYIE`"] pub type LSIRDYIE_R = crate::R<bool, LSIRDYIE_A>; impl LSIRDYIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LSIRDYIE_A { match self.bits { false => LSIRDYIE_A::DISABLED, true => LSIRDYIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == LSIRDYIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == LSIRDYIE_A::ENABLED } } #[doc = "Write proxy for field `LSIRDYIE`"] pub struct LSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> LSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "LSE ready Interrupt Enable"] pub type LSERDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `LSERDYIE`"] pub type LSERDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `LSERDYIE`"] pub struct LSERDYIE_W<'a> { w: &'a mut W, } impl<'a> LSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSERDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "HSI ready Interrupt Enable"] pub type HSIRDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `HSIRDYIE`"] pub type HSIRDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `HSIRDYIE`"] pub struct HSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> HSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "HSE ready Interrupt Enable"] pub type HSERDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `HSERDYIE`"] pub type HSERDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `HSERDYIE`"] pub struct HSERDYIE_W<'a> { w: &'a mut W, } impl<'a> HSERDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSERDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "CSI ready Interrupt Enable"] pub type CSIRDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `CSIRDYIE`"] pub type CSIRDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `CSIRDYIE`"] pub struct CSIRDYIE_W<'a> { w: &'a mut W, } impl<'a> CSIRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CSIRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "RC48 ready Interrupt Enable"] pub type HSI48RDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `HSI48RDYIE`"] pub type HSI48RDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `HSI48RDYIE`"] pub struct HSI48RDYIE_W<'a> { w: &'a mut W, } impl<'a> HSI48RDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: HSI48RDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "PLL1 ready Interrupt Enable"] pub type PLL1RDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `PLL1RDYIE`"] pub type PLL1RDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `PLL1RDYIE`"] pub struct PLL1RDYIE_W<'a> { w: &'a mut W, } impl<'a> PLL1RDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL1RDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "PLL2 ready Interrupt Enable"] pub type PLL2RDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `PLL2RDYIE`"] pub type PLL2RDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `PLL2RDYIE`"] pub struct PLL2RDYIE_W<'a> { w: &'a mut W, } impl<'a> PLL2RDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL2RDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "PLL3 ready Interrupt Enable"] pub type PLL3RDYIE_A = LSIRDYIE_A; #[doc = "Reader of field `PLL3RDYIE`"] pub type PLL3RDYIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `PLL3RDYIE`"] pub struct PLL3RDYIE_W<'a> { w: &'a mut W, } impl<'a> PLL3RDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PLL3RDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "LSE clock security system Interrupt Enable"] pub type LSECSSIE_A = LSIRDYIE_A; #[doc = "Reader of field `LSECSSIE`"] pub type LSECSSIE_R = crate::R<bool, LSIRDYIE_A>; #[doc = "Write proxy for field `LSECSSIE`"] pub struct LSECSSIE_W<'a> { w: &'a mut W, } impl<'a> LSECSSIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LSECSSIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::DISABLED) } #[doc = "Interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(LSIRDYIE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } impl R { #[doc = "Bit 0 - LSI ready Interrupt Enable"] #[inline(always)] pub fn lsirdyie(&self) -> LSIRDYIE_R { LSIRDYIE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - LSE ready Interrupt Enable"] #[inline(always)] pub fn lserdyie(&self) -> LSERDYIE_R { LSERDYIE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - HSI ready Interrupt Enable"] #[inline(always)] pub fn hsirdyie(&self) -> HSIRDYIE_R { HSIRDYIE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - HSE ready Interrupt Enable"] #[inline(always)] pub fn hserdyie(&self) -> HSERDYIE_R { HSERDYIE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - CSI ready Interrupt Enable"] #[inline(always)] pub fn csirdyie(&self) -> CSIRDYIE_R { CSIRDYIE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - RC48 ready Interrupt Enable"] #[inline(always)] pub fn hsi48rdyie(&self) -> HSI48RDYIE_R { HSI48RDYIE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - PLL1 ready Interrupt Enable"] #[inline(always)] pub fn pll1rdyie(&self) -> PLL1RDYIE_R { PLL1RDYIE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - PLL2 ready Interrupt Enable"] #[inline(always)] pub fn pll2rdyie(&self) -> PLL2RDYIE_R { PLL2RDYIE_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - PLL3 ready Interrupt Enable"] #[inline(always)] pub fn pll3rdyie(&self) -> PLL3RDYIE_R { PLL3RDYIE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - LSE clock security system Interrupt Enable"] #[inline(always)] pub fn lsecssie(&self) -> LSECSSIE_R { LSECSSIE_R::new(((self.bits >> 9) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - LSI ready Interrupt Enable"] #[inline(always)] pub fn lsirdyie(&mut self) -> LSIRDYIE_W { LSIRDYIE_W { w: self } } #[doc = "Bit 1 - LSE ready Interrupt Enable"] #[inline(always)] pub fn lserdyie(&mut self) -> LSERDYIE_W { LSERDYIE_W { w: self } } #[doc = "Bit 2 - HSI ready Interrupt Enable"] #[inline(always)] pub fn hsirdyie(&mut self) -> HSIRDYIE_W { HSIRDYIE_W { w: self } } #[doc = "Bit 3 - HSE ready Interrupt Enable"] #[inline(always)] pub fn hserdyie(&mut self) -> HSERDYIE_W { HSERDYIE_W { w: self } } #[doc = "Bit 4 - CSI ready Interrupt Enable"] #[inline(always)] pub fn csirdyie(&mut self) -> CSIRDYIE_W { CSIRDYIE_W { w: self } } #[doc = "Bit 5 - RC48 ready Interrupt Enable"] #[inline(always)] pub fn hsi48rdyie(&mut self) -> HSI48RDYIE_W { HSI48RDYIE_W { w: self } } #[doc = "Bit 6 - PLL1 ready Interrupt Enable"] #[inline(always)] pub fn pll1rdyie(&mut self) -> PLL1RDYIE_W { PLL1RDYIE_W { w: self } } #[doc = "Bit 7 - PLL2 ready Interrupt Enable"] #[inline(always)] pub fn pll2rdyie(&mut self) -> PLL2RDYIE_W { PLL2RDYIE_W { w: self } } #[doc = "Bit 8 - PLL3 ready Interrupt Enable"] #[inline(always)] pub fn pll3rdyie(&mut self) -> PLL3RDYIE_W { PLL3RDYIE_W { w: self } } #[doc = "Bit 9 - LSE clock security system Interrupt Enable"] #[inline(always)] pub fn lsecssie(&mut self) -> LSECSSIE_W { LSECSSIE_W { w: self } } }
use itertools; fn main() { let origs = [6, 3, 5, 8, 6, 34, 1, 5, 7]; for sublen in 0..origs.len() { let unsorted_vals = &origs[..sublen]; let mut sorted_vals = unsorted_vals.to_vec(); quick_sort(&mut sorted_vals); println!("{:?} => {:?}", unsorted_vals, sorted_vals); let oracle_sorted_vals = itertools::sorted(unsorted_vals.iter().cloned()).collect::<Vec<_>>(); assert_eq!(oracle_sorted_vals, sorted_vals); } } fn quick_sort<T: PartialOrd>(vals: &mut [T]) { if vals.len() > 1 { let boundary_idx = partition(vals); quick_sort(&mut vals[..boundary_idx]); quick_sort(&mut vals[boundary_idx + 1..]); } } fn partition<T: PartialOrd>(vals: &mut [T]) -> usize { let pivot_idx = vals.len() - 1; let mut boundary_idx = 0; for i in 0..pivot_idx { if vals[i] < vals[pivot_idx] { vals.swap(i, boundary_idx); boundary_idx += 1; } } vals.swap(boundary_idx, pivot_idx); boundary_idx }
pub fn total_distance(speed: u32, fly: u32, rest: u32, seconds: u32) -> u32 { let mut time_to_fly = fly; let mut time_to_rest = rest; let mut distance = 0; for _ in 0..seconds { if time_to_fly > 0 { distance += speed; time_to_fly -= 1; } else { if time_to_rest > 0 { time_to_rest -= 1; } else { time_to_fly = fly; distance += speed; time_to_fly -= 1; time_to_rest = rest; } } } distance } pub fn parse_string(s: &String) -> (u32, u32, u32) { let can_fly = s.find("can fly").expect("Uh oh!") + 8; let mut km_s = s.find("km/s").expect("Uh oh!") - 1; let speed = s[can_fly..km_s].parse::<u32>().expect("Error parsing speed"); km_s = s.find("km/s").expect("Uh oh!") + 9; let first_seconds = s.find("seconds,").expect("Uh oh!") - 1; let fly = s[km_s..first_seconds].parse::<u32>().expect("Error parsing fly time"); let rest_for = s.find("rest for").expect("Uh oh!") + 9; let second_seconds = s.find("seconds.").expect("Uh oh!") - 1; let rest = s[rest_for..second_seconds].parse::<u32>().expect("Error parsing rest time"); (speed, fly, rest) } #[test] fn comet_distance() { assert_eq!(1120, total_distance(14, 10, 127, 1000)); } #[test] fn dancer_distance() { assert_eq!(1056, total_distance(16, 11, 162, 1000)); } #[test] fn comet_parse() { let input = "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.".to_string(); let (speed, fly, rest) = parse_string(&input); assert_eq!(14, speed); assert_eq!(10, fly); assert_eq!(127, rest); } #[test] fn dancer_parse() { let input = "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.".to_string(); let (speed, fly, rest) = parse_string(&input); assert_eq!(16, speed); assert_eq!(11, fly); assert_eq!(162, rest); }